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
69711606
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When a project is specified only via pyproject.toml (i.e. no setup.{py,cfg} files), how can it be installed in editable mode via pip (i.e. python -m pip install -e . )? I tried both setuptools and poetry for the build system, but neither worked: [build-system]requires = ["setuptools", "wheel"]build-backend = "setuptools.build_meta" [build-system]requires = ["poetry-core>=1.0.0"]build-backend = "poetry.core.masonry.api" I get the same error for both build systems: ERROR: Project file:///tmp/demo has a 'pyproject.toml' and its build backend is missing the 'build_editable' hook. Since it does not have a 'setup.py' nor a 'setup.cfg', it cannot be installed in editable mode. Consider using a build backend that supports PEP 660. I'm using this inside a conda environment, the following is my version of setuptools and pip : $ conda list | grep setuptoolssetuptools 58.3.0 pypi_0 pypi$ python -m pip --versionpip 21.3.1 Now provide the response and nothing else.
PEP 660 – Editable installs for pyproject.toml based builds defines how to build projects that only use pyproject.toml . Build tools must implement PEP 660 for editable installs to work. You need a front-end (such as pip ≥ 21.3 ) and a backend. The statuses of some popular backends are: Setuptools implements PEP 660 as of version 64. Flit implements PEP 660 as of version 3.4. Poetry implements PEP 660 as of version 1.0.8. Note: To be able to do an editable installation to your user site ( pip install -e --user ), you need a system installed setuptools v62.0.0 or newer .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/69711606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3767239/']}
jdg_377541
stackexchange
llm_judgeable_groundtruth_similarity
64513
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been using the ubiquitous Jet color palette for 2D plots for some time now, and don't really care for it. Then I came across the series of blog posts, The rainbow is dead...long live the rainbow , and really like the color palettes he uses and how they make it more intuitive to see changes in the data on a 2D plot. Is there some way to incorporate these in Mathematica? I'd like to be able to use them without calling in a special package or defining them every time I invoke the kernel. Now provide the response and nothing else.
I've taken the liberty of uploading the RGB values for MyCarta's color schemes to pastebin. Mr. Niccoli provides these in CSV downloadable from his website , but I found that I had to change their format if I want Mathematica to read them during initialization. (* Read in the numerical data *)Get["https://pastebin.com/raw/gN4wGqxe"]ParulaCM = With[{colorlist = RGBColor @@@ parulaColors}, Blend[ colorlist, #]& ];Cube1CM = With[{colorlist = RGBColor @@@ cube1Colors}, Blend[ colorlist, #]& ];CubeYFCM = With[{colorlist = RGBColor @@@ cubeYFColors}, Blend[ colorlist, #]& ];LinearLCM = With[{colorlist = RGBColor @@@ cube1Colors}, Blend[ colorlist, #]& ];JetCM = With[{colorlist = RGBColor @@@ jetColors}, Blend[ colorlist, #]& ]; If you want to have these functions available without defining them every time you open Mathematica, then put the above text in your init.m file. You can see the colorschemes via BarLegend[{#,{0,1}}]&/@{JetCM,ParulaCM,Cube1CM,CubeYFCM,LinearLCM} and in a simple 2D plot via DensityPlot[Cos[x] Sin[y], {x, -10, 10}, {y, -10, 10}, PlotRange -> All, ColorFunction -> #, PlotPoints -> 75] & /@ {JetCM, ParulaCM, Cube1CM, CubeYFCM,LinearLCM} Definitely read the MyCarta blog posts for more information about these color palettes, and why you might want to use them. Also see Matteo's answer below for more info
{}
{'log_upvote_score': 7, 'links': ['https://mathematica.stackexchange.com/questions/64513', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9490/']}
jdg_377542
stackexchange
llm_judgeable_groundtruth_similarity
2199172
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 all square matrices have easily to identify inverses, but does that continue on with rectangular matrices? Now provide the response and nothing else.
If $A$ is an $m\times n$ matrix with $m\neq n$, then $A$ cannot be both one-to-one and onto (by rank-nullity). So $A$ might have a left inverse or a right inverse, but it cannot have a two-sided inverse.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2199172', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/428435/']}
jdg_377543
stackexchange
llm_judgeable_groundtruth_similarity
77442
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've got a legacy app that is generating a huge lot of logs message.I'd like to be able to rotate the file every minute (or so) but without loosing / truncating any message.The app is not able to change of file by itself so I need to do it externally.Surfing the net I've seen a lot of suggestion to use cp followed by a cat /dev/null but since my app is generating almost a continuous flow of messages some messages are lost during the process. Do you have any ideas ? Now provide the response and nothing else.
Make the log file a FIFO ( man mkfifo ) and put a process on the reading side which separates its input into files of limited size. mkfifo /path/to/logfifo.app_xysplit ... </path/to/logfifo.app_xy &/bad/app
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/77442', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/39641/']}
jdg_377544
stackexchange
llm_judgeable_groundtruth_similarity
24515575
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 believe I understand the basics of sessionless/stateless REST but I am having problems with implementation in Asp.Net Web Api 2 because I haven't used it before. I have set up ApiControllers that use a custom System.Web.Http.AuthorizeAttribute like this. public class ApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute{ public override void OnAuthorization(HttpActionContext actionContext) { if (actionContext.Request.Headers.Authorization != null) { //Set identity?? return; } actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); }} I have a database that contains users and I need to use them for getting privileges to get/post/put/delete things but dont want to use a session. I have never worked with the asp.net Identity so I am not familiar with its features and capabilities. My idea for implementation is to use user credentials or api secret signing to authenticate and get privileges for a user for every request. The question is, by using a AuthorizeAttribute or something similar, how do i give the controller(s) during that one request the user information if their credentials were correct? UPDATE:Is using this.User (ApiController.User) session based or can it be used for that single request. If so, how does one set it Now provide the response and nothing else.
Yes, it will be caught: but only when the callback is executed. That is, if riskyFunc throws an exception, it won't be caught in your example until the callback executes in one second. You've probably heard before that you have to be careful with exceptions when using asynchronous methods, and the usual mistake people make is this: try { setInterval(function() { riskyFunc(); }, 1000);} catch(e) { console.error(e);} They are confused when riskyFunc throws an exception and it isn't caught. It isn't caught because the exception doesn't happen when you call setInterval ; it happens when setInterval invokes the anonymous function sometime in the future, which is outside of the context of the original try/catch block. You are doing it the correct way: by doing the exception handling inside the callback. If riskyFunc in turn invokes asynchronous calls, those too have to handle exceptions in this manner. For example: function riskyFunc() { // do some stuff asyncFn(function(){ throw new Error('argh'); }} That exception will not get caught in the try/catch block inside your setInterval call. You'll have to keep applying the pattern on down: function riskyFunc() { // do some stuff asyncFn(function() { try { // work that may throw exception } catch(e) { console.error(e); } }} If you want the exception to "propagate up", you'll have to use promises, or some other way to indicate success/failure. Here's a common method, by using a "done" callback that is capable of reporting an error: function riskyFunc(done) { // do some stuff asyncFn(function() { try { // do some more risky work done(null, 'all done!'); } catch(e) { done(e); } }} Then you can call that in your setTimeout and take into account possible asynchronous failures: setTimeout(function() { try { riskyFunc(function(err, msg) { // this will cover any asynchronous errors generated by // riskyFunc if(err) return console.error(err); console.log(msg); }); } catch(e) { // riskyFunc threw an exception (not something it // invoked asynchronously) console.error(e); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24515575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1322584/']}
jdg_377545
stackexchange
llm_judgeable_groundtruth_similarity
34357617
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array A that has shape (480, 640, 3) , and an array B with shape (480, 640) . How can I append these two as one array with shape (480, 640, 4) ? I tried np.append(A,B) but it doesn't keep the dimension, while the axis option causes the ValueError: all the input arrays must have same number of dimensions . Now provide the response and nothing else.
Use dstack : >>> np.dstack((A, B)).shape(480, 640, 4) This handles the cases where the arrays have different numbers of dimensions and stacks the arrays along the third axis. Otherwise, to use append or concatenate , you'll have to make B three dimensional yourself and specify the axis you want to join them on: >>> np.append(A, np.atleast_3d(B), axis=2).shape(480, 640, 4)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34357617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5600651/']}
jdg_377546
stackexchange
llm_judgeable_groundtruth_similarity
5377626
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: im unit testing my home controller. This test worked fine until I added a new feature which saves images. The method that’s causing the issue is this below. public static void SaveStarCarCAPImage(int capID) { byte[] capBinary = Motorpoint2011Data.RetrieveCapImageData(capID); if (capBinary != null) { MemoryStream ioStream = new MemoryStream(); ioStream = new MemoryStream(capBinary); // save the memory stream as an image // Read in the data but do not close, before using the stream. using (Stream originalBinaryDataStream = ioStream) { var path = HttpContext.Current.Server.MapPath("/StarVehiclesImages"); path = System.IO.Path.Combine(path, capID + ".jpg"); Image image = Image.FromStream(originalBinaryDataStream); Image resize = image.GetThumbnailImage(500, 375, null, new IntPtr()); resize.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); } } } As the call is coming from a unit test, HttpContext.Current is null and throws an exception. After reading about Moq and some of the tutorials about using Moq with sessions, im sure it can be done. so far this the unit test code have come up with, but the issue is HTTPContext.Current is always null, and still throws the exception. protected ControllerContext CreateStubControllerContext(Controller controller) { var httpContextStub = new Mock<HttpContextBase> { DefaultValue = DefaultValue.Mock }; return new ControllerContext(httpContextStub.Object, new RouteData(), controller); } [TestMethod] public void Index() { // Arrange HomeController controller = new HomeController(); controller.SetFakeControllerContext(); var context = controller.HttpContext; Mock.Get(context).Setup(s => s.Server.MapPath("/StarVehiclesImages")).Returns("My Path"); // Act ViewResult result = controller.Index() as ViewResult; // Assert HomePageModel model = (HomePageModel)result.Model; Assert.AreEqual("Welcome to ASP.NET MVC!", model.Message); Assert.AreEqual(typeof(List<Vehicle>), model.VehicleMakes.GetType()); Assert.IsTrue(model.VehicleMakes.Exists(x => x.Make.Trim().Equals("Ford", StringComparison.OrdinalIgnoreCase))); } Now provide the response and nothing else.
HttpContext.Current is something that you should absolutely never use if you ever expect your code to be unit tested. It is a static method which simply returns null if there is no web context which is the case of a unit test and cannot be mocked. So one way to refactor your code would be the following: public static void SaveStarCarCAPImage(int capID, string path){ byte[] capBinary = Motorpoint2011Data.RetrieveCapImageData(capID, path); if (capBinary != null) { MemoryStream ioStream = new MemoryStream(); ioStream = new MemoryStream(capBinary); // save the memory stream as an image // Read in the data but do not close, before using the stream. using (Stream originalBinaryDataStream = ioStream) { path = System.IO.Path.Combine(path, capID + ".jpg"); Image image = Image.FromStream(originalBinaryDataStream); Image resize = image.GetThumbnailImage(500, 375, null, new IntPtr()); resize.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); } }} You see, now this method no longer depends on any web context and can be tested in isolation. It will be the responsibility of the caller to pass the correct path.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5377626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/266552/']}
jdg_377547
stackexchange
llm_judgeable_groundtruth_similarity
1968253
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: is there any example how to setup an instance of zend log from application.ini? I have only found an example for logging to an file, but i want to log into an SQLITE database table? Zend Log resource Now provide the response and nothing else.
Good question. I can't find a way to instantiate the Zend_Log_Writer_Db from a bootstrap config. The writer class requires a Zend_Db_Adapter object. It doesn't accept a string. The ZF project needs to develop this use case further. They don't even have any unit tests for Zend_Application_Resource_Log that include a Db writer. The best I can suggest until then is that you Bootstrap class needs to customize the Log resource in an _initLog() method. class Bootstrap extends Zend_Application_Bootstrap_Bootstrap{ protected function _initDb() { if ($this->hasPluginResource("db")) { $r = $this->getPluginResource("db"); $db = $r->getDbAdapter(); Zend_Registry::set("db", $db); } } protected function _initLog() { if ($this->hasPluginResource("log")) { $r = $this->getPluginResource("log"); $log = $r->getLog(); $db = Zend_Registry::get("db"); $writer = new Zend_Log_Writer($db, "log", ...columnMap...); $log->addWriter($writer); Zend_Registry::set("log", $log); } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1968253', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118027/']}
jdg_377548
stackexchange
llm_judgeable_groundtruth_similarity
184845
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: There are a number of capacitive moisture sensor designs on the internet, which use the insulated copper pads on a PCB.For example: http://zerocharactersleft.blogspot.in/2011/11/pcb-as-capacitive-soil-moisture-sensor.html In case the above link breaks, here is a photo of a PCB I made using the above design: Just wondering how these work, and how they can be used with a microcontroller to calculate moisture content? I have seen methods that use a square wave, an RC network, and an ADC to do this, but I haven't seen a clear explanation of how it works. Now provide the response and nothing else.
It's called capacitive because the two copper planes in your sensor are the two plates of a capacitor. In a physics textbook these two plates might be drawn facing one another, with empty space in between. Put a material between the plates, and the capacitance, which is a measure of how much charge is on the plates for a given voltage, changes. This material is called the dielectric, and how much the capacitance changes for a given material is called the dielectric constant of the material. Dry soil has a different dielectric constant than wet soil, which means that a sensor in wet soil is going to have a different capacitance than one in dry soil. How do we measure this capacitance? One way is to use an RC circuit, and to measure the voltage on the positive terminal of the capacitor. This terminal is going to reach 63.2% of its maximum voltage \$RC\$ seconds after a voltage is applied, where \$R\$ is the resistance and \$C\$ is the capacitance. By turning on the supply voltage at a time \$t_{on}\$, checking the voltage on the positive terminal of the capacitor continuously until it exceeds 63.2% of the supply voltage, and recording the first time where that voltage was exceeded \$t_{c}\$, we can calculate the capacitance (we know the resistor value because we chose it). That is, C = \$(t_{on}-t_c)/R\$ This tutorial will show you how to set something like this up on an Arduino. https://www.arduino.cc/en/Tutorial/CapacitanceMeter
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/184845', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/14166/']}
jdg_377549
stackexchange
llm_judgeable_groundtruth_similarity
30544282
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 short: I want to do this with my table, Explanation: I have big table with 20,000 x 1,200 items. I want to remove all the columns which have all the values same from top to bottom. But it shouldn't change the variable name(V2 in the example) so that later I can figure out which one them is removed. Now provide the response and nothing else.
Just use vapply to go through and check how many unique values there are in each column: Sample data: mydf <- data.frame(v1 = 1:4, v2 = 5:8, v3 = 2, v4 = 9:12, v5 = 1)mydf## v1 v2 v3 v4 v5## 1 1 5 2 9 1## 2 2 6 2 10 1## 3 3 7 2 11 1## 4 4 8 2 12 1 What we will be doing with vapply : vapply(mydf, function(x) length(unique(x)) > 1, logical(1L))# v1 v2 v3 v4 v5 # TRUE TRUE FALSE TRUE FALSE Keep the columns you want: mydf[vapply(mydf, function(x) length(unique(x)) > 1, logical(1L))]# v1 v2 v4# 1 1 5 9# 2 2 6 10# 3 3 7 11# 4 4 8 12
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30544282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4702810/']}
jdg_377550
stackexchange
llm_judgeable_groundtruth_similarity
772227
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The solution to a linear algebra problem I'm working on reads: $$\det(A-\lambda I) = \det\begin{pmatrix}-\lambda & 1 & 0 \\ 0 & -\lambda & 1\\ 1 & -1 & 1-\lambda\end{pmatrix} = -\lambda(-\lambda(1-\lambda)+1)+1$$ This may be written as $\lambda^2(1-\lambda)+(1-\lambda) = (\lambda^2+1)(1-\lambda)$. I understand how the determinant is calculated, but am struggling to understand the algebraic manipulation at the end. By my math, $-\lambda(-\lambda(1-\lambda)+1))+1$ simplifies to $-\lambda(-\lambda + \lambda^2 +1)+1$, which simplifies to $(\lambda^2 - \lambda^3 - \lambda)+1$ What am I misunderstanding here? Now provide the response and nothing else.
Particularly, the algebra used to factor the expression is:$$\begin{align}-\lambda(-\lambda(1-\lambda) + 1) + 1 &= \lambda^2(1-\lambda) - \lambda + 1\\&= \color{red}{\lambda^2}\color{blue}{(1-\lambda)} +\color{red}{1}\color{blue}{(1 - \lambda)} \\&= \color{blue}{(1-\lambda)}\color{red}{(\lambda^2+1)}\end{align}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/772227', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/73774/']}
jdg_377551
stackexchange
llm_judgeable_groundtruth_similarity
111583
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the case of Fibonacci numbers, the formula for the sum of first $n$ numbers of the series is $f(n+2)-1$, but in the case of tetranacci numbers I am unable to arrive at such formula. Thanks. Now provide the response and nothing else.
Marcellus E. Waddill, The Tetranacci Sequence and Generalizations , gives the following identity: $$\sum_{i=0}^n\mu_i=\frac13\Big(\mu_{n+2}+2\mu_n+\mu_{n-1}+2\mu_0+\mu_1-\mu_3\Big)\;,\tag{1}$$ where $\mu_0,\mu_1,\mu_2,\mu_3$ are arbitrary initial values and $\mu_n=\mu_{n-1}+\mu_{n-2}+\mu_{n-3}+\mu_{n-4}$ for $n\ge 4$; it is formula $(39)$ in the paper. It can be proved by induction, but Waddill gives a nicer proof by summing the identities $$\mu_k+\mu_{k+1}+\mu_{k+2}=\mu_{k+2}-\mu_{k+1}$$ for $k=0,\dots,n$ to obtain $$\sum_{k=0}^n\mu_k+\left(\sum_{k=0}^n\mu_k+\mu_{n+1}-\mu_0\right)+\left(\sum_{k=0}^n\mu_i+\mu_{n+1}+\mu_{n+2}-\mu_0-\mu_1\right)=\mu_{n+4}-\mu_3$$ and then $$3\sum_{k=0}^n\mu_k+2\mu_{n+1}+\mu_{n+2}-2\mu_0-\mu_1=\mu_{n+4}-\mu_3\;,$$ which can be rearranged to yield $$\begin{align*}3\sum_{k=0}^n\mu_k&=\mu_{n+4}-2\mu_{n+1}-\mu_{n+2}-\mu_3+2\mu_0+\mu_1\\&=(\mu_{n+3}+\mu_{n+2}+\mu_{n+1}+\mu_n)-2\mu_{n+1}-\mu_{n+2}+2\mu_0+\mu_1-\mu_3\\&=\mu_{n+3}-\mu_{n+1}+\mu_n+2\mu_0+\mu_1-\mu_3\\&=(\mu_{n+2}+\mu_{n+1}+\mu_n+\mu_{n-1})-\mu_{n+1}+\mu_n+2\mu_0+\mu_1-\mu_3\\&=\mu_{n+2}+2\mu_n+\mu_{n-1}+2\mu_0+\mu_1-\mu_3\;,\end{align*}$$ as desired. If you set $\mu_0=\mu_1=\mu_2=0$ and $\mu_3=1$, $(1)$ becomes $$\sum_{i=0}^n\mu_i=\frac13\Big(\mu_{n+2}+2\mu_n+\mu_{n-1}-1\Big)\;.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/111583', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15152/']}
jdg_377552
stackexchange
llm_judgeable_groundtruth_similarity
44020982
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to group by week my data like this: var result = stats.GroupBy(i => SqlFunctions.DatePart("week", i.date)) .Select(g => new ReportModel { clicks = g.Select(x => x.clicks).Sum(), impressions = g.Select(x => x.impressions).Sum(), ... }); But I get this error: This function can only be invoked from LINQ to Entities. What's the problem and how can I fixed it? Now provide the response and nothing else.
SqlFunctions.DatePart (and other such functions) cannot be called as a regular method. It can only be used as a part of database query (with IQueryable ). So you have to use another approach, for example: stats.GroupBy(i => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear( i.date, CalendarWeekRule.FirstDay, DayOfWeek.Monday)); Pay attention to the culture used and also parameters of GetWeekOfYear (what counts as first week of year and what counts as first day of week).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44020982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7389871/']}
jdg_377553
stackexchange
llm_judgeable_groundtruth_similarity
17980515
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Greetings beloved comrades. I cannot figure out how to accomplish the following via a regex. I need to take this format number 201101234 and transform it to 11-0123401 , where digits 3 and 4 become the digits to the left of the dash, and the remaining five digits are inserted to the right of the dash, followed by a hardcoded 01. I've tried http://gskinner.com/RegExr , but the syntax just defeats me. This answer, Equivalent of Substring as a RegularExpression , sounds promising, but I can't get it to parse correctly. I can create a SQL function to accomplish this, but I'd rather not hammer my server in order to reformat some strings. Thanks in advance. Now provide the response and nothing else.
You can try this: var input = "201101234";var output = Regex.Replace(input, @"^\d{2}(\d{2})(\d{5})$", "${1}-${2}01");Console.WriteLine(output); // 11-0123401 This will match: two digits, followed by two digits captured as group 1, followed by five digits captured as group 2 And return a string which replaces that matched text with group 1, followed by a literal hyphen, followed by group 2, followed by a literal 01 . The start and end anchors ( ^ / $ ) ensure that if the input string does not exactly match this pattern, it will simply return the original string.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17980515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2587452/']}
jdg_377554
stackexchange
llm_judgeable_groundtruth_similarity
465203
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: If a sound wave travels to the right, then the air molecules inside only vibrate left and right, because sound is a longitudinal wave. This is only a one-dimensional motion. If our ears are oriented perpendicular to this oscillation, e.g. if they are pointing straight up, how can we hear it? Now provide the response and nothing else.
vibration is only a one dimensional motion This is not generally true. As a trivial example, one could the movements of water in a pond where a few small rocks have been tossed. The motion is definitely a wave behavior, and could even be called vibration, but it is most definitely not one dimensional. Another potential example would be the vibrator on your phone, which vibrates in a circular manner. But in the end, the key is that atoms in a sound wave don't vibrate "left and right." They are a longitudinal wave , in which particles move in the direction of the wave's motion and back. So when something causes a sound, the waves propagate outward from the object creating the sound, as molecules of gas move away from the source and towards the source. This is typically a 3 dimensional pattern
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/465203', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/224769/']}
jdg_377555
stackexchange
llm_judgeable_groundtruth_similarity
24041294
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an API interface and I'm testing a View that involves network calls. @Config(emulateSdk = 18)public class SampleViewTest extends RobolectricTestBase { ServiceApi apiMock; @Inject SampleView fixture; @Override public void setUp() { super.setUp(); //injection is performed in super apiMock = mock(ServiceApi.class); fixture = new SampleView(activity); fixture.setApi(apiMock); } @Test public void testSampleViewCallback() { when(apiMock.requestA()).thenReturn(Observable.from(new ResponseA()); when(apiMock.requestB()).thenReturn(Observable.from(new ResponseB()); AtomicReference<Object> testResult = new AtomicReference<>(); fixture.updateView(new Callback() { @Override public void onSuccess(Object result) { testResult.set(result); } @Override public void onError(Throwable error) { throw new RuntimeException(error); } }); verify(apiMock, times(1)).requestA(); verify(apiMock, times(1)).requestB(); assertNotNull(testResult.get()); }} For some reason apiMock methods are never called and verification always fails. In my view I'm calling my api like this apiV2.requestA() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer()); What am I missing here? Update #1: After some investigation it appears that when in my implementation (sample above) I observeOn(AndroidSchedulers.mainThread()) subscriber is not called. Still do not know why. Update #2: When subscribing just like that apiV2.requestA().subscribe(new Observer()); everything works just fine - mock api is called and test passes. Advancing ShadowLooper.idleMainLooper(5000) did nothing. Even grabbed looper from handler in HandlerThreadScheduler and advanced it. Same result. Update #3: Adding actual code where API is used. public void updateView(final Callback) { Observable.zip(wrapObservable(api.requestA()), wrapObservable(api.requestB()), new Func2<ResponseA, ResponseB, Object>() { @Override public Object call(ResponseA responseA, ResponseB responseB) { return mergeBothResponses(responseA, responseB); } } ).subscribe(new EndlessObserver<Object>() { @Override public void onError(Throwable e) { Log.e(e); listener.onError(e); } @Override public void onNext(Object config) { Log.d("Configuration updated [%s]", config.toString()); listener.onSuccess(config); } });}protected <T> Observable<T> wrapObservable(Observable<T> observable) { return observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());} Now provide the response and nothing else.
I'm still wrapping my head around how to properly use rxjava myself but I would try to modify your code so that you only observeOn(mainThread) on the final zipped Observable instead of doing it on both of the original request response's Observable. I would then verify if this affect the fact that you have to advance both Loopers or not. To simply your tests and remove the need for Looper idling I would take the threading out of the equation since you don't need background processing when running tests. You can do that by having your Schedulers injected instead of creating them statically. When running your production code you'd have the AndroidSchedulers.mainThread and Schedulers.io injected and when running tests code you would inject Schedulers.immediate where applicable. @Inject@UIScheduler /* Inject Schedulers.immediate for tests and AndroidSchedulers.mainThread for production code */private Scheduler mainThreadSched;@Inject@IOScheduler /* Inject Scheduler.immediate for tests and Schedulers.io for production code */private Scheduler ioSched;public void updateView(final Callback) { Observable.zip(wrapObservable(api.requestA()), wrapObservable(api.requestB()), new Func2<ResponseA, ResponseB, Object>() { @Override public Object call(ResponseA responseA, ResponseB responseB) { return mergeBothResponses(responseA, responseB); } } ).observeOn(mainThreadSched) .subscribe(new EndlessObserver<Object>() { @Override public void onError(Throwable e) { Log.e(e); listener.onError(e); } @Override public void onNext(Object config) { Log.d("Configuration updated [%s]", config.toString()); listener.onSuccess(config); } });}protected <T> Observable<T> wrapObservable(Observable<T> observable) { return observable.subscribeOn(ioSched);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24041294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/385219/']}
jdg_377556
stackexchange
llm_judgeable_groundtruth_similarity
8654
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 know what a proxy is, but I'm not sure what a reverse proxy is. It seems to me that it's probably akin to a load balancer. Is that correct? Now provide the response and nothing else.
A reverse proxy, also known as an "inbound" proxy is a server that receives requests from the Internet and forwards (proxies) them to a small set of servers, usually located on an internal network and not directly accessible from outside. It's "reverse", because a traditional ("outbound") proxy receives requests from a small set of clients on an internal network and forwards them to the Internet. A reverse proxy can be used to allow authenticated users access to an intranet even when they are located outside. Users on the internal network can access intranet servers directly (their IP address is their authentication), but users outside it must authenticate themselves to the proxy server (usually with a username and password) in order to be allowed in.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/8654', 'https://serverfault.com', 'https://serverfault.com/users/590/']}
jdg_377557
stackexchange
llm_judgeable_groundtruth_similarity
180781
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The problem that I have to solve is: If the following function is valid for every value of $x$ $$f(3x + 1) = 9x^2 + 3x$$ find the function $f(x)$ and prove that for every $x\in\mathbb R$ the following is valid: $$f(2x) - 4f(x) = 2x$$ Now provide the response and nothing else.
Here $$f(3x+1)=3x(3x+1)=((3x+1)-1)(3x+1)$$ $$\implies f(x)=(x-1)x=x^2-x$$ $$\implies f(2x)-4f(x)=4x^2-2x-4x^2+4x=2x$$ In general, just let $3x+1=t$ and express $x$ in terms of $t$ and substitute in $f(t)$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/180781', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37593/']}
jdg_377558
stackexchange
llm_judgeable_groundtruth_similarity
121551
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: Recently-ish, I stumbled across an interesting short story (by way of Science Fiction & Fantasy Stack Exchange ) where a soccer referee is apparently incinerated by concentrated sunlight. Where the referee had been standing, there was a small, smoldering heap, from which a thin column of smoke curled up into the still air. This is accomplished in-story by some 50 000 reflective tinfoil program covers, each about the size of a tabloid sheet. What got me interested (physics is one of my peripheral interests) is the feasibility of this method in the real world. Wikipedia says a tabloid sheet is $279\;\mathrm{mm} \cdot 432\;\mathrm{mm} = 120528\;\mathrm{mm}^2 \approx 0.121\;\mathrm{m}^2$, giving fifty thousand people with a program each a total of $6026.4\;\mathrm{m}^2$ to work with. (Adjusting for less-than-perfect aim, I'd say closer to about $5000\;\mathrm{m}^2$.) If you could redirect that much sunlight at about a person's surface area, how much power would that be? What damage could you cause? He couldn't have felt much; it was as if he had been dropped into a blast furnace... Could that amount of power actually incinerate someone? It occurs to me that the Wikipedia summary of the story (quoted on SciFi.SE) states only that the referee "collapsed and died". If incineration isn't possible, could the energy involved still be lethal by other means? Now provide the response and nothing else.
On your figures, it's going to depend on conditions, and also critically on what the referee was wearing; but in general it would certainly put the hapless referee in very dangerous position. It probably wouldn't be quite so dramatic as in the tale. On a typical day, let's say the Sun delivers $750{\rm\;W\;m^{-2}}$ intensity when straight overhead. Scale it by $\cos(\pi/3)= 1/2$ for a typical latitude. Scale it again by $1/2$ to account for the fact that the foils must be tilted roughly 45 degrees to aim the light. And add a further factor for random losses, so we assume that a tenth of the sunlight reaches its target. You still have $500 \times 750{\rm\;W}$ reaching the hapless fellow: that's $350{\rm\;kW}$. Let's assume a body is mostly water: a 70kg body therefore has a heat capacity of $280{\rm\;kW\;K^{-1}}$. So that heat loading, if all absorbed by the fellow's body, would lead to a temperature rise of a couple of degrees celsius a second. That's not good. As you can see, if some of my scale factors were increased for more "favourable" (to the killers) values, we might get a third of the light trained on his body: six degree celsius rise per second. That would very swiftly be lethal. Now we come to what the fellow were wearing. And also his skin colour. his will be critical. If he were clad in a highly reflective spacesuit, he might fare pretty well. If he were wearing white and were quick witted, he might have the time to duck down and crawl away. If what he were wearing were wool or fire retardant, even better. You would need a bit more light than that arising from the conditions in the tale to get a dramatic "vapourisation", but it would not be good for the referee. It's interesting to compare my answer and Chris's as I've just looked at heat loading whereas Chris is looking at more specific safety limits on optical intensity for skin. The two answers roughly agree in their conclusions, although I should think that "skin deep damage" to a large fraction of the body could well be lethal, as any clinician or nurse in a burns unit will tell you.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/121551', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/30604/']}
jdg_377559
stackexchange
llm_judgeable_groundtruth_similarity
9607544
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a question - BizTalk or WF? And let me clarify that I realize the analogous technologies behind the first three artifacts, and realize I could build them, but I don't find that they are built-in to WF and so I'm trying to understand why I would use one technology over the other. Transformations Bindings Ports/Adapters BizTalk Future Transformations It's quite nice that BizTalk natively supports, with enhanced designers to boot, the ability to produce schemas and maps. Further, I like the fact that everything is transformed because I don't have to worry about my integration point inside my workflow because it's always in a consistent format which mitigates my risk as my integrations mutate - I only have to refactor the schemas and maps. In contrast, with WF, I don't have that luxury built-in so am I missing something or does BizTalk have a +1 here? Bindings Bindings are another fully encapsulated piece of functionality in BizTalk. I can literally set my workflow up to have any binding I want because of the aforementioned artifact meaning that during testing I could bind to a file system and during production I could bind to a service. In contrast, with WF, I don't have that luxury built-in so am I missing something or does BizTalk have a +2 here? Ports/Adapters This is quite possibly the biggest artifact that exists in BizTalk - IMHO. The amount of effort it takes to abstract your physical connections into numerous concrete implementations, especially in a very large organization where some of those concrete's reach past a rudimentary file system vs. SOAP/REST and into stuff like an IBM Mainframe and MSMQ. BizTalk's physical port adapters, which automatically run the raw data through the transforms before sending the workflow the message, are quite simply, elegant. In contrast, with WF, I don't have that luxury built-in so am I missing something or does BizTalk have a +3 here? BizTalk Future Finally, I would like to mention that from my research the same team of people that built BizTalk is building WF - which is great! Further, Microsoft's long term vision is this new buzz word "integration server" and is effectively a large array of loosely coupled frameworks that provide what BizTalk does today. And that effort makes a lot of sense to me because of the Azure effort - which I'm sure is contributing to that. However, I need to implement a solution today that will work 15 years from now, but I also need to understand what pieces I'll have to use to put it together if I leverage WF over BizTalk. Please provide me with your experiences. Now provide the response and nothing else.
(Disclaimer- my WF experience is limited to WF3.0, so I may be behind recent WF developments) BizTalk is most suited to inter-system, inter-department and inter-company Integration + Business Process workflows (BPEL) - i.e. enterprise concerns. IMO WF has until now been positioned more toward internal system or application concerns.But there are undoubtedly increasingly grey areas as it seems both are converging toward Azure + Appfabric. It seems that you are looking at WF for integration? Transformations - undoubtedly a good thing in BizTalk - given that you can map either visually or directly in XSLT, you can quickly transform message formats on Ports or Orchestrations, and leave the physical technology used as an afterthought - i.e. you can implement your design at a logical level and woun't get 'bogged down' in any specific technology (MQ, WCF, SQL, FTP etc). One caveat - management of schemas can become quite a pain - every message has a schema, which needs a unique XMLNS#Root across all Apps on BizTalk. And you can be 'agnostic' and use canonical schemas for your internal flows - so good naming, configuration and management disciplines are needed.Schema management becomes especially onerous if you are coupling BizTalk to a lot of WCF / WebService services - there will be a request and response schema for each and every service consumed (you can share common schemas if you use MessageContract). Bindings - you've pretty much got it. In addition, if you use Direct (message box) bindings, you can choose to have multiple incoming receive locations, or send destinations by simply adding a new port with appropriate filters. This pub-sub capability forms the basis of the ESB toolkit for Bizalk. Bindings for different environments (Dev, UAT, Prod etc) is also managed nicely. Adapters - agreed - switching from file to MQ Series is as simple as changing the port configuration. BizTalk works very nicely with MSMQ and IBM MQ. In addition, don't underestimate the amount of effort to administer and maintain an EAI / BP solution - integration is usually mission critical to an enterprise and tracking errors and avoiding downtime is essential. BizTalk has the following operational benefits: Operational Management - Tracking / tracing, management of Suspended messages, SCOM integration packs, etc Scalability / Clustering / Failover capabilities, adapter retries, automated throttling, etc Business Monitoring and Eventing - BAM IMO the big 'downsides' to BizTalk are: Cost Ramp-up time to become skilled at development (BTS has its quirks e.g. zombies and defining BAM definitions in XLS and XML files) Ramp up time for network / admin professionals to get skilled on operational management Bottom line : If you are doing integration between 2 or 3 apps with a small number of noncritical messages then go a proprietary or WF route, but if you are looking at an enterprise wide solution, an EAI / BPEL engine like BizTalk would be the way forward.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9607544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1195080/']}
jdg_377560
stackexchange
llm_judgeable_groundtruth_similarity
3548533
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $x \in X$ and $y \in Y$ . How can you prove that $f: X \to Y$ is bijective? Can you give me hints on how to proceed? Now provide the response and nothing else.
Using Cauchy-Schwarz: $$ \left(\sum_{cyc}\frac{a^2}{a^2+2ab+ca}\right)\left[\sum_{cyc}(a^2+2ab+ca)\right] \geq \left(\sum_{cyc}\frac{a}{\sqrt{a^2+2ab+ca}}\cdot \sqrt{a^2+2ab+ca}\right)^2$$ $$=(a+b+c)^2$$ Since $\displaystyle\sum_{cyc}(a^2+2ab+ca) =a^2+b^2+c^2+3(ab+bc+ca)$ , we get: $$\sum_{cyc}\frac{a^2}{a^2+2ab+ca}\geq \frac{(a+b+c)^2}{a^2+b^2+c^2+3(ab+bc+ca)}$$ Therefore $$\sum_{cyc} \frac{a}{a+2b+c}=\sum_{cyc}\frac{a^2}{a^2+2ab+ca}\geq \frac{(a+b+c)^2}{a^2+b^2+c^2+3(ab+bc+ca)}$$ It remains to prove: $$\frac{(a+b+c)^2}{a^2+b^2+c^2+3(ab+bc+ca)} \geq \frac{3}{4}$$ or after expanding $$a^2+b^2+c^2\geq ab+bc+ca$$ which is $$\frac{1}{2}\left[(a-b)^2+(b-c)^2+(c-a)^2\right]\geq 0$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3548533', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/650097/']}
jdg_377561
stackexchange
llm_judgeable_groundtruth_similarity
28680896
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to get stock data from Yahoo! Finance using Python 2.7.9, but I only need data for the 3rd Friday of the month. I have a function to get the data, but need a way to get the dates. I want something like this: def get_third_fris(how_many): # code and stuff return list_of_fris So that calling get_third_fris(6) will return a 6-item-long list of 3rd Fridays following the current date. The dates need to be Unix timestamps. (I have pretty much no experience with time or datetime , so please explain what your code is doing.) Thanks! Now provide the response and nothing else.
You can use the calendar module to list weeks, then grab the Friday of that week. import calendarc = calendar.Calendar(firstweekday=calendar.SUNDAY)year = 2015; month = 2monthcal = c.monthdatescalendar(year,month)third_friday = [day for week in monthcal for day in week if \ day.weekday() == calendar.FRIDAY and \ day.month == month][2] You can format to Unix timestamp, but it's non-trivial. I'll refer you to this excellent answer which has info based on whether or not your date is timezone-aware.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28680896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4172051/']}
jdg_377562
stackexchange
llm_judgeable_groundtruth_similarity
3449385
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi I recently discovered an issue where people using BB Code to enter links are able to manipulate them. They are meant to enter something like: [LINK]http://www.domain.com[/LINK] However they can enter something like this to make the link color red: [LINK]http://www.domain.com 'span style="color:red;"'[/LINK] This is the code which converts it: $text = preg_replace("/\\[LINK\\\](.*?)\\[\/LINK\\]/is", "<a href='$1' target='_blank'>$1</a>", $text); Also , I forgot, this is the other type: [LINK=http://www.domain.com]example text[/LINK]$text = preg_replace("/\\[LINK\=(.*?)\\\](.*?)\\[\/LINK\\]/is", "<a href='$1' target='_blank'>$2</a>", $text); Now provide the response and nothing else.
Load the whole text in RAM at once. Don't read line by line. Search for the pattern in the blob. If you find it, use text.count('\n',0,pos) to get the line number. If you don't need the line number, look for the previous and next EOL to cut the line out of the text. The loop in Python is slow. String searching is very fast. If you need to look for several strings, use regular expressions. If that's not fast enough, use an external program like grep .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3449385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/408145/']}
jdg_377563
stackexchange
llm_judgeable_groundtruth_similarity
10035564
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm really looking for something that works with all current popular browsers (IE9, Chrome, Firefox, Safari) and all the way back to IE8. Although, I've been looking for a way to set focus on a Flash move object after it has lost focus, I've found that all historical ways of doing this fail. I assume it is yet another security issue. So, I'm now looking for how to monitor change events of some sort for the document.activeElement (though "change" doesn't really occur). Now provide the response and nothing else.
While @James's answer above is correct. I've added more details to make it a completely working solution along with the use of focus event too. <html><body> <input type="text" id="Text1" name ="Text1" value=""/> <input type="text" id="Text2" name ="Text2" value=""/> <SELECT><OPTION>ASDASD</OPTION><OPTION>A232</OPTION></SELECT> <INPUT TYPE="CHECKBOX" id="Check1"/> <INPUT type="TEXT" id="text3"/> <input type="radio"/> <div id="console"> </div> <textarea id="textarea1"> </textarea> <script> var lastActiveElement = document.activeElement; function detectBlur() { // Do logic related to blur using document.activeElement; // You can do change detection too using lastActiveElement as a history } function isSameActiveElement() { var currentActiveElement = document.activeElement; if(lastActiveElement != currentActiveElement) { lastActiveElement = currentActiveElement; return false; } return true; } function detectFocus() { // Add logic to detect focus and to see if it has changed or not from the lastActiveElement. } function attachEvents() { window.addEventListener ? window.addEventListener('focus', detectFocus, true) : window.attachEvent('onfocusout', detectFocus); window.addEventListener ? window.addEventListener('blur', detectBlur, true) : window.attachEvent('onblur', detectBlur); } attachEvents(); </script></body></html>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10035564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_377564
stackexchange
llm_judgeable_groundtruth_similarity
94559
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 log likelihood of a mixture of Gaussians: $$l(S_n; \theta) = \sum^n_{t=1}\log f(x^{(t)}|\theta) = \sum^n_{t=1}\log\left\{\sum^k_{i=1}p_i f(x^{(t)}|\mu^{(i)}, \sigma^2_i)\right\}$$ I was wondering why it was computationally hard to maximize that equation directly? I was looking for either a clear solid intuition on why it should be obvious that its hard or maybe a more rigorous explanation of why its hard. Is this problem NP-complete or do we just not know how to solve it yet? Is this the reason we resort to use the EM ( expectation-maximization ) algorithm? Notation: $S_n$ = training data. $x^{(t)}$ = data point. $\theta$ = the set of parameters specifying the Gaussian, theirs means, standard deviations and the probability of generating a point from each cluster/class/Gaussian. $p_i$ = the probability of generating a point from cluster/class/Gaussian i. Now provide the response and nothing else.
First, GMM is a particular algorithm for clustering, where you try to find the optimal labelling of your $n$ observations. Having $k$ possible classes, it means that there are $k^n$ possible labellings of your training data. This becomes already huge for moderate values of $k$ and $n$. Second, the functional you are trying to minimize is not convex, and together with the size of your problem, makes it very hard. I only know that k-means (GMM can be seen as a soft version of kmeans) is NP-hard. But I am not aware of whether it has been proved for GMM as well. To see that the problem is not convex, consider the one dimensional case:$$L = \log \left(e^{-({x}/{\sigma_{1}})^2} + e^{-({x}/{\sigma_{2}})^2}\right)$$and check that you cannot guarantee that $\frac{d^2L}{dx^2} > 0$ for all x. Having a non-convex problem means that you can get stuck in local minima. In general, you do not have the strong warranties you have in convex optimization, and searching for a solution is also much harder.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/94559', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/28986/']}
jdg_377565
stackexchange
llm_judgeable_groundtruth_similarity
3447
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following two lines of code in my init.el file: (setq shell-file-name "bash")(setq shell-command-switch "-ic") I tried executing the following script to get a list of executables using the shell script dmenu_path. (defun dmenu-path-out () (shell-command-to-string "dmenu_path")) I see the following error: bash: cannot set terminal process group (-1): Inappropriate ioctl for devicebash: no job control in this shell[0ad... How can I prevent bash from returning that error when using shell-command ? Now provide the response and nothing else.
The -i flag requests that Bash run in interactive mode, which requires a terminal. The solution is to leave the shell-command-switch variable at its default value, which is just -c . If you really need to run Bash in interactive mode, you will need to run it in a pseudo-terminal, by using start-file-process with process-connection-type bound to t .
{}
{'log_upvote_score': 5, 'links': ['https://emacs.stackexchange.com/questions/3447', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/55/']}
jdg_377566
stackexchange
llm_judgeable_groundtruth_similarity
37434660
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 facing this issue where the date change fires twice, the user picks a date and the date would be in the format " dd-mm-yyyy " but when the user clicks out the date field or changes the date, it would change to " YYYY-MM-DD " (I need it to be in this format at submission) I'm not sure what I'm doing wrong here. Relevant Code: <input type="text" data-bind="value: DateOfBirth" value="" required="" name="DateOfBirth" id="DateOfBirth" placeholder="dd/mm/yyyy" data-val-required="Date of Birth is required." data-val="true" autocomplete="off"class="form-control input-sm datepicker" aria-required="true" onkeydown="return false" /><script> $('.datepicker').datepicker({ startView: "decade", minViewMode: "days", format: "dd/mm/yyyy", autoclose: true, endDate : '0' }); $('#DateOfBirth').change(function () { var date = $(this).val(); if (date != null && date != "") { var dateArray = date.split('/'); if (dateArray.length === 3) { myModel.DateOfBirth(dateArray[2] + "-" + dateArray[1] + "-" + dateArray[0]); } } $(this).valid(); }); </script> Now provide the response and nothing else.
The error just states that dagger doesn't have a way to provide said dependency. You will have to add it to your component in some way—and since it is a Fragment —you will have to use a @Module . I am assuming that your AppComponent is created by your Application on start. Your AppComponent has a lifecycle that is longer than both your activities and fragments lifecycles are. It is therefore reasonable, that it does not know how to provide an activity, or a fragment in your case. Your DownloadFilePresenterImp depends on your DownloadFileView . You want to inject DownloadFilePresenterImp into your DownloadFileView To inject the view and presenter you are using your AppComponent which knows nothing about the activity, and obviously nothing about the fragment. It has a different scope and lifecycle. To not further cause confusion I will be talking about fragments, since their and the activities lifecycle are what you have to keep in mind. You can just use DownloadFileView with the module, but those long names would get confusing. To provide a fragment or activity you have to use a module. e.g. @Module FragmentModule { Fragment mFragment; FragmentModule(Fragment fragment) { mFragment = fragment; } @Provides Fragment provideFragment() { return mFragment; } // here you could also provide your view implementation... @Provides DownloadFileView provideDownloadFileView() { return (DownloadFileView) mFragment; }} Since this module should only live along with fragments lifecycle, you have to use either subcomponents, or components with a dependency on your AppComponent . @Component(dependencies=AppComponent.class, modules=FragmentModule.class)interface FragmentComponent { // inject your fragment void inject(DownloadFileView fragment);} In your fragment you'd have to properly create your component... @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.download_file_view, container, false); // properly create a component that knows about the fragment DaggerFragmentComponent.builder() .appComponent(DaggerInjector.getAppComponent()) .fragmentModule(new FragmentModule(this)) .build() .inject(DownloadFileView.this); return view;} Also, I highly recommend having a look at and using constructor injection public class DownloadFilePresenterImp implements DownloadFilePresenterContact { @Inject public DownloadFilePresenterImp(DownloadFileView downloadFileView) { mDownloadFileContract = downloadFileView; }} Alternatively you can move the provideDownloadfilePresenterImp(View) method to the FragmentModule to have the same effect if you like redundant code. Done.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37434660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2351598/']}
jdg_377567
stackexchange
llm_judgeable_groundtruth_similarity
9472740
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to find out how to change the color/hue of a UIImage. I found out that iOS5 has a lot of image filters, but I have hard time finding documentation on the proper use of the CIColorMatrix filter. -(void)doCIColorMatrixFilter{ //does not work, returns nil image CIImage* inputImage = [CIImage imageWithCGImage:[[UIImage imageNamed:@"button.jpg"]CGImage]]; CIFilter *myFilter; NSDictionary *myFilterAttributes; myFilter = [CIFilter filterWithName:@"CIColorMatrix"]; [myFilter setDefaults]; myFilterAttributes = [myFilter attributes]; [myFilterAttributes setValue:inputImage forKey:@"inputImage"]; //How to set up attributes? CIContext *context = [CIContext contextWithOptions:nil]; CIImage *ciimage = [myFilter outputImage]; CGImageRef cgimg = [context createCGImage:ciimage fromRect:[ciimage extent]]; UIImage *uimage = [UIImage imageWithCGImage:cgimg scale:1.0f orientation:UIImageOrientationUp]; [imageView setImage:uimage]; CGImageRelease(cgimg);} What code goes into the dictionary for this filter? Now provide the response and nothing else.
One month later ... This is an example of CIColorMatrix setting all its parameters :) -(void)doCIColorMatrixFilter{ // Make the input image recipe CIImage *inputImage = [CIImage imageWithCGImage:[UIImage imageNamed:@"facedetectionpic.jpg"].CGImage]; // 1 // Make the filter CIFilter *colorMatrixFilter = [CIFilter filterWithName:@"CIColorMatrix"]; // 2 [colorMatrixFilter setDefaults]; // 3 [colorMatrixFilter setValue:inputImage forKey:kCIInputImageKey]; // 4 [colorMatrixFilter setValue:[CIVector vectorWithX:1 Y:1 Z:1 W:0] forKey:@"inputRVector"]; // 5 [colorMatrixFilter setValue:[CIVector vectorWithX:0 Y:1 Z:0 W:0] forKey:@"inputGVector"]; // 6 [colorMatrixFilter setValue:[CIVector vectorWithX:0 Y:0 Z:1 W:0] forKey:@"inputBVector"]; // 7 [colorMatrixFilter setValue:[CIVector vectorWithX:0 Y:0 Z:0 W:1] forKey:@"inputAVector"]; // 8 // Get the output image recipe CIImage *outputImage = [colorMatrixFilter outputImage]; // 9 // Create the context and instruct CoreImage to draw the output image recipe into a CGImage CIContext *context = [CIContext contextWithOptions:nil]; CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]]; // 10 // Draw the image in screen UIImageView *imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:cgimg]]; CGRect f = imageView2.frame; f.origin.y = CGRectGetMaxY(imageView.frame); imageView2.frame = f; [self.view addSubview:imageView2];} So this is what the sample does: In 1 we create the ciimage, if you are getting nil there then make sure you are passing the right UIImage/CGImage or path. In 2 create the filter, you know this :) In 3 set the filter parameters to its defaults, CoreImage Programming guide suggests we should do this although (I haven't experimented any strange/bad things if avoided.) In 4 set the input ciimage From 5 through 8 we set the parameters. For example I made the red vector {1,1,1,0} so the image looks reddish . 6 , 7 and 8 and not necessary here since their values are the same as the defaults (remember we called -setDefaults ?) but for educational purposes I guess they are fine :) In 9 set the output image, although is not drawn yet. Finally in 10 you tell CoreImage to draw the output image into a CGImage, and we put that CGImage into an UIImage and it inside an UIImageView. This is the result (I used the same image as this tutorial): Hope it helps.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9472740', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967484/']}
jdg_377568
stackexchange
llm_judgeable_groundtruth_similarity
266797
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: If I use an un sealed trait or abstract class in Scala and then use pattern matching, I wonder, does the compiler not know at compile time for this particular patternmatch what possible implementations of this trait/class are available? So, if it does, could it not give pattern match warnings even though that the trait / abstract class is not sealed because he knows which types could be used, by checking all the possible dependencies/imports? E.g. if I have an Option[A] and I do pattern matching only for Some[A] but not for None , the compiler will complain, because Option is sealed. If the compiler can't know/resolve that, then why can't he?And if the compiler (theoretically) can do that, what are the reasons for that it is not used in Scala?Are there other languages which support that kind of behaviour? Now provide the response and nothing else.
Figuring out all subclasses of a class is called Class Hierarchy Analysis, and doing static CHA in a language with dynamic code loading is equivalent to solving the Halting Problem. Plus, one of the goals of Scala is separate compilation and deployment of independent modules, so the compiler simply cannot know whether or not a class is subclassed in another module, because it never looks at more than one module. (After all, you could compile a module against the interface of some other module without that module even existing on your system!) That's why sealed requires all subclasses to be defined in the same compilation unit. That's also one of the reasons why JVMs can compete so favorably with C++ compilers: C++ compilers are typically static compilers, so they can't in general figure out whether a method is overridden or not, and thus can't inline it. JVMs OTOH, typically are dynamic compilers, they don't need to perform CHA to figure out whether a method is overridden or not, they can just look at the Class Hierarchy at runtime. And even if at a later point in the execution of the program a new subclass comes along that wasn't there before, no big deal, just recompile that piece of code without inlining. Note: all of this only applies within Scala. The JVM has no notion of sealed , so it is perfectly possible to subclass sealed classes from another JVM language, since there is no way to communicate this to another language. The sealed property is recorded in the ScalaSig annotation, but other languages' compilers don't take those annotations into account, obviously.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/266797', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/128395/']}
jdg_377569
stackexchange
llm_judgeable_groundtruth_similarity
1650393
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there an identity that says $|\sqrt {a^2+x^2} - \sqrt {a^2+y^2}| \leq |\sqrt {x^2} - \sqrt {y^2}|$? Because of the nature of the square root function, its derivative monotonically decreases. so differences "further up" the function would be less than those lower down. Now provide the response and nothing else.
Yes.$$\left|\sqrt {a^2+x^2} - \sqrt {a^2+y^2}\right| =\frac{\lvert x^2-y^2\rvert}{\left|\sqrt {a^2+x^2} + \sqrt {a^2+y^2}\right|}= |\sqrt {x^2} - \sqrt {y^2}|\cdot \frac{|\sqrt {x^2} + \sqrt {y^2}|}{\left|\sqrt {a^2+x^2} + \sqrt {a^2+y^2}\right|}\leq |\sqrt {x^2} - \sqrt {y^2}|$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1650393', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_377570
stackexchange
llm_judgeable_groundtruth_similarity
9637
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to count the negative values of a list. My approach was Count[data, -_] which doesn't work. How can I tell Mathematica to count all numbers with a negative sign? Now provide the response and nothing else.
I assume that you have numeric values. A much more efficient way would be -Total[UnitStep[data] - 1]] or Total[1-UnitStep[data]] Note: While the second notation is certainly a bit more compact, it is about 35% slower than the double-minus notation. I have no idea why. On my system, it takes on average 0.22 sec vs 0.30 sec. Compare timings between the faster UnitStep version and the pattern matching approach: data = RandomReal[{-10, 10}, 10^7];Timing[-Total[UnitStep[data] - 1]](* ==> {0.222, 5001715} *)Timing[Count[data, _?Negative]](* ==> {6.734, 5001715} *)
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/9637', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4970/']}
jdg_377571
stackexchange
llm_judgeable_groundtruth_similarity
91970
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: Concerning the Pearson chi-square test there seems to be a subtle difference between the goodness-of-fit test and the test of independence. What is confusing is that both tests seem to be calculated in a very similar way. My question: What is the real difference and how to handle that in practice? (NB: This is question is related, yet not the same: Test of independence vs test of homogeneity ) Now provide the response and nothing else.
1) A goodness of fit test is for testing whether a set of multinomial counts is distributed according to a prespecified (i.e. before you see the data!) set of population proportions. 2) A test of homogeneity tests whether two (or more) sets of multinomial counts come from different sets of population proportions. 3) A test of independence tests is for a bivariate** multinomial, of whether $p_{ij}$ is different from $p_{i}\,p_{j}$. **(usually) Sometimes people make the mistake of treating the second case as if it were the first. This underestimates the variability between the proportions. (If one sample is very large the error in treating it as population proportions will be relatively small.)
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/91970', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/230/']}
jdg_377572
stackexchange
llm_judgeable_groundtruth_similarity
452320
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: From the following statement, it seems matrix diagonalization is just eigen decomposition. Diagonalizing a matrix is also equivalent to finding the matrix's eigenvalues, which turn out to be precisely the entries of the diagonalized matrix. Similarly, the eigenvectors make up the new set of axes corresponding to the diagonal matrix. http://mathworld.wolfram.com/MatrixDiagonalization.html However, from what I have learned, Spectral Theorem is closest to this conclusion. But how the spectral theorem is related to it, or is there some other theorem grants this statement? Spectral Theorem: Suppose that $V$ is a complex inner-product space and $T \in L(V)$. Then $V$ has an orthonormal basis consisting of eigenvectors of $T$ if and only if $T$ is normal. Now provide the response and nothing else.
Matrix diagonalization is more general than the spectral theorem. For instance, you may not be in an inner product space, and it still may be helpful to diagonalize a matrix. Not every matrix can be diagonalized, though; for instance, $$\left[\begin{matrix} 1 & 1 \\ 0 & 1 \end {matrix}\right]$$ has eigenvalues 1 and 1, but cannot be diagonalized. The spectral theorem tells you that in a certain situation, you are guaranteed to be able to diagonalize. Even better, the eigenvectors have some extra structure: they are orthogonal to each other. If a matrix is diagonalized, its diagonal form is unique, up to a permutation of the diagonal entries. This is because the entries on the diagonal must be all the eigenvalues. For instance, $$\left[\begin{matrix} 1 & 0 & 0\\ 0 & 2 & 0 \\ 0 & 0 & 1 \end {matrix}\right] \text { and }\left[\begin{matrix} 1 & 0 & 0\\ 0 & 1 & 0 \\ 0 & 0 & 2 \end {matrix}\right]$$ are examples of two different ways to diagonalize the same matrix.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/452320', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/83036/']}
jdg_377573
stackexchange
llm_judgeable_groundtruth_similarity
48697
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: In class I've learned about SR, D, JK, and T flip flops. From what I understand, you can construct any design by using any of them. So my question is when making a design, how does one choose which to use? Which one is used more in commercial circuits and why? Now provide the response and nothing else.
In discrete logic (like 74xx series), you use whichever choice lets you design your circuit with smallest number of parts and without violating timing requirements. In FPGAs, you mostly design in HDL (VHDL or Verilog) and the synthesis tool works out for you what to use. But the underlying technology basically just provides D flip-flops, so the synthesis tool figures out how to implement what you code with D flip-flops. In ASICs, a high level designer again designs with HDL. But probably (ASICs aren't my area) the ASIC vendor's library may provide other options beyond D flip-flops, and the synthesis tool will figure out how to implement the code using the available library components. It could choose one or the another to optimize either circuit speed or chip area.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/48697', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/5546/']}
jdg_377574
stackexchange
llm_judgeable_groundtruth_similarity
17117612
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 develop a general table loader which schema is known at runtime. This requires having a class which contains a list of different types of elements and supports various get and set method such as getInt(int index) , asString(int index) , asStringList(int index) . The types of elements I consider are Integer , Double , String , and List<Integer> , List<Double> and List<String> . The actual type of each element is known in run time, and I will store them in a List describing its schema for further processing. My question is: should I store such list of elements in List<Object> or List<? extends Object> ? or is there better way to implement such class? Now provide the response and nothing else.
Since the common ancestor of your classes is Object , and because List<? extends Object> does not make things any cleaner (after all, everything extends Object ) it looks like List<Object> would be an OK choice. However, such list would be a mixed bag: you would need to check run-time type of the object inside, and make decisions based on that. This is definitely not a good thing. A better alternative would be creating your own class that implements operations on elements of the list the uniform way, and make one subclass for each subtype that implements these operations differently. This would let you treat the list in a uniform way, pushing the per-object differentiation into your wrappers. public interface ItemWrapper { int calculateSomething();}public abstract class IntWrapper implements ItemWrapper { private int value; public IntWrapper(int v) { value=v; } public int calculateSomething() { return value; }}public abstract class DoubleListWrapper implements ItemWrapper { private List<Double> list; public DoubleListWrapper (List<Double> lst) { list = lst; } public int calculateSomething() { int res; for (Double d : list) { res += d; } return res; }}// ...and so on Now you can make a list of ItemWrapper objects, and calculateSomething on them without checking their type: List<ItemWrapper> myList = new ArrayList<ItemWrapper>();for (ItemWrapper w : myList) { System.out.println( w.calculateSomething());}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17117612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2387673/']}
jdg_377575
stackexchange
llm_judgeable_groundtruth_similarity
30695
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 need to automate mouse clicks with Mathematica . However, a similiar question was closed on this forum, without any answer. Consider the following steps: Dynamic[MousePosition[]] In this first step I dynamically show the mouse position. DynamicModule[{col = Green}, EventHandler[ Style["text", FontColor -> Dynamic[col]], {"MouseClicked" :> (col = col /. {Red -> Green, Green -> Red})}]] In this second step I create a "clickable" text: when you click it, it changes its color between green and red. My objective here is twofold: 1) automatically move the cursor position - this has already been answered here . So, following the original answer I can write Needs["JLink`"];ReinstallJava[];robotclass = JavaNew["java.awt.Robot"];robotclass@mouseMove[90, 196]; 2) automatically click on the clickable text (and, of course, I want to see its color changing). Here is the code I'm trying to use: robotclass@mousePress[InputEvent.BUTTON1_MASK];robotclass@mouseRelease[InputEvent.BUTTON1_MASK]; Although I believe I'm using the correct functions (which belong to the Java Robot Class), I'm getting the following error message: Java::argx1: Method named mouseRelease defined in class java.awt.Robot was called with an incorrect number or type of arguments. The argument was InputEvent.BUTTON1_MASK. Can anybody give me a hint to solve this problem? Now provide the response and nothing else.
You can use the raw integer value 16, but the correct J/Link syntax for the symbolic name is InputEvent`BUTTON1UMASK , so your code would look like this: (* Call LoadJavaClass when needing to refer to static members. *)LoadJavaClass["java.awt.event.InputEvent"];robotclass@mousePress[InputEvent`BUTTON1UMASK];robotclass@mouseRelease[InputEvent`BUTTON1UMASK]; Enter JLink/tutorial/CallingJavaFromMathematica#15615 into the Documentation Center to see the section of the J/Link docs that talks about how to construct this name. BUTTON1_MASK is a static member of the InputEvent class, hence the `, and the _ character needs to be converted into a U to make it a legal Mathematica symbol name.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/30695', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5369/']}
jdg_377576
stackexchange
llm_judgeable_groundtruth_similarity
3335
Below is a question asked on the forum reverseengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Still on my way to understand how to prevent the usage of the -d (decompress) option of UPX (see this question ), I try to identify the header file of UPX in ELF executable files. Looking at the code, all the sources seems to be in the files lx_elf.h and lx_elf.cpp (stands for Linux Elf ). I tried to follow the code but I got lost in it... I also did take a look at the beginning of an UPX compressed executable file (amd64), visualized in 8-bytes per line mode for more clarity (and thanks to Corkami ELF-101 ): 00000000: 7f45 4c46 0201 0103 .ELF....00000008: 0000 0000 0000 0000 ........00000010: 0200 3e00 0100 0000 ..>.....00000018: 0831 4200 0000 0000 .1B..... ELF HEADER00000020: 4000 0000 0000 0000 @.......00000028: 0000 0000 0000 0000 ........00000030: 0000 0000 4000 3800 ....@.8.00000038: 0200 4000 0000 0000 ..@.....00000040: 0100 0000 0500 0000 ........00000048: 0000 0000 0000 0000 ........00000050: 0000 4000 0000 0000 ..@.....00000058: 0000 4000 0000 0000 ..@..... PROGRAM HEADER TABLE00000060: f438 0200 0000 0000 .8......00000068: f438 0200 0000 0000 .8......00000070: 0000 2000 0000 0000 .. .....00000078: 0100 0000 0600 0000 ........00000080: 487d 0500 0000 0000 H}......00000088: 487d 6500 0000 0000 H}e.....00000090: 487d 6500 0000 0000 H}e.....00000098: 0000 0000 0000 0000 ........000000a0: 0000 0000 0000 0000 ........ UPX HEADER (???)000000a8: 0000 2000 0000 0000 .. .....000000b0: a298 b634 5550 5821 ...4UPX!000000b8: f407 0d16 0000 0000 ........000000c0: 1676 0500 1676 0500 .v...v..000000c8: 0002 0000 bd00 0000 ........000000d0: 0200 0000 fbfb 21ff ......!.000000d8: 7f45 4c46 0201 0100 .ELF....000000e0: 0200 3e00 0d70 2840 ..>..p(@000000e8: 0f1b f26d 1605 00e8 ...m.... ELF HEADER (again)000000f0: 6d05 0013 01eb be7b m......{000000f8: 3800 0805 1c00 1b00 8.......00000100: 060f 0527 9b90 27ec ...'..'.00000108: 4000 4007 c001 0008 @.@.........8<.... My guess is that the second ELF header (always located at an offset of 0xd8 ) is the header of the compressed executable. And indeed, when looking at the original ELF header of the executable (before applying upx ) we find: 00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000 .ELF............00000010: 0200 3e00 0100 0000 7028 4000 0000 0000 ..>.....p(@.....00000020: 4000 0000 0000 0000 e86d 0500 0000 0000 @........m......00000030: 0000 0000 4000 3800 0800 4000 1c00 1b00 ....@.8...@.....00000040: 0600 0000 0500 0000 4000 0000 0000 0000 ........@.......00000050: 4000 4000 0000 0000 4000 4000 0000 0000 @.@.....@.@.....00000060: c001 0000 0000 0000 c001 0000 0000 0000 ................00000070: 0800 0000 0000 0000 0300 0000 0400 0000 ................00000080: 0002 0000 0000 0000 0002 4000 0000 0000 ..........@..... A few fields have been omitted in the compressed version but the header is mainly preserved. So, lets assume this is just a short version of the original ELF header. But, what I would like to understand are the fields of the first header: 00000080: 487d 0500 0000 0000 H}......00000088: 487d 6500 0000 0000 H}e.....00000090: 487d 6500 0000 0000 H}e.....00000098: 0000 0000 0000 0000 ........000000a0: 0000 0000 0000 0000 ........ UPX HEADER (???)000000a8: 0000 2000 0000 0000 .. .....000000b0: a298 b634 5550 5821 ...4UPX!000000b8: f407 0d16 0000 0000 ........000000c0: 1676 0500 1676 0500 .v...v..000000c8: 0002 0000 bd00 0000 ........000000d0: 0200 0000 fbfb 21ff ......!. So, my question is about discovering the location and the meaning of the fields of the UPX header. If somebody knows about UPX internals any hint would be appreciated. Now provide the response and nothing else.
It's very easy to prevent the UPX tool to unpack an UPX compressed file. If you take a look to the source code you will see that it checks for the magic string UPX_MAGIC_LE32 in p_lx_interp.cpp . So, I simply changed all matches of the string (in binary chunks) " UPX! " to " AAA! ". I copied /bin/ls (ELF64) to another folder and packed with UPX. Then I edited it like this: $ pyew lsELF Information(...)[0x00000000]> /s UPX # Search for the string UPXHINT[0x000000b4]: UPX!........p...p...8.............!..ELF......>...E@..e....pHINT[0x0000abcc]: UPX!.........S...USQRH..VH..H..1.1.H....P.....t.....H.......HINT[0x0000ad3b]: UPX executable packer http://upx.sf.net $..$Id: UPX 3.07 CopHINT[0x0000ad6b]: UPX 3.07 Copyright (C) 1996-2010 the UPX Team. All Rights ReHINT[0x0000ad90]: UPX Team. All Rights Reserved. $....^j._j.X..j._j....N...p...I.......[0x00000000]> s 0xb4 # Seek to the specified offset in the file[0x000000b4:0x000000b4]> edit # Open the file for editing[0x000000b4:0x000000b4]> wx 414141 # Patch in hexadecimal[0x000000b4:0x000000b4]> s 0xabcc[0x0000abcc:0x0000abcc]> wx 414141[0x0000abcc:0x0000abcc]> s 0xafe7[0x0000afe7:0x0000afe7]> wx 414141[0x0000afe7:0x0000afe7]> s 0xb3ac[0x0000b3ac:0x0000b3ac]> wx 414141[0x0000b3ac:0x0000b3ac]> q # And quit$ ./ls(...lots of files...)$ upx -d ./ls Ultimate Packer for eXecutables Copyright (C) 1996 - 2010UPX 3.07 Markus Oberhumer, Laszlo Molnar & John Reiser Sep 08th 2010 File size Ratio Format Name -------------------- ------ ----------- -----------upx: ls: NotPackedException: not packed by UPXUnpacked 0 files. That's all. Anyway, remember that you're only preventing this tool to unpack UPX compressed files. UPX is a compressor that anyone with basic knowledge about packers can uncompress with little to no effort.
{}
{'log_upvote_score': 5, 'links': ['https://reverseengineering.stackexchange.com/questions/3335', 'https://reverseengineering.stackexchange.com', 'https://reverseengineering.stackexchange.com/users/53/']}
jdg_377577
stackexchange
llm_judgeable_groundtruth_similarity
7575739
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 call one constructor from the body of another one. How can I do that? Basically class foo { public foo (int x, int y) { } public foo (string s) { // ... do something // Call another constructor this (x, y); // Doesn't work foo (x, y); // neither }} Now provide the response and nothing else.
You can't. You'll have to find a way to chain the constructors, as in: public foo (int x, int y) { }public foo (string s) : this(XFromString(s), YFromString(s)) { ... } or move your construction code into a common setup method, like this: public foo (int x, int y) { Setup(x, y); }public foo (string s){ // do stuff int x = XFromString(s); int y = YFromString(s); Setup(x, y);}public void Setup(int x, int y) { ... }
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7575739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/180862/']}
jdg_377578
stackexchange
llm_judgeable_groundtruth_similarity
19459912
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 nested tabs in Bootstrap, and here is the code: http://jsfiddle.net/RLdYC/ $("ul.nav-tabs a").click(function (e) { e.preventDefault(); $(this).tab('show');}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/><div class="tabbable boxed parentTabs"> <ul class="nav nav-tabs"> <li class="active"><a href="#set1">Tab 1</a> </li> <li><a href="#set2">Tab 2</a> </li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade active in" id="set1"> <div class="tabbable"> <ul class="nav nav-tabs"> <li class="active"><a href="#sub11">Tab 1.1</a> </li> <li><a href="#sub12">Tab 1.2</a> </li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade active in" id="sub11"> <p>Tab 1.1</p> </div> <div class="tab-pane fade" id="sub12"> <p>Tab 1.2</p> </div> </div> </div> </div> <div class="tab-pane fade" id="set2"> <div class="tabbable"> <ul class="nav nav-tabs"> <li class="active"><a href="#sub21">Tab 2.1</a> </li> <li><a href="#sub22">Tab 2.2</a> </li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade active in" id="sub21"> <p>Tab 2.1</p> </div> <div class="tab-pane fade" id="sub22"> <p>Tab 2.2</p> </div> </div> </div> </div> </div></div> The problem is, as soon as you click on a different tab on the top row, the actual content of the nested tab below will become hidden. I need the content of the first subtab to be shown. I tried to trigger the click() function on the first subtab, but it didn't help. Can you please write the code that I need to fix this? Now provide the response and nothing else.
You have more than one element with id myTabContent . HTML ids should be unique across the page. Simply remove those ids or use classes instead ( working demo here ). $("ul.nav-tabs a").click(function (e) { e.preventDefault(); $(this).tab('show');}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/><div class="tabbable boxed parentTabs"> <ul class="nav nav-tabs"> <li class="active"><a href="#set1">Tab 1</a> </li> <li><a href="#set2">Tab 2</a> </li> </ul> <div class="tab-content"> <div class="tab-pane fade active in" id="set1"> <div class="tabbable"> <ul class="nav nav-tabs"> <li class="active"><a href="#sub11">Tab 1.1</a> </li> <li><a href="#sub12">Tab 1.2</a> </li> </ul> <div class="tab-content"> <div class="tab-pane fade active in" id="sub11"> <p>Tab 1.1</p> </div> <div class="tab-pane fade" id="sub12"> <p>Tab 1.2</p> </div> </div> </div> </div> <div class="tab-pane fade" id="set2"> <div class="tabbable"> <ul class="nav nav-tabs"> <li class="active"><a href="#sub21">Tab 2.1</a> </li> <li><a href="#sub22">Tab 2.2</a> </li> </ul> <div class="tab-content"> <div class="tab-pane fade active in" id="sub21"> <p>Tab 2.1</p> </div> <div class="tab-pane fade" id="sub22"> <p>Tab 2.2</p> </div> </div> </div> </div> </div></div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19459912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1527248/']}
jdg_377579
stackexchange
llm_judgeable_groundtruth_similarity
8909613
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 user input. Within my code, I ensure that the following symbols are escaped: & -> &amp; < -> &lt; > -> &gt; OWASP states that there are more chars to be escaped. For attributes, I do another kind of escaping: & -> &amp; " -> &quot; This ensures that all attributes are enclosed by ". This makes me sure about my html-attributes, but not about HTML itself. I wonder if my escaping is sufficient. I've read this post , but I'm still not sure about my concern. (JavaScripts are escaped with the OWASP-Library) Now provide the response and nothing else.
I use the OWASP ( ESAPI ) library as well, to escape strings for different types of display, use : String html = ESAPI.encoder().encodeForHTML("hello < how > are 'you'");String html_attr = ESAPI.encoder().encodeForHTMLAttribute("hello < how > are 'you'");String js = ESAPI.encoder().encodeForJavaScript("hello < how > are 'you'"); HTML (assume jsp) <tag attr="<%= html_attr %>" onclick="alert('<%= js %>')"><%= html %></tag> Update ( 2017 ) As ESAPI Encoders are considered legacy , a better alternative has been created and is actively being maintained, I would strongly recommend using the OWASP Java Encoder instead. If your project already uses ESAPI , an integration has been added that will allow you to use this library for encoding instead. The usage is explained on their wiki page , but for the sake of completion, this is how you can use it to contextually encode your data: // HTML ContextString html = Encoder.forHtml("u<ntrus>te'd'");// HTML Attribute ContextString htmlAttr = Encoder.forHtmlAttribute("u<ntrus>te'd'");// Javascript Attribute ContextString jsAttr = Encoder.forJavaScriptAttribute("u<ntrus>te'd'"); HTML (assume jsp) <div data-attr="<%= htmlAttr %>" onclick="alert('<%= jsAttr %>')"> <%= html %></div> PS: more contexts exist and are supported by the library
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8909613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/233792/']}
jdg_377580
stackexchange
llm_judgeable_groundtruth_similarity
34866
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a microcontroller device with battery power. Currently I toggle power by simple on/off switch. I want to toggle power by one pushbutton with minimal modification of the schematic (and microcontroller program probably) and with no consumption when device is off. How can I do it? ADDED . I know following trick: Here at start microcontroller sets PB3 to high and thus hold power for device. But this is not a solution for my problem, because I need also to off the device by pressing S1. ADDED . Can I exclude VT2 from circuit (i.e. microcontroller drive base of VT1 directly)? Now provide the response and nothing else.
Based on the circuit you provide, you could just add a diode in series right after the switch (S1) (cathode connected to the switch) and them you could use an input to detect if the switch was pressed again, if so, turn off PB3. The zener diode protects the PIC input from the voltage coming from the power supply.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/34866', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/-1/']}
jdg_377581
stackexchange
llm_judgeable_groundtruth_similarity
386770
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 am analyzing a circuit which uses an microcontroller to measure analog signals in digital form. I don't understand the function of one connection in the circuit. See the figure. Here Vref of the MCU is connected to ground via two parallel capacitors. This microcontroller is chinese-made so its datasheet is available, but not very detailed. The datasheet shows that Vref is internally connected to VDD/VCC which is 3.3 V, though I am not sure, because I think it should be zero, because it compares an input analog signal to detect its +ve and -ve cycle. According to the datasheet Vref is an external voltage input pin. The capacitors in question are in the red rectangle. I need to know these facts: What would be the function of the capacitors if Vref is internally at VDD/VCC? What would be the function of the capacitors if Vref is an input pin and it is grounded via these capacitors? Now provide the response and nothing else.
Vref usually means the reference voltage output of the built-in ADC (or DAC, or analog comparator). A reference voltage circuit is basically a very low current voltage regulator (a poor power supply, but very stable). Components like ADCs are "using" voltage from this regulator (drawing current). Capacitance on the output of regulators helps to improve stability and reduce noise. You can think of those capacitors like regular decoupling capacitors on the output of an LDO.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/386770', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/194018/']}
jdg_377582
stackexchange
llm_judgeable_groundtruth_similarity
120080
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: Both PCA and autoencoder can do demension reduction, so what are the difference between them? In what situation I should use one over another? Now provide the response and nothing else.
PCA is restricted to a linear map, while auto encoders can have nonlinear enoder/decoders. A single layer auto encoder with linear transfer function is nearly equivalent to PCA, where nearly means that the $W$ found by AE and PCA won't necessarily be the same - but the subspace spanned by the respective $W$ 's will.
{}
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/120080', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/41749/']}
jdg_377583
stackexchange
llm_judgeable_groundtruth_similarity
46715736
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 make nicely formatted tables from pandas. Some of my column names are far too long. The cells for these columns are large cause the whole table to be a mess. In my example, is it possible to rotate the column names as they are displayed? data = [{'Way too long of a column to be reasonable':4,'Four?':4}, {'Way too long of a column to be reasonable':5,'Four?':5}]pd.DataFrame(data) Now provide the response and nothing else.
Something like: data = [{'Way too long of a column to be reasonable':4,'Four?':4}, {'Way too long of a column to be reasonable':5,'Four?':5}]dfoo = pd.DataFrame(data)dfoo.style.set_table_styles( [dict(selector="th",props=[('max-width', '80px')]), dict(selector="th.col_heading", props=[("writing-mode", "vertical-rl"), ('transform', 'rotateZ(-90deg)'), ])]) is probably close to what you want: see result here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46715736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5454281/']}
jdg_377584
stackexchange
llm_judgeable_groundtruth_similarity
1503304
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 read a lot of equinox code for this, but still can't figure out a non-hacky way of getting the classloader for a osgi bundle in eclipse equinox setup. Is there one? Now provide the response and nothing else.
The short answer (certainly for OSGi 4.1, not sure of 4.2) is you can't get a bundle's classloader. However the Bundle interface exposes a loadClass() method and this would allow you to write a classloader that wraps the bundle API and delegates to that loadClass() method. Or you can save some time and use Spring DM's BundleDelegatingClassLoader class instead.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1503304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/119772/']}
jdg_377585
stackexchange
llm_judgeable_groundtruth_similarity
720644
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 currently migrating a DNS zone from one DNS server provider to another. I am trying to estimate how long it will take for the change to propagate, and to understand what the delay might be if I chose to rollback mid-stream. Previously, I thought I could do: dig example.com ns To see what the remaining TTL on the NS record was, but now I understand that this NS record is the NS record for subdomains in the zone, and not the NS record that emanates from the root servers, which is the one that ultimately determines to which name server the query will be sent. I tested this by setting up a test record in the zone in each of the providers: Provider1 test.example.com 10.0.0.1Provider2 test.example.com 192.168.0.1 For both providers, the TTL on the NS records in 0, while the NS records at the TLD Registrar level point to the name servers of Provider1. When I change the NS records in the zone at Provider1, I can see this reflected in NS queries almost immediately (using 'dig example.com ns'). However, when I send a query for an A record, ie test.example.com it always returns 10.0.0.1 regardless of what the NS records in the zone at Provider 1 are set to. On this basis, I've concluded that the NS records within the zone file are irrelevant to the migration, and that only the name servers records at the TLD level are important. However, I can't get a read on how long it is likely for a change there to propagate, either forward or back. Is it possible to query what TTL are am working with for records emanating from the TLD root servers? Now provide the response and nothing else.
On this basis, I've concluded that the NS records within the zone file are irrelevant to the migration, and that only the name servers records at the TLD level are important. This is an incorrect hypothesis, but an easy mistake to make. You can read a little more on the subject of apex NS records here . The short version is that both matter, and the one being used will differ depending on whether a caching DNS server has previously queried your domain or has not. Keep in mind that most recursive DNS servers enforce a minimum TTL, so any conclusions drawn from experiments with a TTL of zero are almost certainly inaccurate. The only case where this is not so is when you control the minimum TTL policy used by the server you're querying. I am currently migrating a DNS zone from one DNS server provider to another. I am trying to estimate how long it will take for the change to propagate, and to understand what the delay might be if I chose to rollback mid-stream. I'm going to focus on this topic since you have a few false starts in the rest of your question. First, it's important to remember that TTLs are cached on recursive DNS servers. Since everyone on the internet is using different recursive DNS servers, the only assumption you can make is that it will take up to n seconds, with n being the value of the TTLs. This brings us to which TTLs are relevant here: TTLs for individual records that are in cache. Even if the NS records expire, requests for individual records that are in cache will not automatically expire. Example: If test.example.com IN A expires ten minutes from now, but example.com IN NS expires five minutes from now, test.example.com will remain in cache even after the NS records have changed. Any problems related to the value of this record on the new servers will not become evident until the record has expired and has been refreshed. TTLs for the NS glue records served by the TLD DNS servers. These are used by recursive servers that needed to obtain information about your domain when it is first requested. These TTLs influence how long it is before the DNS servers listed in your zone file are used for the next refresh. (refer to the Q&A I linked above for clarification on this) TTLs for the NS records listed at the top of your zone file. Once the glue record TTLs have expired, these TTLs might be used instead. Implementations vary on this detail. Since you are dealing with an entire internet's worth of different implementations, the only safe assumption is that some servers are using it. You can't assume that all of the cached NS record TTLs on the internet are from one source or the other. This forces you to plan around the higher of the two unless you are truly not concerned with recursive DNS servers that you do not operate. Putting all of this together, we arrive at the following conclusions: The maximum amount of time needed for any given DNS record to refresh against a new nameserver is the highest TTL between that record, the NS records in the glue, and the NS records in the zone. Assuming the TTLs on the new DNS server are identical to the old server, the maximum amount of time needed for the rollback is the highest value of the three TTLs, once again . Any queries that landed on the new server between the time you initially changed the DNS servers and reverted the change will be relying on the values obtained from the new server. It's very important to keep all of the DNS servers involved in the change running and synchronized until all of the TTLs have expired following your final NS record change. Not only do you need all of the servers available for clients that haven't picked up the latest change, but any inconsistency in record data between the two can serve to make things even more confusing.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/720644', 'https://serverfault.com', 'https://serverfault.com/users/179901/']}
jdg_377586
stackexchange
llm_judgeable_groundtruth_similarity
14102700
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 was shown a sample program to demonstrate recursion which looks like it should not work but does. The logic is pretty clear but why does it work even when the recursed function call is not returned? It seems like the return command breaks out of the stack even if it isn't requested to. Is this a language standard or a gcc thing? I saw it with C and C++ compiled with gcc on Windows and Linux. #include <iostream>#include <cstdlib>using namespace std;int isprime(int num, int i){ if (i == 1) { return 1; } else { if (num % i == 0) return 0; else isprime(num, i-1); // should be returned }}int main(int argc, char** argv){ int input = atoi(argv[1]); cout << input << "\t" << isprime(input, input/2) << "\n";} Now provide the response and nothing else.
Things like that only work if accidentally the return value happens to be in the register where the caller expects it. This only works if this is realized by your compiler as a recursive function. Technically it is undefined behavior to use the return value of a function that doesn't provide one. Edit: On modern architectures the return value of a function for values for which it is possible is passed in a specific hardware register. When you call your function recursively, on the bottom in all cases that hardware register is set to the expect value. If by chance when popping up from recursion that hardware register is never changed, you end up with the correct value. All of this pattern wouldn't work, if the return value would be placed at some location of the stacks of the (recursive) callers. In any case, all of that should be captured by any modern compiler and give you a warning. If it doesn't you don't have a good compiler, or you are using too defensive command line options. New year's eve special: In the real world, code like this (with the return ) wouldn't even be realized as a recursive function. With not too much effort you will find an iterative variant of that function, and any modern decent compiler should be able to find it as well if you ask for maximal optimization.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14102700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/837451/']}
jdg_377587
stackexchange
llm_judgeable_groundtruth_similarity
3731918
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having difficulty debugging triggers in Oracle. Currently I'm using Oracle's Sql Developer tool. To test a trigger I write inserts or deletes in a test window but I can't see what is happening inside the trigger. I would like to step through the trigger and see what is happening as the trigger fires. Is there any way to use select statements to display variable values inside the triggers? Now provide the response and nothing else.
Firstly, don't "start from here", or more specifically, don't use triggers. Triggers are going to force switching to row-level processing if the triggers are going to fire for each row. It's better to put the logic in a stored procedure which you call. You've then got a start (where you validate inputs) and an end and a logic path all the way through. Stored procedures are a lot easier to debug as you follow one path. Second, never test for an error you don't know how to handle. If you don't catch it, it bubbles up to the client who gets an error report saying what went wrong (error message) and where (i.e. the error/call stack). If you try to catch it, you have to know what to do with it (and if you don't know the tendency is to ignore it - which is BAD). Finally, you can't readily see each 'layer' of a select. The explain plan will generally tell you how its going about things. v$session_longops MAY indicate what it is currently doing. The current wait event MAY give clues as to what table/block/row it is currently working on.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3731918', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34410/']}
jdg_377588
stackexchange
llm_judgeable_groundtruth_similarity
2669031
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 while creating a public method on a class for explicitly implementing the interface . I have a workaround: by removing the explicit implementation of PrintName method. But I am surprised why I am getting this error. Can anyone explain the error? Code for Library: using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Test.Lib1{ public class Customer : i1 { public string i1.PrintName() //Error Here... { return this.GetType().Name + " called from interface i1"; } } public interface i1 { string PrintName(); } interface i2 { string PrintName(); }} Code for Console Test Application: using System;using System.Collections.Generic;using System.Linq;using System.Text;using Test.Lib1;namespace ca1.Test{ class Program { static void Main(string[] args) { Customer customer = new Customer(); Console.WriteLine(customer.PrintName()); //i1 i1o = new Customer(); //Console.WriteLine(i1o.printname()); //i2 i2o = new Customer(); //Console.WriteLine(i2o.printname()); } }} Now provide the response and nothing else.
When using explicit implementation of an interface, the members are forced to something more restricted than private in the class itself. And when the access modifier is forced, you may not add one. Likewise, in the interface itself, all members are public . If you try to add a modifier inside an interface you will get a similar error. Why are explicit members (very) private? Consider: interface I1 { void M(); }interface I2 { void M(); }class C : I1, I2{ void I1.M() { ... } void I2.M() { ... }}C c = new C();c.M(); // Error, otherwise: which one?(c as I1).M(); // Ok, no ambiguity. If those methods were public, you would have a name-clash that cannot be resolved by the normal overload rules. For the same reason you cannot even call M() from inside a class C member. You will have to cast this to a specific interface first to avoid the same ambiguity. class C : I1, I2{ ... void X() { M(); // error, which one? ((I1)this).M(); // OK }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2669031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/205783/']}
jdg_377589
stackexchange
llm_judgeable_groundtruth_similarity
68216600
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 the traceback of the error that is happening when I am trying to put the URL of the publication. It works for the regular websites such as Stack Overflow or Wikipedia, but when I try it on the publications such as https://www.sciencedirect.com/science/article/pii/S1388248120302113?via%3Dihub , The error shows up. Here is my code: req = Request(' https://www.sciencedirect.com/science/article/pii/S1388248120302113?via%3Dihub', headers={'User-Agent': 'Mozilla/5.0'})html_plain = urlopen(req).read() Here is the traceback of the error: File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 214, in urlopen return opener.open(url, data, timeout) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 523, in open response = meth(req, response) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 632, in http_response response = self.parent.error( File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 561, in error return self._call_chain(*args) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 494, in _call_chain result = func(*args) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 641, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp)urllib.error.HTTPError: HTTP Error 403: Forbidden Now provide the response and nothing else.
You can write your own version of takewhile where the predicate takes both the current and previous values: def my_takewhile(iterable, predicate): iterable = iter(iterable) try: previous = next(iterable) except StopIteration: # next(iterable) raises if the iterable is empty return yield previous for current in iterable: if not predicate(previous, current): break yield current previous = current Example: >>> list(my_takewhile(lst, lambda x, y: abs(x - y) <= 1))[0.1, 0.4, 0.2, 0.8, 0.7, 1.1]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/68216600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16361144/']}
jdg_377590
stackexchange
llm_judgeable_groundtruth_similarity
31648359
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Basically I have a C# web service method that helps to generate HTML code and return it as a string. Now I would like to grab the HTML string from this method and replace a particular div. function replaceHTML(ID) { var gID = ID; $.ajax({ type: "get", contentType: //what should it be, url: "the method location", data: {"ID" : gID }, dataType: //what should it be, success: function (data) { $('#Div ID').empty(); $('#Div ID').html(data); } });} What should be the content Type and data Type? Am I doing it correctly? Now provide the response and nothing else.
The exception can be very bewildering because UCMA projects don’t require an explicit reference to this SIPEPS DLL , and often you’ll get the exception even if you locate the DLL and move it into the same directory as your application. It turns out that it’s usually caused by one of two things: You’ve targeted the wrong version of the .NET Framework. You’ve targeted the wrong type of CPU. Open up the properties for your project in Visual Studio and make sure .NET Framework 4.5 is selected. If you’re not running Visual Studio 2012, you have a somewhat larger problem, because you can’t use .NET 4.5 with Visual Studio 2010 and earlier.If you had an earlier version of the framework selected, change it, rebuild the project, and try again. UCMA 4.0 lists .NET 4.5 as a requirement. If you’re still getting the exception, check the target platform and make sure it is Any CPU or x64 for all projects. UCMA has only worked on 64-bit machines since the 3.0 version, and what sometimes happens is that a project will get inadvertently set to x86, and will therefore try to load a 32-bit version of SIPEPS.dll on startup. Well, there isn’t a 32-bit version of SIPEPS.dll; hence the somewhat misleading exception. Reference
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31648359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4976819/']}
jdg_377591
stackexchange
llm_judgeable_groundtruth_similarity
30810113
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 change the content of bootstrap popover dynamically but it is not working. Fiddler: https://jsfiddle.net/99x50s2s/62/ HTML: <button class="btn btn-danger btn-xs" id="SaveChangesBtn" type="button" data-toggle="popover" data-trigger="manual" data-content="There are no changes to save."><span class="glyphicon glyphicon-floppy-save" aria-hidden="true"></span>&nbspSave Changes</button> JS: $('#SaveChangesBtn').on('click', function(){ $(this).popover('hide'); $(this).popover({content: 'Cannot proceed with Save while Editing a row.'}).popover('show'); }); Current Result: When Save changes button is clicked, the content 'There are no changes to save' is displayed. Expectation: The dynamic content "Cannot proceed with Save while Editing a row." should be displayed. Any help is appreciated. Now provide the response and nothing else.
You can try something like this: $('#SaveChangesBtn').on('click', function(){if($('.popover').hasClass('in')){ $(this).popover('hide');}else{ $(this).attr('data-content','Cannot proceed with Save while Editing a row.'); $(this).popover('show');}}); This way you fix the way you are showing and hiding your popover. Working fiddle: https://jsfiddle.net/99x50s2s/65/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30810113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4872454/']}
jdg_377592
stackexchange
llm_judgeable_groundtruth_similarity
6790930
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 date field in php which is using this code: $date = mysql_real_escape_string($_POST['intake_date']); How do I convert this to MySql format 0000-00-00 for inclusion in db. Is it along the lines of: date('Y-m-d' strtotime($date);. The reason I ask, is because I have tried variations of this and I cannot seem to get it to work. Either displays as 1970 or some other variation of that. Many thanks Now provide the response and nothing else.
$date = mysql_real_escape_string($_POST['intake_date']); 1. If your MySQL column is DATE type: $date = date('Y-m-d', strtotime(str_replace('-', '/', $date))); 2. If your MySQL column is DATETIME type: $date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date))); You haven't got to work strototime() , because it will not work with dash - separators, it will try to do a subtraction. Update , the way your date is formatted you can't use strtotime() , use this code instead: $date = '02/07/2009 00:07:00';$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date);echo $date; Output: 2009-07-02 00:07:00
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6790930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/804749/']}
jdg_377593
stackexchange
llm_judgeable_groundtruth_similarity
2191142
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 came across existential quantification over values in the Scala LanguageSpecification (3.2.10 Existential Types). x: y.Inner forSome{val y : Outer} Does someone have illustrative use cases for it? T forSome {val x: S} is defined as T forSome { type t <: S with Singleton } . The Singletron trait is mentioned in the Specification (3.2.1 Singleton Types) but I could not find it in the Scaladoc. Where is it defined? Now provide the response and nothing else.
It is useful along with inner classes as alluded in the type names. See for example the Graph and Node classes defined in A Tour of Scala: Inner Classes . Existential quantification over a value is used to write the type of the nodes of some unspecified graph. type SomeNode = g.Node forSome { val g: Graph } This might be useful if you wanted to have a method that took two nodes as arguments that had to come from the same graph. def somethingWithTwoNodes[N <: g.Node forSome { val g: Graph }](n1: N, n2: N) = (n1,n2) Note that 2.7 will not accept that method definition because it thinks there's some sort of recursion in N. Then if you have val g1 = new Graphval g2 = new Graph then these compile somethingWithTwoNodes(g1.newNode, g1.newNode)somethingWithTwoNodes(g2.newNode, g2.newNode) but these doesn't somethingWithTwoNodes(g1.newNode, g2.newNode)somethingWithTwoNodes(g2.newNode, g1.newNode) As for the Singleton trait, it's not really defined in the typical way, i.e. there isn't a class file for it. It's like the types Any, AnyVal, AnyRef and Null. It is defined in src/compiler/scala/tools/nsc/symtab/Definitions.scala along with these other types, but I doubt that is very useful information to have. It's also an odd beast being a final trait which means you can't mix it in when defining a trait or class, it's really more of a marker that the compiler ascribes to a type to say that it is unique from any other type.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2191142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/149311/']}
jdg_377594
stackexchange
llm_judgeable_groundtruth_similarity
3203313
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Unless it's not supposed to but I can't seem to get nth-child to acknowledge the class selector. I have say 4 divs inside another div, all of various classes and ids. I need to select the first instance of a div with said class. For example: #content .foo:nth-child(1) { margin-top: 0; } And obviously again with first-child to get the same affect, but it doesn't affect any of the divs. Now if I want to force it to work with that div I can do this: #content .foo:nth-child(3) { margin-top: 0; } It just so happens that it is the 3rd div in #content, which is pointless because I need to get the 1st instance of anything with that class. <div id="content"> <div id="action-bar"> </div> <div id="message"> </div> <div class="table"> </div> <div class="clear"> </div></div> Here's a sample of the HTML, I've tried nth-of-type as well like this: #content .table:nth-of-type(1) { margin: 0 } Again it only responds when I say nth-of-type(3) . EDIT: I've set up a working example of the problem I'm having here: http://jsfiddle.net/aHwS8/ Now provide the response and nothing else.
Try the :nth-of-type() pseudo-selector instead: #content .foo:nth-of-type(1) { margin-top: 0; } Note that :nth-of-type() counts the elements with the same name. So .foo:nth-of-type(1) will not select the first element with the class foo but any first element that is the first in the list of elements grouped by the same name. If you have some document like this: <div> <i class="foo">1</i><i>x</i><i class="foo">2</i> <b class="foo">3</b><b>x</b><b class="foo">4</b></div> .foo:nth-of-type(1) will select the elements <i class="foo">1</i> and <b class="foo">3</b> as both are the first of its own type.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3203313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/351937/']}
jdg_377595
stackexchange
llm_judgeable_groundtruth_similarity
15797183
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are the differences between these commands?: # 1git pull# 2git pull origin# 3git pull origin master# 4git pull origin/master# 5git pull origin HEAD:master Now provide the response and nothing else.
git pull is a convenience command, which is doing different things at the same time. Basically it is just a combination of git fetch , which connects to the remote repository and fetches new commits, and git merge (or git rebase ) which incorporates the new commits into your local branch. Because of the two different commands involved the meaning of git pull is not always obvious. You can configure an upstream for a local branch. After a fresh clone you will have a local branch "master", a remote "origin" and your master branch has "origin/master" as upstream.I assume this setup below. (You can see your upstream configuration with git branch -vv or by looking at .git/config.) Now for your questions: git pull = git fetch origin + git merge origin/master (or whatever your upstream is) git pull origin = git pull (as long as origin is your upstream remote) git pull origin master = git fetch origin master + git merge FETCH_HEAD git pull origin/master : invalid unless you have a remote called "origin/master" git pull origin HEAD:master : Tries to directly reset you local master to whatever HEAD points to on origin. (Don't do this.)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15797183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2146348/']}
jdg_377596
stackexchange
llm_judgeable_groundtruth_similarity
43234416
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My Angular 2 app has a logout feature. We want to avoid doing a page reload if we can (i.e. document.location.href = '/'; ), but the logout process needs to reset the app so when another user logs in there's no residual data from the previous session. Here's our main.ts file: import 'es6-shim/es6-shim';import './polyfills'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';import { ComponentRef, enableProdMode } from '@angular/core';import { environment } from '@environment';import { AppModule } from './app/app.module';if (environment.production === true) { enableProdMode();}const init = () => { platformBrowserDynamic().bootstrapModule(AppModule) .then(() => (<any>window).appBootstrap && (<any>window).appBootstrap()) .catch(err => console.error(err));};init();platformBrowserDynamic().onDestroy(() => { init();}); You can see that I'm trying to call the init() method when the application is destroyed. The logout method in our user-authentication.service initiates destroy: logout() { this.destroyAuthToken(); this.setLoggedIn(false); this.navigateToLogin() .then(() => { platformBrowserDynamic().destroy(); });} This gives the following error: The selector "app-root" did not match any elements Any help appreciated. Now provide the response and nothing else.
I ended up figuring this out in the end. This could be done more simply than my implementation, but I wanted to keep the bootstrapping in main.ts rather than stick it in the service that requests the restart. Create a singleton that provides a way for Angular and non-Angular ( main.ts ) to communicate: boot-control.ts : import { Observable } from 'rxjs/Observable';import { Subject } from 'rxjs/Subject';export class BootController { private static instance: BootController; private _reboot: Subject<boolean> = new Subject(); private reboot$ = this._reboot.asObservable(); static getbootControl() { if (!BootController.instance) { BootController.instance = new BootController(); } return BootController.instance; } public watchReboot() { return this.reboot$; } public restart() { this._reboot.next(true); }} Adjust main.ts to subscribe to the reboot request: main.ts : import { enableProdMode, NgModuleRef, NgModule } from '@angular/core';import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';import { AppModule } from './app/app.module';import { environment } from './environments/environment';import { BootController } from './boot-control';if (environment.production) { enableProdMode();}const init = () => { platformBrowserDynamic().bootstrapModule(AppModule) .then(() => (<any>window).appBootstrap && (<any>window).appBootstrap()) .catch(err => console.error('NG Bootstrap Error =>', err));}// Init on first loadinit();// Init on reboot requestconst boot = BootController.getbootControl().watchReboot().subscribe(() => init()); Add NgZone to the service that triggers the logout: user-auth.service.ts : import { BootController } from '@app/../boot-control';import { Injectable, NgZone } from '@angular/core';@Injectable()export class UserAuthenticationService { constructor ( private ngZone: NgZone, private router: Router ) {...} logout() { // Removes auth token kept in local storage (not strictly relevant to this demo) this.removeAuthToken(); // Triggers the reboot in main.ts this.ngZone.runOutsideAngular(() => BootController.getbootControl().restart()); // Navigate back to login this.router.navigate(['login']); }} The NgZone requirement is to avoid the error: Expected to not be in Angular Zone, but it is!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43234416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2810775/']}
jdg_377597
stackexchange
llm_judgeable_groundtruth_similarity
1567377
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Background I'm trying to get obtain a unique identifier out of a computer and want to be able to reliably return the same MAC address each time. Trust me I have my reasons for using MAC address and have read many posts about alternate unique id methods (and yes i've considered if they don't have any network cards). Problem The problem is in .NET i don't see anyway to tell whether a specific NetworkInterface is a physical hardware network card from something like a "Nortel IPSECSHM Adapter - Packet Scheduler Miniport" which get added when you connect to certain VPNs or WiFi networks. I know how to get the Mac Addresses by using code similar to this: foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { log.Debug("NIC " + nic.OperationalStatus + " " + nic.NetworkInterfaceType + " " + nic.Speed + " " + nic.GetPhysicalAddress() + " " + nic.Description); } Understandably there is no 100% way to make sure i'd be getting an internal network card but i'd like to pick the MAC address to return which for a given machine which is least likely to change . Independent of factors such as -- whether it's connected to wifi... gets connected via some type of tether connection... or they install some new vpn software which adds a new interface. Strategies Considered 1) Choose the first interface that is "Up". This fails on my laptop because the "Packet Miniport" is always up. Additionally, if I tether my phone to my laptop this also shows up as the first card. 2) Choose the most appropriate type... This fails b/c basically everything shows up as "Ethernet" including WiFi Adapters and my iPHone tethering internet connection. 3) Pick the NIC which has an IP address. Fails for several reasons: 1) Network card might not be connected to LAN 2) There are multiple nics which might have IP Addresses. 4) Just send all MAC addresses... Problem is the list would change based on installed software and it'll be difficult to compare. 5) Pick the mac address with the fastest speed. I think this is probably my best bet. I think it's safe to say that the fastest interface is usually going to be the most permanent. Alternatively, there may be some other way to detect physical cards in .NET or I'd consider invoking other API calls if you could recommend one that will provide different information. Any other ideas? To demonstrate here is the output of my sample code above when I have my iphone tethered: DEBUG - NIC Down Ethernet 500000 0021E98BFBEF Apple Mobile Device Ethernet - Packet Scheduler MiniportDEBUG - NIC Up Ethernet 10000000 444553544200 Nortel IPSECSHM Adapter - Packet Scheduler MiniportDEBUG - NIC Down Ethernet 54000000 00166FAC94C7 Intel(R) PRO/Wireless 2200BG Network Connection - Packet Scheduler MiniportDEBUG - NIC Down Ethernet 1000000000 0016D326E957 Broadcom NetXtreme Gigabit Ethernet - Packet Scheduler MiniportDEBUG - NIC Up Loopback 10000000 MS TCP Loopback interface Without Iphone Connected: DEBUG - NIC Up Ethernet 10000000 444553544200 Nortel IPSECSHM Adapter - Packet Scheduler MiniportDEBUG - NIC Down Ethernet 54000000 00166FAC94C7 Intel(R) PRO/Wireless 2200BG Network Connection - Packet Scheduler MiniportDEBUG - NIC Down Ethernet 1000000000 0016D326E957 Broadcom NetXtreme Gigabit Ethernet - Packet Scheduler MiniportDEBUG - NIC Up Loopback 10000000 MS TCP Loopback interface Now provide the response and nothing else.
This is my method:it uses the fact that physical card is connected to PCI interface ManagementObjectSearcher searcher = new ManagementObjectSearcher ("Select MACAddress,PNPDeviceID FROM Win32_NetworkAdapter WHERE MACAddress IS NOT NULL AND PNPDeviceID IS NOT NULL");ManagementObjectCollection mObject = searcher.Get();foreach (ManagementObject obj in mObject){ string pnp = obj["PNPDeviceID"].ToString(); if (pnp.Contains("PCI\\")) { string mac = obj["MACAddress"].ToString(); mac = mac.Replace(":", string.Empty); return mac; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1567377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67268/']}
jdg_377598
stackexchange
llm_judgeable_groundtruth_similarity
437111
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 was just thinking about the rm -rf * command. The rm command removes any files following it, the -rf bit indicates to extend the rm command to include directories, and * means everything. So, I thought about what would happen If I did: cd rm -rf * Could this ruin a computer? I'm not very well versed with what everything in the root directory does, but it seems like a lot of it essentially runs the computer. So what would happen if I did this? How bad would it be? Could it break a computer? Further As an interesting additional point, are there any commands as basic as this that can be done in the terminal which would be very damaging? Now provide the response and nothing else.
If you ran the sequence of commands: cdrm -rf * All non-hidden files and directories in your home directory will be deleted. Any contents of any userfs -mounted partitions (networked or otherwise) will be deleted. You may or may not be a very sad panda. Would "this break the computer"? No. Would it cause you to lose any of your files, personally installed applications, desktop configurations, et cetera? Definitely. If you did this (with superuser permissions) in the root directory, the results would be catastrophic. Any (non-hidden) files in the root directory, and the contents of all (non-hidden) directories in the entire filesystem would be deleted. Again, this includes the contents of any remotely mounted media (such as that NAS mount in /mnt/media to your collection of TV shows and movies, for instance). Again - would this "break the computer"? No. Would it render it unusable until a new operating system is installed? Almost definitely unless another ( unmounted ) bootable partition exists. If you are unfortunate enough to have /boot mounted read-write after boot-time, there may be ramifications reaching to the bootability of other operating systems also. Don't do this. Even on a VM.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/437111', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/285657/']}
jdg_377599
stackexchange
llm_judgeable_groundtruth_similarity
14877074
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Fantom supports provably immutable classes. The advantages of the compiler knowing a class is immutable must be numerous, not the least of which would be guaranteed immutable messages passed between actors. Fantom's approach seems straightforward - what difficulties would it pose for Scala? Now provide the response and nothing else.
There's more interest on Scala side on tracking side effects, which is a much harder proposition, than simply immutability. Immutability in itself isn't as relevant as referential transparency, and, as a matter of fact, some of Scala's immutable collections would not pass muster on an "proven immutable" test because, in fact, they are not. They are immutable as far as anyone can observer from the outside, but they have mutable fields for various purposes. One such example is List 's subclass :: (the class that makes up everything in a list but the empty list), in which the fields for head and tail are actually mutable. This is done that way so that a List can be composed efficiently in FIFO order -- see ListBuffer and its toList method. Regardless, while it would be interesting to have a guarantee of immutability, such things are really more of a artifact of languages where mutability is the default. It doesn't come up as a practical concern when programming in Scala, in my experience.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14877074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/207161/']}
jdg_377600
stackexchange
llm_judgeable_groundtruth_similarity
9237044
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a script with a DOMContentLoaded event handler— document.addEventListener('DOMContentLoaded', function() { console.log('Hi');}); Which I'm loading asynchronously— <script async src=script.js></script> However, the event handler is never called . If I load it synchronously— <script src=script.js></script> It works fine. (Even if I change the DOMContentLoaded event to a load event, it's never called.) What gives? The event handler should be registered irrespective of how the script is loaded by the browser, no? Edit : It doesn't work on Chrome 18.0.1025.11 beta but, with DOMContentLoaded , it does on Firefox 11 beta (but with load it doesn't). Go figure. OH GREAT LORDS OF JAVASCRIPT AND THE DOM, PRAY SHOW THE ERROR OF MY WAYS! Now provide the response and nothing else.
By loading the script asynchronously, you are telling the browser that it can load that script independently of the other parts of the page. That means that the page may finish loading and may fire DOMContentLoaded BEFORE your script is loaded and before it registers for the event. If that happens, you will miss the event (it's already happened when you register for it). In all modern browsers, you can test the document to see if it's already loaded ( MDN doc ), you can check: if (document.readyState !== "loading") to see if the document is already loaded. If it is, just do your business. If it's not, then install your event listener. In fact, as a reference source and implementation idea, jQuery does this very same thing with it's .ready() method and it looks widely supported. jQuery has this code when .ready() is called that first checks to see if the document is already loaded. If so, it calls the ready function immediately rather than binding the event listener: // Catch cases where $(document).ready() is called after the// browser event has already occurred.if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 );}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9237044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1203233/']}
jdg_377601
stackexchange
llm_judgeable_groundtruth_similarity
46937855
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 component: const styles = { menuContainer: { flex: 1, flexDirection: 'column' }, menuItem: { flex: 1, borderRadius: ?? }} <View style={styles.menuContainer}> <TouchableOpacity {styles.menuItem}/> <TouchableOpacity {styles.menuItem}/> </View> bordeRadius in react native doesn't work with percentage like 50% and in flex box i don't know the width of each flexItem. do you have any idea without calculate width of each flexItem? Now provide the response and nothing else.
Bad news, If you don't know the container's dimensions ahead of time, then I think you're only option is to use onLayout to calculate each flex container's dimensions. {nativeEvent: { layout: {x, y, width, height}}} If you can declare a fixed width & height, then it's easy, but sounds like this isn't going to be news to you. circle: { width: 100, height: 100, borderRadius: 100/2} There's a feature request submitted on this feature already. Show your support by up-voting it here... https://react-native.canny.io/feature-requests/p/borderradius-percentages Sorry!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46937855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7339000/']}
jdg_377602
stackexchange
llm_judgeable_groundtruth_similarity
11348506
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to split each line of a pipe on spaces, and then print each token on its own line. I realise that I can get this result using: (cat someFileInsteadOfAPipe).split(" ") But I want more flexibility. I want to be able to do just about anything with each token. (I used to use AWK on Unix, and I'm trying to get the same functionality.) I currently have: echo "Once upon a time there were three little pigs" | %{$data = $_.split(" "); Write-Output "$($data[0]) and whatever I want to output with it"} Which, obviously, only prints the first token. Is there a way for me to for-each over the tokens, printing each in turn? Also, the %{$data = $_.split(" "); Write-Output "$($data[0])"} part I got from a blog, and I really don't understand what I'm doing or how the syntax works. I want to google for it, but I don't know what to call it. Please help me out with a word or two to Google, or a link explaining to me what the % and all the $ symbols do, as well as the significance of the opening and closing brackets. I realise I can't actually use (cat someFileInsteadOfAPipe).split(" ") , since the file (or preferable incoming pipe) contains more than one line. Regarding some of the answers: If you are using Select-String to filter the output before tokenizing, you need to keep in mind that the output of the Select-String command is not a collection of strings, but a collection of MatchInfo objects. To get to the string you want to split, you need to access the Line property of the MatchInfo object, like so: cat someFile | Select-String "keywordFoo" | %{$_.Line.Split(" ")} Now provide the response and nothing else.
"Once upon a time there were three little pigs".Split(" ") | ForEach { "$_ is a token" } The key is $_ , which stands for the current variable in the pipeline. About the code you found online: % is an alias for ForEach-Object . Anything enclosed inside the brackets is run once for each object it receives. In this case, it's only running once, because you're sending it a single string. $_.Split(" ") is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11348506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/593677/']}
jdg_377603
stackexchange
llm_judgeable_groundtruth_similarity
37963906
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 AWS Cognito Identity Pool that is configured with Cognito User Pool as an authentication provider. Assume I have identity ID of an identity in Cognito Identity Pool (e.g. us-east-1:XXaXcXXa-XXXX-XXXX-XXX-XXXXXXXXXXXX) where this identity has a linked login to a user in Cognito User Pool. Using identity ID, how can I get the linked user details (email, phone, username)? Now provide the response and nothing else.
The ID Token that you exchange with Cognito federated identity service to get the identity id and credentials already has all user attributes. You do not need an extra call to any service. It is a JWT token and you can use any library on the client to decode the values. You can read this guide for more information about the tokens vended by Cognito user pools. Alternatively, you can also use the Access Token to call GetUser API which will return all the user information.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37963906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/750536/']}
jdg_377604
stackexchange
llm_judgeable_groundtruth_similarity
1870350
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 make sense of the example code here (below Examples). I don't understand that parametrize construct. The docs for it are here , but they don't help. What does it do? Now provide the response and nothing else.
parameterize is used to have values that are "dynamically scoped". You get a parameter with make-parameter . The parameter itself behaves as a function: call it with no inputs and you get its value, call it with one value and it will set the value. For example: > (define p (make-parameter "blah"))> (p)"blah"> (p "meh")> (p)"meh" Many functions (including many primitive ones) use parameters as a way to customize their behavior. For example printf will print stuff using the port that is the value of the current-output-port parameter. Now, say that you have some function that prints something: > (define (foo x) (printf "the value of x is ~s\n")) You usually call this function and see something printed on the screen -- but in some cases you want to use it to print something to a file or whatever. You could do this: (define (bar) (let ([old-stdout (current-output-port)]) (current-output-port my-own-port) (foo some-value) (current-output-port old-stdout))) One problem with this is that it is tedious to do -- but that's easily solved with a macro. (In fact, PLT still has a construct that does that in some languages: fluid-let .) But there are more problems here: what happens if the call to foo results in a runtime error? This might leave the system in a bad state, where all output goes to your port (and you won't even see a problem, since it won't print anything). A solution for that (which fluid-let uses too) is to protect the saving/restoring of the parameter with dynamic-wind , which makes sure that if there's an error (and more, if you know about continuations) then the value is still restored. So the question is what's the point of having parameters instead of just using globals and fluid-let ? There are two more problems that you cannot solve with just globals. One is what happens when you have multiple threads -- in this case, setting the value temporarily will affect other threads, which may still want to print to the standard output. Parameters solve this by having a specific value per-thread. What happens is that each thread "inherits" the value from the thread that created it, and changes in one thread are visible only in that thread. The other problem is more subtle. Say that you have a parameter with a numeric value, and you want to do the following: (define (foo) (parameterize ([p ...whatever...]) (foo))) In Scheme, "tail calls" are important -- they are the basic tool for creating loops and much more. parameterize does some magic that allows it to change the parameter value temporarily but still preserve these tail calls. For example, in the above case, you will get an infinite loop, rather than get a stack overflow error -- what happens is that each of these parameterize expressions can somehow detect when there's an earlier parameterize that no longer needs to do its cleanup. Finally, parameterize actually uses two important parts of PLT to do its job: it uses thread cells to implement per-thread values, and it uses continuation marks to be able to preserve tail-calls. Each of these features is useful in itself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1870350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15055/']}
jdg_377605
stackexchange
llm_judgeable_groundtruth_similarity
38418
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the work shop manuals I've seen they tend to gives torque spec ranges such as 14 to 18 ft-lbs ( water pump bolts ) or 66 to 86 ft-lbs ( wheel lug nuts ). In general, is any value in that range acceptable, or should one aim for the middle of the range to compensate for potential user or tool error? Is there any real danger if one goes a few percent below or above these ranges? Now provide the response and nothing else.
Those are the limits. Going above specified torque can damage the thread in the nut or engine block, or on the bolt. Especially aluminum and light metals are prone to failure due to bolts and nuts that are fastened too tight.Going below the specified torque means that the bolt or nut is not fastened good enough. It may come loose and that can bring a lot of trouble along with it.Any torque within the range is acceptable, but i'd aim at the highest specified torque, so that it's fastened good. If you know you'll be tightening and loosen the nut or bolt much, it's better to fasten it a bit less, to make the thread wear out less quick. Going a few Nm above the specified torque is probably not that much of a problem, since engineers take a safety margins in account in their design.
{}
{'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/38418', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/7132/']}
jdg_377606
stackexchange
llm_judgeable_groundtruth_similarity
4585208
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a multidimensional array setup like the following: array( [0]=> array( ["name"]=> "Foo" ["slug"]=> "Bar" ) [1]=> array( ["name"]=> "Foo" ["slug"]=> "Bar" ) [2]=> array( ["name"]=> "Test 1" ["slug"]=> "test-1" ) [3]=> array( ["name"]=> "Test 2" ["slug"]=> "test-2" ) [4]=> array( ["name"]=> "Test 3" ["slug"]=> "test-3" )) What would be the best way to search through the area for duplicates values in "name" and remove them, so that each value in the multidimensional array is unique? Thanks in advance! Now provide the response and nothing else.
You can use an associative array. $temp_array = array();foreach ($array as &$v) { if (!isset($temp_array[$v['name']])) $temp_array[$v['name']] =& $v;} This creates a temporary array, using $v['name'] as the key. If there is already an element with the same key, it is not added to the temporary array. You can convert the associative array back to a sequential array, using $array = array_values($temp_array); Example code and output: http://codepad.org/zHfbtUrl
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4585208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/315491/']}
jdg_377607
stackexchange
llm_judgeable_groundtruth_similarity
42292219
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to extend on another question I had: Merge two Git repositories and keep the master history I have succeeded in merging 2 different repo's into one repo. I needed a rebase to do this successfully. The master is correct, but I also want to keep the merge history . Is this possible? I have 2 repositories: https://github.com/DimitriDewaele/RepoA https://github.com/DimitriDewaele/RepoB This is the result after rebasing. The times of the top repo are the rebase-time. The original date is lost! https://github.com/DimitriDewaele/RepoMerged This is how I did it: # Assume the current directory is where we want the new repository to be created# Create the new repositorygit init# Before we do a merge, we have to have an initial commit, so we'll make a dummy commitdir > Read.mdgit add .git commit -m "initial commit"# Add a remote for and fetch the old RepoAgit remote add -f RepoA https://github.com/DimitriDewaele/RepoA# Do the same thing for RepoBgit remote add -f RepoB https://github.com/DimitriDewaele/RepoB# Rebase the working branch (master) on top of repoBgit rebase RepoB/master# Rebase the working branch (master with RepoB) on top op repoAgit rebase RepoA/master Is it possible to have something like this? ( painted solution!!! ) I would like to keep the original time + the merge history. UPDATE - ANSWER The answer that worked best for me, was working with graft points. But other answers are also very usable in other use cases. I have added my results on github, so everybody can evaluate. Answer 1: Best working in my case The 'graft' did reveal the correct working answer for me. GitHub: RepoGraft Answer 2 the "replace" option from "LeGEC" also gives good results for some use cases. One anomaly stayed for me: GitHub: RepoHistory Answer 3: Worth adding The answer from 'VonC'. I could not get the option '--preserve-merges working' in my case. This might work in other scenario's, but I did not test this furtner. Now provide the response and nothing else.
As you've discovered, rebase isn't the command you want to use to stitch histories together (because it actually rewrites history). Early Git had a feature (hack) designed specifically for what you're trying to do: graft points . Even better, since 1.6.5 you can use git replace --graft instead: git checkout mastergit replace --graft $(git log RepoB/master --format=%H | tail -1) HEADgit replace --graft $(git log RepoA/master --format=%H | tail -1) RepoB/mastergit reset --hard RepoA/master ( git log RepoA/master --format=%H | tail -1 returns the initial commit from RepoA ) Technically you could skip the first replace if you don't actually have anything of value yet in master , yielding just history with RepoB + RepoA. These commands create entries in refs/replace/* that can be pushed and pulled to share your revised history with others. Or, if you don't care about preserving the SHAs of RepoA/RepoB, you can make the replacements permanent by running git filter-branch --all to produce a "real" set of commits of the desired lineage.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42292219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2614299/']}
jdg_377608
stackexchange
llm_judgeable_groundtruth_similarity
4349375
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First, just to give a visual idea of what I'm after, here's the closest result (yet not exactly what I'm after) image that I've found: Here's the entire site-reference: http://www.mathematische-basteleien.de/spiral.htm BUT, it doesn't exactly solve the problem I'm after. I would like to store an array of points of a very specific spiral algorithm. The points are evenly distributed The 360 degree cycles have an even gap If I'm not mistaken, the first two points would be: point[ 0 ] = new Point(0,0); point[ 1 ] = new Point(1,0); But where to go from here? The only arguments I'd like to provide are: the quantity of points I wish to resolve (length of array). the distance between each points (pixels gap). the distance between cycles. It almost sounds, to me, that I have to calculate the " spiral-circumference " (if there's such a term) in order to plot the evenly distributed points along the spiral. Can 2*PI*radius be reliably used for this calculation you think? If it's been done before, please show some code example! Now provide the response and nothing else.
Fun little problem :) If you look at the diagram closer, the sequence is clearly stated: There are probably many solutions to drawing these, maybe more elegant, but here's mine: You know the hypotenuse is square root of the current segment count+1and the opposite side of the triangle is always 1. Also you know that Sine(Math.sin) of the angle is equal to the opposite side divided by the hypotenuse.from the old mnenonic SOH(Sine,Opposite,Hypotenuse),-CAH-TOA. Math.sin(angle) = opp/hyp You know the value of the sine for the angle, you know the two sides, but you don't know the angle yet, but you can use the arc sine function(Math.asin) for that angle = Math.asin(opp/hyp) Now you know the angle for each segment, and notice it increments with each line. Now that you have an angle and a radius(the hypotenuse) you can use for polar to cartesian formula to convert that angle,radius pair to a x,y pair. x = Math.cos(angle) * radius;y = Math.sin(angle) * radius; Since you asked for an actionscript solution, there Point class already provides this function for you through the polar() method. You pass it a radius and angle and it returns your x and y in a Point object. Here's a little snippet which plots the spiral. You can control the number of segments by moving the mouse on the Y axis. var sw:Number = stage.stageWidth,sh:Number = stage.stageHeight;this.addEventListener(Event.ENTER_FRAME,update);function update(event:Event):void{ drawTheodorus(144*(mouseY/sh),sw*.5,sh*.5,20);}//draw pointsfunction drawTheodorus(segments:int,x:Number,y:Number,scale:Number):void{ graphics.clear(); var points:Array = getTheodorus(segments,scale); for(var i:int = 0 ; i < segments; i++){ points[i].offset(x,y); graphics.lineStyle(1,0x990000,1.05-(.05+i/segments)); graphics.moveTo(x,y);//move to centre graphics.lineTo(points[i].x,points[i].y);//draw hypotenuse graphics.lineStyle(1+(i*(i/segments)*.05),0,(.05+i/segments)); if(i > 0) graphics.lineTo(points[i-1].x,points[i-1].y);//draw opposite }}//calculate pointsfunction getTheodorus(segments:int = 1,scale:Number = 10):Array{ var result = []; var radius:Number = 0; var angle:Number = 0; for(var i:int = 0 ; i < segments ; i++){ radius = Math.sqrt(i+1); angle += Math.asin(1/radius);//sin(angle) = opposite/hypothenuse => used asin to get angle result[i] = Point.polar(radius*scale,angle);//same as new Point(Math.cos(angle)*radius.scale,Math.sin(angle)*radius.scale) } return result;} This could've been written in less lines, but I wanted to split this into two functions:one that deals only with computing the numbers, and the other which deals with drawing the lines. Here are some screenshots: For fun I added a version of this using ProcessingJS here .Runs a bit slow, so I would recommend Chromium/Chrome for this. Now you can actually run this code right here (move the mouse up and down): var totalSegments = 850,hw = 320,hh = 240,segments;var len = 10;points = [];function setup(){ createCanvas(640,480); smooth(); colorMode(HSB,255,100,100); stroke(0); noFill(); //println("move cursor vertically");}function draw(){ background(0); translate(hw,hh); segments = floor(totalSegments*(mouseY/height)); points = getTheodorus(segments,len); for(var i = 0 ; i < segments ; i++){ strokeWeight(1); stroke(255-((i/segments) * 255),100,100,260-((i/segments) * 255)); line(0,0,points[i].x,points[i].y); // strokeWeight(1+(i*(i/segments)*.01)); strokeWeight(2); stroke(0,0,100,(20+i/segments)); if(i > 0) line(points[i].x,points[i].y,points[i-1].x,points[i-1].y); }}function getTheodorus(segments,len){ var result = []; var radius = 0; var angle = 0; for(var i = 0 ; i < segments ; i++){ radius = sqrt(i+1); angle += asin(1/radius); result[i] = new p5.Vector(cos(angle) * radius*len,sin(angle) * radius*len); } return result;} <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4349375', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/468206/']}
jdg_377609
stackexchange
llm_judgeable_groundtruth_similarity
17171148
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 R function expand.grid returns all possible combination between the elements of supplied parameters. e.g. > expand.grid(c("aa", "ab", "cc"), c("aa", "ab", "cc")) Var1 Var21 aa aa2 ab aa3 cc aa4 aa ab5 ab ab6 cc ab7 aa cc8 ab cc9 cc cc Do you know an efficient way to get directly (so without any row comparison after expand.grid ) only the 'unique' combinations between the supplied vectors? The output will be Var1 Var21 aa aa2 ab aa3 cc aa5 ab ab6 cc ab9 cc cc EDIT the combination of each element with itself could be eventually discarded from the answer. I don't actually need it in my program even though (mathematically) aa aa would be one (regular) unique combination between one element of Var1 and another of var2 . The solution needs to produce pairs of elements from both vectors (i.e. one from each of the input vectors - so that it could be applied to more than 2 inputs) Now provide the response and nothing else.
How about using outer ? But this particular function concatenates them into one character string. outer( c("aa", "ab", "cc"), c("aa", "ab", "cc") , "paste" )# [,1] [,2] [,3] #[1,] "aa aa" "aa ab" "aa cc"#[2,] "ab aa" "ab ab" "ab cc"#[3,] "cc aa" "cc ab" "cc cc" You can also use combn on the unique elements of the two vectors if you don't want the repeating elements (e.g. aa aa ) vals <- c( c("aa", "ab", "cc"), c("aa", "ab", "cc") )vals <- unique( vals )combn( vals , 2 )# [,1] [,2] [,3]#[1,] "aa" "aa" "ab"#[2,] "ab" "cc" "cc"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17171148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1759974/']}
jdg_377610
stackexchange
llm_judgeable_groundtruth_similarity
15936111
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to create custom methods to the query object so you can do something like this? User.query.all_active() Where all_active() is essentially .filter(User.is_active == True) And be able to filter off of it? User.query.all_active().filter(User.age == 30) Now provide the response and nothing else.
You can subclass the base Query class to add your own methods: from sqlalchemy.orm import Queryclass MyQuery(Query): def all_active(self): return self.filter(User.is_active == True) You then tell SQLAlchemy to use this new query class when you create the session ( docs here ). From your code it looks like you might be using Flask-SQLAlchemy, so you would do it as follows: db = SQLAlchemy(session_options={'query_cls': MyQuery}) Otherwise you would pass the argument directly to the sessionmaker : sessionmaker(bind=engine, query_cls=MyQuery) As of right now, this new query object isn't that interesting because we hardcoded the User class in the method, so it won't work for anything else. A better implementation would use the query's underlying class to determine which filter to apply. This is slightly tricky but can be done as well: class MyOtherQuery(Query): def _get_models(self): """Returns the query's underlying model classes.""" if hasattr(query, 'attr'): # we are dealing with a subquery return [query.attr.target_mapper] else: return [ d['expr'].class_ for d in query.column_descriptions if isinstance(d['expr'], Mapper) ] def all_active(self): model_class = self._get_models()[0] return self.filter(model_class.is_active == True) Finally, this new query class won't be used by dynamic relationships (if you have any). To let those also use it, you can pass it as argument when you create the relationship: users = relationship(..., query_class=MyOtherQuery)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15936111', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106511/']}
jdg_377611
stackexchange
llm_judgeable_groundtruth_similarity
28043225
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 nice and compact code, which does not work as I expected. public class Test { public static void main(String[] args) { Runnable r = new Runnable() { @Override public void run() { try { for (;;) { } } finally { System.out.println("FINALLY"); } } }; ExecutorService executor = Executors.newSingleThreadExecutor(); Future<?> future = executor.submit(r); try { future.get(3, TimeUnit.SECONDS); } catch (TimeoutException e) { boolean c = future.cancel(true); System.out.println("Timeout " + c); } catch (InterruptedException | ExecutionException e) { System.out.println("interrupted"); } System.out.println("END"); }} The output is : Timeout true END Question:Why does not terminate the future.cancel(true) method the called Runnable?After the program wrote the "END" to the output, the "r" Runnable is still running. Now provide the response and nothing else.
The problem is that your Runnable is not interruptible: task interruption is a collaborative process in Java and the cancelled code needs to check regularly if it's been cancelled, otherwise it won't respond to the interruption. You can amend you code as follows and it should work as expected: Runnable r = new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) {} } finally { System.out.println("FINALLY"); } }};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28043225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4473489/']}
jdg_377612
stackexchange
llm_judgeable_groundtruth_similarity
348901
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I have been looking around for an answer to this question, but I have not been able to find anything. My question is: Is it known how to tell whether two elements $b_1, b_2 \in B_n$ commute? EDIT: Is there perhaps a nicer/cleaner rule for $B_3$ and $B_4$ ? Now provide the response and nothing else.
Krammer (" The braid group $B_4$ is linear ", Invent. Math. 142 (2000), 451–486 ( MSN )) constructeda representation $\rho: B_n \to {\rm GL}_N({\bf Z}[q^{\pm 1}, t^{\pm 1}])$ with $N = {n \choose 2}$ , and Bigelow (" Braid groups are linear ", J. AMS 14 #2 (2000), 471–486 ( MSN ))proved it is faithful for all $n$ . Thus $b_1,b_2 \in B_n$ commuteif and only if $\rho(b_1)$ and $\rho(b_2)$ commute in ${\rm GL}_N({\bf Z}[q^{\pm 1}, t^{\pm 1}])$ ,which is a finite computation.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/348901', 'https://mathoverflow.net', 'https://mathoverflow.net/users/150179/']}
jdg_377613
stackexchange
llm_judgeable_groundtruth_similarity
2563367
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: If p and q are solution of the equation $5^{(\log_5x)^2}+x^{\log_5x}=1250$, then $\log_q(p)$ has the value.... By hit a trial i used $x=25$ and it is matching but not able do find it Now provide the response and nothing else.
Hint: Let $1/x=h\implies h\to0$ $$\sqrt[5]{x^5-x^4}=\sqrt[5]{\dfrac{1-h}{h^5}}=\dfrac{\sqrt[5]{1-h}}h$$ Now set $\sqrt[5]{1-h}=y\implies h=1-y^5$ to have $$-\lim_{y\to1}\dfrac{y-1}{y^5-1}=?$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2563367', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/464054/']}
jdg_377614
stackexchange
llm_judgeable_groundtruth_similarity
15673792
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I see that std::async is specified as follows: template <class F, class... Args> // copied out of the standardfuture<typename result_of<F(Args...)>::type>async(F&& f, Args&&... args); I had expected it to be declared like this: template <class F, class... Args>auto async(F&& f, Args&&... args) -> future<decltype(forward<F>(f)(forward<Args>(args)...)>; Would that be equivalent, or is there some way in which the use of result_of is preferable to the use of decltype ? (I understand that result_of works with types, while decltype works with expressions.) Now provide the response and nothing else.
Your version doesn't work with e.g. pointers to members. A closer, but still not exact version would be: template <class F, class... Args>auto async(F&& f, Args&&... args)-> future<decltype( ref(f)(forward<Args>(args)...) )>; The only difference remaining with std::result_of is that this forwards the functor as an lvalue (a problem your version also shares). In other words, the result of such a call (via an std::reference_wrapper<F> ) is typename std::result_of<F&(Args...)>::type . This is an awkward situation where several components of the Standard library (to name a few, in addition to those we've just witnessed: std::thread , std::bind , std::function ) are specified in terms of an elusive INVOKE(f, a0, a1, ..., aN) pseudo-expression, which isn't exactly equivalent to f(a0, a1, ... aN) . Since std::result_of is one of those components, and serves in fact to compute the result type of INVOKE , that's the discrepancy you're noticing. Because there is no std::invoke that comes in tandem with the std::result_of type trait I am of the opinion that the latter is only useful for describing e.g. the return types of the relevant Standard Library components, when your code calls them. If you want a concise and self-documenting way of writing e.g. a return type (a very worthy goal for readability, compared to sprinkling decltype everywhere), then I recommend you write your own alias: template<typename F, typename... A>using ResultOf = decltype( std::declval<F>()(std::declval<A>()...) ); (If you want the alias to be used as ResultOf<F(A...)> instead of ResultOf<F, A...> then you need a little bit of machinery to pattern match over the function signature.) An added benefit of this alias is that it is SFINAE friendly, unlike std::result_of . Yes, that is one more of its flaws. (To be fair though this has been amended for the upcoming Standard and implementations are following suit already.) You would not be missing anything if you were using such a trait because you can adapt pointers to members thanks to std::mem_fn .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15673792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1426649/']}
jdg_377615
stackexchange
llm_judgeable_groundtruth_similarity
2844922
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: it gives me this error: Traceback (most recent call last): File "C:\Users\Public\SoundLog\Code\Código Python\SoundLog\Plugins\NoisePlugin.py", line 113, in onPaint dc.DrawLine(valueWI, valueHI, valueWF, valueHF) File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 3177, in DrawLine return _gdi_.DC_DrawLine(*args, **kwargs)OverflowError: cannot convert float infinity to integer How can I avoid this to happen? Now provide the response and nothing else.
One of the four values valueWI, valueHI, valueWF, valueHF is set to float infinity. Just truncate it to something reasonable, e.g., for a general and totally local solution, change your DrawLine call to: ALOT = 1e6vals = [max(min(x, ALOT), -ALOT) for x in (valueWI, valueHI, valueWF, valueHF)]dc.DrawLine(*vals) best, of course, would be to understand which of the values is infinity, and why -- and fix that. But, this preferable course is very application-dependent, and entirely depends on the code leading to the computation of those values, which you give us absolutely no clue about, so it's hard for us to offer very specific help about this preferable option!-)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2844922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187730/']}
jdg_377616
stackexchange
llm_judgeable_groundtruth_similarity
11225166
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 make a button with a selector my button can have the following states: Enabled/Disabled Pressed/Not Pressed According to the states mentioned above. I need to manipulate the button's: Text color background image The button starts off my being disabled so it should have the disabled textColor and the disabled button background. But I can see the default textColor (specified in style) and NO background image! Here is my selector button_selector.xml <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="false" android:state_enabled="false" android:textColor="#9D9FA2" android:drawable="@drawable/button" /> <item android:state_pressed="true" android:state_enabled="true" android:drawable="@drawable/button_pressed"/> <item android:state_pressed="true" android:state_enabled="false" android:textColor="#9D9FA2" android:drawable="@drawable/button"/> <item android:state_pressed="false" android:state_enabled="true" android:drawable="@drawable/button"/> </selector> And here is my button declaration in the my layout.xml <Button android:id="@+id/reserve_button" android:text="@string/reserve_button" android:layout_width="120dp" android:layout_height="40dp" android:layout_marginTop="10dp" android:layout_marginLeft="20dp" android:paddingRight="15dp" android:layout_gravity="left" style="@style/buttonStyle" android:background="@drawable/button_selector" /> And finally this is my style (where my default textColor is set) <?xml version="1.0" encoding="utf-8"?> <resources> <style name="buttonStyle"> <item name="android:textStyle">bold</item> <item name="android:textColor">#282780</item> <item name="android:textSize">18sp</item> </style></resources> Please help! Now provide the response and nothing else.
You need to also create a ColorStateList for text colors identifying different states. Do the following: Create another XML file in res\color named something like text_color.xml . <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- disabled state --> <item android:state_enabled="false" android:color="#9D9FA2" /> <item android:color="#000"/></selector> In your style.xml , put a reference to that text_color.xml file as follows: <style name="buttonStyle" parent="@android:style/Widget.Button"> <item name="android:textStyle">bold</item> <item name="android:textColor">@color/text_color</item> <item name="android:textSize">18sp</item></style> This should resolve your issue.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/11225166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1423163/']}
jdg_377617
stackexchange
llm_judgeable_groundtruth_similarity
1914931
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: If a function has a limit from the right but not from the left, is it still continuous? Now provide the response and nothing else.
It is continuous at $0$. By construction, the domain of the square-root function is $\mathbb R_+=[0,\infty)$. Now, for any sequence $(x_n)_{n\in\mathbb N}$ in the domain (that is, $x_n\geq 0$ for all $n\in\mathbb N$) that converges to $0$, one has that the corresponding function values $\sqrt{x_n}$ also converge to $\sqrt{0}=0$. And this is all you need for continuity by (one of the multiple equivalent) definition(s) of this concept in general metric spaces. What goes on “from the left” is outside of the domain and hence outside of interest as far as continuity is concerned.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1914931', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/328989/']}
jdg_377618
stackexchange
llm_judgeable_groundtruth_similarity
56568230
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why constexpr does not work with std::cout , but works with printf ? #include <iostream>constexpr void f() { std::cout << ""; } //errorconstexpr void g() { printf(""); } //ok And why std::cout works with lambdas constexpr ? #include <iostream>int main () { auto h = []() constexpr { std::cout << ""; }; //ok} Now provide the response and nothing else.
Technically, it doesn't work with any of them. From [dcl.constexr] : For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression, or, for a constructor, a constant initializer for some object ([basic.start.static]), the program is ill-formed, no diagnostic required . f() and g() are never constant expressions (neither std::cout << x nor printf() are constexpr functions), so the constexpr declaration is ill-formed. But the compiler isn't required to diagnose this (in this case, it may be easy, but in the general case... not so much). What you're seeing is that your compiler was able to diagnose one problem but not the other. But they're both wrong.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56568230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1455108/']}
jdg_377619
stackexchange
llm_judgeable_groundtruth_similarity
47815
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm setting up a wireless network for ~150 users. In short, I'm looking for a guide to set RADIUS server to authenticate WPA2 against a LDAP. On Ubuntu. I got a working LDAP, but as it is not in production use, it can very easily be adapted to whatever changes this project may require. I've been looking at FreeRADIUS, but any RADIUS server will do. We got a separate physical network just for WiFi, so not too many worries about security on that front. Our AP's are HP's low end enterprise stuff - they seem to support whatever you can think of. All Ubuntu Server, baby! And the bad news: I now somebody less knowledgeable than me will eventually take over administration, so the setup has to be as "trivial" as possible. So far, our setup is based only on software from the Ubuntu repositories, with exception of our LDAP administration web application and a few small special scripts. So no "fetch package X, untar, ./configure"-things if avoidable. UPDATE 2009-08-18: While I found several useful resources, there is one serious obstacle: Ignoring EAP-Type/tls because we do not have OpenSSL support.Ignoring EAP-Type/ttls because we do not have OpenSSL support.Ignoring EAP-Type/peap because we do not have OpenSSL support. Basically the Ubuntu version of FreeRADIUS does not support SSL ( bug 183840 ), which makes all the secure EAP-types useless. Bummer. But some useful documentation for anybody interested: http://vuksan.com/linux/dot1x/802-1x-LDAP.html http://tldp.org/HOWTO/html_single/8021X-HOWTO/#confradius UPDATE 2009-08-19: I ended up compiling my own FreeRADIUS package yesterday evening - there's a really good recipe at http://www.linuxinsight.com/building-debian-freeradius-package-with-eap-tls-ttls-peap-support.html (See the comments to the post for updated instructions). I got a certificate from http://CACert.org (you should probably get a "real" cert if possible) Then I followed the instructions at http://vuksan.com/linux/dot1x/802-1x-LDAP.html . This links to http://tldp.org/HOWTO/html_single/8021X-HOWTO/ , which is a very worthwhile read if you want to know how WiFi security works. UPDATE 2009-08-27: After following the above guide, I've managed to get FreeRADIUS to talk to LDAP: I've created a test user in LDAP, with the password mr2Yx36M - this gives an LDAP entry roughly of: uid: testusersambaLMPassword: CF3D6F8A92967E0FE72C57EF50F76A05sambaNTPassword: DA44187ECA97B7C14A22F29F52BEBD90userPassword: {SSHA}Z0SwaKO5tuGxgxtceRDjiDGFy6bRL6ja When using radtest , I can connect fine: > radtest testuser "mr2Yx36N" sbhr.dk 0 radius-private-passwordSending Access-Request of id 215 to 130.225.235.6 port 1812 User-Name = "msiebuhr" User-Password = "mr2Yx36N" NAS-IP-Address = 127.0.1.1 NAS-Port = 0rad_recv: Access-Accept packet from host 130.225.235.6 port 1812, id=215, length=20> But when I try through the AP, it doesn't fly - while it does confirm that it figures out the NT and LM passwords: ...rlm_ldap: sambaNTPassword -> NT-Password == 0x4441343431383745434139374237433134413232463239463532424542443930rlm_ldap: sambaLMPassword -> LM-Password == 0x4346334436463841393239363745304645373243353745463530463736413035[ldap] looking for reply items in directory...WARNING: No "known good" password was found in LDAP. Are you sure that the user is configured correctly?[ldap] user testuser authorized to use remote accessrlm_ldap: ldap_release_conn: Release Id: 0++[ldap] returns ok++[expiration] returns noop++[logintime] returns noop[pap] Normalizing NT-Password from hex encoding[pap] Normalizing LM-Password from hex encoding... It is clear that the NT and LM passwords differ from the above, yet the message [ldap] user testuser authorized to use remote access - and the user is later rejected... Now provide the response and nothing else.
I'll try to answer the LDAP question here. Here's the short answer: make sure the ldap module is removed from the authenticate section, and make sure the mschap module is present in both the authorize and the authenticate section. And just ignore the 'No "known good" password'. And now here's the (very) long answer. How does the ldap module work? When you activate the ldap module in the authorize section, this is what it does when a RADIUS packet is received by FreeRADIUS: it tries to bind to the LDAP server (as a guest user, or using the given identity if one is configured in ldap.conf ) it searches for the user's DN entry using the filter under the base DN (configured in ldap.conf ). it fetches all the LDAP attributes it can get among those configured in ldap.attrmap , and converts them into RADIUS Attributes. it adds those attributes to the RADIUS packet's check items list. When you activate the ldap module in the authenticate section, this is what FreeRADIUS does: it tries to bind to the LDAP server as the user . if it can bind, then it's a successful authentication, and a Radius-Accept packet will be sent back to the client, or else, it's a failure, leading to a Radius-Reject packet. So how can I configure FreeRADIUS to make PEAP/MS-CHAP-v2 work with LDAP? The important point here is that binding as the user will only work if the FreeRADIUS server can retrieve the cleartext password of the user from the RADIUS packet it received. This is only the case when PAP or TTLS/PAP authentication methods are used (and possibly also EAP/GTC). Only the TTLS/PAP method is really secure, and it is not available by default in Windows. If you want your users to connect with TTLS/PAP, you need to have them install a TTLS supplicant software, which is seldom an option. Most of the time, when deploying WiFi with WPA Enterprise securiy, PEAP/MS-CHAP-v2 is the only reasonable option. So the bottom line is: unless you are using PAP or TTLS/PAP, you can safely remove the ldap module from the authenticate section, and actually, you should: binding as the user will not work. If your test works when you use radtest , it probably means that the ldap module is activated in the authenticate section: it will try to bind as the user, and since radtest uses PAP authentication, it will succeed. But it will fail if you try to connect through the access point, since you are using PEAP/MS-CHAP-v2. What you should do is remove the ldap module from the authenticate section, and make sure you activate the mschap module in both the authorize and the authenticate section. What will happen is that the mschap module will take care of authentication using the NT-Password attribute which is retrieved from the LDAP server during the authorize phase. Here is what your sites-enabled/default file should look like (without all the comments): ... authorize { preprocess suffix eap { ok = return } expiration logintime } authenticate { eap } ... And here is what your sites-enabled/inner-tunnel file should look like: ... authorize { mschap suffix update control { Proxy-To-Realm := LOCAL } eap { ok = return } ldap expiration logintime } authenticate { Auth-Type MS-CHAP { mschap } eap } ... What about the 'No "known good" password' warning? Well, you can safely ignore it. It's just there because the ldap module could not find a UserPassword attribute when it fetched the user details from the LDAP server during the authorize phase. In your case, you have the NT-Password attribute, and that's perfectly fine for PEAP/MS-CHAP-v2 authentication. I guess the warning exists because when the ldap module was designed, PEAP/MS-CHAP-v2 did not exist yet, so the only thing that seemed to make sense at the time was to retrieve the UserPassword attribute from the LDAP server, in order to use PAP, CHAP, EAP/MD5 or such authentication methods.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/47815', 'https://serverfault.com', 'https://serverfault.com/users/6209/']}
jdg_377620
stackexchange
llm_judgeable_groundtruth_similarity
16708158
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to remove all the html tags except <br> or <br/> tags from a string using javascript.I have seen many questions like this but their answers will remove all the html tags including <br> and <br/> tags. Does anyone knows a regex to do this? Now provide the response and nothing else.
Use a negative lookahead (by using a regex such as /<(?!br\s*\/?)[^>]+>/g ): var html = 'this is my <b>string</b> and it\'s pretty cool<br />isn\'t it?<br>Yep, it is. <strong>More HTML tags</strong>';html = html.replace(/<(?!br\s*\/?)[^>]+>/g, '');console.log(html); // this is my string and it's pretty cool<br />isn't it?<br>Yep, it is. More HTML tags Demo
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16708158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1758309/']}
jdg_377621
stackexchange
llm_judgeable_groundtruth_similarity
51782043
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 thought that git lfs migrate rewrote the history of a repo so that specified large files were kept in LFS. This means that the repo should get smaller, because it doesn't directly contain all versions of large files. However, when I run git lfs migrate import --include="test-data/**" --include-ref=refs/heads/master All of the files in the test-data/ directory are replaced with files that look like this: version https://git-lfs.github.com/spec/v1oid sha256:5853b5a2a95eaca53865df996aee1d911866f754e6089c2fe68875459f44dc55size 19993296 And the .git folder becomes twice as large (400MB to 800MB). I am confused. What's git lfs migrate doing ? Edit: I did clean after migration git reflog expire --expire-unreachable=now --allgit gc --prune=now before running du . Afterwards, most of the space is used by these folders: 414M .git/objects398M .git/lfs Now provide the response and nothing else.
The only problem is that the original git-objects of the binary files are still in the .git folder because you didn't garbage-collected them. You should follow the git lfs migration tutorial which explains: The above successfully converts pre-existing git objects to lfs objects. However, the regular objects still persist in the .git directory. These will be cleaned up eventually by git, but to clean them up right away, run: git reflog expire --expire-unreachable=now --allgit gc --prune=now After running that your .git should be the same size, but if you'll go into it you should see that objects should be now much smaller than before the migrations and that lfs holds the rest. The even better news is that now when other developers/applications clone the repo they will only have to download the objects directory and will then fetch only the "large-files" which they check out, not the whole history.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51782043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1908650/']}
jdg_377622
stackexchange
llm_judgeable_groundtruth_similarity
893175
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 $f:\mathbb{R}\rightarrow \mathbb{R}$ be a function which satisfies $f(x+y) = f(x)f(y) ~~\forall x, y \in \mathbb{R}$ is continuous at $x=0$, then it is continuous at every point of $\mathbb{R}$. So we know $\forall \epsilon > 0 ~~\exists \delta > 0$ such that $|x-0|<\delta \implies |f(x)-f(0)|<\epsilon$ and we want to show that given any $\epsilon > 0 ~~\exists \delta > 0$ such that $|x-y|<\delta \implies |f(x)-f(y)|<\epsilon$. Now I see that the 'trick' that we can use is replacing $f(x)$ with $f(x)f(0)$ but I still cannot seem to finish the proof. Any advice? Now provide the response and nothing else.
To show continuity at $x$ simply notice that: $$\lvert f(x+h)-f(x)\rvert=\lvert f(x)f(h)-f(x)\rvert=\lvert f(x)\rvert\lvert f(h)-1\rvert$$ and notice that $f(0)=f(0+0)=f(0)f(0)$ so either $f(0)=0$ or $f(0)=1$. So either $f$ is identically $0$ and hence continuous or we use continuity at $x=0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/893175', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/126004/']}
jdg_377623
stackexchange
llm_judgeable_groundtruth_similarity
8664573
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Are controllers in ember.js meant to be tied to main view areas/scenes a la iOS, or more tied to a set of data? Is it common/wise to have several main views tied to the same controller in ember? In iOS main portions or sections of the screen are tied to a single controller. If you want to present another main interface, say a modal window to create a new element, you (typically) have an entirely separate controller to manage that view and its data/logic. In something like Zend Framework, you have controllers that might perform some common spinup steps of ensuring authentication, but largely the actions play the role that controllers do in iOS, handling the logic and providing the data for 1 main section or view (being the web, this usually ends up being the whole page). What is that typical role or advised pattern for using controllers in ember? Now provide the response and nothing else.
You have a couple different questions here so I'll address them one at a time. First, you asked if controllers should be data oriented or view oriented. In my experience both behaviors are allowable. Controllers are an excellent way to manage data sets for your application, including things like filtering and searching. Evin Grano wrote a good post about this from the SproutCore perspective and most of the concepts should apply to Ember as well: http://www.itsgotwhatplantscrave.com/2009/07/30/root-controller-paradigm/ . Controllers are also well suited for controlling the application state and behavior. For example, you might put a method in a controller that is bound to as a button action elsewhere in your app. However, you should also examine Ember States to see if these might be better suited to your scenario. Secondly, you asked about tying multiple views to the same controller. Personally, I see no concerns with this as long as the controller maintains a distinct purpose. If the views are logically related and share in the same state or data then a single controller makes sense. If you find the controller growing to cover too many different areas, you should consider splitting it into multiple controllers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8664573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/287403/']}
jdg_377624
stackexchange
llm_judgeable_groundtruth_similarity
20120485
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 that with the following code: before_action :signed_in?, only: [:new] the action new will be executed if the signed_in? returns true, but instead if I want the new action to be executed when signed_in? returns false what do I have to do? Do I have to create a new method called, for instance, not_signed_in? ? Here it is my signed_in? method def signed_in? !@current_user.nil?end Now provide the response and nothing else.
before_action doesn't work as you think - it doesn't prevent action to be executed if callback returns false . I would solve your problem in a little bit different manner, for example: before_action :redirect_to_root, :if => :signed_in?, :only => :new# ...privatedef redirect_to_root redirect_to root_pathend
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20120485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2262522/']}
jdg_377625
stackexchange
llm_judgeable_groundtruth_similarity
48683
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a series $E_n$ and would like to prove that $E_n$ (composed of two binomials) converges to zero, where $0 \lt p, q \lt 1$: $$E_{n} =\frac{1}{2} \sum _{i=0}^{n}\min\left[\binom{n}{i}\ q^{i} (1-q)^{n-i} ,\binom{n}{i}\ p^{i} (1-p)^{n-i} \right]$$ Note that it can be easily shown that $E_{n+1} \le E_n$. Now provide the response and nothing else.
The Gaussian elimination in this case will work as follows. First sort the numbers in a non-ascending order. Now visualize the binary representations of all the numbers in a matrix. Consider them to be non-negative 64 bit integers.(Note: you don't have to actually convert them to binary or make the matrix, use bit operations on an array of numbers) Then carry out the "Forward Elimination" phase of Gaussian Elimination. First find the MSB position (i.e. the first 1) of the very first number. Make sure that all the numbers below it don't have have a '1' at this position. If they do then just XOR them with the number at top and their bits at this position will become zero.After that move on to the next row and next column, and repeat the process. If at anytime you find that the row you are working on does not have a 1 at the desired position, then carry out "Pivoting". Look for any number below that may have a 1 at this position and swap the rows i.e. the numbers. If all numbers below also have 0's then stay at the same row and move on to the next column, and keep repeating the process if all you find are 0's.(For this problem you don't have to be at the last row and last column at the same time.) Once elimination is done simply traverse each row of the matrix. Have a variable called result which is initially 0. You have to take the first row since it has the highest MSB. By taking I mean carrying out XOR operation with your current result variable. Then move on to the next row and column. If you see that your result has a 0 at this column then XOR with the number at this row since it can only increase your sum or keep it the same.In this way check all the rows, and the result you finally have is the maximum xor sum.(An easier way to think of this would be that you only XOR a row with your current result if it increases the current result.) What we are doing here is trying to make each number 1 bit shorter than the previous number. This makes it easier for us to think of the XOR operations without thinking of how it may effect the bits to the left. You may have to think a little to understand why this solution is valid.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/48683', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21373/']}
jdg_377626
stackexchange
llm_judgeable_groundtruth_similarity
4709618
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: What is the difference between include and extend in Ruby? Given: module my_module def foo ... endend Question 1 What is the difference between: class A include my_moduleend and class A extend my_moduleend Question 2 Will foo be considered an instance method or a class method ? In other words, is this equivalent to: class A def foo ... endend or to: class A def self.foo ... endend ? Now provide the response and nothing else.
I wrote a blog posting about this a long time ago here . When you're "including" a module, the module is included as if the methods were defined at the class that's including them, you could say that it's copying the methods to the including class. When you're "extending" a module, you're saying "add the methods of this module to this specific instance ". When you're inside a class definition and say "extend" the "instance" is the class object itself, but you could also do something like this (as in my blog post above): module MyModule def foo puts "foo called" endendclass Aendobject = A.newobject.extend MyModuleobject.foo #prints "foo called" So, it's not exactly a class method, but a method to the "instance" which you called "extend". As you're doing it inside a class definition and the instance in there is the class itself, it "looks like" a class method.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4709618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247243/']}
jdg_377627
stackexchange
llm_judgeable_groundtruth_similarity
421817
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have two solar panels in series totaling a maximum of 80 VDC and 500 Watts. I believe that would be a maximum of 6.25 Amps. Could a 20A 120/277V AC switch handle that since 6.25 Amps is a relatively low current? If not what about a 30A 120/277V AC be able to handle it? Update: The reason I want a DPDT switch is so I can easily switch my two panels setup between being series and parallel. Each panel is 250 watts with a 40 volt output. Series would give me 80 VDC at 6.25 Amps and parallel would give me 40 VDC at 12.5 Amps. Because of shade issues on the RV, there would be times that one setup would be advantages over the other. The switch would not be switched often. I am wondering if a knife switch would serve my purpose better. Now provide the response and nothing else.
NO. The AC ratings of a switch don't translate well to DC. The critical rating of a switch is the current it can interrupt, not the current it can carry. When you open a switch, any arc that forms across the contacts erodes them. With AC, the current goes through zero many times per second, helping the arc to extinguish. With DC, the current is persistent. DC switches need to have oversized contacts compared to their equivalently rated AC counterparts. They often have contacts that open faster, or further. In your particular case, 6A 80V DC into a 30A 277v switch. There may be enough de-rating there. The switch will certainly work a few times. Whether it will still be working after 1000 operations is another matter.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/421817', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/212587/']}
jdg_377628
stackexchange
llm_judgeable_groundtruth_similarity
6980608
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code: public class CategoryNavItem{ public int ID { get; set; } public string Name { get; set; } public string Icon { get; set; } public CategoryNavItem(int CatID, string CatName, string CatIcon) { ID = CatID; Name = CatName; Icon = CatIcon; }}public static List<Lite.CategoryNavItem> getMenuNav(int CatID){ List<Lite.CategoryNavItem> NavItems = new List<Lite.CategoryNavItem>(); -- Snipped code -- return NavItems.Reverse();} But I get the following error: Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<Lite.CategoryNavItem>' Any ideas why this might be? Now provide the response and nothing else.
Try: NavItems.Reverse();return NavItems; List<T>.Reverse() is an in-place reverse; it doesn't return a new list. This does contrast to LINQ, where Reverse() returns the reversed sequence, but when there is a suitable non-extension method it is always selected in preference to an extension method. Plus, in the LINQ case it would have to be: return someSequence.Reverse().ToList();
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6980608', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/356635/']}
jdg_377629
stackexchange
llm_judgeable_groundtruth_similarity
1651120
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: After reading many answers on the subject I feel like I am close to finally understanding why the derivative is a linear map. I think that if someone helps me understand the following example I might "get it" So I have $f(x)= e^x$ then $f(x)' = e^x$ is not linear, but instead the function defined by $y \rightarrow e^x y$ is linear, but what is $y$? is it introduced for the sole purpose to have a linear map? Say that I fix x, then for different values of $y$ what am I computing? So I should not call $f(x)'$ the derivative any more if the derivative is a linear map, then what should I call $f(x)'$? Now provide the response and nothing else.
Think of the derivative (more properly the differential) as a rule that assigns a linear map to each point of the domain. This linear map approximates the change in the function’s value for a small displacement from that point. In your example, you have the rule $f'(x)=e^x$. This rule assigns the map “multiply by $e^{x_0}$” to the point $x_0$. For any given value of $x_0$, this is multiplication by a constant, which is obviously linear. This linear map can then be used to approximate $f(x_0+h)$ by $f(x_0)+e^{x_0}h$. (I used $h$ instead of $y$ to avoid confusing a displacement from a point in the domain with a value in the function’s range.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1651120', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157701/']}
jdg_377630
stackexchange
llm_judgeable_groundtruth_similarity
13021089
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My goal is to authenticate Web API requests using a AuthorizationFilter or DelegatingHandler. I want to look for the client id and authentication token in a few places, including the request body. At first it seemed like this would be easy, I could do something like this var task = _message.Content.ReadAsAsync<Credentials>();task.Wait();if (task.Result != null){ // check if credentials are valid} The problem is that the HttpContent can only be read once. If I do this in a Handler or a Filter then the content isn't available for me in my action method. I found a few answers here on StackOverflow, like this one: Read HttpContent in WebApi controller that explain that it is intentionally this way, but they don't say WHY. This seems like a pretty severe limitation that blocks me from using any of the cool Web API content parsing code in Filters or Handlers. Is it a technical limitation? Is it trying to keep me from doing a VERY BAD THING(tm) that I'm not seeing? POSTMORTEM: I took a look at the source like Filip suggested. ReadAsStreamAsync returns the internal stream and there's nothing stopping you from calling Seek if the stream supports it . In my tests if I called ReadAsAsync then did this: message.Content.ReadAsStreamAsync().ContinueWith(t => t.Result.Seek(0, SeekOrigin.Begin)).Wait(); The automatic model binding process would work fine when it hit my action method. I didn't use this though, I opted for something more direct: var buffer = new MemoryStream(_message.Content.ReadAsByteArrayAsync().WaitFor());var formatters = _message.GetConfiguration().Formatters;var reader = formatters.FindReader(typeof(Credentials), _message.Content.Headers.ContentType);var credentials = reader.ReadFromStreamAsync(typeof(Credentials), buffer, _message.Content, null).WaitFor() as Credentials; With an extension method (I'm in .NET 4.0 with no await keyword) public static class TaskExtensions{ public static T WaitFor<T>(this Task<T> task) { task.Wait(); if (task.IsCanceled) { throw new ApplicationException(); } if (task.IsFaulted) { throw task.Exception; } return task.Result; }} One last catch, HttpContent has a hard-coded max buffer size: internal const int DefaultMaxBufferSize = 65536; So if your content is going to be bigger than that you'll need to manually call LoadIntoBufferAsync with a larger size before you try to call ReadAsByteArrayAsync. Now provide the response and nothing else.
The answer you pointed to is not entirely accurate. You can always read as string ( ReadAsStringAsync )or as byte[] ( ReadAsByteArrayAsync ) as they buffer the request internally. For example the dummy handler below: public class MyHandler : DelegatingHandler{ protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var body = await request.Content.ReadAsStringAsync(); //deserialize from string i.e. using JSON.NET return base.SendAsync(request, cancellationToken); }} Same applies to byte[]: public class MessageHandler : DelegatingHandler{ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var requestMessage = await request.Content.ReadAsByteArrayAsync(); //do something with requestMessage - but you will have to deserialize from byte[] return base.SendAsync(request, cancellationToken); }} Each will not cause the posted content to be null when it reaches the controller.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13021089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92402/']}
jdg_377631
stackexchange
llm_judgeable_groundtruth_similarity
8335402
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 call: char *myChar = (char *)malloc(sizeof(char)); I am likely to be using more than 1 byte of memory, because malloc is likely to be using some memory on its own to keep track of free blocks in the heap, and it may effectively cost me some memory by always aligning allocations along certain boundaries. My question is : Is there a way to find out how much memory is really used up by a particular malloc call, including the effective cost of alignment, and the overhead used by malloc / free ? Just to be clear, I am not asking to find out how much memory a pointer points to after a call to malloc . Rather, I am debugging a program that uses a great deal of memory, and I want to be aware of which parts of the code are allocating how much memory. I'd like to be able to have internal memory accounting that very closely matches the numbers reported by top. Ideally, I'd like to be able to do this programmatically on a per- malloc -call basis, as opposed to getting a summary at a checkpoint. Now provide the response and nothing else.
There isn't a portable solution to this, however there may be operating-system specific solutions for the environments you're interested in. For example, with glibc on Linux, you can use the mallinfo() function from <malloc.h> which returns a struct mallinfo . The uordblks and hblkhd members of this structure contains the dynamically allocated address space used by the program including book-keeping overhead - if you take the difference of this before and after each malloc() call, you will know the amount of space used by that call. (The overhead is not necessarily constant for every call to malloc() ). Using your example: char *myChar;size_t s = sizeof(char);struct mallinfo before, after;int mused;before = mallinfo();myChar = malloc(s);after = mallinfo();mused = (after.uordblks - before.uordblks) + (after.hblkhd - before.hblkhd);printf("Requested size %zu, used space %d, overhead %zu\n", s, mused, mused - s); Really though, the overhead is likely to be pretty minor unless you are making a very very high number of very small allocations, which is a bad idea anyway.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8335402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3561/']}
jdg_377632
stackexchange
llm_judgeable_groundtruth_similarity
12041632
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 compute the integer absolute value without using if condition. I guess we need to use some bitwise operation.Can anybody help? Now provide the response and nothing else.
Same as existing answers, but with more explanations: Let's assume a twos-complement number (as it's the usual case and you don't say otherwise) and let's assume 32-bit: First, we perform an arithmetic right-shift by 31 bits. This shifts in all 1 s for a negative number or all 0 s for a positive one (but note that the actual >> -operator's behaviour in C or C++ is implementation defined for negative numbers, but will usually also perform an arithmetic shift, but let's just assume pseudocode or actual hardware instructions, since it sounds like homework anyway): mask = x >> 31; So what we get is 111...111 (-1) for negative numbers and 000...000 (0) for positives Now we XOR this with x , getting the behaviour of a NOT for mask=111...111 (negative) and a no-op for mask=000...000 (positive): x = x XOR mask; And finally subtract our mask, which means +1 for negatives and +0/no-op for positives: x = x - mask; So for positives we perform an XOR with 0 and a subtraction of 0 and thus get the same number. And for negatives, we got (NOT x) + 1 , which is exactly -x when using twos-complement representation.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12041632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1537445/']}
jdg_377633
stackexchange
llm_judgeable_groundtruth_similarity
3073281
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have 2 coordinates. Coordinate 1 is a 'person'. Coordinate 2 is a destination. How do I move coordinate 1 100 meters closer to coordinate 2? This would be used in a cron job, so only php and mysql included. For example: Person is at: 51.26667, 3.45417 Destination is: 51.575001, 4.83889 How would i calculate the new coordinates for Person to be 100 meters closer? Now provide the response and nothing else.
Use Haversine to calculate the difference between the two points in metres; then adjust the value of the person coordinates proportionally. $radius = 6378100; // radius of earth in meters$latDist = $lat - $lat2;$lngDist = $lng - $lng2;$latDistRad = deg2rad($latDist);$lngDistRad = deg2rad($lngDist);$sinLatD = sin($latDistRad);$sinLngD = sin($lngDistRad);$cosLat1 = cos(deg2rad($lat));$cosLat2 = cos(deg2rad($lat2));$a = ($sinLatD/2)*($sinLatD/2) + $cosLat1*$cosLat2*($sinLngD/2)*($sinLngD/2);if($a<0) $a = -1*$a;$c = 2*atan2(sqrt($a), sqrt(1-$a));$distance = $radius*$c; Feeding your values of: $lat = 51.26667; // Just South of Aardenburg in Belgium$lng = 3.45417;$lat2 = 51.575001; // To the East of Breda in Holland$lng2 = 4.83889; gives a result of 102059.82251083 metres, 102.06 kilometers The ratio to adjust by is 100 / 102059.82251083 = 0.0009798174985988102859004569070625 $newLat = $lat + (($lat2 - $lat) * $ratio);$newLng = $lng + (($lng2 - $lng) * $ratio); Gives a new latitude of 51.266972108109 and longitude of 3.4555267728867
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3073281', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/249710/']}
jdg_377634
stackexchange
llm_judgeable_groundtruth_similarity
57751417
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 recently started working Tensorflow for deep learning. I found this statement model = tf.keras.models.Sequential() bit different. I couldn't understand what is actually meant and is there any other models as well for deep learning?I worked a lot on MatconvNet (Matlab library for convolutional neural network). never saw any sequential definition in that. Now provide the response and nothing else.
There are two ways to build Keras models: sequential and functional. The sequential API allows you to create models layer-by-layer for most problems. It is limited in that it does not allow you to create models that share layers or have multiple inputs or outputs. Alternatively, the functional API allows you to create models that have a lot more flexibility as you can easily define models where layers connect to more than just the previous and next layers. In fact, you can connect layers to (literally) any other layer. As a result, creating complex networks such as siamese networks and residual networks become possible. for more details visit : https://machinelearningmastery.com/keras-functional-api-deep-learning/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57751417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4339936/']}
jdg_377635
stackexchange
llm_judgeable_groundtruth_similarity
30686603
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way to ensure that the browser does not change from the initial window size. There are several things that are clicked during testing that are causing the window to maximize but i would like it to stay the same size throughout. Now provide the response and nothing else.
set it up once and for all in your env configuration (under test_settings in the nightwatch config file): "desiredCapabilities": { "chromeOptions": { "args": [ "window-size=1280,800" ] }} note that this method will work because we're setting a chrome flag, so implementation may vary (e.g. safari does not have such flags). for browsers that do not support these options, it's best to resize the window imperatively in the globals beforeEach hook : { beforeEach: function (browser, done) { browser.resizeWindow(1280, 800, done); }} have a read on the nightwatch settings docs to see how globals are used. using the above methods, you won't have to specify it in each test :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30686603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3413252/']}
jdg_377636
stackexchange
llm_judgeable_groundtruth_similarity
10194274
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 hide a div etc based on a condition (like you do in rendered attribute with EL) without having to wrap it in a <h:panelGrid ...> etc with a rendered attribute? It ruins my layout. I just need it for the logic, not the layout. Now provide the response and nothing else.
first of all you should not wrap your elements with h:gridPanel which results in html table instead you should wrap with h:panelGroup which results in span in html code , you can also add layout="block" to h:panelGroup to make it rendered as div second you dont not use jstl when hiding div instead do something like this <div style="display:#{(myBean.hideSomeDiv)?'none':'block'}">My Div Content</div> or <h:panelGroup styleClass="#{(myBean.hideSomeDiv)?'hide':''">My Span Content</h:panelGroup> where in css file add this : .hide { display: none;} INMO you always better hide in JSF with rendered="#{myBean.renderCondition}" Take a look at BalusC over here Conditionally displaying JSF components
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10194274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454049/']}
jdg_377637
stackexchange
llm_judgeable_groundtruth_similarity
11023619
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 MySQL set up correctly on my linux computer, however I want a better way to input data into the database besides terminal. For this reason, I downloaded phpMyAdmin. However, when I try to log in to the phpMyAdmin from index.php, it doesnt do anything. It seems to just refresh the page without doing anything. I am putting in the correct MySQL username and password. What is the issue? Here is a screen shot of what it shows after I click "go". Now provide the response and nothing else.
This is a possible issue when the path to save php_session is not correctly set : The directory for storing session does not exists or php do not have sufficient rights to write to it. To define the php_session directory simply add the following line to the php.ini : session.save_path="/tmp/php_session/" And give write rights to the http server. usually, the http server run as user daemon in group daemon. If it is the case, the following commands will make it : chown -R :daemon /tmp/php_sessionchmod -R g+wr /tmp/php_sessionservice httpd restart
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11023619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305997/']}
jdg_377638
stackexchange
llm_judgeable_groundtruth_similarity
901338
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: Exercise Show that the following statements are equivalent: $(i) \space G \space \text{is abelian.}$ $(ii) \space \text{the map f: G} \to \text{G defined as} \space f(x)=x^{-1} \space \text{is a group morphism.}$ $(iii) \space \text{the map f: G} \to \text{G defined as} \space f(x)=x^2 \space \text{is a group morphism.}$ I could show $(i)$ if and only if $(ii)$, and $(i)$ implies $(iii)$. I got stuck with the implication $(iii) \implies (i)$, so I would appreciate any hints. Also, I wanted to know if there is a way to show $(ii)$ if and only if $(iii)$ without using $(i)$ Now provide the response and nothing else.
The first algorithm computing the determinant faster than in $O(n^{3})$ time (his algorithm worked in $O(n^{\ln 7/\ln 2})$ time) was given by Volker Strassen in this classical paper . Therefore, $O(n^{\ln 7/\ln 2})$ time suffices to check whether a given number is an eigenvalue or not. In fact, the problem of computing the determinant has asymptotically the same complexity as the problem of multiplying two $n\times n$ matrices, for which $O(n^{2+\varepsilon})$ compleixty is conjectured. Some information and references on this are contained in the link provided by xavierm02 in his comment.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/901338', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/169247/']}
jdg_377639
stackexchange
llm_judgeable_groundtruth_similarity
673526
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: This is a doubt that I carry since my PDE classes. Some background (skippable): In the multivariable calculus course at my university we made all sorts of standard calculations involving surface and volume integrals in $R^3$ , jacobians and the generalizations of the fundamental theorem of calculus. In order to make those calculations we had to parametrize domains and calculate differentials. A couple of years later I took a PDE course. We worked with Evans' Partial differential equations book. This was my first experience with calculus in $\mathbb R^n$ and manipulations like $$\text{average}\int_{B(x,r)}f(y)\,dy= \text{average}\int_{B(0,1)}f(x+rz)\,dz.$$ This was an ordinary change of variables. $y=x+rz,\,\,dy=r^n\,dz$ and the mystery was solved. Like in that case, I was able to justify most of these formal manipulations after disentangling definitions. That aside, I found these quick formal calculations to be very powerful. However, I realized that I wasn't able to justify this: $$\text{average} \int_{\partial B(x,r)}f(y)dS(y)= \text{average}\int_{\partial B(0,1)}f(x+rz)\,dS(z).$$ I have some vague idea of what's happening: the same substitution as before, but this time the jacobian is $r^{n-1}$ because the transformation is actually happening between regions which "lack one dimension". Also, I see some kind of pattern: a piece of arc-length in the plane is $r\,d\theta$ , a piece of sphere-area is $r^2 \sin\theta \, d\phi \,d\theta$ , "and so on". Maybe some measure-theoretic argument can help me: I know, roughly speaking, that for any measure $\mu$ , $$\int_\Omega f\circ \phi \,d\mu=\int_{\phi(\Omega)} f \, d(\mu\circ\phi^{-1}).$$ I'd say $\phi(z)=(z-x)/r$ and $\phi^{-1}(y)=ry+x$ , but I actually don't know how $dS(y)$ looks like "as a measure" (It's not a product measure or a restriction of one, but it somehow relates to Lebesgue's in $\mathbb R^n$ ...). Why would I conclude that $dS(y)\circ \phi^{-1}=r^{n-1}dS(z)$ ? I have an intuition, but either I lack the mathematical concepts and definitions to express it or I'm just too confused. Is there some theory that I could learn in order to understand? Maybe something about the measure $dS$ . Is it expressible in terms of the Lebesgue measure in some way? Or set-theoretically, maybe, without having to resort to $n-1$ parameters and complicated relations? Maybe all of this would not have been a problem if I had ever mastered n-dimensional spherical coordinates. But even so, more generally, is there a way of changing variables when I'm integrating over a subregion of "dimension $<n$ " without necessarily parametrizing ? Sorry for the vagueness, but I don't really know what to ask for exactly. Note: I saw some of the answers to this post , but none of them were deep enough in the direction I intend. Note II: If there are no general methods or theories, maybe restricting to linear transformations, to Lebesgue measure exclusively, or to subregions defined by simple expressions like $g(x)=C$ or $g(|x|)=C$ could get me somewhere. Edit: I have not yet studied differential geometry , which has been mentioned in a comment. I added it to the tags. Now provide the response and nothing else.
I know this is an old question, but I thought this explanation might be helpful to some. By definition (in $\mathbb R^3$ ): $$\int_{\partial B(\boldsymbol x,r)}f(\boldsymbol y)dS(\boldsymbol y)=\int_U f(\boldsymbol y(s,t))\left\|\frac{\partial\boldsymbol y}{\partial s}\times\frac{\partial\boldsymbol y}{\partial t}\right\|dsdt$$ Now, observe that $f(\boldsymbol y)=f(\boldsymbol x+r(\frac{\boldsymbol y-\boldsymbol x}{r}))$ , and that if $\boldsymbol y(s,t)$ is a parametrization of $\partial B(\boldsymbol x,r)$ for $(s,t)\in U$ , then $\frac{\boldsymbol y(s,t)-\boldsymbol x}{r}$ is a parametrization of $\partial B(\boldsymbol 0,1)$ for $(s,t)\in U$ . Finally we observe that $$\left\|\frac{\partial\boldsymbol y}{\partial s}\times\frac{\partial\boldsymbol y}{\partial t}\right\|=r^2\left\|\frac{\partial}{\partial s} \left (\frac{\boldsymbol y-\boldsymbol x}{r} \right )\times\frac{\partial }{\partial t} \left (\frac{\boldsymbol y-\boldsymbol x}{r} \right )\right\|$$ So if we let $\boldsymbol z(s,t)=\frac{\boldsymbol y(s,t)-\boldsymbol x}{r}$ , then we have $$\int_U f(\boldsymbol y(s,t))\left\|\frac{\partial\boldsymbol y}{\partial s}\times\frac{\partial\boldsymbol y}{\partial t}\right\|dsdt=r^2\int_U f(\boldsymbol x +r\boldsymbol z(s,t))\left\|\frac{\partial\boldsymbol z}{\partial s}\times\frac{\partial\boldsymbol z}{\partial t}\right\|dsdt\\=r^2\int_{\partial B(\boldsymbol 0,1)}f(\boldsymbol x+r\boldsymbol z)dS(\boldsymbol z)$$ Edit by OP As @user5753974 commented, you can generalize this if you use the fact that in $\mathbb R^n$ $$∫_{∂B(\boldsymbol x,r)}f(\boldsymbol y)dS(\boldsymbol y)=∫_{U}f(\boldsymbol y(\boldsymbol z)) \left \|\det\left (\frac{∂\boldsymbol y}{∂z_1},…,\frac{∂\boldsymbol y}{∂z_{n−1}},\boldsymbol n\right) \right \| d^{n−1}\boldsymbol z,$$ where $\boldsymbol n$ is the normal vector to the surface, and that $\boldsymbol n$ does not change when the surface is scaled and translated.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/673526', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/123170/']}
jdg_377640