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 | 10374134 |
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 looking at these examples on Microsoft.com here: http://support.microsoft.com/kb/316005 http://msdn.microsoft.com/en-us/library/aa225754%28v=sql.80%29.aspx But it's saying in part of it's steps that VBScript code has to be executed, and I wasn't able to find where the VBScript should be executed. Is it possible to be executed in SQL Server itself? The code from the site looks something like this: Set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkLoad") objBL.ConnectionString = "provider=SQLOLEDB.1;data source=MySQLServer; database=MyDatabase;uid=MyAccount;pwd=MyPassword" objBL.ErrorLogFile = "c:\error.log" objBL.Execute "c:\customermapping.xml", "c:\customers.xml" Set objBL = Nothing This looks like it could be executed in classic asp or something, but I prefer to keep it inside SQL Server. Does anyone know how to execute something like this all with-in SQL Server? or does anyone have a better method for Bulk import XML into SQL server?
Now provide the response and nothing else.
| SQL Server is capable of reading XML and inserting it as you need. Here is an example of an XML file and insertion pulled from here : XML: <Products> <Product> <SKU>1</SKU> <Desc>Book</Desc> </Product> <Product> <SKU>2</SKU> <Desc>DVD</Desc> </Product> <Product> <SKU>3</SKU> <Desc>Video</Desc> </Product></Products> Insert statement that is parsing the XML: INSERT INTO Products (sku, product_desc) SELECT X.product.query('SKU').value('.', 'INT'), X.product.query('Desc').value('.', 'VARCHAR(30)')FROM ( SELECT CAST(x AS XML)FROM OPENROWSET( BULK 'C:\Products.xml', SINGLE_BLOB) AS T(x) ) AS T(x)CROSS APPLY x.nodes('Products/Product') AS X(product); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10374134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/916535/']} | jdg_85041 |
stackexchange | llm_judgeable_groundtruth_similarity | 62762329 |
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 that returns error body with the correct error information when a bad request is sent. For eg I get status code 400 and the following body - { "errorCode": 1011, "errorMessage": "Unable to get Child information"} Now when I am writing a ktor client in a multi-platform module for this, I catch this in a response validator like - HttpResponseValidator { validateResponse { val statusCode = it.status.value when (statusCode) { in 300..399 -> print(it.content.toString()) in 400..499 -> { print(it.content.toString()) throw ClientRequestException(it) } in 500..599 -> print(it.content.toString()) } } handleResponseException { print(it.message) } } My query here is I am not able to access the response error body in either validateResponse or handleResponseException . Is there a way i can catch and parse that to get the actual error sent by server?
Now provide the response and nothing else.
| You can declare a data class Error to represent the error response you expect. import kotlinx.serialization.Serializable@Serializabledata class Error( val errorCode: Int, //if by errorCode you mean the http status code is not really necessary to include here as you already know it from the validateResponse val errorMessage: String) you can have a suspend fun to parse the response and have it as an instance of the Error data class suspend fun getError(responseContent: ByteReadChannel): Error { responseContent.readUTF8Line()?.let { return Json(JsonConfiguration.Stable).parse(Error.serializer(), it) } throw IllegalArgumentException("not a parsable error")} then inside the handleResponseException handleResponseException { cause -> val error = when (cause) { is ClientRequestException -> exceptionHandler.getError(cause.response.content)// other cases here else -> // throw Exception() do whatever you need }//resume with the error } you can implement some logic based on the error you get to throw an exception and catch it somewhere else in your codefor example when (error.errorCode) { 1-> throw MyCustomException(error.errorMessage) else -> throw Exception(error.errorMessage) } I hope it helps | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62762329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1273240/']} | jdg_85042 |
stackexchange | llm_judgeable_groundtruth_similarity | 44642966 |
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 plot a multi-color line using pandas series. I know matplotlib.collections.LineCollection will sharply promote the efficiency.But LineCollection require line segments must be float. I want to use datatime index of pandas as x-axis. points = np.array((np.array[df_index.astype('float'), values]).T.reshape(-1,1,2))segments = np.concatenate([points[:-1],points[1:]], axis=1)lc = LineCollection(segments)fig = plt.figure()plt.gca().add_collection(lc)plt.show() But the picture can't make me satisfied.Is there any solution?
Now provide the response and nothing else.
| To produce a multi-colored line, you will need to convert the dates to numbers first, as matplotlib internally only works with numeric values. For the conversion matplotlib provides matplotlib.dates.date2num . This understands datetime objects, so you would first need to convert your time series to datetime using series.index.to_pydatetime() and then apply date2num . s = pd.Series(y, index=dates)inxval = mdates.date2num(s.index.to_pydatetime()) You can then work with the numeric points as usual , e.g. plotting as Polygon or LineCollection[ 1 , 2 ]. The complete example: import pandas as pdimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport numpy as npfrom matplotlib.collections import LineCollectiondates = pd.date_range("2017-01-01", "2017-06-20", freq="7D" )y = np.cumsum(np.random.normal(size=len(dates)))s = pd.Series(y, index=dates)fig, ax = plt.subplots()#convert dates to numbers firstinxval = mdates.date2num(s.index.to_pydatetime())points = np.array([inxval, s.values]).T.reshape(-1,1,2)segments = np.concatenate([points[:-1],points[1:]], axis=1)lc = LineCollection(segments, cmap="plasma", linewidth=3)# set color to date valueslc.set_array(inxval)# note that you could also set the colors according to y values# lc.set_array(s.values)# add collection to axesax.add_collection(lc)ax.xaxis.set_major_locator(mdates.MonthLocator())ax.xaxis.set_minor_locator(mdates.DayLocator())monthFmt = mdates.DateFormatter("%b")ax.xaxis.set_major_formatter(monthFmt)ax.autoscale_view()plt.show() Since people seem to have problems abstacting this concept, here is a the same piece of code as above without the use of pandas and with an independent color array: import matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport numpy as np; np.random.seed(42)from matplotlib.collections import LineCollectiondates = np.arange("2017-01-01", "2017-06-20", dtype="datetime64[D]" )y = np.cumsum(np.random.normal(size=len(dates)))c = np.cumsum(np.random.normal(size=len(dates)))fig, ax = plt.subplots()#convert dates to numbers firstinxval = mdates.date2num(dates)points = np.array([inxval, y]).T.reshape(-1,1,2)segments = np.concatenate([points[:-1],points[1:]], axis=1)lc = LineCollection(segments, cmap="plasma", linewidth=3)# set color to date valueslc.set_array(c)ax.add_collection(lc)ax.xaxis_date()ax.autoscale_view()plt.show() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44642966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5940710/']} | jdg_85043 |
stackexchange | llm_judgeable_groundtruth_similarity | 949465 |
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 the query: SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as AgeFROM availablesINNER JOIN roomsON availables.room_id=rooms.idWHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094GROUP BY availables.bookdate Which returns something like: Date Age2009-06-25 02009-06-26 22009-06-27 12009-06-28 02009-06-29 0 How can I then do a Count on the number of rows which is returned.. (in this case 5) and an SUM of the Ages? To return just one row with the Count and the SUM? Count SUM5 3 Thanks
Now provide the response and nothing else.
| Usually you can plug a Query's result (which is basically a table) as the FROM clause sourceof another query, so something like this will be written: SELECT COUNT(*), SUM(SUBQUERY.AGE) from( SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age FROM availables INNER JOIN rooms ON availables.room_id=rooms.id WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate) AS SUBQUERY | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/949465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/116522/']} | jdg_85044 |
stackexchange | llm_judgeable_groundtruth_similarity | 4499093 |
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 the following way to do this integral by writing it as $$I=\int_0^\frac{\pi}{2}\ln(\cos(x))dx=\int_0^\frac{\pi}{2}\ln(\sin(x))dx$$ and then $$2I=\int_0^\frac{\pi}{2}\ln(\cos(x)\sin(x))dx$$ Afterwards, it can be converted to $$2I=\int_0^\frac{\pi}{2}\ln(\sin(2x))dx-\int_0^\frac{\pi}{2}\ln(2)dx$$ With substitution $2x=y$ $$2I=\frac{1}{2}\int_0^\pi\ln(\sin(y))dy-\int_0^\frac{\pi}{2}\ln(2)dx$$ $$\implies2I=\frac{1}{2}(2\int_0^\frac{\pi}{2}\ln(\sin(y))dy)-\int_0^\frac{\pi}{2}\ln(2)dx$$ The first integral can be written as $2I$ $$2I=\frac{1}{2}(2I)-\int_0^\frac{\pi}{2}\ln(2)dx$$ $$\implies I=-\int_0^\frac{\pi}{2}\ln(2)dx=-\frac{\pi}{2}\ln(2)$$ But, I want to know some other creative approaches to solve this integral, without using much advanced calculus. Also, please explain thought process behind your solution.
Now provide the response and nothing else.
| \begin{align}\int_0^\frac{\pi}{2}\ln(\cos x)dx&=\int_0^\frac{\pi}{2}\ln(\sin x)dx\overset{ibp}=-\int_0^\frac{\pi}{2}\frac x{\tan x}dx\\=&-\int_0^\frac{\pi}{2}\int_0^1 \frac 1{1+t^2\tan^2x}dtdx=-\frac\pi2\int_0^1\frac1{1+t}dt=-\frac\pi2\ln2\end{align} | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4499093', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1074057/']} | jdg_85045 |
stackexchange | llm_judgeable_groundtruth_similarity | 87967 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The real numbers is a locally compact Tychonoff connected complete ordered topological field. I am looking at minimal collections of adjectives that can characterize the reals. The one often used to define the reals is that it is (Dedekind- or Cauchy-) complete ordered field. Consider the real numbers among other ordered topological rings. I am wondering if the real numbers is the smallest connected ordered topological ring? Here "smallest" means that it embeds into every other connected ordered topological ring. If this is not true, do you have some minimal collection of additional adjectives (advoiding the word "complete") that can characterize the real numbers among ordered topological rings? "Minimal" means that if you drop an adjective then you there are other ordered topological rings that also fulfil your definition.
Now provide the response and nothing else.
| The following characterization of $\mathbb R$ and $\mathbb C$ among topological rings is due to Pontryagin and seems to be in the spirit of your question: Theorem : If $F$ is a field with a Hausdorff ring topology which is locally compact and connected then $F$ is isomorphic as a topological field to either $\mathbb R$ or $\mathbb C$ with their usual topologies. (If you substitute "field" with "division ring" then you must add the quaternions $\mathbb H$ to the list.) | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/87967', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_85046 |
stackexchange | llm_judgeable_groundtruth_similarity | 85560 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
"Examples first:" Consider so(3,C). (Co)Adjoint Orbits can be described by equations x^2+y^2+z^2 = R. R=0 - is nilpotent cone - algebraic closure of the orbit of nilpotent element. (It is union of two orbits - {0} and {Cone w/o {0}} ). R$\ne$ 0 are orbits of semi-simple elements.So we have degeneration R->0 - semi-simple orbit degenerates to nilpotent. Question Is there similar description for the other nilpotent orbits in higher dimensions e.g. for gl(n,c) ? I mean can we write some equations depending on parameters F_t(g)=0,such that for general "t" we get semi-simple orbits, but for specific values we have nilpotent orbit (more precisely their closures)? (Here "t" can be vector and F is vector-valued algebraic function). Of course this can be done the biggest orbit - for nilpotent cone itself. Consider matrices "M" which satisfy the condition, that their characterestic polynom is fixed with values eigs $a_i$: $det(M-x) = (x-a_1)(x-a_2)...(x-a_n)$ For $a_i$ generic - this is semisimple orbit, but if $a_i = 0$ we get nilpotent cone. Question Reformulated Is it possible to do the same for smaller dimensional orbits ? As far as I heard nilpotent orbits can be described by the equations on their rank and $M^l=0$, however this does not seems to answer the question. Part of motivation for asking is related to the following questions: On an affine analogue of the fact $\mathbb{C}[\mathfrak{g}]^G$ is a polynomial ring Primitive ideals of the universal enveloping algebras of affine Lie algebras In particular if the answer would be YES - then probably we can do the same in the"affine case" so answering the question "What replaces the concept of the nilpotent orbit in that case?"
Now provide the response and nothing else.
| The answer is often "yes". Here is the sketch of how to obtain a nilpotent orbit as a degeneration of semisimple orbits in the $GL_n$ case. Let $d$ be a partition of $n$ with $k$ parts and $\overline{\mathcal{O}}_{d'}$ be the closure of the conjugacy class of nilpotent $n\times n$ matrices with Jordan blocks sizes given by the dual partition $d'.$ Denote by $\mathcal{O}_d(t_1,\ldots, t_k)$ the conjugacy class of the block diagonal matrix with scalar diagonal blocks $t_i I_{d_i}.$ Then $$\lim_{t\to 0}\ \mathcal{O}_d(t_1,\ldots, t_k)=\overline{\mathcal{O}}_{d'}.$$ This is manifested on the level of defining equations using Oshima's approach from A quantization of conjugacy classes of matrices. Adv. Math. 196 (2005), no. 1, 124–146. For a general $\mathfrak{g},$ this amounts to the induction of (zero-dimensional) orbits and to the correspondence between semisimple and regular orbits. In particular, every Richardson nilpotent orbit can be obtained as a degeneration in the same way. However, the defining equations are not known to the same degree of explicitness. On the other hand, if $\mathfrak{g}$ is simple of type other than "A" then the minimal nilpotent orbit is rigid , meaning that it cannot be deformed within the family of adjoint orbits. Existence of rigid orbits makes quantization of orbits a non-trivial task, since a very natural prescription for quantization of semisimple orbits needs to be supplemented by ad hoc quantizations of rigid orbits (several papers of Joseph addressed this question). Rigid orbits have been completely classified: if my memory serves, the answer is in Collingwood-McGovern. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/85560', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10446/']} | jdg_85047 |
stackexchange | llm_judgeable_groundtruth_similarity | 26022113 |
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 implemented automatic dynamic tableview cell heights for iOS 8 by using self.tableView.rowHeight = UITableViewAutomaticDimension; For pre-iOS 8, which does not support automatic dynamic cell heights, I overrided the heightForRowAtIndexPath method. This is a similar to what I did: Using Auto Layout in UITableView for dynamic cell layouts & variable row heights The problem is to how to write code that uses automatic cell height for iOS 8 but overrides heightForRowAtIndexPath for earlier iOS versions. I'd like my custom heightForRowAtIndexPath method only if iOS version is less than 8.Any suggestions on how to do this?
Now provide the response and nothing else.
| One solution would be to override the respondsToSelector: method in your view controller. Have it return NO under iOS 8 when checking for the heightForRowAtIndexPath: method. - (BOOL)respondsToSelector:(SEL)selector { static BOOL useSelector; static dispatch_once_t predicate = 0; dispatch_once(&predicate, ^{ useSelector = [[UIDevice currentDevice].systemVersion floatValue] < 8.0 ? YES : NO; }); if (selector == @selector(tableView:heightForRowAtIndexPath:)) { return useSelector; } return [super respondsToSelector:selector];} This way, when the table view make a call like: if ([self.delegate respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)]) {} your code will return NO under iOS 8 or later and YES under iOS 7 or earlier. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26022113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1349768/']} | jdg_85048 |
stackexchange | llm_judgeable_groundtruth_similarity | 40137100 |
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 found that transition is not firing on dynamic route with parameters. For exemple with the code below, when I am in /chapter/1 and I go to /chapter/2 there is no transition. But when I am in /chapter/1 and I go to /profile/1 there is one ! main.js file require('normalize.css')import Vue from 'vue'import VueRouter from 'vue-router'import App from './App'import Panel from './components/Panel'import Profile from './components/Profile'window.bus = new Vue()Vue.use(VueRouter)const router = new VueRouter({ routes: [ { path: '/', redirect: '/chapter/1' }, { name:'chapter', path: '/chapter/:id', component: Panel}, { name:'profile', path: '/profile/:id', component: Profile} ]})new Vue({ router, el: '#app', render: h => h(App)}) App.vue template <template> <div id="app"> <transition name="fade" mode="out-in"> <router-view></router-view> </transition> <div class="controls"> <router-link :to="{ name: 'chapter', params: { id: Math.max(1, parseInt($route.params.id) - 1) }}"> Prev </router-link> <router-link :to="{ name: 'chapter', params: { id: parseInt($route.params.id) + 1 }}"> Next </router-link> </div> </div></template> Maybe is due to the fact that vue-router doesn't destroy the parent component ? I didn't found a way to run the transition from the code. I tried this configuration on vue-router example pack and the behavior is the same. quote from the doc One thing to note when using routes with params is that when the user navigates from /user/foo to /user/bar, the same component instance will be reused. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one. However, this also means that the lifecycle hooks of the component will not be called. To react to params changes in the same component, you can simply watch the $route object Should I post an issue ? Thanks for your help !
Now provide the response and nothing else.
| Can you check this working example: https://jsfiddle.net/mani04/dLnz4rbL/ I attempted to use the method described under Transitioning Between Elements in the docs. In my fiddle example, which mostly uses the code from your question description, I used a transition wrapper within component, as shown below: <transition name="fade" mode="out-in"> <div class="page-contents" :key="$route.params.id"> This is my chapter component. Page: {{parseInt($route.params.id)}} </div></transition> The document specifies that we need to provide a key to make them distinct elements for Vue.js. So I added your chapter ID as key. I don't know if this is a hack or a proper solution, I moved from Angular2 to Vue only 2 weeks ago. But till someone gives you a better solution, you may use this method to get your transitions for dynamic routes. Regarding posting this as an issue in github page of vue-router , I am not sure if this qualifies to be addressed / fixed, but you may definitely bring it to their notice. Fix may involve not reusing components, which is also not ideal. So it is a tough call for them. But the discussion should definitely be interesting! Please post back the issue link here if you decide to create one :-) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40137100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3759551/']} | jdg_85049 |
stackexchange | llm_judgeable_groundtruth_similarity | 2942068 |
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:
It is easy to give an example of a polynomial of degree 3 with integer coefficients having: (a) three distinct rational roots, (b) one rational root and two irrational roots. But for a while I am trying to construct one that all its roots are irrational but I can't. It seems that it is not possible at all? Also, can a polynomial with integer coefficients of degree 3 have two rational roots and one irrational root?
Now provide the response and nothing else.
| By Vieta the sum of the roots must be rational, hence this excludes a single irrational. All other cases are possible. $$\begin{align}0&:x(x^2-1)=0,\\2&:x(x^2-2)=0,\\3&:8x^3-6x-1=0.\end{align}$$ The last one was built from $$\cos3\theta=4\cos^3\theta-3\cos\theta=\cos\frac\pi3$$ so that the roots are $$\cos\frac\pi9, \cos\frac{7\pi}9, \cos\frac{13\pi}9.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2942068', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_85050 |
stackexchange | llm_judgeable_groundtruth_similarity | 74396 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So i just started learning about NAT and networking in general. As powerful as this technology may seem, it was specifically made for reducing the amount of IPV4 addresses used throughout the internet, so firstly Is there even another way to get public IPs besides using NAT and how is it done? and secondly: If by pure coincidence, two devices were to configure static NAT and use the same public IP address, what'll happen ?Thanks again
Now provide the response and nothing else.
| As powerful as this technology may seem... NAPT actually hamstrings IPv4 by breaking the IP paradigm of end-to-end connections, and only TCP, UDP, and ICMP work on NAPT. Even some applications and application-layer protocols are broken by NAPT. It also prevents development of new, more modern transport protocols. I think you are confused and have things backwards. NAT or NAPT does not get public addressing, but you may or may not use NAT or NAPT with any public IPv4 addressing you do get (IPv6 does not have a NAT standard the way IPv4 does; it has an experimental NAT RFC, but it forbids NAPT). is there even another way to get public ips besides using NAT and howit is done IPv4 addresses are exhausted. IANA has run out of IPv4 addresses to assign to the RIRs, which, in turn, have run out of IPv4 addresses to assign to businesses. There is now an open market for public IPv4 addresses where businesses with excess public IPv4 addresses can sell the excess to other businesses needing public IPv4 addresses, but a business still needs to qualify through its RIR to buy the addresses. Another possibility is that one or more businesses to which a business connects may lease that business one or a block of IPv4 addresses. This has nothing to do with NAT or NAPT. if by pure coincidence, two devices were to configure static NAT anduse the same public Ip address, what'll happen ? Again, this question does not really relate to NAT or NAPT. Public addresses must be unique (excepting anycast). The businesses making up the public Internet will ostracize any business using IP addresses that it is not authorized to use. | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/74396', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/76677/']} | jdg_85051 |
stackexchange | llm_judgeable_groundtruth_similarity | 44579300 |
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 able to get the range values using getValues() and put it into a string by declaring the following variables in Google App Script var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName("Test"); var range_input = ss.getRange("A1:A").getValues(); However, I realize I am getting a lot of commas in my string probably from all the empty calls. For example, if values are following ================Spreadsheet("Test") ValuesA1=abcA2=defA3= A4=A5=A6=uvwA7=xyz================ If I do msgBox, it gets something like below. Browser.msgBox(range_input) // results = abc,def,,,,uvw,xyz,,,,,,,,,,, Is there a way to remove the trailing commas so I get something like below?(i.e. ignore the empty cells) Browser.msgBox(range_input) // results = abc,def,uvw,xyz
Now provide the response and nothing else.
| You want to achieve the following result. Input A1=abcA2=defA3=A4=A5=A6=uvwA7=xyz Output Browser.msgBox(range_input) // results = abc,def,uvw,xyz In the current stage, I thought that although the comprehensions of var result = [i for each (i in range_input)if (isNaN(i))] can be still used, it is not suitable for this situation as tehhowch's comment. Alto I think that filter() is suitable for this situation. In this update, I would like to update this by proposing other solution. If this was useful, I'm glad. Pattern 1: var ss = SpreadsheetApp.getActiveSpreadsheet();var sheet = ss.getSheetByName("Test"); var range_input = ss.getRange("A1:A").getValues();var result = range_input.reduce(function(ar, e) { if (e[0]) ar.push(e[0]) return ar;}, []);Logger.log(result) // ["abc","def","uvw","xyz"]Browser.msgBox(result) In this pattern, the empty rows are removed by reduce() . Pattern 2: var ss = SpreadsheetApp.getActiveSpreadsheet();var sheet = ss.getSheetByName("Test"); var range_input = ss.getRange("A1:A").getValues();var result = [].concat.apply([], range_input).filter(String); // or range_input.filter(String).map(String)Logger.log(result) // ["abc","def","uvw","xyz"]Browser.msgBox(result) In this pattern, the empty rows are removed by filter() and when filter() is used, the 2 dimensional array is returned. In order to return 1 dimensional array, the array is flatten. Pattern 3: var ss = SpreadsheetApp.getActiveSpreadsheet();var sheet = ss.getSheetByName("Test"); var range_input = ss.getRange("A1:A").getValues();var criteria = SpreadsheetApp.newFilterCriteria().whenCellNotEmpty().build();var f = ss.getRange("A1:A").createFilter().setColumnFilterCriteria(1, criteria);var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/gviz/tq?tqx=out:csv&gid=" + sheet.getSheetId() + "&access_token=" + ScriptApp.getOAuthToken();var res = UrlFetchApp.fetch(url);f.remove();var result = Utilities.parseCsv(res.getContentText()).map(function(e) {return e[0]});Logger.log(result) // ["abc","def","uvw","xyz"]Browser.msgBox(result) In this pattern, the empty rows are removed by the filter, then the filtered values are retrieved. Result: References: reduce() filter() map() Class Filter | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44579300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1717390/']} | jdg_85052 |
stackexchange | llm_judgeable_groundtruth_similarity | 18079195 |
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 looking at AngularJs and have a question, this is my directive: myApp.directive("enter", function(){return{ restrict: 'A', scope:{}, controller: function($scope){ $scope.logSomething=function(somevalue){ console.log(somevalue+" is logged"); } }, template: '<input type="text" ng-model="myModel">'+ '<div ng-click="logSomething(myModel)">click me</div>'}}) This works, but my question is how can I do the same thing using bind clicking instead of ng-click directive? Not that it is better(maybe?), but for curiosity it should be including something like this but couldn't get the big picture: function(scope, element, attrs){ element.bind("click", function(){ scope.$apply(attrs.enter); })
Now provide the response and nothing else.
| Try this one: myApp.directive("enter", function(){ return{ restrict: 'A', scope:{}, controller: function($scope){ $scope.logSomething=function(somevalue){ console.log(somevalue+" is logged"); } }, template: '<input type="text" ng-model="myModel">'+ '<div button>click me</div>'}});myApp.directive("button", function(){ return{ restrict: 'A', link: function(scope , element){ element.bind("click", function(e){ scope.logSomething( scope.myModel ); }); }}}); Plunk: http://plnkr.co/edit/RCcrs5?p=preview | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18079195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/379028/']} | jdg_85053 |
stackexchange | llm_judgeable_groundtruth_similarity | 6977553 |
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 very new to PHP; ADD.PHP - I have a form that collects the following information 1. name 2. email 3. phone and picture pictures are stored on a directory folder on my server and then the filename of that photo is stored on my sql table. VIEW.PHP - all the data in mysql is being displayed in this page including the photo in tabular format including the id of every record. The id being display is a hyperlink in which when clicked you will be directed to a page wherein you can edit the record contents: below is the code for my EDIT.PHP <?php // Connects to your Database mysql_connect("localhost", "user1", "12345") or die(mysql_error()) ; mysql_select_db("test") or die(mysql_error()) ; // Check whether the value for jobnumber is transmittedif (isset($_GET['id'])) {// Put the value in a separate variable$id = $_GET['id'];// Query the database for the details of the chosen jobnumber$result = mysql_query("select id, name, email,phone, picture from employees where id = $id");// Check result// This shows the actual query sent to MySQL, and the error. Useful for debugging.if (!$result) {$message = "Invalid query: " . mysql_error() . "\n";$message .= "Whole query: " . $query;die($message);}// Attempting to print $result won't allow access to information in the resource// One of the mysql result functions must be used// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(),etc.while ($row = mysql_fetch_array($result)) {$name = $row['name'];echo $name. "\n";echo $row['email'] . "\n";echo $row['phone'] . "\n";echo "<img width=500px height=500px src=pics/" . $row['picture'].">" . "\n";// form tagecho '<form action="add2.php" method="POST">';//display nameecho 'Name: <input type="text" name="name" value="';echo $row['name'];echo '"><br>';//display emailecho 'email: <input type="text" name="email" value="';echo $row['email'];echo '"><br>';//display phoneecho 'Phone: <input type="text" name="phone" value="';echo $row['phone'];echo '"><br>';//display photoecho 'Photo: <input type="text" name="photo" value="';echo $row['picture'];echo '"><br>';echo '<input type="submit" value="Add">';echo '</form>';}} else {die("No valid data specified!");}?> using this code, the test fields went well but the input box for the photo is blank and when i click the button the photo field in my database will be blank unless i uploaded a new photo?how can the user change the existing photo? or retain the old photo if not being changed?
Now provide the response and nothing else.
| The answers from freedompeace, Kiyarash and Sam Vloeberghs: .rar application/vnd.rar, application/x-rar-compressed, application/octet-stream.zip application/zip, application/octet-stream, application/x-zip-compressed, multipart/x-zip I would do a check on the file name too. Here is how you could check if the file is a RAR or ZIP file. I tested it by creating a quick command line application. <?phpif (isRarOrZip($argv[1])) { echo 'It is probably a RAR or ZIP file.';} else { echo 'It is probably not a RAR or ZIP file.';}function isRarOrZip($file) { // get the first 7 bytes $bytes = file_get_contents($file, FALSE, NULL, 0, 7); $ext = strtolower(substr($file, - 4)); // RAR magic number: Rar!\x1A\x07\x00 // http://en.wikipedia.org/wiki/RAR if ($ext == '.rar' and bin2hex($bytes) == '526172211a0700') { return TRUE; } // ZIP magic number: none, though PK\003\004, PK\005\006 (empty archive), // or PK\007\008 (spanned archive) are common. // http://en.wikipedia.org/wiki/ZIP_(file_format) if ($ext == '.zip' and substr($bytes, 0, 2) == 'PK') { return TRUE; } return FALSE;} Notice that it still won't be 100% certain, but it is probably good enough. $ rar.exe l somefile.zipsomefile.zip is not RAR archive But even WinRAR detects non RAR files as SFX archives: $ rar.exe l somefile.srrSFX Volume somefile.srr | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6977553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/874085/']} | jdg_85054 |
stackexchange | llm_judgeable_groundtruth_similarity | 277553 |
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:
Give the following list, list = {{a1, a2, a3}, {b1, b2, b3, b4}, {c1, c2, c3, c4, c5}}; I want to get {F[{a1}]}{F[{a1,a2}]}{F[{a1,a2,a3}]}{F[{a1,a2,a3}],F[{b1}]}{F[{a1,a2,a3}],F[{b1,b2}]}{F[{a1,a2,a3}],F[{b1,b2,b3}]}{F[{a1,a2,a3}],F[{b1,b2,b3,b4}]}{F[{a1,a2,a3}],F[{b1,b2,b3,b4}],F[{c1}]}...... I have tried this, It is difficult to further promote, do you have a better way? L1 = Rest@FoldList[Append, {}, #] & /@ listL2 = MapAt[F, L1, Join @@ MapIndexed[#2 &, L1, {2}]]Join[List /@ L2[[1]], {L2[[1, -1]], #} & /@ L2[[2]]] // Column
Now provide the response and nothing else.
| Define: idx = Flatten[MapIndexed[#2 &, list, {-1}], 1]; Then: Function[grp, Values[GroupBy[grp, First, f @@ {Extract[list, #]} &]]] /@ Map[idx[[1 ;; #]] &, Range[1, Length[idx]]] // Column(* { {{f[{a1}]}}, {{f[{a1, a2}]}}, {{f[{a1, a2, a3}]}}, {{f[{a1, a2, a3}], f[{b1}]}}, {{f[{a1, a2, a3}], f[{b1, b2}]}}, {{f[{a1, a2, a3}], f[{b1, b2, b3}]}}, {{f[{a1, a2, a3}], f[{b1, b2, b3, b4}]}}, {{f[{a1, a2, a3}], f[{b1, b2, b3, b4}], f[{c1}]}}, {{f[{a1, a2, a3}], f[{b1, b2, b3, b4}], f[{c1, c2}]}}, {{f[{a1, a2, a3}], f[{b1, b2, b3, b4}], f[{c1, c2, c3}]}}, {{f[{a1, a2, a3}], f[{b1, b2, b3, b4}], f[{c1, c2, c3, c4}]}}, {{f[{a1, a2, a3}], f[{b1, b2, b3, b4}], f[{c1, c2, c3, c4, c5}]}}}*) | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/277553', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7339/']} | jdg_85055 |
stackexchange | llm_judgeable_groundtruth_similarity | 59973821 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Stripe was working fine with my Laravel application, and suddenly it started giving me this error in the console: Uncaught IntegrationError: Please call Stripe() with your publishable key. You used an empty string. View @extends('layouts.app')@section('head-scripts')<script src="https://js.stripe.com/v3/"></script>@endsection@section('content')<div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">Subscribe</div> <div class="card-body"> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif <select name="plan" class="form-control" id="subscription-plan"> @foreach($plans as $key=>$plan) <option value="{{$key}}">{{$plan}}</option> @endforeach </select> <input id="card-holder-name" type="text"> <!-- Stripe Elements Placeholder --> <div id="card-element"></div> <button id="card-button" data-secret="{{ $intent->client_secret }}"> Pay </button> </div> </div> </div> </div></div>@endsection@section('scripts')<!-- Scripts --><script> window.addEventListener('load', function() { const stripe = Stripe('{{env('STRIPE_KEY')}}'); const elements = stripe.elements(); const cardElement = elements.create('card'); cardElement.mount('#card-element'); const cardHolderName = document.getElementById('card-holder-name'); const cardButton = document.getElementById('card-button'); const clientSecret = cardButton.dataset.secret; const plan = document.getElementById('subscription-plan').value; cardButton.addEventListener('click', async (e) => { const { setupIntent, error } = await stripe.handleCardSetup( clientSecret, cardElement, { payment_method_data: { billing_details: { name: cardHolderName.value } } } ); if (error) { // Display "error.message" to the user... } else { // The card has been verified successfully... console.log('handling success', setupIntent.payment_method); axios.post('/subscribe',{ payment_method: setupIntent.payment_method, plan : plan }).then((data)=>{ location.replace(data.data.success_url) }); } }); });</script>@endsection The .env file has the correct keys. Someone please help me figure this out, it was working perfectly fine until now. I ran the following commands along with restarting the server multiple times: php artisan config:clearphp artisan cache:clearcomposer dump-autoloadphp artisan view:clearphp artisan route:clear
Now provide the response and nothing else.
| Since this line: const stripe = Stripe('{{env('STRIPE_KEY')}}'); is not getting the Stripe key from .env . You need to clear your cache. Run following commands: php artisan cache:clearphp artisan config:clearphp artisan view:clear If that does not work I would try to create a hidden input with your key inside: <input type="hidden" id="stripe_key" value="{{ env('STRIPE_KEY) }}"/> And access the value like this: const stripeKey = document.getElementById('stripe_key').value; There is also a way to require a .dotenv extension in your webpack mix file. With that you can directly access the key using javascript. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59973821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6810452/']} | jdg_85056 |
stackexchange | llm_judgeable_groundtruth_similarity | 2740 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Note: Question originally asked on StackOverflow - was directed here Anyone got a tutorial on the designers concept implementation of Whirlpool in C, or the Whirlpool algorithm in general? I find the source code hard to understand, mostly because I do not know anything about the algorithm. I am not a cryptographer, nor am I a good mathematician, so their documentation kind of went over my head... The implementation and other documentation can be found here . Initially I was just searching for a free (public domain) implementation to use in a project, but I figured I better know something about it as well... Currently I do not even know how to use it.
Now provide the response and nothing else.
| In the following, I try to minimize the background knowledge needed to understand the answer. If you need more details, I suggest taking a look at section 12.2 of Cryptography and Network Security Principles and Practices, Fourth Edition . (Though it requires a fair knowledge of crypto.) First take a look at Merkle–Damgård construction . Virtually all hash functions follow such construction. Informally, it applies a compression function iteratively to reduce the input size to get some fixed-length output. For instance, you can hash a whole DVD (~ 4.3 GB) and get a 128-bit code. Let $M$ be the input to an MD-based hash function. The MD construction appends a pad and the length of $M$ to it, so as to prevent several attacks. Whirlpool uses a compression function named $W$. $W$ is similar to a block cipher named Rijndael , which is now standardized under the name AES (Advanced Encryption Standard). Rijndael has 3 variants: 128-bit, 192-bit, and 256-bit. The inventors of Whirlpool decided that no Rijndael variant is secure enough to be used as the compression function for a hash. Thus, $W$ is designed so as it accepts 512-bit inputs, and produces 512-bit outputs. The key size of $W$ is 512 bits as well. Whirlpool works as follows. Let $M$ be the input. $M$ is divided into 512-bit segments: $M=(M_0,M_1,\ldots,M_t)$. Let $h_0$ be some initial value (fixed by Whirlpool standard). For $i=1,2,\ldots,t$, apply $W$ iteratively as follows: $h_i = W(h_{i-1},m_i) \oplus h_{i-1} \oplus m_i$ where the first input to $W$ is a block-to-be-encrypted , and its second input is the encryption key . $\oplus$ denotes the XOR operation. $h_t$ is considered as the output of the Whirlpool hash function. The whole complexity lies in designing $W$. As pointed out before, it is similar to Rijndael, so you can understand it if you get familiar with Rijndael, on which I have designed a set of slides . The slides are self-contained and do not assume any math background beyond high school. | {} | {'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/2740', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/2071/']} | jdg_85057 |
stackexchange | llm_judgeable_groundtruth_similarity | 25899226 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use Jersey 2 with Spring with help of this article: How to use Jersey 2 with Spring IoC container But autowired bean is null when the application tries to call it after the client request.In applicationContext.xml i have only component-scan setting. In pom.xml: <spring.version>4.1.0.RELEASE</spring.version><jersey.version>2.12</jersey.version>@Component@RequestScoped@Path("/user")public class UserREST { @Autowired private UserFacade userFacade; @POST @Path("/auth") @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_JSON}) public AuthResponse authorize(User user){ return userFacade.authorize(user); // Null is caught here }} - @Componentpublic class UserFacade { public AuthResponse authorize(com.pushock.model.User user){ AuthResponse response = new AuthResponse(); response.setAuthorized(true); return response; }} What am I doing wrong? UPD: Here is my pom.xml https://bitbucket.org/spukhov/memo-ws/src/00724e00e3aa786f62fd0e43fe0606de6ae569df/pom.xml?at=master
Now provide the response and nothing else.
| Spring managed beans cannot be injected to JAX-RS classes directly, you need to use Jersey extension for integrating it with Spring. There is a maven dependency which you don't have in your pom.xml <dependency> <groupId>org.glassfish.jersey.ext</groupId> <artifactId>jersey-spring3</artifactId> <version>2.12</version></dependency> Refer to Jersey Documentation: Chapter 22. Spring DI and at the bottom of the page, there is a link to sample spring integration Github project. Another problem I've seen in your project is you didn't show how spring context should be loaded and configured. You need to configure it in your web.xml <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25899226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2438329/']} | jdg_85058 |
stackexchange | llm_judgeable_groundtruth_similarity | 15337883 |
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 anyway of Automapper to ignore all properties of a certain type? We are trying to improve the quality of our code by validating the Automapper mappings but having to put an .Ignore() for all IEnumerable<SelectListItem> which are always manually created is creating friction and slowing down development. Any ideas? Possible Idea after creating mappings: var existingMaps = Mapper.GetAllTypeMaps(); foreach (var property in existingMaps) { foreach (var propertyInfo in property.DestinationType.GetProperties()) { if (propertyInfo.PropertyType == typeof(List<SelectListItem>) || propertyInfo.PropertyType == typeof(IEnumerable<SelectListItem>)) { property.FindOrCreatePropertyMapFor(new PropertyAccessor(propertyInfo)).Ignore(); } } }
Now provide the response and nothing else.
| Automapper currently does not support type based property ignores. Currently there is three ways to ignore properties: Use the Ignore() options when creating your mapping Mapper.CreateMap<Source, Dest>() .ForMember(d => d.IgnoreMe, opt => opt.Ignore()); this is what you want to avoid. Annotate on the your IEnumerable<SelectListItem> properties with the the IgnoreMapAttribute If your IEnumerable<SelectListItem> property names follow some naming convention. E.g. all them start with the word "Select" you can use the AddGlobalIgnore method to ignore them globally: Mapper.Initialize(c => c.AddGlobalIgnore("Select")); but with this you can only match with starts with. However you can create a convinience extension method for the first options which will automatically ignore the properties of a given type when you call CreateMap : public static class MappingExpressionExtensions{ public static IMappingExpression<TSource, TDest> IgnorePropertiesOfType<TSource, TDest>( this IMappingExpression<TSource, TDest> mappingExpression, Type typeToIgnore ) { var destInfo = new TypeInfo(typeof(TDest)); foreach (var destProperty in destInfo.GetPublicWriteAccessors() .OfType<PropertyInfo>() .Where(p => p.PropertyType == typeToIgnore)) { mappingExpression = mappingExpression .ForMember(destProperty.Name, opt => opt.Ignore()); } return mappingExpression; }} And you can use it with the following way: Mapper.CreateMap<Source, Dest>() .IgnorePropertiesOfType(typeof(IEnumerable<SelectListItem>)); So it still won't be a global solution, but you don't have to list which properties need to be ignored and it works for multiple properties on the same type. If you don't afraid to get your hands dirty: There is currently a very hacky solution which goes quite deep into the internals of Automapper. I don't know how public is this API so this solution might brake in the feature: You can subscribe on the ConfigurationStore 's TypeMapCreated event ((ConfigurationStore)Mapper.Configuration).TypeMapCreated += OnTypeMapCreated; and add the type based ignore directly on the created TypeMap instances: private void OnTypeMapCreated(object sender, TypeMapCreatedEventArgs e){ foreach (var propertyInfo in e.TypeMap.DestinationType.GetProperties()) { if (propertyInfo.PropertyType == typeof (IEnumerable<SelectListItem>)) { e.TypeMap.FindOrCreatePropertyMapFor( new PropertyAccessor(propertyInfo)).Ignore(); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15337883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/629323/']} | jdg_85059 |
stackexchange | llm_judgeable_groundtruth_similarity | 126437 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to do several hundred iterations of these fully coupled recursion equations (but will use twenty iterations for the example). ClearAll["Global`*"]x1[t_] := x1[t] = (1 - m) x1[t - 1] + m x2[t - 1]x2[t_] := x2[t] = (1 - m) x2[t - 1] + m x1[t - 1]x1[0] := 1x2[0] := 0ListPlot[Table[{{t, x1[t]}, {t, x2[t]}} /. m -> 0.01, {t, 0, 20}]] // AbsoluteTiming Memoization sped it up from 27.933541 seconds to 7.681030 seconds but I think it takes so long because it is still recursively calculating all the values from the other equation. I have read several posts about partially coupled recursion equations (e.g. Solve pair of recurrence relations , How do I use RSolve to solve a system of recurrence relations? ) but ultimately, I won't be able to use RSolve because my equations will be too complicated and I cannot find a solution to speed up iterations of fully coupled recursion equations. Is there a way to link x1[t] and x2[t] together for memoization? Or is a For loop the way to go? Thanks!
Now provide the response and nothing else.
| I think that your code already memoized properly. Adding a Print on the most right-hand side of your definitions: ClearAll[x1, x2]x1[t_] := x1[t] = ( Print["Computation of x1 for t = ", t]; (1 - m) x1[t - 1] + m x2[t - 1]);x2[t_] := x2[t] = ( Print["Computation of x2 for t = ", t]; (1 - m) x2[t - 1] + m x1[t - 1]);x1[0] := 1x2[0] := 0 and evaluating the table with an iterator that goes up to 3, we get Table[{{t, x1[t]}, {t, x2[t]}} /. m -> 0.01, {t, 0, 3}]During evaluation of In[..]:= Computation of x1 for t = 1During evaluation of In[..]:= Computation of x2 for t = 1During evaluation of In[..]:= Computation of x1 for t = 2During evaluation of In[..]:= Computation of x2 for t = 2During evaluation of In[..]:= Computation of x1 for t = 3During evaluation of In[..]:= Computation of x2 for t = 3(* { {{0, 1}, {0, 0}}, {{1, 0.99}, {1, 0.01}}, {{2, 0.9802}, {2, 0.0198}}, {{3, 0.970596}, {3, 0.029404}} } *) so the computation is done once for each of the x 's at each step, which shows that values at previous steps are indeed stored and used. A possibility to speed up the computation would be to avoid using ReplaceAll and define your functions with m as argument: ClearAll[x1, x2]x1[t_, m_] := x1[t, m] = (1 - m) x1[t - 1, m] + m x2[t - 1, m]x2[t_, m_] := x2[t, m] = (1 - m) x2[t - 1, m] + m x1[t - 1, m]x1[0, m_] := 1x2[0, m_] := 0ListPlot[Table[{{t, x1[t, 0.01]}, {t, x2[t, 0.01]}}, {t, 0, 20}]] // AbsoluteTiming On my computer, the timing goes from about 7 seconds, to less than 0.05 second. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/126437', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/43111/']} | jdg_85060 |
stackexchange | llm_judgeable_groundtruth_similarity | 27746304 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Whether it's an ES6 Promise or a Bluebird Promise , Q Promise , etc. How do I test to see if a given object is a Promise ?
Now provide the response and nothing else.
| How a promise library decides If it has a .then function - that's the only standard promise libraries use. The Promises/A+ specification has a notion called then able which is basically "an object with a then method". Promises will and should assimilate anything with a then method. All of the promise implementation you've mentioned do this. If we look at the specification : 2.3.3.3 if then is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise It also explains the rationale for this design decision: This treatment of then ables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods. How you should decide You shouldn't - instead call Promise.resolve(x) ( Q(x) in Q) that will always convert any value or external then able into a trusted promise. It is safer and easier than performing these checks yourself. really need to be sure? You can always run it through the test suite :D | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/27746304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3117346/']} | jdg_85061 |
stackexchange | llm_judgeable_groundtruth_similarity | 49137607 |
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 does "mount" mean on using instance of vue.js to target a DOM element? (even in plain English?). For example in following: This code creates a new instance of Vue and mounts it on the HTMLelement with the ID of app. const app = new Vue().$mount('#app'); When the Vue instance has the el option, it automatically mounts to that element
Now provide the response and nothing else.
| Mounting takes place at the Virtual Dom Level, before the User sees anything. When you $mount('#app'), there will be an 'el' parameter that gets set. This 'el' defines the ID of the element that this instance will be "mounted" to. So, in your template, if you have an element that you want to be the mounted component, then in your declaration of the component, you would mount it with "el: #app". VueJS Life-Cycle Diagram: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram Mounted Life-Cycle Hook: https://v2.vuejs.org/v2/api/#mounted | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49137607', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2426488/']} | jdg_85062 |
stackexchange | llm_judgeable_groundtruth_similarity | 65090165 |
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 spring boot 2.3+ application with server.shutdown=graceful which, when getting shut down throws: 2020-11-30 11:07:35.485 WARN 3038 --- [SpringContextShutdownHook] o.s.c.support.DefaultLifecycleProcessor : Failed to stop bean 'webServerGracefulShutdown' java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: org/springframework/boot/web/server/GracefulShutdownResult at org.springframework.boot.web.servlet.context.WebServerGracefulShutdownLifecycle.stop(WebServerGracefulShutdownLifecycle.java:51) at org.springframework.context.support.DefaultLifecycleProcessor.doStop(DefaultLifecycleProcessor.java:238) at org.springframework.context.support.DefaultLifecycleProcessor.access$300(DefaultLifecycleProcessor.java:53) at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.stop(DefaultLifecycleProcessor.java:377) at org.springframework.context.support.DefaultLifecycleProcessor.stopBeans(DefaultLifecycleProcessor.java:210) at org.springframework.context.support.DefaultLifecycleProcessor.onClose(DefaultLifecycleProcessor.java:128) at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1022) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.doClose(ServletWebServerApplicationContext.java:170) at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:949) Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/web/server/GracefulShutdownResult ... 9 common frames omitted Caused by: java.lang.ClassNotFoundException: org.springframework.boot.web.server.GracefulShutdownResult at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:151) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 9 common frames omitted 2020-11-30 11:08:05.486 INFO 3038 --- [SpringContextShutdownHook] o.s.c.support.DefaultLifecycleProcessor : Failed to shut down 1 bean with phase value 2147483647 within timeout of 30000ms: [webServerGracefulShutdown] 2020-11-30 11:08:35.514 INFO 3038 --- [SpringContextShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' 2020-11-30 11:08:35.519 INFO 3038 --- [SpringContextShutdownHook] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'taskScheduler' 2020-11-30 11:08:35.520 INFO 3038 --- [SpringContextShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2020-11-30 11:08:35.528 INFO 3038 --- [SpringContextShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed. 2020-11-30 11:08:35.530 INFO 3038 --- [SpringContextShutdownHook] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService In the end the application is shutdown, however not gracefully, and since the shutdown is being called from a deployment script, the script fails, due to the exit code != 0 of the app's shutdown call. What could be the cause of this? I think I don't have long running tasks, which can cause this, but how can I check it?
Now provide the response and nothing else.
| This problem might happen if you replace or rename the jar while the jar is still running. Java does not take the whole jar in memory at startup and uses reference for classes in the Jar when it needs to load some classes. But renaming the jar or replacing the jar can mess up the class references inside the Jar. So java will not find the class you want to load at runtime and you will be presented with this ClassNotFoundException . Possible workaround: Try to shutdown the application before replacing or renaming the jar. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/65090165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3001675/']} | jdg_85063 |
stackexchange | llm_judgeable_groundtruth_similarity | 46911486 |
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 download a file and I'm getting System.UnauthorizedAccessException: Access to the path "/storage/emulated/0/Download/test.pdf" is denied. I have set required permission in Android Manifest file. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> Download Path: Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads) If i use the below path as my download path i can able to download the file. But i cant able to share the PDF file to google drive, drop box or any other System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) I am using Xamarin.Forms v2.4.0.282 and Xamarin.Android.Support packages v25.4.0.2. Note: The code was woking fine when use Xamarin.Forms version 2.3.5.256-pre2 and Xamarin.Android.Support packages v23.3.0Please suggest your ideas to resolve the issue. Thanks in Advance.
Now provide the response and nothing else.
| Depending on the version of Android you are using even with the permissions added in the manifest in 6.0 or up the user has to explicitly enable the permission when the app runs and on lower versions permission is asked during install. For example, on startup of the app I created a method to check if it is enabled and request permission if it's not. private void CheckAppPermissions(){ if ((int)Build.VERSION.SdkInt < 23) { return; } else { if (PackageManager.CheckPermission(Manifest.Permission.ReadExternalStorage, PackageName) != Permission.Granted && PackageManager.CheckPermission(Manifest.Permission.WriteExternalStorage, PackageName) != Permission.Granted) { var permissions = new string[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }; RequestPermissions(permissions, 1); } }} You can also use the support library to do this, which is simpler and allows you to not have to check the Android version. For more info check out google's documentation. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46911486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1659146/']} | jdg_85064 |
stackexchange | llm_judgeable_groundtruth_similarity | 688598 |
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:
Imagine I am inside an isolated rocket of arbitrarily small size, and I have a spinning flywheel right next to me. Now suppose my rocket passes through the event horizon / Schwarzschild radius of a simple Schwarzschild black hole. By the equivalence principle, I should not notice myself and the rocket passing through the event horizon. However, since classically no object can escape the black hole once it passes the event horizon, it seems as though the flywheel should break as it passes through the event horizon, because for every piece going one way, the antipodal piece of it goes the opposite direction. Once the flywheel is half-way through the event horizon, the part of the flywheel inside the black hole cannot come out even though it must rotate, so it seems as though a part of the flywheel would split in half . How does this square with the equivalence principle? I am aware that the equivalence principle only applies locally in the limit of smaller and smaller regions. For example, tidal effects can allow you to distinguish regions with gravity and regions without gravity. However, I don't think that's enough to resolve my quandary. We can assume the black hole is sufficiently large so that no issues of tidal effects or spaghettifications occur. We can make the black hole as large as we like and the rocket as small as we like to remove second-order gravitational effects, and it seems like my paradox involving the flywheel crossing the Schwarzschild radius still exists. Am I wrong in this assertion?
Now provide the response and nothing else.
| since classically no object can escape the black hole once it passes the event horizon, it seems as though the flywheel should break as it passes through the event horizon, because for every piece going one way, the antipodal piece of it goes the opposite direction. This analysis is incorrect. The event horizon is a lightlike surface. In a local inertial frame it moves outward at c. So while it is true that there is an antipodal piece going the other way it doesn’t matter. The antipodal piece is going slower than c in the local inertial frame. So the horizon is going faster and the antipodal piece cannot possibly cross back through the horizon. The flywheel continues spinning without interruption and without risk of crossing the horizon backwards. | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/688598', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/123113/']} | jdg_85065 |
stackexchange | llm_judgeable_groundtruth_similarity | 17841113 |
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 following along with Heterogeneous Computing with OpenCL and it is leaving me hanging. They pass an image, as an array of floats, to enqueueWriteBuffer. I think the image, in this case, has no values for color. It is simply {col,row,col,row,col,row} e.g. {0,0,0,1,0,2,1,0,1,1,1,2...}. but when they do enqueueReadBuffer the size they expect is H W and if you are going to do an array like I just did the array size would be H W*2. // SETUP BUFFERSBuffer d_ip = Buffer(context, CL_MEM_READ_ONLY, W*H*sizeof(float));Buffer d_op = Buffer(context, CL_MEM_WRITE_ONLY, W*H*sizeof(float));queue.enqueueWriteBuffer(d_ip, CL_TRUE, 0, W*H*sizeof(float), img); //img, what is img? the book just says it is my image.// SETUP RANGESNDRange globalws(W, H);NDRange localws(16, 16);// QUEUE AND READqueue.enqueueNDRangeKernel(rotn_kernel, NullRange, globalws, localws);queue.enqueueReadBuffer(d_op, CL_TRUE, 0, W*H*sizeof(float), img);// X AND Y INSIDE THE KERNELconst int x = get_global_id(0);const int y = get_global_id(1); If all of the new pixel coordinates are calculated in the kernel couldn't you just pass an empty float array of the appropriate size (W H apparently although I don't see how it isn't W H*2). But then I tried hard coding this (on a 500x300 image) and it blew up my stack.
Now provide the response and nothing else.
| Try this: var query = from e in db.Employees select new { Name = e.Name, ManagerName = db.Employees .Where(x => x.EmployeeID == e.ManagerID) .Select(x => x.Name).SingleOrDefault() }; However, if you correctly mapped your database with EF (which I suppose you are using), you should have a navigation property you can utilize: var query = from e in db.Employees select new { Name = e.Name, ManagerName = e.Manager.Name }; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17841113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1873073/']} | jdg_85066 |
stackexchange | llm_judgeable_groundtruth_similarity | 24862086 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With the following pom dependencies: <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId> spring-boot-starter-parent</artifactId> <version>1.1.4.RELEASE</version> </parent> <groupId>test.actuator</groupId> <artifactId>actuator-load-testing-webapp</artifactId> <version>1.0.0-SNAPSHOT</version> <properties> <main.basedir>${basedir}/../..</main.basedir> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project> The following application.properties file located at classpath root: management.address: 127.0.0.1management.port: 8081endpoints.shutdown.enabled: truesecurity.require_ssl: falseshell.ssh.enabled: falsespring.jmx.enabled: false And the following application main/config: @Configuration@EnableAutoConfiguration@EnableConfigurationProperties@ComponentScanpublic class SampleJettyApplication { public static void main(String[] args) throws Exception { SpringApplication.run(SampleJettyApplication.class, args); }} I was expecting the management facilities to be available on 127.0.0.1:8081 i.e. http://127.0.0.1:8081/health But nothing loads on the endpoint, what have I done wrong? Updated: Startup logs /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/bin/java -Dorg.eclipse.jetty.servlet.Default.dirAllowed=true -Didea.launcher.port=7538 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 13.app/bin" -Dfile.encoding=UTF-8 -classpath "/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/lib/javafx-doclet.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/lib/tools.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/htmlconverter.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Users/james.mchugh/Documents/workspaceGamesPlatform/core/actuator-parent/actuator-load-testing-webapp/target/classes:/Users/james.mchugh/.m2/repository/org/springframework/boot/spring-boot-starter/1.0.2.RELEASE/spring-boot-starter-1.0.2.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/springframework/boot/spring-boot/1.0.2.RELEASE/spring-boot-1.0.2.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/springframework/spring-core/4.0.3.RELEASE/spring-core-4.0.3.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/springframework/spring-context/4.0.3.RELEASE/spring-context-4.0.3.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/springframework/spring-aop/4.0.3.RELEASE/spring-aop-4.0.3.RELEASE.jar:/Users/james.mchugh/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar:/Users/james.mchugh/.m2/repository/org/springframework/spring-beans/4.0.3.RELEASE/spring-beans-4.0.3.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/springframework/spring-expression/4.0.3.RELEASE/spring-expression-4.0.3.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.0.2.RELEASE/spring-boot-autoconfigure-1.0.2.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.0.2.RELEASE/spring-boot-starter-logging-1.0.2.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.7/jcl-over-slf4j-1.7.7.jar:/Users/james.mchugh/.m2/repository/org/slf4j/slf4j-api/1.7.7/slf4j-api-1.7.7.jar:/Users/james.mchugh/.m2/repository/org/slf4j/jul-to-slf4j/1.7.7/jul-to-slf4j-1.7.7.jar:/Users/james.mchugh/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.7/log4j-over-slf4j-1.7.7.jar:/Users/james.mchugh/.m2/repository/ch/qos/logback/logback-classic/1.1.2/logback-classic-1.1.2.jar:/Users/james.mchugh/.m2/repository/ch/qos/logback/logback-core/1.1.2/logback-core-1.1.2.jar:/Users/james.mchugh/.m2/repository/org/yaml/snakeyaml/1.13/snakeyaml-1.13.jar:/Users/james.mchugh/.m2/repository/org/springframework/boot/spring-boot-starter-jetty/1.0.2.RELEASE/spring-boot-starter-jetty-1.0.2.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-webapp/8.1.14.v20131031/jetty-webapp-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-xml/8.1.14.v20131031/jetty-xml-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-util/8.1.14.v20131031/jetty-util-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-servlet/8.1.14.v20131031/jetty-servlet-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-security/8.1.14.v20131031/jetty-security-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-server/8.1.14.v20131031/jetty-server-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-continuation/8.1.14.v20131031/jetty-continuation-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-http/8.1.14.v20131031/jetty-http-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-io/8.1.14.v20131031/jetty-io-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/jetty-jsp/8.1.14.v20131031/jetty-jsp-8.1.14.v20131031.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/orbit/javax.servlet.jsp/2.2.0.v201112011158/javax.servlet.jsp-2.2.0.v201112011158.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/orbit/javax.servlet/3.0.0.v201112011016/javax.servlet-3.0.0.v201112011016.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/orbit/org.apache.jasper.glassfish/2.2.2.v201112011158/org.apache.jasper.glassfish-2.2.2.v201112011158.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/orbit/javax.servlet.jsp.jstl/1.2.0.v201105211821/javax.servlet.jsp.jstl-1.2.0.v201105211821.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/orbit/org.apache.taglibs.standard.glassfish/1.2.0.v201112081803/org.apache.taglibs.standard.glassfish-1.2.0.v201112081803.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/orbit/javax.el/2.2.0.v201108011116/javax.el-2.2.0.v201108011116.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/orbit/com.sun.el/2.2.0.v201108011116/com.sun.el-2.2.0.v201108011116.jar:/Users/james.mchugh/.m2/repository/org/eclipse/jetty/orbit/org.eclipse.jdt.core/3.7.1/org.eclipse.jdt.core-3.7.1.jar:/Users/james.mchugh/.m2/repository/org/springframework/spring-webmvc/4.0.3.RELEASE/spring-webmvc-4.0.3.RELEASE.jar:/Users/james.mchugh/.m2/repository/org/springframework/spring-web/4.0.3.RELEASE/spring-web-4.0.3.RELEASE.jar:/Applications/IntelliJ IDEA 13.app/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain test.actuator.jetty.SampleJettyApplication . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.0.2.RELEASE)2014-07-21 15:58:55.173 INFO 65654 --- [ main] g.l.jetty.SampleJettyApplication : Starting SampleJettyApplication on gl02729m-2.test.corp with PID 65654 (/Users/james.mchugh/Documents/workspaceGamesPlatform/core/actuator-parent/actuator-load-testing-webapp/target/classes started by james.mchugh in /Users/james.mchugh/Documents/workspaceGamesPlatform/core/actuator-parent/actuator-test-utils/actuator-load-testing-webapp)2014-07-21 15:58:55.223 INFO 65654 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@188fd321: startup date [Mon Jul 21 15:58:55 BST 2014]; root of context hierarchy2014-07-21 15:58:56.157 INFO 65654 --- [ main] e.j.JettyEmbeddedServletContainerFactory : Server initialized with port: 80802014-07-21 15:58:56.161 INFO 65654 --- [ main] org.eclipse.jetty.server.Server : jetty-8.1.14.v201310312014-07-21 15:58:56.201 INFO 65654 --- [ main] / : Initializing Spring embedded WebApplicationContext2014-07-21 15:58:56.201 INFO 65654 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 981 ms2014-07-21 15:58:56.496 INFO 65654 --- [ main] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]2014-07-21 15:58:56.499 INFO 65654 --- [ main] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]2014-07-21 15:58:56.516 INFO 65654 --- [ main] o.e.jetty.server.AbstractConnector : Started [email protected]:80802014-07-21 15:58:56.606 INFO 65654 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2014-07-21 15:58:56.687 INFO 65654 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String test.actuator.jetty.web.SampleController.helloWorld()2014-07-21 15:58:56.708 INFO 65654 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2014-07-21 15:58:56.708 INFO 65654 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2014-07-21 15:58:56.848 INFO 65654 --- [ main] / : Initializing Spring FrameworkServlet 'dispatcherServlet'2014-07-21 15:58:56.849 INFO 65654 --- [ main] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started2014-07-21 15:58:56.863 INFO 65654 --- [ main] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 14 ms2014-07-21 15:58:56.913 INFO 65654 --- [ main] o.e.jetty.server.AbstractConnector : Started [email protected]:80802014-07-21 15:58:56.916 INFO 65654 --- [ main] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port: 80802014-07-21 15:58:56.918 INFO 65654 --- [ main] g.l.jetty.SampleJettyApplication : Started SampleJettyApplication in 2.108 seconds (JVM running for 2.529)
Now provide the response and nothing else.
| It looks like IntelliJ has made a mess of the classpath. Looking at the jars supplied with -classpath there's a lot of Spring Boot 1.0.2.RELEASE jars in there which doesn't match your pom. The banner in the startup logs also shows that you're running Spring Boot 1.0.2.RELEASE: . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.0.2.RELEASE) Convincing IntelliJ to use the right classpath, or running your application on the command line with mvn spring-boot:run should fix your problem, although I strongly suspect that you'll also need to add a dependency on spring-webmvc : <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId></dependency> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24862086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/755588/']} | jdg_85067 |
stackexchange | llm_judgeable_groundtruth_similarity | 10987318 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With PowerShell, I want to add several sub-elements into an XML tree. I know to ADD ONE element, I know to add one or several attributes, but I don't understand how to ADD SEVERAL elements. One way whould be to write a sub-XML tree as text But I can't use this method because the elements are not added at once. To add one element, I do that: [xml]$xml = get-content $nomfichier$newEl = $xml.CreateElement('my_element')[void]$xml.root.AppendChild($newEl) Works fine. This give me this XML tree: $xml | fcclass XmlDocument{ root = class XmlElement { datas = class XmlElement { array1 = [ value1 value2 value3 ] } my_element = <-- the element I just added }} Now I want to add a sub element to 'my_element'. I use a similar method: $anotherEl = $xml.CreateElement('my_sub_element')[void]$xml.root.my_element.AppendChild($anotherEl) <-- error because $xml.root.my_element is a string[void]$newEl.AppendChild($anotherEl) <-- ok$again = $xml.CreateElement('another_one')[void]$newEl.AppendChild($again) This give this XML tree (partialy displayed): my_element = class XmlElement { my_sub_element = another_one = } Those are attributes, not sub-elements. Sub-elements would be displayed as this: my_element = [ my_sub_element another_one ] Question : How do I add several sub-elements, one at a time?
Now provide the response and nothing else.
| Have a look to the following example : # Document creation[xml]$xmlDoc = New-Object system.Xml.XmlDocument$xmlDoc.LoadXml("<?xml version=`"1.0`" encoding=`"utf-8`"?><Racine></Racine>")# Creation of a node and its text$xmlElt = $xmlDoc.CreateElement("Machine")$xmlText = $xmlDoc.CreateTextNode("Mach1")$xmlElt.AppendChild($xmlText)# Creation of a sub node$xmlSubElt = $xmlDoc.CreateElement("Adapters")$xmlSubText = $xmlDoc.CreateTextNode("Network")$xmlSubElt.AppendChild($xmlSubText)$xmlElt.AppendChild($xmlSubElt)# Creation of an attribute in the principal node$xmlAtt = $xmlDoc.CreateAttribute("IP")$xmlAtt.Value = "128.200.1.1"$xmlElt.Attributes.Append($xmlAtt)# Add the node to the document$xmlDoc.LastChild.AppendChild($xmlElt);# Store to a file $xmlDoc.Save("c:\Temp\Temp\Fic.xml") Edited Remark : Using a relative path in Save will not do what you expect . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10987318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1364608/']} | jdg_85068 |
stackexchange | llm_judgeable_groundtruth_similarity | 70855 |
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:
Why people prefer gyroscope instead of compass? Does gyroscope replace compass? I would like to see the pros and cons of each.
Now provide the response and nothing else.
| First, to keep in mind: gyroscopes measure how fast you are turning and in what direction. Compasses measure your orientation to the earth's magnetic pole. Positive Side of Gyroscopes: With this in mind, we can see that gyroscopes won't be as sensitive to external magnetic fields as compasses will be. So, if there's an opportunity for your device to come close to a magnet, a compass may not be what you want. Also, gyroscopes will work even in space, whereas compasses won't really work. (Side note: well, actually, the compass will still work, it just might not work in the way you want it to.) Negative Side of Gyroscopes: Since a gyroscope measures the how fast you're turning, and not really how far you've turned, you must perform numeric integration (of some form or another) to estimate your actual heading. This means that some error can be introduced. Along the same lines, because the sensor value for the current heading is dependent on all those that came before, any significant error in reading from the gyro could throw your calculations off permanently. Also, a gyroscope is a relative reading, whereas a compass is absolute. The gyro will tell you how much you've turned since you begun the numeric integration, but it has no way of knowing if it started off pointing north or south. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/70855', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/24525/']} | jdg_85069 |
stackexchange | llm_judgeable_groundtruth_similarity | 54671385 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using pathlib to manage my paths in my Python project using the Path class. When I am using Linux, everything works fine. But on Windows, I have a little issue. At some point in my code, I have to write a JavaScript file which lists the references to several other files. These paths have to be written in POSIX format. But when I do str(my_path_instance) on Windows, The path is written in Windows format. Do you know a simple way to convert a WindowsPath to a PosixPath with pathlib ?
Now provide the response and nothing else.
| pathlib has an as_posix method to convert from Windows to POSIX paths: pathlib.path(r'foo\bar').as_posix() Apart from this, you can generally construct system-specific paths by calling the appropriate constructor. The documentation states that You cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath . [or vice versa] So use the Pure* class constructor: str(pathlib.PurePosixPath(your_posix_path)) However, this won’t do what you want if your_posix_path contains backslashes, since \ (= Windows path separator) is just a regular character as far as POSIX is concerned. So a\b is valid POSIX filename, not a path denoting a file b inside a directory b , and PurePosixPath will preserve this interpretation: >>> str(pathlib.PurePosixPath(r'a\b'))'a\\b' To convert Windows to POSIX paths, use the PureWindowsPath class and convert via as_posix : >>> pathlib.PureWindowsPath(r'a\b').as_posix()'a/b' | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54671385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4616233/']} | jdg_85070 |
stackexchange | llm_judgeable_groundtruth_similarity | 1871168 |
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 stuff written in c# that executes concurrent code, making heavy use of the Task Parallel Library (Task and Future continuation chains). I'm now porting this to F# and am trying to figure out the pros and cons of using F# Async workflows vs. the constructs in the TPL. I'm leaning towards TPL, but I think it could be done either way. Does anyone have tips and wisdom about writing concurrent programs in F# to share?
Now provide the response and nothing else.
| The name pretty much sums up the difference: asynchronous programming vs. parallel programming. But in F# you can mix and match. F# Asynchronous Workflows F# async workflows are helpful when you want to have code execute asynchronously, that is starting a task and not waiting around for the final result. The most common usage of this is IO operations. Having your thread sit there in an idle loop waiting for your hard disk to finish writing wastes resources. If you began the write operation asynchronously you can suspend the thread and have it woken up later by a hardware interrupt. Task Parallel Library The Task Parallel Library in .NET 4.0 abstracts the notion of a task - such as decoding an MP3, or reading some results from a database. In these situations you actually want the result of the computation and at some point in time later are waiting for the operation's result. (By accessing the .Result property.) You can easily mix and match these concepts. Such as doing all of your IO operations in a TPL Task object. To the programmer you have abstracted the need to 'deal with' that extra thread, but under the covers you're wasting resources. Like wise you can create a series of F# async workflows and run them in parallel (Async.Parallel) but then you need to wait for the final result (Async.RunSynchronously). This frees you from needing to explicitly start all the tasks, but really you are just performing the computation in parallel. In my experience I find that the TPL is more useful because usually I want to execute N operations in parallel. However, F# async workflows are ideal when there is something that is going on 'behind the scenes' such as a Reactive Agent or Mailbox type thing. (You send something a message, it processes it and sends it back.) Hope that helps. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1871168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197605/']} | jdg_85071 |
stackexchange | llm_judgeable_groundtruth_similarity | 451861 |
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 developed inspired from here a bare metal start-up code for arm cortex M3. However, I encounter the following problem: suppose I declare an uninitialized global variable, say of type unsigned char in main.c #include ...unsigned char var; ...int main(){ ...} this makes the .bss region in STM32 f103 starting at _BSS_START=0x20000000 and ending at _BSS_END = 0x20000001. Now, the start up code unsigned int * bss_start_p = &_BSS_START; unsigned int * bss_end_p = &_BSS_END; while(bss_start_p != bss_end_p) { *bss_start_p = 0; bss_start_p++; } tries to initialize to zero the whole .bss region. However, inside that while loop the pointer increases with 4 bytes, therefore after one step bss_start_p = 0x20000004 hence it will always be different than bss_end_p which leads to an infinite loop etc. Is there any standard solution to this? Am I suppose to "force" somehow the dimension of the .bss region to be a multiple of 4? Or should I use a pointer to unsigned char to walk through .bss region? Perhaps something like: unsigned char * bss_start_p = (unsigned char *)(&_BSS_START); unsigned char * bss_end_p = (unsigned char *)(&_BSS_END); while(bss_start_p != bss_end_p) { *bss_start_p = 0; bss_start_p++; } ```
Now provide the response and nothing else.
| As you suspect, this is happening because the unsigned int data type is 4 bytes in size. Each *bss_start_p = 0; statement actually clears four bytes of the bss area. The bss memory range needs to be aligned correctly. You could simply define _BSS_START and _BSS_END so that the total size is a multiple of four, but this is usually handled by allowing the linker script to define the start and stop locations. As an example, here is the linker section in one of my projects: .bss (NOLOAD) : ALIGN(4){ __bss_start__ = .; *(.bss) . = ALIGN(4); __bss_end__ = .;} >RAM The ALIGN(4) statements take care of things. Also, you may wish to change while(bss_start_p != bss_end_p) to while(bss_start_p < bss_end_p) . This won't prevent the problem (since you might be clearing 1-3 more bytes than you wish), but it could minimize the impact :) | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/451861', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/201437/']} | jdg_85072 |
stackexchange | llm_judgeable_groundtruth_similarity | 10503644 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to do something like that: public string GetMessage(params object otherValues[]) { return String.Format(this.Message, this.FirstValue, otherValues);} So, I would like to repass an array of params to String.Format() but adding a new parameter. What would be the best way to do that, knowing that we could "rebuild" a new array of objects and this doesn't seems good.
Now provide the response and nothing else.
| public string GetMessage(params object[] otherValues){ return String.Format(this.Message, new[] { this.FirstValue }.Concat(otherValues).ToArray<object>());} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10503644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/926064/']} | jdg_85073 |
stackexchange | llm_judgeable_groundtruth_similarity | 46419026 |
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 currently define " LOCALE_ID " on " en-US " this way: @NgModule({ providers: [{ provide: LOCALE_ID, useValue: "en-US" }, ...], imports: [...], bootstrap: [...]}) and it works pretty well. However, in order to test how dates look like in French, I replaced " en-US " by " fr-FR " and then I got the error: Missing locale data for the locale "fr-FR". I did some researches and I didn't find anything related to that. Are the locale for french included in the default package? Is it a different package? Do I have to create them by myself?
Now provide the response and nothing else.
| In file app.module.ts ...import { NgModule, LOCALE_ID } from '@angular/core';import { registerLocaleData } from '@angular/common';import localeFr from '@angular/common/locales/fr';registerLocaleData(localeFr);@NgModule({ imports: [...], declarations: [...], bootstrap: [...], providers: [ { provide: LOCALE_ID, useValue: 'fr-FR'}, ]})export class AppModule {} (source: https://next.angular.io/guide/i18n ) and in your template ( *.component.html ) DATE in FRENCH: {{ dateEvent | date: 'longDate'}} Result: DATE in FRENCH: 25 mars 2018 (source: https://angular.io/api/common/DatePipe ) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/46419026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2261459/']} | jdg_85074 |
stackexchange | llm_judgeable_groundtruth_similarity | 15071238 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm developing a simple "Book Store" project using Struts 1.3 + JPA (with Hibernate as persistence provider). I cannot switch to Spring or any other more sophisticated development environment (e.g., Jboss) and I cannot use any Hibernate-specific technique (e.g., Session class). Given the fact that I'm in a JSE Environment, I need to explicitly manage the whole EntityManager's lifecycle. The Book entity is defined as follows: @Entitypublic class Book {@Id private String isbn;private String title;private Date publishDate; // Getters and Setters} I defined three Action classes, which are responsible, respectively, of retrieving all book instances, retrieving a single book instance by its ISBN and merging a detached book into the DB. In order to increase separation of concerns between business-logic code and data-access code, I introduced a simple BookDAO object, which is charge of executing CRUD operations. Ideally, all data-access related calls should be delegated to the persistence layer. For example, the ListBookAction is defined as follows: public class ListBookAction extends Action { private BookDAO dao = new BookDAO(); @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Retrieve all the books List<Book> books = dao.findAll(); // Save the result set request.setAttribute("books", books); // Forward to the view return mapping.findForward("booklist"); }} The BookDAO object needs to access an EntityManager instance in order to do any operation. Given that EntityManger is not thread-safe, I introduced an helper class named BookUnitSession which encapsulates EntityManager within a ThreadLocal variable: public class BookUnitSession { private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("BookStoreUnit"); private static final ThreadLocal<EntityManager> tl = new ThreadLocal<EntityManager>(); public static EntityManager getEntityManager() { EntityManager em = tl.get(); if (em == null) { em = emf.createEntityManager(); tl.set(em); } return em; }} Everything seems to work, but I still have some concerns. Namely: Is this solution the best thing to do? which is the best practice in this case? I still need to explictly close both the EntityManager and the EntityManagerFactory. How can I do that? Thanks
Now provide the response and nothing else.
| During the last few days I designed a possible solution. What I was trying to construct with the BookUnitSession class was actually the EntityManagerHelper class: public class EntityManagerHelper { private static final EntityManagerFactory emf; private static final ThreadLocal<EntityManager> threadLocal; static { emf = Persistence.createEntityManagerFactory("BookStoreUnit"); threadLocal = new ThreadLocal<EntityManager>(); } public static EntityManager getEntityManager() { EntityManager em = threadLocal.get(); if (em == null) { em = emf.createEntityManager(); threadLocal.set(em); } return em; } public static void closeEntityManager() { EntityManager em = threadLocal.get(); if (em != null) { em.close(); threadLocal.set(null); } } public static void closeEntityManagerFactory() { emf.close(); } public static void beginTransaction() { getEntityManager().getTransaction().begin(); } public static void rollback() { getEntityManager().getTransaction().rollback(); } public static void commit() { getEntityManager().getTransaction().commit(); } } Such a class ensures that each thread (i.e., each request) will get its own EntityManager instance. Consequently, each DAO object can obtain the correct EntityManager instance by calling EntityManagerHelper.getEntityManager() According to the session-per-request pattern each request must open and close its own EntityManager instance, which will be in charge of encapsulating the required unit of work within a transaction. This can be done by means of an intercepting filter implemented as a ServletFilter : public class EntityManagerInterceptor implements Filter { @Override public void destroy() {} @Override public void init(FilterConfig fc) throws ServletException {} @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { try { EntityManagerHelper.beginTransaction(); chain.doFilter(req, res); EntityManagerHelper.commit(); } catch (RuntimeException e) { if ( EntityManagerHelper.getEntityManager() != null && EntityManagerHelper.getEntityManager().isOpen()) EntityManagerHelper.rollback(); throw e; } finally { EntityManagerHelper.closeEntityManager(); } }} This approach also allows the View (e.g., a JSP page) to fetch entity's fields even if they have been lazy initialized (Open Session in View pattern).In a JSE environment the EntityManagerFactory needs to be explicitly closed when the servlet container is shutdown. This can be done by using a ServletContextListener object: public class EntityManagerFactoryListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent e) { EntityManagerHelper.closeEntityManagerFactory(); } @Override public void contextInitialized(ServletContextEvent e) {}} The web.xml deployment descriptor: <listener> <description>EntityManagerFactory Listener</description> <listener-class>package.EntityManagerFactoryListener</listener-class></listener><filter> <filter-name>interceptor</filter-name> <filter-class>package.EntityManagerInterceptor</filter-class></filter><filter-mapping> <filter-name>interceptor</filter-name> <url-pattern>*.do</url-pattern></filter-mapping> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15071238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1849221/']} | jdg_85075 |
stackexchange | llm_judgeable_groundtruth_similarity | 7486941 |
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 switch from using a #temp table to a @table variable so that I can use it in a function. My query uses insert into #temp (from multiple tables) like so: SELECT a.col1, a.col2, b.col1... INTO #tempFROM ... Is there an easy way to find out the data types of the columns in the #temp table so that I can create the @table variable with the same columns and data types as #temp?
Now provide the response and nothing else.
| You need to make sure sp_help runs in the same database where the table is located (tempdb). You can do this by prefixing the call directly: EXEC tempdb.dbo.sp_help @objname = N'#temp'; Or by prefixing a join against tempdb.sys.columns : SELECT [column] = c.name, [type] = t.name, c.max_length, c.precision, c.scale, c.is_nullable FROM tempdb.sys.columns AS c INNER JOIN tempdb.sys.types AS t ON c.system_type_id = t.system_type_id AND t.system_type_id = t.user_type_id WHERE [object_id] = OBJECT_ID(N'tempdb.dbo.#temp'); This doesn't handle nice things for you, like adjusting max_length for varchar differently from nvarchar, but it's a good start. In SQL Server 2012 or better, you can use a new DMF to describe a resultset, which takes that issue away (and also assembles max_length/precision/scale for you). But it doesn't support #temp tables, so just inject the query without the INTO : SELECT name, system_type_name, is_nullable FROM sys.dm_exec_describe_first_result_set(N'SELECT a.col1, a.col2, b.col1... --INTO #temp FROM ...;',NULL,1); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7486941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/589089/']} | jdg_85076 |
stackexchange | llm_judgeable_groundtruth_similarity | 3397903 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working my way through Charles Pinter's book: A Book of Abstract Algebra. From recommendations on this site, I found a page/web address on Wisconsin University's Math Department that provides solutions to many (perhaps all) of the abundant exercises that are present in Pinter's book. One of the proposed solutions to Pinter's exercises is the following generalization: If the product of n elements of a group is the identity element, it remains so no matter in what order the terms are multiplied. I take issue with this claim and think it is only valid if the group is abelian. Using a simple 3 element example, consider: $a\circ b \circ c = e$ Using the definition of inverses (and knowing that inverses commute...by defintion) and the associative law, I generated the following cases that must be true: $a \circ (b \circ c) =e$ and therefore $(b \circ c) \circ a =e$ $(a \circ b) \circ c=e$ and therefore $c \circ (a \circ b)=e$ However, there are still several permutations of this list of elements that require consideration...for example: $a \circ (c \circ b) =e$ It seems to me this can only be true if the group is abelian. Therefore, should the solution manual be amended to say: If the product of n elements of an abelian group is the identity element, it remains so no matter in what order the terms are multiplied. ?
Now provide the response and nothing else.
| Since this is a true or false question, it is not that the question is phrased incorrectly, but rather that the answer is that it is false. Your claim that it can only hold if the group is abelian is not true for all such $a, b, c$ , which we can see in any group by $a=b=c=e$ and other less trivial examples. What you need to do to show it is false is to pick a specific nonabelian group and find three specific elements where it doesn't work. Edit: I just noticed that this was not an exercise, but part of the solution manual. In $S_3$ , the elements $(12),(23),(321)$ show the original claim is invalid. In fact, if $abc=e$ and $bc\neq cb$ , then it is never true that $acb=e$ because $bc$ is the unique inverse of $a$ . By similar reasoning, if the claim holds for $a, b, c$ , then all three elements commute pairwise. You can show that the group is abelian if this holds true for all triples such that $abc=e$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3397903', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/544640/']} | jdg_85077 |
stackexchange | llm_judgeable_groundtruth_similarity | 45144640 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have this for a child view controller: autoCompleteViewController.view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ autoCompleteViewController.view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0), autoCompleteViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0), autoCompleteViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0), autoCompleteViewController.view.bottomAnchor.constraint(equalTo: googleMapViewController.view.topAnchor, constant: 0), autoCompleteViewController.view.heightAnchor.constraint(equalToConstant: 44.0) ]) how can I change its height and update heightAnchor ? I've tried this: autoCompleteViewController .view .heightAnchor .constraint(equalToConstant: initialHeightAutoCompleteViewController + CGFloat(numberOfSuggestions * 45)) .isActive = true but with no luck. I also tried to add layoutIfNeeded() and some other similar methods but it didn't work. How can I update view height with anchors?
Now provide the response and nothing else.
| Additionally to @Mukesh answer is simply updating the constraint: var heightAnchor:NSLayoutConstraint!override func viewDidLoad() { super.viewDidLoad() heightAnchor = autoCompleteViewController.view.heightAnchor.constraint(equalToConstant:44.0) heightAnchor.isActive = true}func changeMyHeight(numberOfSuggestions: Int) { heightAnchor.constant = 44.0 + CGFloat(numberOfSuggestions * 45)} Notes: You cannot fully declare this variable at the class level, as autoCompleteViewController.view is not yet instantiated. You cannot set up the constraint and set isActive = true at the same time. I've always gotten a build error. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45144640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7991732/']} | jdg_85078 |
stackexchange | llm_judgeable_groundtruth_similarity | 31769887 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using the hypothesis python package for testing. I am getting the following error: Flaky: Hypothesis test_visiting produces unreliable results: Falsified on the first call but did not on a subsequent one As far as I can tell, the test is working correctly. How do I get around this?
Now provide the response and nothing else.
| It means more or less what it says: You have a test which failed the first time but succeeded the second time when rerun with the same example. This could be a Hypothesis bug, but it usually isn't. The most common cause of this is that you have a test which depends on some external state - e.g. if you're using a system random number generator rather than a Hypothesis provided one, or if your test creates some files and only fails if the files did not exist at the start of the test. The second most common cause of this is that your failure is a recursion error and the example which triggered it at one level of function calls did not at another. You haven't really provided enough information to say what's actually happening, so it's hard to provide more specific advice than that. If you're running a recent version of Hypothesis (e.g. 1.9.0 certainly does it) you should have been given quite detailed diagnostics about what is going on - it will tell you what the original exception you got was and it will report if the values passed in seemed to change between calls. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31769887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/390785/']} | jdg_85079 |
stackexchange | llm_judgeable_groundtruth_similarity | 31449216 |
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 check whether a number is multiple of second. What's wrong with the following code? def is_multiple(x,y): if x!=0 & (y%x)==0 : print("true") else: print("false") endprint("A program in python")x=input("enter a number :")y=input("enter its multiple :")is_multiple(x,y) error: TypeError: not all arguments converted during string formatting
Now provide the response and nothing else.
| You are using the binary AND operator & ; you want the boolean AND operator here, and : x and (y % x) == 0 Next, you want to get your inputs converted to integers: x = int(input("enter a number :"))y = int(input("enter its multiple :")) You'll get a NameError for that end expression on a line, drop that altogether, Python doesn't need those. You can test for just x ; in a boolean context such as an if statement, a number is considered to be false if 0: if x and y % x == 0: Your function is_multiple() should probably just return a boolean; leave printing to the part of the program doing all the other input/output: def is_multiple(x, y): return x and (y % x) == 0print("A program in python")x = int(input("enter a number :"))y = int(input("enter its multiple :"))if is_multiple(x, y): print("true")else: print("false") That last part could simplified if using a conditional expression: print("A program in python")x = int(input("enter a number :"))y = int(input("enter its multiple :"))print("true" if is_multiple(x, y) else "false") | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31449216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5122664/']} | jdg_85080 |
stackexchange | llm_judgeable_groundtruth_similarity | 136988 |
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 two lists: a = {{4, 5, 6}, {7, 8, 9}, {10, 11, 12}};b = {11, 8, 13}; I'm looking for a clean way to drop all elements of a which contain an element from b . The desired output for this example would be c = {{4, 5, 6}} where a[[2]] and a[[3]] have been dropped because they contain elements 8 and 11 from b. Any help would be greatly appreciated!
Now provide the response and nothing else.
| a = {{4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {1, 2, 3}, {11, 12, 13}};b = {11, 8, 13};Select[a, DisjointQ[b, #] &]Select[a, {} == b ⋂ # &] {{4, 5, 6}, {1, 2, 3}}{{4, 5, 6}, {1, 2, 3}} DisjointQ introduced in Mathematica 10. Use the second line in earlier versions. Actually the second line appears to be faster in every test I have performed so I would use it regardless of version. For example: SeedRandom[1]a = RandomInteger[999, {5000, 100}];b = {11, 8, 13};Select[a, DisjointQ[b, #] &] // Length // RepeatedTimingSelect[a, {} == b ⋂ # &] // Length // RepeatedTiming {0.11, 3686}{0.0286, 3686} In this particular case using Alternatives falls somewhere in the middle: Select[a, FreeQ[Alternatives @@ b]] // Length // RepeatedTiming {0.0463, 3686} Due to its early exit behavior in a case where most of the lists will be rejected it pulls ahead: SeedRandom[1]a = RandomInteger[99, {5000, 100}];Select[a, {} == b ⋂ # &] // Length // RepeatedTimingSelect[a, FreeQ[Alternatives @@ b]] // Length // RepeatedTiming {0.0291, 223}{0.0247, 223} | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/136988', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1932/']} | jdg_85081 |
stackexchange | llm_judgeable_groundtruth_similarity | 776193 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Every so often I find that I have accidentally broken data binding in my application. Either by renaming a property and not renaming it in the XAML or by a property throwing an exception for some reason. By default data binding errors are logged to debug output and exceptions that are thrown are caught and suppressed. Is there an easy way to have an exception thrown after the debug output is logged? I want to know as soon as possible if data binding is broken (ideally picking it up in an automated test) and not risk the chance that it might go unnoticed until tested by a human.
Now provide the response and nothing else.
| After some procrastination I finally set about coding a solution to my original issue. My solution uses a custom TraceListener (originally suggested by John) that logs to an output window. The output window is automatically displayed and bought to the foreground when an error occurs. Here is my TraceListener : public class ErrorLogTraceListener : TraceListener{ public override void Write(string message) { ... } public override void WriteLine(string message) { ... }} TraceListener is defined in System.Diagnostics. The custom TraceListener must be hooked into the system to be used. The official way to do this is to set something in the registry and then use the App.config file to configure the TraceListener . However I found that there is a much easier way to do this programmatically: ErrorLogTraceListener listener = new ErrorLogTraceListener();PresentationTraceSources.Refresh();PresentationTraceSources.DataBindingSource.Listeners.Add(listener);PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error; PresentationTraceSources is also defined in System.Diagnostics . For more information on trace sources see Mike Hillberg's blog . Bea Stollnitz has some useful info on her blog . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/776193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/25868/']} | jdg_85082 |
stackexchange | llm_judgeable_groundtruth_similarity | 469700 |
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 already read a few EE texts where a sine wave is often seen. Why is the sine wave often used as a test function for a circuit or a system? Why don't we use any other signal instead of sine? Do we use sine waves as test signal because of the fact that they are common, (for example, AC power)?
Now provide the response and nothing else.
| Because sinusoids have some important mathemtical properties. The first being how they behave under differentiation and integration. $$\frac{d}{dt}\sin(\omega t+\varphi) = \omega\cos(\omega t+\varphi) = \omega\sin(\omega t+\varphi+\frac{\pi}{2})$$ In other words when we differentiate or integrate a sinusoid we get a sinusoid of the same frequency. The sinusoids are the only periodic functions (from the reals to the reals)* for which this is true. The second being how they behave under addition. Two sinusoids of the same frequency but different phase add together to make a sinusoid of the same frequency (unless they are equal and opposite in which case they cancel to produce zero). $$a\sin(\omega t)+b\sin(\omega t+\theta)= \sqrt{a^2 + b^2 + 2ab\cos \theta} \sin(\omega t+\operatorname{atan2} \left( b\,\sin\theta, a + b\cos\theta \right))$$ These properties mean that when we feed a sinusoid into a linear time invariant system we get a sinusoid of the same frequency out. Many real-world systems behave to a first approximation as linear time invariant systems, especially for small signals. We can characterise a linear time invariant system by measuring its magnitude and phase response to a sinusoidal sweep and then we can predict its response to other signals by breaking those signals down into combinations of sine waves and then applying the superposition principle. If we tried to do a similar frequency sweep test with any other waveform we would have an output waveform a different shape to our input waveform, which we would have to deal with somehow, making the characterisation process much trickier. * As has been pointed out in the comments the exponential is it's own derivative, but the exponential of a real variable is not periodic. The exponential of a real variable multiplied by the imaginary unit is periodic but produces a complex result. If we decompose it into it's real and imaginary parts using Euler's formula then we are back to a pair of sinusoids. | {} | {'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/469700', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/232404/']} | jdg_85083 |
stackexchange | llm_judgeable_groundtruth_similarity | 173140 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Solve the following inequality $x^2+x+1\gt 0$ I understand how to solve inequalities and what the graphs look like. Usually the first step is to set this as in equation and then find the zeros. But for this one when I used the quadratic formula my two answers were: $$\dfrac{-1+i\sqrt{3}}{2}$$$$\dfrac{-1-i\sqrt{3}}{2}$$ I do not know what to do after this, or if I messed up in any way. Or, if there is another way to solve this problem. Any hints help. Please do not solve this problem in any way for me. Thanks!
Now provide the response and nothing else.
| Complete the square: $x^2+x+1=\left(x+\frac12\right)^2+\frac34$. For what values of $x$ is this positive? Added: Here’s an explanation of completing the square. Suppose that you have a quadratic $x^2+ax+b$. You want to write this in the form $(x+c)^2+d$ for some constants $c$ and $d$. We know that $(x+c)^2+d=x^2+2cx+(c^2+d)$, and we want this to be identically equal to $x^2+ax+b$. That is, we want $x^2+2cx+(c^2+d)$ and $x^2+ax+b$ to be the same polynomial. Clearly this means that we must have $2c=a$ and $c^2+d=b$. In particular, we must have $c=\frac{a}2$. I could also solve for $d$, but in practice it’s easier to work it out each time than it is to use a formula. Knowing now that $c=\frac{a}2$, I write $\left(x+\frac{a}2\right)^2$ as a first approximation to $x^2+ax+b$, and then I multiply it out to get $x^2+ax+\frac{a^2}4$. This approximation gives me the right $x^2$ and $x$ terms, but in general it gives me the wrong constant term, because $\frac{a^2}4$ is rarely equal to $b$. Therefore I have to adjust my approximation $\left(x+\frac{a}2\right)^2$. I do so by subtracting $\frac{a^2}4$ and adding $b$: $$\left(x+\frac{a}2\right)^2-\frac{a^2}4+b=x^2+ax+b\;,$$ as desired. In the case of the quadratic $x^2+x+1$, $a=1$, so $c=\frac{a}2=\frac12$, and my first approximation was $\left(x+\frac12\right)^2$. This has a constant term of $\frac14$ instead of the desired $1$, so I knew that I had to add another $\frac34$. The only remaining issue is what to do when the coefficient of $x^2$ isn’t $1$, i.e., when we’re dealing with $ax^2+bx+c$ with $a\ne 1$. The easiest approach is to factor out the $a$ to get $$a\left(x^2+\frac{b}ax+\frac{c}a\right)\;.$$ Then complete the square on $x^2+\frac{b}ax+\frac{c}a$ to get $$a\left(\left(x+\frac{b}{2a}\right)^2+\text{some constant}\right)\;.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/173140', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35812/']} | jdg_85084 |
stackexchange | llm_judgeable_groundtruth_similarity | 9320 |
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Chapter 6 of "Quantum Computation and Quantum Information" textbook by Nielsen and Chuang, Exercise 6.5 p.255: We have an oracle gate $O$ for $n$ qubit ( $2^n=N$ searching items), and we would like to construct new oracle gate $O'$ for $n+1$ qubit ( $2^{n+1}=2N$ searching items) using oracle gate $O$ and extra bit $|q\rangle$ so that new oracle gate $O'$ should mark an item only if it is solution for the oracle gate $O$ and extra bit $|q\rangle$ is $|0\rangle$ . The exact question in the Nielsen and Chuang textbook as follows: A new augmented oracle $O'$ is constructed which marks an item only if it is a solution to the search problem and the extra bit is set to zero. Exercise 6.5: Show that the augmented oracle $O'$ may be constructed using one application of $O$ , and elementary quantum gates, using the extra qubit $|q\rangle$ . Possible not very good solutions: The problem with this solution is related to the fact that it requires to open up an Oracle gate $O$ in order to "control" it. Does anybody have an idea of how to construct gate $O'$ using "pure" gate $O$ without "open up" them?
Now provide the response and nothing else.
| The simplest solution is to use an ancilla in the $|+\rangle$ state. Swap that ancilla for the oracle's output qubit, conditioned on the control qubit being false, before and after applying the oracle. Since toggling the $|+\rangle$ state has no effect, this deactivates the oracle when the control is set. Here's this technique applied to a simple comparison oracle : If you're not allowed to use an ancilla, I'm not sure how to make it work unless you have access to the square root of the oracle. The best I know how to do is to have the controlled oracle bitflip and phaseflip the target. Or to bitflip the target but have a 90 degree phase kickback onto the control for satisfying inputs. Summary Update - simple solution with ancilla | {} | {'log_upvote_score': 4, 'links': ['https://quantumcomputing.stackexchange.com/questions/9320', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/9545/']} | jdg_85085 |
stackexchange | llm_judgeable_groundtruth_similarity | 7546620 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There is such code: #include <iostream>int main(){ unsigned int* wsk2 = new unsigned int(5); std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl; delete wsk2; wsk2 = new unsigned int; std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl; return 0;} Result: wsk2: 0x928e008 5wsk2: 0x928e008 0 I have read that new doesn't initialize memory with zeroes. But here it seems that it does. How does it work?
Now provide the response and nothing else.
| There are two versions: wsk = new unsigned int; // default initialized (ie nothing happens)wsk = new unsigned int(); // zero initialized (ie set to 0) Also works for arrays: wsa = new unsigned int[5]; // default initialized (ie nothing happens)wsa = new unsigned int[5](); // zero initialized (ie all elements set to 0) In answer to comment below. Ehm... are you sure that new unsigned int[5]() zeroes the integers? Apparently yes: [C++11: 5.3.4/15]: A new-expression that creates an object of type T initializes that object as follows: If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value. Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization. #include <new>#include <iostream>int main(){ unsigned int wsa[5] = {1,2,3,4,5}; // Use placement new (to use a know piece of memory). // In the way described above. // unsigned int* wsp = new (wsa) unsigned int[5](); std::cout << wsa[0] << "\n"; // If these are zero then it worked as described. std::cout << wsa[1] << "\n"; // If they contain the numbers 1 - 5 then it failed. std::cout << wsa[2] << "\n"; std::cout << wsa[3] << "\n"; std::cout << wsa[4] << "\n";} Results: > g++ --versionConfigured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)Target: x86_64-apple-darwin13.2.0Thread model: posix> g++ t.cpp> ./a.out00000> | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7546620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/738811/']} | jdg_85086 |
stackexchange | llm_judgeable_groundtruth_similarity | 45851 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Taiwan News reported the following on February 5: As many experts question the veracity of China's statistics for the Wuhan coronavirus outbreak, Tencent over the weekend seems to have inadvertently released what is potentially the actual number of infections and deaths, which were astronomically higher than official figures, but are eerily in line with predictions from a respected scientific journal. [...] On late Saturday evening (Feb. 1), the Tencent webpage showed confirmed cases of the Wuhan virus in China as standing at 154,023, 10 times the official figure at the time. It listed the number of suspected cases as 79,808, four times the official figure. The number of cured cases was only 269, well below the official number that day of 300. Most ominously, the death toll listed was 24,589, vastly higher than the 300 officially listed that day. Were these numbers released by Tencent , and are they more accurate than the official figures?
Now provide the response and nothing else.
| The Tencent screenshot is almost certainly a hoax, for the simple reason that such screenshots are extremely easy to fake. For example, here's how easy it is to get a "screenshot" of the New York Times showing millions of people dead in Japan. First, we search for coronavirus and pick a random article. Here's a good one: Next, hit F12 to open up developer tools. Click the selector button. If you're using Chrome, it'll be in the upper left hand corner, like so: Once you've selected the selector, select the headline: Go back to developer tools, and you'll notice that the headline has been automated located in the page HTML for you: Change it to something suitably apocalyptic: And bam, just like that, you have a screenshot of the New York Times accidentally leaking the horrible truth about the coronavirus: So the question is, what's more likely - that, in a world filled with coronavirus hoaxes, someone took two minutes to make yet another hoax, or that the secret "real" coronavirus numbers somehow made their way onto a private company's content management system for their website? I'm leaning toward the first. | {} | {'log_upvote_score': 4, 'links': ['https://skeptics.stackexchange.com/questions/45851', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/53376/']} | jdg_85087 |
stackexchange | llm_judgeable_groundtruth_similarity | 4718342 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have lots of DOM on the page and I set them all to display: none, the browser still reacts quickly (scrolling is fast, page feels snappy). However, if I visibility: hidden the elements, the browser is as slow as if they were all drawn on the screen. Can someone explain, in detail, why this is the case?
Now provide the response and nothing else.
| Well in a way, they are drawn (but not really): The browser keeps space for them, so it must consider the items when laying out the visible ones. See MDC visibility:hidden : The box is invisible (fully transparent, nothing is drawn), but still affects layout . Descendants of the element will be visible if they have visibility:visible (this doesn't work in IE up to version 7). If you specify display: none instead, the browser only as to care about and layout the visible ones. It does not have to take the others into account at all. Depending on your visible/invisible ratio and the number of elements, this can make a difference. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4718342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/572140/']} | jdg_85088 |
stackexchange | llm_judgeable_groundtruth_similarity | 6812003 |
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: Android Activity Life Cycle - difference between onPause() and OnStop() I was wondering - what is the difference between onCreate() and onStart() methods? I think that onStart() is a redundant method. onCreate() will ALWAYS be called (At least in my last two projects). Can any one explain the difference?
Now provide the response and nothing else.
| Take a look on life cycle of Activity Where ***onCreate()*** Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.Always followed by onStart(). ***onStart()*** Called when the activity is becoming visible to the user.Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden. And you can write your simple class to take a look when these methods call public class TestActivity extends Activity { /** Called when the activity is first created. */ private final static String TAG = "TestActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.i(TAG, "On Create ....."); } /* (non-Javadoc) * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { super.onDestroy(); Log.i(TAG, "On Destroy ....."); } /* (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); Log.i(TAG, "On Pause ....."); } /* (non-Javadoc) * @see android.app.Activity#onRestart() */ @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "On Restart ....."); } /* (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { super.onResume(); Log.i(TAG, "On Resume ....."); } /* (non-Javadoc) * @see android.app.Activity#onStart() */ @Override protected void onStart() { super.onStart(); Log.i(TAG, "On Start ....."); } /* (non-Javadoc) * @see android.app.Activity#onStop() */ @Override protected void onStop() { super.onStop(); Log.i(TAG, "On Stop ....."); }} Hope this will clear your confusion. And take a look here for details. Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/6812003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/543711/']} | jdg_85089 |
stackexchange | llm_judgeable_groundtruth_similarity | 694895 |
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:
In Verhulst's model of population growth and control, Let $K$ represent the carrying capacity for a particular organism in a given environment, and let $r$ be a real number that represents the growth rate. The function $P(t)$ represents the population of this organism as a function of time $t$ , and the constant $P_0$ represents the initial population (population of the organism at time $t=0$ . Then the logistic differential equation is $${dP}/{dt}=rP\left(1−\dfrac{P}{K}\right)$$ . I have understood the cause for doing this, where $K\gg P$ the value of parenthesis is 1 and follows the normal exponential equation: $${dP}/{dt}=rP$$ However, isn't the original exponential equation a 1st order LINEAR differential equation...whereas the logistic model equation seems to me to be a 1st order NON Linear differential equation. Is that okay because we are describing the same system in the end.
Now provide the response and nothing else.
| Everything is "okay" as long as it describes what you observe. Posing ordinary differential equations is not an exercise in reproducing academic showcases, but rather serves the purpose of predicting the future from the current state. In your case, the linear differential equation (exponential growth) is an approximation of the nonlinear differential equation (logistic growth) for the case $P \to 0$ . The former is easier to solve (and is probably accurate enough in case of high capacity systems), while the latter is more accurate (with respect to biological systems - possibly), but also more difficult to solve. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/694895', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/281942/']} | jdg_85090 |
stackexchange | llm_judgeable_groundtruth_similarity | 3464061 |
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 extend the Networkx python package and add a few methods to the Graph class for my particular need The way I thought about doing this is simplying deriving a new class say NewGraph , and adding the required methods. However there are several other functions in networkx which create and return Graph objects (e.g. generate a random graph). I now need to turn these Graph objects into NewGraph objects so that I can use my new methods. What is the best way of doing this? Or should I be tackling the problem in a completely different manner?
Now provide the response and nothing else.
| If you are just adding behavior, and not depending on additional instance values, you can assign to the object's __class__ : from math import piclass Circle(object): def __init__(self, radius): self.radius = radius def area(self): return pi * self.radius**2class CirclePlus(Circle): def diameter(self): return self.radius*2 def circumference(self): return self.radius*2*pic = Circle(10)print c.radiusprint c.area()print repr(c)c.__class__ = CirclePlusprint c.diameter()print c.circumference()print repr(c) Prints: 10314.159265359<__main__.Circle object at 0x00A0E270>2062.8318530718<__main__.CirclePlus object at 0x00A0E270> This is as close to a "cast" as you can get in Python, and like casting in C, it is not to be done without giving the matter some thought. I've posted a fairly limited example, but if you can stay within the constraints (just add behavior, no new instance vars), then this might help address your problem. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3464061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/93580/']} | jdg_85091 |
stackexchange | llm_judgeable_groundtruth_similarity | 59860674 |
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 try to concatenate string to construct a path: $SourceDirectoryPath = $(System.DefaultWorkingDirectory) + "/solution/project/bin/Debug"$TargetFilePath = $(System.DefaultWorkingDirectory) + "/solution/project/bin/Debug/" + $(Release.ReleaseName) +$(Release.EnvironmentName) but instead of getting string concatenated I get error for the second line: d:\a\r1\a : The term 'd:\a\r1\a' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At D:\a_temp\9de874c9-3acd-4a19-a4dd-763074d38e40.ps1:2 char:25 where obviously d:\a\r1\a is a $(System.DefaultWorkingDirectory) but why it throws this error instead of just concatenating the string?
Now provide the response and nothing else.
| tl;dr It is Azure that expands $(System.DefaultWorkingDirectory) before PowerShell sees the resulting commands; if the expanded $(...) value is to be seen as a string by PowerShell, it must be enclosed in quotes ( '$(...)' ): Using $(...) (Azure macro syntax) embeds the Azure variable's verbatim value in the command text that PowerShell ends up interpreting. Note : Azure 's macro syntax - which is evaluated before PowerShell sees the resulting command text - is not to be confused with PowerShell 's own subexpression operator , $(...) . For string values this means that you situationally have to surround the macro with quotes in order to make it work syntactically in PowerShell code, for which '...' -quoting (single-quoting) is best : '$(System.DefaultWorkingDirectory)' Shayki Abramczyk's answer provides an effective solution, but let me provide some background information : The variable expansion (substitution) that Azure performs via macro syntax ( $(...) ) functions like a preprocessor: it replaces the referenced variable with its verbatim value . You need to make sure that this verbatim value works syntactically in the context of the target command . As currently written: $SourceDirectoryPath = $(System.DefaultWorkingDirectory) + "/solution/project/bin/Debug" turns into the following command seen by PowerShell , assuming that the value of Azure property System.DefaultWorkingDirectory is d:\a\r1\a : $SourceDirectoryPath = d:\a\r1\a + "/solution/project/bin/Debug" This is a broken PowerShell command, because d:\a\r1\a - due to lack of quoting - is interpreted as a command name or path ; that is, an attempt is made to execute putative executable d:\a\r1\a - see about_Parsing . Therefore, in order for PowerShell to recognize the Azure-expanded value d:\a\r1\a as a string , you need to quote it - see about_Quoting_Rules . Since the expanded-by-Azure value needs no further interpolation, single quotes are the best choice (for both operands, actually): $SourceDirectoryPath = '$(System.DefaultWorkingDirectory)' + '/solution/project/bin/Debug' In fact, you don't need string concatenation ( + ) at all in your case: $SourceDirectoryPath = '$(System.DefaultWorkingDirectory)/solution/project/bin/Debug' You could even combine that with expandable PowerShell strings ( "..." ), as long as the Azure-expanded value doesn't contain $ -prefixed tokens that PowerShell could end up interpreting (unless that is your (unusual) intent). One caveat re something like "$(System.DefaultWorkingDirectory)/$projectRoot/bin/Debug" (mixing an Azure-expanded value with a PowerShell variable reference) is that Azure's macro syntax ( $(...) ) looks the same as PowerShell's own subexpression operator , which is typically - but not exclusively - used in order to embed expressions in expandable strings (e.g., in pure PowerShell code, "1 + 1 equals $(1 + 1)" ). As of this writing, the Define variables Azure help topic doesn't spell it out, but based on the official comment in a GitHub docs issue , ambiguity is avoided as follows : There is no escape mechanism; instead, $(...) constructs that do not refer to Azure variables are left unchanged and therefore passed through to PowerShell. In the typical case, PowerShell expressions will not look like an Azure variable reference (e.g, $($foo.bar) rather than $(foo.bar) ), though hypothetically there can be ambiguity: $(hostname) , which is a valid PowerShell subexpression, could be preempted by Azure if a hostname Azure variable were defined. In such a corner case, the solution is to avoid use of an inline script and instead place the code in an external script file . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59860674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1123020/']} | jdg_85092 |
stackexchange | llm_judgeable_groundtruth_similarity | 2822889 |
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:
My confusion is how order arises from the Peano axioms (wikipedia link) . From this question I'm not sure that "successor" means "greater than." It seems you could take $\mathbf{0}$ and then the successor could simply be (roughly) "produce a new element not seen before" and then (via the linked question) just name these items $1, 2, 3, ... $. From an outside perspective it seems fine to associate an ordering with these numbers, but it seems to beg the question on whether order is valid and what it "means" in PA. I must be missing something simple, because arriving at the concept of order seems "obvious" but I'm just not seeing how it arises from the axioms given.
Now provide the response and nothing else.
| I think underlying this question is the assumption that "order" in PA corresponds to the intuitive notion of "magnitude". In particular, I note that the OP says I'm not sure that "successor" means "greater than." This is in fact a very good observation! In general the symbol $ < $ does not necessarily denote a comparison of sizes , and our convention of reading it aloud as "less than" is probably a source of a lot of confusion. The symbol $<$ means "comes before" (or, if you prefer a single word, "precedes") -- and nothing more than that. $a<b$ means "$a$ comes before $b$". It does not mean that $a$ is "smaller" than $b$ in any sense. There are many ordered structures in which thinking of $<$ as denoting size is really unhelpful and potentially misleading; see Fields that can be ordered in more than one way for examples. This detail is a source of confusion even in elementary contexts; students often have trouble with the language "$-5$ is less than $-2$", because "less than" connotes a comparison of magnitudes , and all we really mean when we write "$-5<-2$" is that $-5$ is to the left of $-2$ on a number line. It is solely a statement about order, and has nothing to do with size. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2822889', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114910/']} | jdg_85093 |
stackexchange | llm_judgeable_groundtruth_similarity | 114238 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to write some code to allow me switching to some directories that I usually go to. Say this program is mycd , and /a/very/long/path/name is the directory that I want to go to. So I can simply type mycd 2 instead of cd /a/very/long/path/name . Here I assume mycd knows 2 refers to that /a/very/long/path/name . There might also be mycd 1 , mycd 3 , ... etc. The problem is I have to write mycd as a shell script and type . mycd 2 to do the desired thing because otherwise the script just get executed in a child script which doesn't change anything about the parent shell that I actually care about. My question is: can I do it without using source ? because . mycd assumes mycd has to be a shell script and this might also introduce some functions that I don't want. can I implement it in some other programming languages?
Now provide the response and nothing else.
| make mycd a function so the cd command executes in your current shell. Save it in your ~/.bashrc file. function mycd { if (( $# == 0 )); then echo "usage: $FUNCNAME [1|2|3|...]" return fi case $1 in 1) cd /tmp ;; 2) cd /a/very/long/path/name ;; 3) cd /some/where/else ;; *) echo "unknown parameter" ;; esac} | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/114238', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/59925/']} | jdg_85094 |
stackexchange | llm_judgeable_groundtruth_similarity | 257938 |
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:
class Employee{ String name; int id; //No explicit constructors} Now I can invoke the following statement: Employee e1 = new Employee(); With the above code, the compiler will provide the definition for the constructor Employee() . If I define a single explicit constructor as follows: class Employee{ String name; int id; Employee(String aName){ this.name=aName; }} Now, why can't I invoke the following statement: Employee e2 = new Employee(); Even though the compiler knows how to provide definition of Employee() . Now, just because I have defined an explicit constructor Employee(String aName) , why can't I use a default constructor? Also, if the compiler had allowed the use of the default constructor even after defining an explicit one, it would have helped us to reuse the code for default constructor.
Now provide the response and nothing else.
| A constructor with arguments isn't just a handy shorthand for using setters. You write a constructor in order to ensure that an object will never, ever exist without certain data being present. If there is no such requirement, fine. But if there is one, as indicated by the fact that you've written such a constructor, then it would be irresponsible to generate a default constructor, through which a client could circumvent the "no object without data" rule. Doubly so, because the auto-generated default constructor is invisible to a casual code reader, which hides the fact that it exists! No, if you want constructors with arguments and a default constructor, you must write the default constructor yourself. It's not as if it's a lot of effort to write an empty block, anyway. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/257938', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/146096/']} | jdg_85095 |
stackexchange | llm_judgeable_groundtruth_similarity | 415188 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
A postgres SELECT query ran out of control on our DB server and started eating up tons of memory and swap until the server ran out of memory. I found the particular process via ps aux | grep postgres and ran kill -9 pid . This killed the process and the memory freed up as expected. The rest of the system and postgres queries appeared to be unaffected. This server is running postgres 9.1.3 on SLES 9 SP4. However, one of our developers chewed me out for killing a postgres process with kill -9 , saying that it will take down the entire postgres service. In reality, it did not. I've done this before a handful of times and have not seen any negative side effects. With that said, and after further reading, it looks like kill pid without the flags is the preferred way to kill a runaway postgres process, but per other users in the postgres community, it also sounds like postgres has "gotten better" over the years such that kill -9 on an individual query process/thread is no longer a death sentence. Can someone enlighten me on the proper way to kill a runaway postgres process as well as the how disastrous (or benign) using kill -9 is with Postgres these days? Thanks for the insight.
Now provide the response and nothing else.
| voretaq7 's answer covers the key points, including the correct way to terminate backends but I'd like to add a little more explanation. kill -9 (ie SIGKILL ) should never, ever, ever be your first-choice default . It should be your last resort when the process doesn't respond to its normal shutdown requests and a SIGTERM ( kill -15 ) has had no effect. That's true of Pg and pretty much everything else. kill -9 gives the killed process no chance to do any cleanup at all. When it comes to PostgreSQL, Pg sees a backed that's terminated by kill -9 as a backed crash . It knows the backend might have corrupted shared memory - because you could've interrupted it half way through writing a page into shm or modifying one, for example - so it terminates and restarts all the other backends when it notices that a backend has suddenly vanished and exited with a non-zero error code. You'll see this reported in the logs. If it appears to do no harm, that because Pg is restarting everything after the crash and your application is recovering from the lost connections cleanly. That doesn't make it a good idea. If nothing else backend crashes are less well tested than the normal-functioning parts of Pg and are much more complicated/varied, so the chances of a bug lurking in backend crash handling and recovery are higher. BTW, if you kill -9 the postmaster then remove postmaster.pid and start it again without making sure every postgres backend is gone, very bad things can happen . This could easily happen if you accidentally killed the postmaster instead of a backend, saw the database had gone down, tried to restart it, removed the "stale" .pid file when the restart failed, and tried to restart it again. That's one of the reasons you should avoid waving kill -9 around Pg, and shouldn't delete postmaster.pid . A demonstration: To see exactly what happens when you kill -9 a backend, try these simple steps. Open two terminals, open psql in each, and in each run SELECT pg_backend_pid(); . In another terminal kill -9 one of the PIDs. Now run SELECT pg_backend_pid(); in both psql sessions again. Notice how they both lost their connections? Session 1, which we killed: $ psql regresspsql (9.1.4)Type "help" for help.regress=# select pg_backend_pid(); pg_backend_pid ---------------- 6357(1 row)[kill -9 of session one happens at this point]regress=# select pg_backend_pid();server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.The connection to the server was lost. Attempting reset: Succeeded.regress=# select pg_backend_pid(); pg_backend_pid ---------------- 6463(1 row) Session 2, which was collateral damage: $ psql regresspsql (9.1.4)Type "help" for help.regress=# select pg_backend_pid(); pg_backend_pid ---------------- 6283(1 row)[kill -9 of session one happens at this point]regress=# select pg_backend_pid();WARNING: terminating connection because of crash of another server processDETAIL: The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.HINT: In a moment you should be able to reconnect to the database and repeat your command.server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.The connection to the server was lost. Attempting reset: Succeeded.regress=# select pg_backend_pid(); pg_backend_pid ---------------- 6464(1 row) See how both sessions were broken? That's why you don't kill -9 a backend. | {} | {'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/415188', 'https://serverfault.com', 'https://serverfault.com/users/30415/']} | jdg_85096 |
stackexchange | llm_judgeable_groundtruth_similarity | 28948614 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Could you please explain the difference between the following two types of transactions: Hibernate transaction Spring transaction Also I would like to know about the @Transactional annotation.
Now provide the response and nothing else.
| Well for starters they are both Transactions, but they encompass different concepts and components. TL;DR Hibernate deals with database specific transactions, whereas spring provides a general transaction management service. @Transactional is a nice way of configuring transaction management behaviour. The long story: Transactions Transactions are basically units of work (ie changes to something) that are managed as a single operation that can be either committed or rolled back. There are lots of different types of transactions in the java world - database, messaging systems like JMS, inter application transactions (for those who are not faint of heart) or anything else that may need to be included in a transaction. In the Java standard transactions are managed using the Java Transaction API which sets the rules for how to participate in a transaction. Hibernate Hibernate is an ORM for abstracting database components to Java objects, so its transactions are specifically related to changes made within a database. A transaction may be made up of one or many writes to various database tables that are all committed once the operation is completed. Rolling back the transaction, eg f there are any errors during the operation, allows all the changes to be undone. Spring At its lowest level Spring is a application framework for managing configuration and dependencies between objects. In addition it also provides an interface for managing higher level services that are used in modern applications such as databases, messaging services, MVC frameworks and transactions. Spring is designed to be used as an all-encompassing master of objects and services within your application, so its concept of a transaction is at a higher level than the database specific transactions that hibernate concerns itself with. Spring Transactions are designed to give you fine grained control of all your transactional resources while abstracting away the often messy coding required to co-ordinate the transactions. @Transactional Spring provides a few different methods for using transactions - among others there xml based aspects, coding to the API and annotation based declarative transactions. The annotation based transactions are handy because you dont need to add the transaction management boilerplate code to your app (even using PlatformTransactionManager via the API has quite a bit of coding overhead). So basically what happens with @Transactional is that at runtime spring scans your code base for @Transactional classes and methods and wraps them up in the transaction specific management code, based on what you have configured via the annotation. So a method like this: @Transactional(propagation = REQUIRES_NEW, rollbackFor = {Exception.class})public void saveAndSendMessage(Foo foo) throws Exception { dbManager.save(foo); Bar bar = transform(foo); jmsSystem.send(bar);} can have spring set up a new transaction for the database and jms system, and co-ordinate them without needing to add all the specific tx management code automagically. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28948614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1808811/']} | jdg_85097 |
stackexchange | llm_judgeable_groundtruth_similarity | 17587697 |
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 get the Week number of the year from the date.I tried the code as follow but gives me a wrong week number. My code for week number: NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"YYYY-MM-dd"]; NSDate *date = [dateFormatter dateFromString:@"2012-09-15"]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSLog(@"week: %i", [[calendar components: NSWeekOfYearCalendarUnit fromDate:date] weekOfYear]); //Display 38 instead of 37} Note: If i try with with [NSDate date] display the correct. Help me to solve this.. Thank you,
Now provide the response and nothing else.
| ObjectiveC: NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *dateComponent = [calendar components:(NSWeekOfYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]]; NSLog(@"%@",dateComponent); Update NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *dateComponent = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:date]; NSLog(@"%@",dateComponent); Swift: let calendar = NSCalendar.currentCalendar()let dateComponent = calendar.components([.WeekOfYear, .Day, .Month, .Year], fromDate: NSDate(timeIntervalSinceNow: 0))print("weekOfYear \(dateComponent.weekOfYear)") Swift 3 - Swift 5: let component = Calendar.current.component(.weekOfYear, from: Date())print("Week of Year \(component)") | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17587697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2526811/']} | jdg_85098 |
stackexchange | llm_judgeable_groundtruth_similarity | 17136084 |
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 this question has been asked a few times before, and I have read various posts about this. However I am struggling to get this to work. bool isClicked() { Vector2 origLoc = Location; Matrix rotationMatrix = Matrix.CreateRotationZ(-Rotation); Location = new Vector2(0 -(Texture.Width/2), 0 - (Texture.Height/2)); Vector2 rotatedPoint = new Vector2(Game1.mouseState.X, Game1.mouseState.Y); rotatedPoint = Vector2.Transform(rotatedPoint, rotationMatrix); if (Game1.mouseState.LeftButton == ButtonState.Pressed && rotatedPoint.X > Location.X && rotatedPoint.X < Location.X + Texture.Width && rotatedPoint.Y > Location.Y && rotatedPoint.Y < Location.Y + Texture.Height) { Location = origLoc; return true; } Location = origLoc; return false; }
Now provide the response and nothing else.
| Let point P(x,y) , and rectangle A(x1,y1) , B(x2,y2) , C(x3,y3) , D(x4,y4) . Calculate the sum of areas of △APD , △DPC , △CPB , △PBA . If this sum is greater than the area of the rectangle: Then point P(x,y) is outside the rectangle. Else it is in or on the rectangle. The area of each triangle can be calculated using only coordinates with this formula: Assuming the three points are: A(x,y) , B(x,y) , C(x,y) ... Area = abs( (Bx * Ay - Ax * By) + (Cx * By - Bx * Cy) + (Ax * Cy - Cx * Ay) ) / 2 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17136084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2113140/']} | jdg_85099 |
stackexchange | llm_judgeable_groundtruth_similarity | 29617693 |
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 just started with C and I'm trying to understand the basics. Plenty of tutorials will tell you things and have you believe it without any real explanation and there are no answers on that I can find that are human readable. In the following: #include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]){ int *a; a = malloc(5 * sizeof(int)); a[2] = 4; printf("%d\n", a[0]); // Prints 0 printf("%d\n", a[2]); // Prints 4 return 0;} I have not explicitly declared int *a as a pointer to an array, but if I allocate it some memory, I can then use a like I had declared it as an array. Is declaring a pointer with square brackets just a shortcut for what I've done below? Are square brackets actually doing some pointer arithmetic? Cheeky Second question Why is the memory address assigned to a and not *a ?
Now provide the response and nothing else.
| I have not explicitly declared int *a as a pointer to an array, but if I allocate it some memory, I can then use a like I had declared it as an array. Is declaring a pointer with square brackets just a shortcut for what I've done below? Similar, but no. int *a declares a as pointer to int . int b[5] allocates space for 5 int s, declares b as constant pointer to int an array-of- int reference (which can in most cases be treated as a constant pointer to int ), and defines b to be the pointer to the allocated space. Thus, int b[5] is doing way more than int *a , which also means int *a is more flexible than int b[5] . For example, you can increment a , but not b . malloc allocates memory on heap. int b[5] , if a global variable, will be in the program's data segment (i.e. it is literally compiled into the executable). If local, it will be allocated on stack. Again, similar, but different. Are square brackets actually doing some pointer arithmetic? In declaration, no. When you use pointer variables, yes: x[y] is identical to *(x + y) . So a[1] is the same as *(a + 1) , which is the same as *(1 + a) , which is again the same as 1[a] (but please don't use this last one). Why is the memory address assigned to a and not *a ? Cheeky answer for a cheeky question: Because you wrote a = ... and not *a = ... . EDIT: John Bode gave a useful pointer (heh): constant pointers and array references are not the same thing, although they are pretty damn similar. For one thing, sizeof(...) will give a different result. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29617693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2423179/']} | jdg_85100 |
stackexchange | llm_judgeable_groundtruth_similarity | 61051679 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried to update my laravel/installer using the command: composer global update laravel/installer But it only upgraded its minor version (assuming that it uses Semantic Versioning). Package operations: 0 installs, 1 update, 0 removals - Updating laravel/installer (v2.1.0 => v2.3.0): Downloading (100%) Then I execute the update command again: composer global update laravel/installer But outputs: Nothing to install or update I now uses PHP 7.4.4 (cli) obtained using php -v so I assume that it should be able to upgrade to latest which is Laravel Installer 3.0.1 .
Now provide the response and nothing else.
| If running composer global update laravel/installer is not enough to upgrade the the desired version, there might be package dependencies that restricts the upgrade to the latest. I do not know if there is a composer option to do that on global scope but the following commands works for me: # uninstall the packagecomposer global remove laravel/installer# reinstallcomposer global require laravel/installer The 1st process outputs the outdated packages dependencies that are removed with the laravel/installer package. Then the 2nd process installs the latest laravel/installer with the updates dependencies. Laravel documentation does not include how to update the installer package yet. Update: Adding Documentation link on how to update a composer package. composer require specific version documentation . php composer.phar require "vendor/package:2.*" vendor/package2:dev-master As we can see, specific version could be supplied after the colon. https://getcomposer.org/doc/03-cli.md#require | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61051679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1500392/']} | jdg_85101 |
stackexchange | llm_judgeable_groundtruth_similarity | 364556 |
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 curious to how people are deploying FreeBSD's ports in their environment. I assume that most people using FreeBSD are indeed using Ports (and often portupgrade for upgrading with binaries). I am however interested in how you have this setup, as I'm not satisfied with how things work in recent versions. I'm now running FreeBSD 9.0 and are having issues. I've set things up as follows: /usr/ports is shared via NFS from one node (with nightly 'portsnap fetch update'). Each node mounts /usr/ports with read-write I've set "WRKDIRPREFIX=/usr/tmp" in /etc/make.conf on all nodes I've configured the Portsnap to use a local index by adding the following to /usr/local/etc/pkgtools.conf: ENV['LOCALINDICES'] ||= '/var/db' ENV['PORTS_INDEX'] ||= ENV['LOCALINDICES'] + '/INDEX.local' I can successfully run portupgrade -p package to build a package and then portupgrade -P package to install the binary on the other nodes. Yet, sometime I receive the following issue: /var/db/INDEX.local:23265:dbm_store failed I cannot think of any other optimizations I can do to the system, as the index now resides locally, and the only thing really exported is the ports-tree and nothing is ever written to there from the nodes.
Now provide the response and nothing else.
| I have never been fully satisfied with the ports system in a large environment -- It always seems like you need to apply some external management to it in order to make it work well. My best tips (in order of ascending preference, "worst" solution to "best" solution): If you're building on each host, don't . If you must, don't do it over NFS with read-write mounts like you describe: You can usually trust the ports to Do The Right Thing and not stomp on the ports tree if you provide alternate work directories, but it's always better to be safe than sorry: Run a local CVS/csup mirror and csup all your hosts from that box, then build locally as you would if they were individual machines. Yes, I know this means having more disk space on the hosts and an extra step. It's also almost guaranteed to be problem-free. Caveat: You probably want to sync the package configuration files (rsync or similar) from a designated "configuration host" to ensure consistency on each machine (you can even rsync the whole ports tree if you want, rather than using csup on each node). Use a Build Host, create packages, and install those. A much better solution than building on each individual machine: Use a build host to create packages, and point your tools at those packages. This means keeping a build host around for every architecture you run (or cross-compiling), but it's ultimately nicer for your target machines (no large compile jobs, a guarantee of consistency) Use a configuration/system management tool. This is the solution I wound up with -- I build a standard server image and deploy it around my environment using radmind . You can do similar things with Puppet or Chef . This has all the advantages of using a build host (consistency, less load on the individual servers), and adds the benefit of configuration management. Caveat: This only works really well if your machines are "identical" -- That is you can install the same set of ports on all of them. It can work if you have varying sets of ports, but that substantially increases the administrative overhead. Disclaimer: I'm the port maintainer for sysutils/radmind . Yeah, I like it that much that I adopted it. All of this is based on my experience managing various-sized FreeBSD environments (ranging from 1-2 machines to over 100). Configuration/System Management tools that push and maintain a standardized image are really the best way to handle this in my experience. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/364556', 'https://serverfault.com', 'https://serverfault.com/users/38917/']} | jdg_85102 |
stackexchange | llm_judgeable_groundtruth_similarity | 5796764 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like Photoshop to automatically execute the following task for a given folder: Load all PNG files in a given folder. Convert each file's mode to RGB color Add one layer to each file Save the files as PSD in the same folder I have been told that this can be done with Photoshop scripting, but I don't know how to get started since unfortunately I don't have much experience with JavaScript. One thing I know is that I can't run the task above using Actions because when I record the last step (4), Photoshop records the action to save the PSD files in the folder that I use when recording the macro (instead of the one used to load the original PNG files). In other words, it fixes the destination folder to the one used in the macro. This takes me to the following question: Is there a way to automatically generate the Photoshop Javascript code that runs a given action ? If so, I wouldn't mind learning how to modify the script to fix the above folder problem.
Now provide the response and nothing else.
| I made a script which does the required job: #target photoshop#strict onrunthis();function runthis(){ var path = "/d/PhotoshopScript/Images/"; var inputFolder = new Folder(path ); var inputFiles = inputFolder.getFiles("*.png"); for(index in inputFiles) { // open the file var fileToOpen = new File(inputFiles[index]); open(fileToOpen); // Change mode to rgb activeDocument.changeMode(ChangeMode.RGB); // add a new layer activeDocument.artLayers.add(); //save var psdOptions = new PhotoshopSaveOptions(); psdOptions.alphaChannels = true; psdOptions.annotations = false; psdOptions.embedColorProfile = false; psdOptions.layers = true; psdOptions.spotColors = false; var file = new File(path + GetFileName(String(inputFiles[index]))); activeDocument.saveAs(file, psdOptions); activeDocument.close(); // dispose fileToOpen = null; psdOptions = null; file = null; } // dispose inputFolder = null; inputFiles = null;}function GetFileName(fullPath){ var m = fullPath.match(/(.*)[\/\\]([^\/\\]+)\.\w+$/); return m[2];} It can be improved in many ways, but I hope it helps. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5796764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283296/']} | jdg_85103 |
stackexchange | llm_judgeable_groundtruth_similarity | 186676 |
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'm trying to build a diving flashlight and now I'm stuck with the electrical part. I have a \$12\$V \$10\$W high brightness LED, and am now trying to decide which is the best option for the batteries. For now, I guess the best choice is a pack of \$18650\; \left(3.7\; V\right)\$. Found a package with \$10\$ batteries with nominal capacity* of \$4200\$ mAh for $\$15\$. So, the plan is to put \$3\$ groups of \$3\$ batteries in series. This way, it should provide \$\left(3\times4.2\right)=12.6\;\$V at full charge* and \$\left(3*2.7\right)=8.1\;\$V at minimum charge*, and a nominal \$\left(3\times 4200\right)=12600\;\$mAh of capacity*. To maintain the brightness of the LED constant, is there an easy way to build a regulator with input \$8 \sim13\$V and output \$12\;\$V without losing much power? Or another better idea? UPDATE I don't have so much skill about electronics, and don't know exactly how to find the correct datasheet, but the LED is this: *: Edited and replaced with correct terms
Now provide the response and nothing else.
| DO NOT USE A VOLTAGE REGULATOR You should never voltage regulate a LED. As an LED is a constant voltage device, voltage regulation is meaningless. The Power to Voltage graph (PV graph) is non-linear (or even polynomial) and very sensitive. A tiny over-voltage would produce a huge increase in power (destroying your LED). EDIT: As Temlib says. Another reason that you should never drive an LED with a constant voltage source is that LEDs are made of semiconductors. Semiconductors when heated will reduce in resistance. Given that As the Resistance decreases, the power (Ohmic heating) output increases, this leads to further reduction in resistance, which leads to more power .... This process is called Thermal Runaway, and is a very common cause of LED failure. Use a Constant Current Source The correct way to drive an LED is to use a CURRENT regulator, as the the Power to Current relationship is near linear, and you can much more accurately control the power being delivered to your LED (and prevent it from releasing the magic smoke). | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/186676', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/83722/']} | jdg_85104 |
stackexchange | llm_judgeable_groundtruth_similarity | 28112891 |
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 looking to pass a Class as a parameter to a Scala function like so: def sampleFunc (c : Class) : List[Any] (Side question: should the type in the parameter be Class or Class[_]?) The reason I'm passing a Class type is to check whether an object belongs to a particular type or not. At the moment, as a workaround, I'm passing a sample object to the method and comparing the two object's .getClass result. I hardly think this is ideal though and I'm sure there's a clearly defined way of passing Types in Scala.
Now provide the response and nothing else.
| Well, to your original question: Yes, you can pass Scala Class as an argument.As Class is a type constructor, it needs a concrete type to make a type to be used in argument. You can use the wildcard existential type Class[_] as you have done. def sample(c: Class[_]) = println("Get a class")sample(classOf[Int]) However, if you want to check whether an object is of certain type, I recommend you to use =:= , in combination with default parameter def checkType[T](obj: T)(implict ev: T =:= Int = null) = if (ev == null) "get other" else "get int"checkType(123) // get intcheckType("123") // get other | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28112891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/543818/']} | jdg_85105 |
stackexchange | llm_judgeable_groundtruth_similarity | 103707 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For an image hosting web application: For my stored images, is it feasible to create thumbnails on the fly using PHP (or whatever), or should I save 1 or more different sized thumbnails to disk and just load those? Any help is appreciated.
Now provide the response and nothing else.
| Save thumbnails to disk. Image processing takes a lot of resources and, depending on the size of the image, might exceed the default allowed memory limit for php. It is less of a concern if you have your own server with only your application running but it still takes a lot of cpu power and memory to resize images. If you're considering creating thumbnails on the fly anyway, you don't have to change much - upon the first request, create the thumbnail from the source file, save it to disk and upon subsequent requests just read it off the disk. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/103707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_85106 |
stackexchange | llm_judgeable_groundtruth_similarity | 13406387 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using boost::split(strs, r_strCommandLine, boost::is_any_of("\t ")); to spit a string into tokens for parsing a simple script. So far, so good. However, for the following string command_name first_argument "Second argument which is a quoted string." i would like my tokens to be strs[0] = command_namestrs[1] = first_argumentstrs[2] = "Second argument which is a quoted string." Of course, I could search for quote characters at beginning and ending of tokens and merging using " " delimiters the tokens between the the occurrence of a token beginning with a quote and a token ending with a quote to recreate the quoted string but I am wondering if there is a more efficient/elegant way of doing this. Any ideas?
Now provide the response and nothing else.
| Example using boost::tokenizer : #include <string>#include <iostream>using std::cout;using std::string;#include <boost/tokenizer.hpp>using boost::tokenizer;using boost::escaped_list_separator;typedef tokenizer<escaped_list_separator<char> > so_tokenizer;int main(){ string s("command_name first_argument " "\"Second argument which is a quoted string.\""); so_tokenizer tok(s, escaped_list_separator<char>('\\', ' ', '\"')); for(so_tokenizer::iterator beg=tok.begin(); beg!=tok.end(); ++beg) { cout << *beg << "\n"; } return 0;} Output: command_namefirst_argumentSecond argument which is a quoted string. See demo at https://ideone.com/gwCpug . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13406387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1825043/']} | jdg_85107 |
stackexchange | llm_judgeable_groundtruth_similarity | 10587824 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently, I have the following fragment to check and install Windows Installer 4.5 if the user is on Windows XP. <Fragment> <Property Id="WinXPx86HasInstaller"> <![CDATA[VersionNT = 'v5.1' AND VersionMsi >= "4.5.6001.22159"]]> </Property> <PackageGroup Id="Windows.Installer.4.5"> <ExePackage Id="WinXp_x86" Cache="no" Compressed="no" PerMachine="yes" Permanent="yes" Vital="yes" InstallCommand="/norestart /passive" SourceFile="WindowsXP-KB942288-v3-x86.exe" DownloadUrl="http://download.microsoft.com/download/2/6/1/261fca42-22c0-4f91-9451-0e0f2e08356d/WindowsXP-KB942288-v3-x86.exe" DetectCondition="WinXPx86HasInstaller" InstallCondition="NOT WinXPx86HasInstaller"> <ExitCode Behavior="forceReboot" /> </ExePackage> </PackageGroup></Fragment> However, this is not working and the property "WinXPx86HasInstaller" always evaluates to false even when it is installed. What am I doing wrong?
Now provide the response and nothing else.
| It's somewhat annoying that, unlike WiX, there's no way to easily test Burn InstallConditions - only DetectConditions are printed out in the log at runtime. After spending a while to test inverted InstallConditions as DetectConditions [*], this fragment appears to work for me: <!-- Windows Installer 4.5 --><Fragment> <PackageGroup Id="WindowsInstaller45"> <ExePackage Cache="no" Compressed="no" PerMachine="yes" Permanent="yes" Vital="yes" SourceFile="redist\WindowsXP-KB942288-v3-x86.exe" DownloadUrl="http://download.microsoft.com/download/2/6/1/261fca42-22c0-4f91-9451-0e0f2e08356d/WindowsXP-KB942288-v3-x86.exe" InstallCondition="VersionNT=v5.1 AND NOT VersionNT64 AND VersionMsi < v4.5" InstallCommand="/quiet /norestart"> <ExitCode Behavior="forceReboot"/> </ExePackage> <ExePackage Cache="no" Compressed="no" PerMachine="yes" Permanent="yes" Vital="yes" SourceFile="redist\WindowsServer2003-KB942288-v4-x86.exe" DownloadUrl="http://download.microsoft.com/download/2/6/1/261fca42-22c0-4f91-9451-0e0f2e08356d/WindowsServer2003-KB942288-v4-x86.exe" InstallCondition="VersionNT=v5.2 AND NOT VersionNT64 AND VersionMsi < v4.5" InstallCommand="/quiet /norestart"> <ExitCode Behavior="forceReboot"/> </ExePackage> <ExePackage Cache="no" Compressed="no" PerMachine="yes" Permanent="yes" Vital="yes" SourceFile="redist\WindowsServer2003-KB942288-v4-x64.exe" DownloadUrl="http://download.microsoft.com/download/2/6/1/261fca42-22c0-4f91-9451-0e0f2e08356d/WindowsServer2003-KB942288-v4-x64.exe" InstallCondition="VersionNT=v5.2 AND VersionNT64 AND VersionMsi < v4.5" InstallCommand="/quiet /norestart"> <ExitCode Behavior="forceReboot"/> </ExePackage> <MsuPackage Cache="no" Compressed="no" Permanent="yes" Vital="yes" KB="KB942288" SourceFile="redist\Windows6.0-KB942288-v2-x86.msu" DownloadUrl="http://download.microsoft.com/download/2/6/1/261fca42-22c0-4f91-9451-0e0f2e08356d/Windows6.0-KB942288-v2-x86.msu" InstallCondition="VersionNT=v6.0 AND NOT VersionNT64 AND VersionMsi < v4.5"/> <MsuPackage Cache="no" Compressed="no" Permanent="yes" Vital="yes" KB="KB942288" SourceFile="redist\Windows6.0-KB942288-v2-x64.msu" DownloadUrl="http://download.microsoft.com/download/2/6/1/261fca42-22c0-4f91-9451-0e0f2e08356d/Windows6.0-KB942288-v2-x64.msu" InstallCondition="VersionNT=v6.0 AND VersionNT64 AND VersionMsi < v4.5"/> </PackageGroup></Fragment> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10587824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90689/']} | jdg_85108 |
stackexchange | llm_judgeable_groundtruth_similarity | 16062059 |
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 razor if I had something like: @Html.EditorFor(model => model.name) or even: @Html.CheckBoxFor(m => m.RememberMe) How would I add a css class or an id to them? I have been reading about helpers, but would I have to make a helper for every single element? is there no easy way to add a class or id to razor form elements?
Now provide the response and nothing else.
| You cannot do that with the EditorFor helper simply because you don't know what template will be used. You could achieve it but you will need to write a custom editor template. For example this could be achieved by overriding the default editor template and taking into account the second parameter which represents an additional view data. Here's an example of how such a custom editor template could look for string types ( ~/Views/Shared/EditorTemplates/string.cshtml ): @Html.TextBox( "", ViewData.TemplateInfo.FormattedModelValue, ViewData) and then you could use it like that: @Html.EditorFor(model => model.name, new { @class = "myclass" }) With the CheckBoxFor helper you could do that: @Html.CheckBoxFor(m => m.RememberMe, new { @class = "myclass" }) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16062059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1270259/']} | jdg_85109 |
stackexchange | llm_judgeable_groundtruth_similarity | 12724653 |
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 customize the default error message " Value is required and can't be empty "in zf2 I am using following code to add customise default error message in validators of inputfilter $inputFilter->add($factory->createInput(array( 'name' => 'username', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 4, 'max' => 20, 'messages' => array( 'isEmpty' => 'Please enter User Name between 4 to 20 character!' ), ), ), ), ))); But I am getting following error. Zend\Validator\Exception\InvalidArgumentExceptionFile: /home/website/vendor/zendframework/zendframework/library/Zend/Validator/AbstractValidator.php:220Message: No message template exists for key 'isEmpty' What I am doing wrong? reference
Now provide the response and nothing else.
| try this $inputFilter->add($factory->createInput(array( 'name' => 'username', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' =>'NotEmpty', 'options' => array( 'messages' => array( \Zend\Validator\NotEmpty::IS_EMPTY => 'Please enter User Name!' ), ), ), array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 4, 'max' => 20, 'messages' => array( 'stringLengthTooShort' => 'Please enter User Name between 4 to 20 character!', 'stringLengthTooLong' => 'Please enter User Name between 4 to 20 character!' ), ), ), ), ))); reference Other validator set | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12724653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/376702/']} | jdg_85110 |
stackexchange | llm_judgeable_groundtruth_similarity | 4489861 |
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 $p\ge 3$ be a prime number. $G$ is a subgroup of $GL_n(\mathbb{Z})$ and $|G|<\infty$ . Let $\sigma: GL_n(\mathbb{Z})\to GL_n(\mathbb{F}_p)$ be the natural map. Prove that $\sigma|_G$ is injective. Suppose $\exists A,B \in G,A\ne B$ , s.t. $\sigma(A)=\sigma(B)$ i.e. $A=B \pmod{ p}$ . Since $|G|<\infty$ , $\exists m,k\in\mathbb{Z}^+$ , $A^m=B^k=I$ . In linear algebra we know $A=C\ {\rm diag}(\zeta_1,\dots,\zeta_n)\ C^{-1}$ where $\zeta_i^m=1,C\in GL_n(\mathbb{C})$ . But I don't know if $m=k$ . Taking trace and norm can't solve this problem. I think $A=B \pmod{p} $ is not easy to use. Any ideas?
Now provide the response and nothing else.
| Let $A \in \mathrm{Ker}(\sigma_{|G})$ . Then $A \equiv I_n \ [\mathrm{mod}\ p]$ , so there exists $N \in \mathcal{M}_n(\mathbb{Z})$ such that $A = I_n + pN$ . But by Lagrange theorem, $A^{|G|}=I_n$ , so $(I_n + pN)^{|G|}=I_n$ . So the polynomial $(1+pX)^{|G|}-1$ is a vanishing polynomial for $N$ , and since it is splitted and has simple roots over $\mathbb{C}$ , then $N$ is diagonalizable, and the eigenvalues of $N$ are among its roots, which are the $$\frac{e^{2ik\pi/|G|}-1}{p}, \quad \quad k=1, ..., |G|$$ These eigenvalues have modulus $<1$ (because $p\geq 3$ ), so $\lim_{k \rightarrow +\infty} N^k = 0$ . But $N \in \mathcal{M}_n(\mathbb{Z})$ , so the sequence $(N^k)_{k \geq 1}$ is eventually constant equal to $0$ , so $N$ is nilpotent. So $N$ being diagonalizable and nilpotent, then $N=0$ , so $A=I_n$ and you are done. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4489861', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/998395/']} | jdg_85111 |
stackexchange | llm_judgeable_groundtruth_similarity | 578452 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a Cisco (877) router acting as the main gateway for a network; it has a DSL connection and performs NAT from the internal network to its external, public IP address. The router allows SSH access for management, and this has been limited using an access list: access-list 1 permit <internal network range>line vty 0 4 transport input ssh access-class 1 in The router's internal web server isn't enabled, but if it was, I know its access could be limited using the same logic: ip http access-class 1 Now, the gotcha: this router also acts as a DNS server, forwarding queries to external servers: ip name-server <ISP DNS 1>ip name-server <ISP DNS 2>ip dns server My problem is: the router is perfectly happy to answer DNS queries when receiving them on its external interface . How can I block this kind of traffic so that the router only answers DNS queries from the internal network?
Now provide the response and nothing else.
| !Deny DNS from Public ip access-list extended ACL-IN_FROM-WAN remark allow OpenDNS lookups permit udp 208.67.222.222 0.0.0.0 any eq domain permit tcp 208.67.220.220 0.0.0.0 any eq domain remark deny all others and log the attempts deny udp any any eq domain log deny tcp any any eq domain log permit ip any any! Apply to WAN interface int WAN ip access-group ACLIN-TO_WAN in | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/578452', 'https://serverfault.com', 'https://serverfault.com/users/6352/']} | jdg_85112 |
stackexchange | llm_judgeable_groundtruth_similarity | 4961355 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on a form layout for a Login Activity in my Android App. The image below is how I want it to look like: I was able to achieve this layout with the following XML . The problem is, it's a bit hackish. I had to hard-code a width for the host EditText. Specifically, I had to specify: android:layout_width="172dp" I'd really like to give a percentage width to the host and port EditText's . (Something like 80% for the host, 20% for the port.) Is this possible? The following XML works on my Droid, but it doesn't seem to work for all screens. I would really like a more robust solution. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/host_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/home" android:paddingLeft="15dp" android:paddingTop="0dp" android:text="host" android:textColor="#a5d4e2" android:textSize="25sp" android:textStyle="normal" /> <TextView android:id="@+id/port_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/home" android:layout_toRightOf="@+id/host_input" android:paddingTop="0dp" android:text="port" android:textColor="#a5d4e2" android:textSize="25sp" android:textStyle="normal" /> <EditText android:id="@+id/host_input" android:layout_width="172dp" android:layout_height="wrap_content" android:layout_below="@id/host_label" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="4dp" android:background="@android:drawable/editbox_background" android:inputType="textEmailAddress" /> <EditText android:id="@+id/port_input" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_below="@id/host_label" android:layout_marginTop="4dp" android:layout_toRightOf="@id/host_input" android:background="@android:drawable/editbox_background" android:inputType="number" /> <TextView android:id="@+id/username_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/host_input" android:paddingLeft="15dp" android:paddingTop="15dp" android:text="username" android:textColor="#a5d4e2" android:textSize="25sp" android:textStyle="normal" /> <EditText android:id="@+id/username_input" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/username_label" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="4dp" android:background="@android:drawable/editbox_background" android:inputType="textEmailAddress" /> <TextView android:id="@+id/password_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/username_input" android:paddingLeft="15dp" android:paddingTop="15dp" android:text="password" android:textColor="#a5d4e2" android:textSize="25sp" android:textStyle="normal" /> <EditText android:id="@+id/password_input" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/password_label" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="4dp" android:background="@android:drawable/editbox_background" android:inputType="textPassword" /> <ImageView android:id="@+id/home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_centerVertical="false" android:paddingLeft="15dp" android:paddingRight="15dp" android:paddingTop="15dp" android:scaleType="fitStart" android:src="@drawable/home" /> <Button android:id="@+id/login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/password_input" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:text=" login " android:textSize="18sp" > </Button></RelativeLayout>
Now provide the response and nothing else.
| You are looking for the android:layout_weight attribute. It will allow you to use percentages to define your layout. In the following example, the left button uses 70% of the space, and the right button 30%. <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:text="left" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight=".70" /> <Button android:text="right" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight=".30" /></LinearLayout> It works the same with any kind of View, you can replace the buttons with some EditText to fit your needs. Be sure to set the layout_width to 0dp or your views may not be scaled properly. Note that the weight sum doesn't have to equal 1, I just find it easier to read like this. You can set the first weight to 7 and the second to 3 and it will give the same result. | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/4961355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/611921/']} | jdg_85113 |
stackexchange | llm_judgeable_groundtruth_similarity | 6027057 |
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 using Androids built in way of handling preferences which works by writing all settings in an xml file. It's really nice but I can't find any good way of doing it without using magic strings in the xml and Java code. The only way I could think of is to save the preference key as String but that doesn't feels right either. Anyone got a good way of solving this?
Now provide the response and nothing else.
| You can move your "magic string" to string resources: In you preference xml file: <EditTextPreference android:key="@string/preferences_pdn_key" android:title="@string/preferences_pdn_title" android:summary="@string/preferences_pdn_summary" android:dialogMessage="@string/input_pdn_message" /> In your values/strings.xml files: ...<string name="preferences_pdn_key">pdn</string>... You then can reference preference from your Activity or PreferenceActivity : SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);String pdnKey = getString(R.string.prefernece_pdn_key);String pdn = sharedPreferences.getString(pdnKey, null); If you don't like to fetch preference keys from string resources all the time you can do yet another trick: public class PreferenceNames { /* categories */ public static final String LoginCategory = MyApplication.getResourceString(R.string.preferences_login_category_key); ... /* preferences */ public static final String Pdn = MyApplication.getResourceString(R.string.preferences_pdn_key); ...} So you can now reference you preference key next way: SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);String pdn = sharedPreferences.getString(PreferenceNames.Pdn, null); And here is how your MyApplication class should look like: public class MyApplication extends Application { private static VvmApplication s_instance; public MyApplication(){ s_instance = this; } public static Context getContext(){ return s_instance; } public static String getResourceString(int resId){ return getContext().getString(resId); }} Plus you need to add next thing to your AndroidManifest.xml : <application android:name="com.mypackage.application.MyApplication" ... >...</application> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6027057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/756833/']} | jdg_85114 |
stackexchange | llm_judgeable_groundtruth_similarity | 56028635 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have a parent component with two child components: const Parent = () => { const [myVar, setmyVar] = useState(false) return ( <> <MyChildComponent1 myVar={myVar} setMyVar={setMyVar} \> <MyChildComponent2 myVar={myVar} \> </> )} Now how would I go about setting the type correctly in MyChildComponent2 ? This is what I've come up with so far: const MyChildComponent1 = ( {myVar, setMyVar}: {myVar: boolean, setMyVar: (value: boolean) => void}) = (...) Is the type for setMyvar correct? Or should it be something else?
Now provide the response and nothing else.
| The type that would match the function returned from invoking useState would be: setMyVar: (value: boolean | ((prevVar: boolean) => boolean)) => void; If we look at the type definition file from DefinitelyTyped [1], we can see that the second type in the return type is a dispatch: function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>]; Thus the generic type provided is passed through to SetStateAction<S> , which is defined as: type SetStateAction<S> = S | ((prevState: S) => S); So essentially, an interface for your component would be the following: interface IProps { myVar: boolean; setMyVar?: (value: boolean | (prevVar: boolean) => boolean) => void;} As @Retsam said, it's best to use React's exported types: import { Dispatch, SetStateAction } from "react";interface IProps { myVar: boolean; setMyVar?: Dispatch<SetStateAction<boolean>>;} References:[1] https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L845 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/56028635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/528617/']} | jdg_85115 |
stackexchange | llm_judgeable_groundtruth_similarity | 22303828 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create components and implement them into my JFrame from different classes within my program. I have created a JTabbedPane, and each tab represents a class. All of the components for each tab are placed in their respective tabs. //creates the JTabbedPane, and the panels. object creation.//panelx corisponds to the tab number as well. tabbs are counted from left to right. tabpane1 = new JTabbedPane();JPanel panel1 = new JPanel();JPanel panel2 = new JPanel();JPanel panel3 = new JPanel();JPanel panel4 = new JPanel();JPanel panel5 = new JPanel();JPanel panel6 = new JPanel();JLabel searchlabel1 = new JLabel("hey");JLabel searchlabel2 = new JLabel("hi");panel1.add(searchlabel1);panel1.add(searchlabel2); //SearchFlight searchflightComp = new SearchFlight(); tabpane1.addTab("Search Flight", panel1); tabpane1.addTab("Select Flight", panel2); tabpane1.addTab("Flight Price", new JLabel("This is tab 1ffff")); tabpane1.addTab("Book Ticket", new JLabel("This is tab 1fff")); tabpane1.addTab("Book Ticket", new JLabel("This is tab fs1")); tabpane1.addTab("Payment", new JLabel("This is tabgf 1")); tabpane1.addTab("Booking Summary", new JLabel("This is tabgf 1")); //added the JTabbedPane to JFrame. frame.getContentPane().add(tabpane1); this works. I am only really working with the first tab right now to get the feel for how it works ect. But I dont even know how to begin. Would I create the a panel in the other class and then return it? or extend the JFrame? thanks guys!
Now provide the response and nothing else.
| The basic question is "why are you calling GetVersionExW in the first place?" The answer to that question determines what you should do instead. The deprecation warning is there to give developers a heads-up about the appcompat behavior change that started in Windows 8.1. See Windows and Windows Server compatibility cookbook: Windows 8, Windows 8.1, and Windows Server 2012 . In short, that function doesn't return what you think it returns by default. Historically, badly written OS version checks are the primary source of appcompat bugs for Windows OS upgrades. There've been a number of different approaches to trying to mitigate this problem (the AppVerifier version lie, the VerifyVersionInfo API, etc.), and this is the most aggressive to date. The VersionHelpers.h mentioned in the comments are in the Windows 8.1 SDK that comes with Visual Studio 2013. They are not a new API; they are just utility code that makes use of the VerifyVersionInfo API introduced back in Windows 2000. These functions are for doing "You must be this high to ride this ride" style checks which are the class of version checks that are most often badly written. The code is pretty simple. For example, the IsWindowsVistaSP2OrGreater test is: VERSIONHELPERAPIIsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor){ OSVERSIONINFOEXW osvi = {}; osvi.dwOSVersionInfoSize = sizeof(osvi); DWORDLONG const dwlConditionMask = VerSetConditionMask( VerSetConditionMask( VerSetConditionMask( 0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); osvi.dwMajorVersion = wMajorVersion; osvi.dwMinorVersion = wMinorVersion; osvi.wServicePackMajor = wServicePackMajor; return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE;}VERSIONHELPERAPIIsWindowsVistaSP2OrGreater(){ return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 2);} You don't need to use VersionHelpers.h as you could just do this kind of code yourself, but they are convenient if you are already using the VS 2013 compiler. For games, I have an article What's in a version number? which uses VerifyVersionInfo to do the kind of reasonable checks one should for game deployment. Note if you are using VS 2013 with the v120_xp platform toolset to target Windows XP, you'll actually be using the Windows 7.1A SDK and #include <VersionHelpers.h> won't work. You can of course use VerifyVersionInfo directly. The other major use of GetVersionExW is diagnostic logs and telemetry. In this case, one option is to continue to use that API and make sure you have the right manifest entries in your application to ensure reasonably accurate results. See Manifest Madness for details on what you do here to achieve this. The main thing to keep in mind is that unless you routinely update your code, you will eventually stop getting fully accurate information in a future version of the OS. Note that it is recommended you put the <compatibility> section in an embedded manifest whether or not you care about the results of GetVersionEx as general best practice. This allows the OS to automatically apply future appcompat fixes based on knowing how the app was originally tested. For diagnostic logs, another approach that might be a bit more robust is to grab the version number out of a system DLL like kernel32.dll using GetFileVersionInfoW . This approach has a major caveat: Do not try parsing, doing comparisons, or making code assumptions based on the file version you obtain this way; just write it out somewhere . Otherwise you risk recreating the same bad OS version check problem that is better solved with VerifyVersionInfo . This option is not available to Windows Store apps, Windows phone apps, etc. but should work for Win32 desktop apps. #include <Windows.h>#include <cstdint>#include <memory>#pragma comment(lib, "version.lib" )bool GetOSVersionString( WCHAR* version, size_t maxlen ){ WCHAR path[ _MAX_PATH ] = {}; if ( !GetSystemDirectoryW( path, _MAX_PATH ) ) return false; wcscat_s( path, L"\\kernel32.dll" ); // // Based on example code from this article // http://support.microsoft.com/kb/167597 // DWORD handle;#if (_WIN32_WINNT >= _WIN32_WINNT_VISTA) DWORD len = GetFileVersionInfoSizeExW( FILE_VER_GET_NEUTRAL, path, &handle );#else DWORD len = GetFileVersionInfoSizeW( path, &handle );#endif if ( !len ) return false; std::unique_ptr<uint8_t> buff( new (std::nothrow) uint8_t[ len ] ); if ( !buff ) return false;#if (_WIN32_WINNT >= _WIN32_WINNT_VISTA) if ( !GetFileVersionInfoExW( FILE_VER_GET_NEUTRAL, path, 0, len, buff.get() ) )#else if ( !GetFileVersionInfoW( path, 0, len, buff.get() ) )#endif return false; VS_FIXEDFILEINFO *vInfo = nullptr; UINT infoSize; if ( !VerQueryValueW( buff.get(), L"\\", reinterpret_cast<LPVOID*>( &vInfo ), &infoSize ) ) return false; if ( !infoSize ) return false; swprintf_s( version, maxlen, L"%u.%u.%u.%u", HIWORD( vInfo->dwFileVersionMS ), LOWORD(vInfo->dwFileVersionMS), HIWORD(vInfo->dwFileVersionLS), LOWORD(vInfo->dwFileVersionLS) ); return true;} If there is some other reason you are calling GetVersionExW , you probably shouldn't be calling it. Checking for a component that might be missing shouldn't be tied to a version check. For example, if your application requires Media Foundation, you should set a "You must be this high to ride this ride check" like the VersionHelpers.h IsWindowsVistaOrGreater for deployment, but at runtime you should use explicit linking via LoadLibrary or LoadLibaryEx to report an error or use a fallback if MFPLAT.DLL is not found. Explicit linking is not an option for Windows Store apps. Windows 8.x solves thisparticular problem by having a stub MFPLAT.DLL and MFStartUp will return E_NOTIMPL.See "Who moved my [Windows Media] Cheese"? Another example: if your application wants to use Direct3D 11.2 if it is available and otherwise uses DirectX 11.0, you'd use set a IsWindowsVistaSP2OrGreater minimum bar for deployment perhaps using the D3D11InstallHelper . Then at runtime, you'd create the DirectX 11.0 device and if it fails, you'd report an error. If you obtain a ID3D11Device , then you'd QueryInterface for a ID3D11Device2 which if it succeeds means you are using an OS that supports DirectX 11.2. See Anatomy of Direct3D 11 Create Device . If this hypothetical Direct3D application supports Windows XP, you'd use a deployment bar of IsWindowsXPSP2OrGreater or IsWindowsXPSP3OrGreater , and then at run time use explicit linking to try to find the D3D11.DLL . If it wasn't present, you'd fall back to using Direct3D 9--since we set the minimum bar, we know that DirectX 9.0c or later is always present. They key point here is that in most cases, you should not use GetVersionEx . Note that with Windows 10 , VerifyVersionInfo and getting the file version stamp via GetFileVersionInfo for kernel32.lib are now subject to the same manifest based behavior as GetVersionEx (i.e. without the manifest GUID for Windows 10, it returns results as if the OS version were 6.2 rather than 10.0). For universal Windows apps on Windows 10, you can a new WinRT API AnalyticsInfo to get a version stamp string for diagnostic logs and telemetry. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22303828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026473/']} | jdg_85116 |
stackexchange | llm_judgeable_groundtruth_similarity | 36803044 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Data : var data = [ { "id": 1, "level": "1", "text": "Sammy", "type": "Item", "items": [ { "id": 11, "level": "2", "text": "Table", "type": "Item", "items": [ { "id": 111, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 112, "level": "3", "text": "Cat", "type": "Item", "items": null } ] }, { "id": 12, "level": "2", "text": "Chair", "type": "Item", "items": [ { "id": 121, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 122, "level": "3", "text": "Cat", "type": "Item", "items": null } ] } ] }, { "id": 2, "level": "1", "text": "Sundy", "type": "Item", "items": [ { "id": 21, "level": "2", "text": "MTable", "type": "Item", "items": [ { "id": 211, "level": "3", "text": "MTDog", "type": "Item", "items": null }, { "id": 212, "level": "3", "text": "MTCat", "type": "Item", "items": null } ] }, { "id": 22, "level": "2", "text": "MChair", "type": "Item", "items": [ { "id": 221, "level": "3", "text": "MCDog", "type": "Item", "items": null }, { "id": 222, "level": "3", "text": "MCCat", "type": "Item", "items": null } ] } ] }, { "id": 3, "level": "1", "text": "Bruce", "type": "Folder", "items": [ { "id": 31, "level": "2", "text": "BTable", "type": "Item", "items": [ { "id": 311, "level": "3", "text": "BTDog", "type": "Item", "items": null }, { "id": 312, "level": "3", "text": "BTCat", "type": "Item", "items": null } ] }, { "id": 32, "level": "2", "text": "Chair", "type": "Item", "items": [ { "id": 321, "level": "3", "text": "BCDog", "type": "Item", "items": null }, { "id": 322, "level": "3", "text": "BCCat", "type": "Item", "items": null } ] } ] } ]; Code : var fdr = [];var fd = function(n) { if (n.items) { _.forEach(n.items, function (value){ fd(value); }); } fdr.push(n);};_.forEach(data, fd);console.log(fdr); Desired output : var data = [ { "id": 1, "level": "1", "text": "Sammy", "type": "Item", "items": [] }, { "id": 11, "level": "2", "text": "Table", "type": "Item", "items": [] }, { "id": 111, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 112, "level": "3", "text": "Cat", "type": "Item", "items": null }, { "id": 12, "level": "2", "text": "Chair", "type": "Item", "items": [] }, { "id": 121, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 122, "level": "3", "text": "Cat", "type": "Item", "items": null }, { "id": 2, "level": "1", "text": "Sundy", "type": "Item", "items": [] }, { "id": 21, "level": "2", "text": "MTable", "type": "Item", "items": [] }, { "id": 211, "level": "3", "text": "MTDog", "type": "Item", "items": null }, { "id": 212, "level": "3", "text": "MTCat", "type": "Item", "items": null }, { "id": 22, "level": "2", "text": "MChair", "type": "Item", "items": [] }, { "id": 221, "level": "3", "text": "MCDog", "type": "Item", "items": null }, { "id": 222, "level": "3", "text": "MCCat", "type": "Item", "items": null }, { "id": 3, "level": "1", "text": "Bruce", "type": "Folder", "items": [] }, { "id": 31, "level": "2", "text": "BTable", "type": "Item", "items": [] }, { "id": 311, "level": "3", "text": "BTDog", "type": "Item", "items": null }, { "id": 312, "level": "3", "text": "BTCat", "type": "Item", "items": null }, { "id": 32, "level": "2", "text": "Chair", "type": "Item", "items": [] }, { "id": 321, "level": "3", "text": "BCDog", "type": "Item", "items": null }, { "id": 322, "level": "3", "text": "BCCat", "type": "Item", "items": null } ]; Conditions : Object have unknowns level. Some child item may have one level down and some could have up to 5. Questions The fd function in the code is what I have come up with. I believe there's a 'cleaner' way to do this, just can't think of something. Plus, the function return items object, render it circular object. JsBin: http://jsbin.com/debojiqove/2/edit?html,js,output Is there a way to flatten object recursively with lodash or just plain JavaScript?.
Now provide the response and nothing else.
| A solution in plain Javascript with respect to the items. It does not mutate the source array. function flat(r, a) { var b = {}; Object.keys(a).forEach(function (k) { if (k !== 'items') { b[k] = a[k]; } }); r.push(b); if (Array.isArray(a.items)) { b.items = a.items.map(function (a) { return a.id; }); return a.items.reduce(flat, r); } return r;}var data = [{ "id": 1, "level": "1", "text": "Sammy", "type": "Item", "items": [{ "id": 11, "level": "2", "text": "Table", "type": "Item", "items": [{ "id": 111, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 112, "level": "3", "text": "Cat", "type": "Item", "items": null }] }, { "id": 12, "level": "2", "text": "Chair", "type": "Item", "items": [{ "id": 121, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 122, "level": "3", "text": "Cat", "type": "Item", "items": null }] }] }, { "id": 2, "level": "1", "text": "Sundy", "type": "Item", "items": [{ "id": 21, "level": "2", "text": "MTable", "type": "Item", "items": [{ "id": 211, "level": "3", "text": "MTDog", "type": "Item", "items": null }, { "id": 212, "level": "3", "text": "MTCat", "type": "Item", "items": null }] }, { "id": 22, "level": "2", "text": "MChair", "type": "Item", "items": [{ "id": 221, "level": "3", "text": "MCDog", "type": "Item", "items": null }, { "id": 222, "level": "3", "text": "MCCat", "type": "Item", "items": null }] }] }, { "id": 3, "level": "1", "text": "Bruce", "type": "Folder", "items": [{ "id": 31, "level": "2", "text": "BTable", "type": "Item", "items": [{ "id": 311, "level": "3", "text": "BTDog", "type": "Item", "items": null }, { "id": 312, "level": "3", "text": "BTCat", "type": "Item", "items": null }] }, { "id": 32, "level": "2", "text": "Chair", "type": "Item", "items": [{ "id": 321, "level": "3", "text": "BCDog", "type": "Item", "items": null }, { "id": 322, "level": "3", "text": "BCCat", "type": "Item", "items": null }] }] }];document.write('<pre>' + JSON.stringify(data.reduce(flat, []), 0, 4) + '</pre>'); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36803044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/661900/']} | jdg_85117 |
stackexchange | llm_judgeable_groundtruth_similarity | 321547 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am considering learning C. But why do people use C (or C++) if it can be used 'dangerously'? By dangerous, I mean with pointers and other similar stuff. Like the Stack Overflow question Why is the gets function so dangerous that it should not be used? . Why do programmers not just use Java or Python or another compiled language like Visual Basic?
Now provide the response and nothing else.
| C predates many of the other languages you're thinking of. A lot of what we now know about how to make programming "safer" comes from experience with languages like C. Many of the safer languages that have come out since C rely on a larger runtime, a more complicated feature set and/or a virtual machine to achieve their goals. As a result, C has remained something of a "lowest common denominator" among all the popular/mainstream languages. C is a much easier language to implement because it's relatively small, and more likely to perform adequately in even the weakest environment, so many embedded systems that need to develop their own compilers and other tools are more likely to be able to provide a functional compiler for C. Because C is so small and so simple, other programming languages tend to communicate with each other using a C-like API. This is likely the main reason why C will never truly die, even if most of us only ever interact with it through wrappers. Many of the "safer" languages that try to improve on C and C++ are not trying to be "systems languages" that give you almost total control over the memory usage and runtime behavior of your program. While it's true that more and more applications these days simply do not need that level of control, there will always be a small handful of cases where it is necessary (particularly inside the virtual machines and browsers that implement all these nice, safe languages for the rest of us). Today, there are a few systems programming languages (Rust, Nim, D, ...) which are safer than C or C++. They have the benefits of hindsight, and realize that most of the times, such fine control is not needed, so offer a generally safe interface with a few unsafe hooks/modes one can switch to when really necessary. Even within C, we've learned a lot of rules and guidelines that tend to drastically reduce the number of insidious bugs that show up in practice. It's generally impossible to get the standard to enforce these rules retroactively because that would break too much existing code, but it is common to use compiler warnings, linters and other static analysis tools to detect these sorts of easily preventable issues. The subset of C programs that pass these tools with flying colors is already far safer than "just C", and any competent C programmer these days will be using some of them. Also, you'll never make an obfuscated Java contest as entertaining as the obfuscated C contest . | {} | {'log_upvote_score': 9, 'links': ['https://softwareengineering.stackexchange.com/questions/321547', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/232425/']} | jdg_85118 |
stackexchange | llm_judgeable_groundtruth_similarity | 2274256 |
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 came across this question in my class: There are 11 different points in the plane with no 3 points are on the same line. a) How many circles do these points define? (Points define a circle if there is a unique circle through those points.) b) How many circles would they define, if 4 points were on the same line? I think, that we just need 2 points, to define a circle (one for the centre and 1 for the radius). In that case a) would be $11\times10=110$ different circles, however that seems to be incorrect. How would you solve it?
Now provide the response and nothing else.
| It doesn't take two points to define a circle, because either of those two points could be the centre. Instead, the solution for part (a) is simply $\binom{11}3=165$ because three non-collinear points uniquely define a circle (assuming that multiplicity is counted, or that no four points are concyclic; if such a quartet existed the number of distinct circles would be lower). For part (b), $\binom43=4$ circles become degenerate and need to be subtracted, so the answer is 161 circles in this case (again, with one of the assumptions above). | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2274256', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/445008/']} | jdg_85119 |
stackexchange | llm_judgeable_groundtruth_similarity | 1634725 |
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 probably easier than I am making it, but basically what I need to do is select the row that has the closest number in a column as a specified value. For example: List of values in database for 3 rows in a specified column: 10, 15, 16 If I specify that I want the row that is closest to 14, it would pick the row with 15. Also, if there are 2+ rows that are the same distance, pick one of them randomly.
Now provide the response and nothing else.
| One option would be something along the lines of: select the_value, abs(the_value - 14) as distance_from_testfrom the_tableorder by distance_from_testlimit 1 To select a random record, you can add , rand() to the order by clause. The disadvantage of this method is that you don't get any benefit from indices because you have to sort on the derived value distance_from_test . If you have an index on the_value and you relax your requirement for the result to be random in the case of ties, you can perform a pair of limited range queries to select the first value immediately above the test value and the first value immediately below the test value and pick whichever is closest to the test value: (select the_valuefrom the_tablewhere the_value >= 14order by the_value asclimit 1)union(select the_valuefrom the_tablewhere the_value < 14order by the_value desclimit 1)order by abs(the_value - 14)limit 1 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1634725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115182/']} | jdg_85120 |
stackexchange | llm_judgeable_groundtruth_similarity | 41127 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My understanding is that the moon was created a long time ago when Earth was hit by a big asteroid. The debris then agglomerated into the Moon, which happens to be orbiting at the exact speed required to neither crash back into the Earth, nor escape into space. Having the exact correct speed seems extremely unlikely. Yet, our moon is there, and many other planets have moons. Are these just the few survivors out of thousands of events that didnt have the « goldilock » speed? 2022 Edit: I got my "ah HA!" moment where everything makes sense after playing 10 minutes of the tutorial of the "Kerbal Space Program" game. Highly recommended.
Now provide the response and nothing else.
| There isn't a "Goldilocks speed" for orbit. If you put two objects in space, and give them a velocity relative to each other, then provided that velocity is less than the escape velocity (at their relative distance) the two objects will orbit each other. Those orbits will be elliptical, and it is possible that the ellipse is skinny and "eccentric" enough for the two bodies to collide when they are closest to each other. But for an object that is several hundred thousand km from Earth, there is a quite a wide range of possible elliptical orbits. So when (and if) the grand collision happened, there was a huge amount of matter that was ejected up into space. Some probably was moving so fast that it escaped, Some certainly went into orbits that didn't have enough energy and so were small skinny ellipses and the matter fell back to Earth. But there was a lot that ended up in some kind of elliptical orbit. This matter was not all in the same orbit, but it started to coalesce, and form into a single ball, under its own gravity. Other moons weren't formed like this, they either formed at the same time as their planets as a "mini solar system" (such as the four major moons of Jupiter) or they were captured from the asteroid or Kuiper belts). Initially, the captured moons may have had rather elliptical orbits. But most moons are in rather circular orbits. Even if the moon was originally in an elliptical orbit, tidal effects will tend to make the orbit more circular. A planet and moon system has a certain amount of angular momentum and a certain amount of energy. The angular momentum can't change, but energy can be converted into heat and since tides dissipate some energy as heat, the orbit will tend to change to a shape that minimizes energy, for a given amount of angular momentum. That shape is a circle. (See Is the moon's orbit circularizing? Why does tidal heating circularize orbits? ) So the effect of tides is to give moons the "Goldilocks speed" that keeps them in a circular orbit. | {} | {'log_upvote_score': 7, 'links': ['https://astronomy.stackexchange.com/questions/41127', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/37869/']} | jdg_85121 |
stackexchange | llm_judgeable_groundtruth_similarity | 14673929 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Due to the need to do some server side code - mainly sending emails I have decided to use Nodejs & Express for the server side element along with Firebase to hold the data - Partly from a learning experience. My question is whats the best approach with regards to using the client side Firebase library and the Nodejs library when doing authentication using the Simple Email & Password API. If I do the authentication client side and then subsequently call a different route on the NodeJS side will the authentication for that user be carried across in the request. What would be the approach to test the user is authenticated within Node. One approach I assume is to get the current users username & password from firebase and then post these to NodeJS and then use the firebase security API on the server to test.
Now provide the response and nothing else.
| Essentially the problem here is you need to securely convey to your NodeJS server who the client is authenticated as to Firebase. There are several ways you could go about this, but the easiest is probably to have all of your client<->NodeJS communication go through Firebase itself. So instead of having the client hit a REST endpoint served by your NodeJS server, have the client write to a Firebase location that your NodeJS server is monitoring. Then you can use Firebase Security Rules to validate the data written by the client and your server can trust it. For example, if you wanted to make it so users could send arbitrary emails through your app (with your NodeJS server taking care of actually sending the emails), you could have a /emails_to_send location with rules something like this: { "rules": { "emails_to_send": { "$id": { ".write": "!data.exists() && newData.child('from').val() == auth.email", ".validate": "newData.hasChildren(['from', 'to', 'subject', 'body'])" } } }} Then in the client you can do: ref.child('emails_to_send').push({ from: '[email protected]', to: '[email protected]', subject: 'hi', body: 'Hey, how\'s it going?'}); And in your NodeJS code you could call .auth() with your Firebase Secret (so you can read and write everything) and then do: ref.child('emails_to_send').on('child_added', function(emailSnap) { var email = emailSnap.val(); sendEmailHelper(email.from, email.to, email.subject, email.body); // Remove it now that we've processed it. emailSnap.ref().remove();}); This is going to be the easiest as well as the most correct solution. For example, if the user logs out via Firebase, they'll no longer be able to write to Firebase so they'll no longer be able to make your NodeJS server send emails, which is most likely the behavior you'd want. It also means if your server is temporarily down, when you start it back up, it'll "catch up" sending emails and everything will continue to work. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14673929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/421828/']} | jdg_85122 |
stackexchange | llm_judgeable_groundtruth_similarity | 18371741 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Our development team has been using the GitFlow branching strategy and it has been great ! Recently we recruited a couple testers to improve our software quality. The idea is that every feature should be tested/QA by a tester. In the past, developers work on features on separate feature branches and merge them back to the develop branch when done. The developer will test his work himself on that feature branch. Now with testers, we start asking this Question On which branch should the tester test new features ? Obviously, there are two options: on the individual feature branch on the develop branch Testing On Develop Branch Initially, we believed this is the sure way to go because: The feature is tested with all other features merged to the develop branch since it's development started. Any conflicts can be detected earlier than later It makes the tester's job easy, he is only dealing with one branch ( develop ) at all time. He doesn't need to ask the developer about which branch is for which feature ( feature branches are personal branches managed exclusively and freely by relevant developers ) The biggest problems with this is: The develop branch is polluted with bugs. When the tester finds bugs or conflicts, he reports them back to the developer, who fixes the issue on the develop branch (the feature branch were abandoned once merged ), and there could be more fixes required afterward. Multiple subsequence commits or merges (if a branch is recreated off develop branch again for fixing the bugs) makes rolling back the feature from the develop branch very difficult if possible. There are multiple features merging to and being fixed on the develop branch at different times. This creates a big issue when we want to create a release with just some of the features in the develop branch Testing On Feature Branch So we thought again and decided we should test features on the feature branches. Before we test, we merge the changes from the develop branch to the feature branch ( catch up with the develop branch ). This is good: You still test the feature with other features in the mainstream Further development ( e.g. bug fix, resolving conflict ) will not pollute the develop branch; You can easily decide not to release the feature until it is fully tested and approved; However, there are some drawbacks The tester has to do the merging of the code, and if there's any conflict (very likely), he has to ask the developer for help. Our testers specialize in test and are not capable of coding. a feature could be tested without the existence of another new feature. e.g. Feature A and B are both under test at the same time, the two features are unaware of each other because neither of them has been merged to the develop branch. These means you will have to test against the develop branch again when both of the features are merged to the develop branch anyway. And you have to remember to test this in the future. If Feature A and B are both tested and approved, but when merged a conflict is identified, both of the developers for both features believe it is not his own fault/job because his feature branch past the test. There is an extra overhead in communication, and sometimes whoever resolving the conflict is frustrated. Above is our story. With limited resource, I would like to avoid testing everything everywhere. We are still looking for a better way to cope with this. I would love to hear how other teams handle this kind of situations.
Now provide the response and nothing else.
| The way we do it is the following: We test on the feature branches after we merge the latest develop branch code on them. The main reason is that we do not want to "pollute" the develop branch code before a feature is accepted. In case a feature would not be accepted after testing but we would like to release other features already merged on develop that would be hell. Develop is a branch from which a release is made and thus should better be in a releasable state. The long version is that we test in many phases. More analytically: Developer creates a feature branch for every new feature. The feature branch is (automatically) deployed on our TEST environment with every commit for the developer to test. When the developer is done with deployment and the feature is ready to be tested he merges the develop branch on the feature branch and deploys the feature branch that contains all the latest develop changes on TEST. The tester tests on TEST. When he is done he "accepts" the story and merges the feature branch on develop. Since the developer had previously merged the develop branch on feature we normally don't expect too many conflicts. However, if that's the case the developer can help. This is a tricky step, I think the best way to avoid it is to keep features as small/specific as possible. Different features have to be eventually merged, one way or another. Of course the size of the team plays a role on this step's complexity. The develop branch is also (automatically) deployed on TEST. We have a policy that even though the features branch builds can fail the develop branch should never fail. Once we have reached a feature freeze we create a release from develop. This is automatically deployed on STAGING. Extensive end to end tests take place on there before the production deployment. (ok maybe I exaggerate a bit they are not very extensive but I think they should be). Ideally beta testers/colleagues i.e. real users should test there. What do you think of this approach? | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18371741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2218907/']} | jdg_85123 |
stackexchange | llm_judgeable_groundtruth_similarity | 584824 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does C++ provide a guarantee for the lifetime of a temporary variable that is created within a function call but not used as a parameter? Here's an example class: class StringBuffer{public: StringBuffer(std::string & str) : m_str(str) { m_buffer.push_back(0); } ~StringBuffer() { m_str = &m_buffer[0]; } char * Size(int maxlength) { m_buffer.resize(maxlength + 1, 0); return &m_buffer[0]; }private: std::string & m_str; std::vector<char> m_buffer;}; And here's how you would use it: // this is from a crusty old API that can't be changedvoid GetString(char * str, int maxlength);std::string mystring;GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN); When will the destructor for the temporary StringBuffer object get called? Is it: Before the call to GetString? After GetString returns? Compiler dependent? I know that C++ guarantees that a local temporary variable will be valid as long as there's a reference to it - does this apply to parent objects when there's a reference to a member variable? Thanks.
Now provide the response and nothing else.
| The destructor for that sort of temporaries is called at the end of the full-expression. That's the most outer expression which is not part of any other expression. That is in your case after the function returns and the value is evaluated. So, it will work all nice. It's in fact what makes expression templates work: They can keep hold references to that sort of temporaries in an expression like e = a + b * c / d Because every temporary will last until the expression x = y Is evaluated completely. It's quite concisely described in 12.2 Temporary objects in the Standard. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/584824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5987/']} | jdg_85124 |
stackexchange | llm_judgeable_groundtruth_similarity | 2563849 |
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 wish to determine the intersection point between a ray and a box. The box is defined by its min 3D coordinate and max 3D coordinate and the ray is defined by its origin and the direction to which it points. Currently, I am forming a plane for each face of the box and I'm intersecting the ray with the plane. If the ray intersects the plane, then I check whether or not the intersection point is actually on the surface of the box. If so, I check whether it is the closest intersection for this ray and I return the closest intersection. The way I check whether the plane-intersection point is on the box surface itself is through a function bool PointOnBoxFace(R3Point point, R3Point corner1, R3Point corner2){ double min_x = min(corner1.X(), corner2.X()); double max_x = max(corner1.X(), corner2.X()); double min_y = min(corner1.Y(), corner2.Y()); double max_y = max(corner1.Y(), corner2.Y()); double min_z = min(corner1.Z(), corner2.Z()); double max_z = max(corner1.Z(), corner2.Z()); if(point.X() >= min_x && point.X() <= max_x && point.Y() >= min_y && point.Y() <= max_y && point.Z() >= min_z && point.Z() <= max_z) return true; return false;} where corner1 is one corner of the rectangle for that box face and corner2 is the opposite corner. My implementation works most of the time but sometimes it gives me the wrong intersection. Please see image: The image shows rays coming from the camera's eye and hitting the box surface. The other rays are the normals to the box surface. It can be seen that the one ray in particular (it's actually the normal that is seen) comes out from the "back" of the box, whereas the normal should be coming up from the top of the box. This seems to be strange since there are multiple other rays that hit the top of the box correctly. I was wondering if the way I'm checking whether the intersection point is on the box is correct or if I should use some other algorithm. Thanks.
Now provide the response and nothing else.
| Increasing things by epsilon is not actually a great way to do this, as you now have a border of size epsilon at the edge of your box through which rays can pass. So you'll get rid of this (relatively common) weird set of errors, and end up with another (rarer) set of weird errors. I assume that you're already envisioning that your ray is traveling at some speed along its vector and find the time of intersection with each plane. So, for example, if you are intersecting the plane at x=x0 , and your ray is going in direction (rx,ry,rz) from (0,0,0) , then the time of intersection is t = x0/rx . If t is negative, ignore it--you're going the other way. If t is zero, you have to decide how to handle that special case--if you're in a plane already, do you bounce off it, or pass through it? You may also want to handle rx==0 as a special case (so that you can hit the edge of the box). Anyway, now you have exactly the coordinates where you struck that plane: they are (t*rx , t*ry , t*rz) . Now you can just read off whether t*ry and t*rz are within the rectangle they need to be in (i.e. between the min and max for the cube along those axes). You don't test the x coordinate because you already know that you hit it Again, you have to decide whether/how to handle hitting corners as a special case. Furthermore, now you can order your collisions with the various surfaces by time and pick the first one as your collision point. This allows you to compute, without resorting to arbitrary epsilon-factors, whether and where your ray intersects your cube, to the accuracy possible with floating point arithmetic. So you just need three functions like the one you've already got: one for testing whether you hit within yz assuming you hit x , and the corresponding ones for xz and xy assuming that you hit y and z respectively. Edit: code added to (verbosely) show how to do the tests differently for each axis: #define X_FACE 0#define Y_FACE 1#define Z_FACE 2#define MAX_FACE 4// true if we hit a box face, false otherwisebool hit_face(double uhit,double vhit, double umin,double umax,double vmin,double vmax){ return (umin <= uhit && uhit <= umax && vmin <= vhit && vhit <= vmax);}// 0.0 if we missed, the time of impact otherwisedouble hit_box(double rx,double ry, double rz, double min_x,double min_y,double min_z, double max_x,double max_y,double max_z){ double times[6]; bool hits[6]; int faces[6]; double t; if (rx==0) { times[0] = times[1] = 0.0; } else { t = min_x/rx; times[0] = t; faces[0] = X_FACE; hits[0] = hit_box(t*ry , t*rz , min_y , max_y , min_z , max_z); t = max_x/rx; times[1] = t; faces[1] = X_FACE + MAX_FACE; hits[1] = hit_box(t*ry , t*rz , min_y , max_y , min_z , max_z); } if (ry==0) { times[2] = times[3] = 0.0; } else { t = min_y/ry; times[2] = t; faces[2] = Y_FACE; hits[2] = hit_box(t*rx , t*rz , min_x , max_x , min_z , max_z); t = max_y/ry; times[3] = t; faces[3] = Y_FACE + MAX_FACE; hits[3] = hit_box(t*rx , t*rz , min_x , max_x , min_z , max_z); } if (rz==0) { times[4] = times[5] = 0.0; } else { t = min_z/rz; times[4] = t; faces[4] = Z_FACE; hits[4] = hit_box(t*rx , t*ry , min_x , max_x , min_y , max_y); t = max_z/rz; times[5] = t; faces[5] = Z_FACE + MAX_FACE; hits[5] = hit_box(t*rx , t*ry , min_x , max_x , min_y , max_y); } int first = 6; t = 0.0; for (int i=0 ; i<6 ; i++) { if (times[i] > 0.0 && (times[i]<t || t==0.0)) { first = i; t = times[i]; } } if (first>5) return 0.0; // Found nothing else return times[first]; // Probably want hits[first] and faces[first] also....} (I just typed this, didn't compile it, so beware of bugs.)(Edit: just corrected an i -> first .) Anyway, the point is that you treat the three directions separately, and test to see whether the impact has occurred within the right box in (u,v) coordinates, where (u,v) are either (x,y), (x,z), or (y,z) depending on which plane you hit. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2563849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278793/']} | jdg_85125 |
stackexchange | llm_judgeable_groundtruth_similarity | 10383305 |
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 sending a string representation of an SVG file to the server and using Imagick to turn this into a jpeg in the following manner: $image = stripslashes($_POST['json']);$filename = $_POST['filename'];$unique = time();$im = new Imagick();$im->readImageBlob($image);$im->setImageFormat("jpeg");$im->writeImage('../photos/' . $type . '/humourised_' . $unique . $filename);$im->clear();$im->destroy(); However I wish to resize the SVG prior to rasterizing it so the the resulting image is larger than the dimensions specified within the SVG file. I modified my code to the following: $image = stripslashes($_POST['json']);$filename = $_POST['filename'];$unique = time();$im = new Imagick();$im->readImageBlob($image);$res = $im->getImageResolution();$x_ratio = $res['x'] / $im->getImageWidth();$y_ratio = $res['y'] / $im->getImageHeight();$im->removeImage();$im->setResolution($width_in_pixels * $x_ratio, $height_in_pixels * $y_ratio);$im->readImageBlob($image);$im->setImageFormat("jpeg");$im->writeImage('../photos/' . $type . '/humourised_' . $unique . $filename);$im->clear();$im->destroy(); This code should work out the resolution and resize the SVG accordingly. It works perfectly if the SVG canvas and it's elements have 'percentage' based widths, however it doesn't appear to work with elements defined in 'px'. Which is unfortunately a requirement. A typical SVG string that will be sent to the server looks like this: <?xml version="1.0" encoding="ISO-8859-1" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd"><svg id="tempsvg" style="overflow: hidden; position: relative;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="333" version="1.1" height="444"> <image transform="matrix(1,0,0,1,0,0)" preserveAspectRatio="none" x="0" y="0" width="333" height="444" xlink:href="http://www.songbanc.com/assets/embed/photos/full/133578615720079914224f9e7aad9ac871.jpg"></image> <image transform="matrix(1,0,0,1,0,0)" preserveAspectRatio="none" x="85.5" y="114" width="50" height="38" xlink:href="http://www.songbanc.com/assets/embed/humourise/elements/thumb/thumb_lips4.png"></image> <path transform="matrix(1,0,0,1,0,0)" fill="none" stroke="#000" d="M110.5,133L140.5,133" stroke-dasharray="- " opacity="0.5"></path> <circle transform="matrix(1,0,0,1,0,0)" cx="140.5" cy="133" r="5" fill="#000" stroke="#000"></circle> <path transform="matrix(1,0,0,1,0,0)" fill="none" stroke="#000" d="M110.5,133L110.5,155.8" stroke-dasharray="- " opacity="0.5"></path> <circle transform="matrix(1,0,0,1,0,0)" cx="110.5" cy="155.8" r="5" fill="#000" stroke="#000"></circle> <circle transform="matrix(1,0,0,1,0,0)" cx="110.5" cy="133" r="5" fill="#000" stroke="#000"></circle></svg> As you can see the elements that make up this SVG has pixel definition widths and heights (using percentages is unfortunately not an option for this application) Is there any way around this? Or any other method of converting an SVG to png and rendering it at a given size without loss of quality. Thanks. EDIT: Although I never actually managed to find a perfect solution. Instead I ended sending the SVG data as json, looping through it server side and scaling the pixels to the intended height. Then, after much trial and error I realised that imagemagick had issues wih the standard SVG transform/rotate commands, throwing any manipulated elements out of whack. I ended up switching too 'inkscape' to render the resulting SVG as a rasterised image. And all is well. I'm still digging into a potential formulatic solution to offset the differences that imagemagick makes. If I have any success I will update this question again.
Now provide the response and nothing else.
| As a workaround of php_imagick's bug , you can scale svg's width=".." and height="..": function svgScaleHack($svg, $minWidth, $minHeight){ $reW = '/(.*<svg[^>]* width=")([\d.]+px)(.*)/si'; $reH = '/(.*<svg[^>]* height=")([\d.]+px)(.*)/si'; preg_match($reW, $svg, $mw); preg_match($reH, $svg, $mh); $width = floatval($mw[2]); $height = floatval($mh[2]); if (!$width || !$height) return false; // scale to make width and height big enough $scale = 1; if ($width < $minWidth) $scale = $minWidth/$width; if ($height < $minHeight) $scale = max($scale, ($minHeight/$height)); $width *= $scale*2; $height *= $scale*2; $svg = preg_replace($reW, "\${1}{$width}px\${3}", $svg); $svg = preg_replace($reH, "\${1}{$height}px\${3}", $svg); return $svg;} Then you can easily create nice transparent PNG! createThumbnail('a.svg', 'a.png');function createThumbnail($filename, $thname, $size=50){ $im = new Imagick(); $svgdata = file_get_contents($filename); $svgdata = svgScaleHack($svgdata, $size, $size); $im->setBackgroundColor(new ImagickPixel('transparent')); $im->readImageBlob($svgdata); $im->setImageFormat("png32"); $im->resizeImage($size, $size, imagick::FILTER_LANCZOS, 1); file_put_contents($thname, $im->getImageBlob()); $im->clear(); $im->destroy();} Note:I've been searching for a solution how to rescale SVG from its initial small size. However it seems that imagick::setResolution is broken. However, ImageMagick library itself is working, so you can use exec('convert...') (might be disabled for security reasons by hosting provider). So to create thumbnail 50x50 from smaller svg you would do: convert -density 500 -resize 50 50 -background transparent a.svg PNG32:a.png | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10383305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/884934/']} | jdg_85126 |
stackexchange | llm_judgeable_groundtruth_similarity | 12210378 |
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 table called Users : CreateTime UserName========================================2012-08-30 14:23:12:000 zhang2012-08-30 15:11:13:000 li2012-08-30 16:32:22:000 wang2012-08-31 11:23:12:000 steven2012-08-31 12:05:14:000 zhao2012-08-31 08:23:12:000 ddd and a query: select UserName from Users where CreateTime >= '2012-08-30' and CreateTime <= '2012-08-31' So, the results should be 6 rows, but it does not. How to solve this? Using SQL Server Convert function CONVERT(VARCHAR(23), CreateTime, 121) ?
Now provide the response and nothing else.
| It is not showing 6 rows because 2012-08-31 is received by the interpreter as 2012-08-31 00:00:00 AM . Since you want to see data up to and including the 31st, you can either explicitly mention the time or query the next day's date. Example Using the Next Day's Date SELECT UserName FROM Users WHERE CreateTime >= '2012-08-30' AND CreateTime < '2012-09-01' Example with Time Explicitly Mentioned SELECT UserName FROM Users WHERE CreateTime >= '2012-08-30 00:00:00' AND CreateTime < '2012-09-31 23:59:59' | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12210378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441222/']} | jdg_85127 |
stackexchange | llm_judgeable_groundtruth_similarity | 98651 |
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:
How can the speed of sound be calculated for temperatures below 0 °C (down to -40 °C)? Does the calculation $v=331\ \frac{m}{s} + 0.6 \frac{m}{s°C} \times T$ still hold (where T's unit is °C)?
Now provide the response and nothing else.
| The speed of sound in an ideal gas is given by $$a = \sqrt{\gamma R T}$$ Where $\gamma = \frac{C_p}{C_v}$, $R$ is the specific ideal gas constant and $T$ is the absolute temperature. Taking standard values for air, this makes a graph like this: The linear approximation is plotted by your formula, $a = 331\ \frac{m}{s}\ +\ 0.6 \frac{m}{sK} (T - 273\ K)$, with the 273 K to convert it to the Kelvin scale. As you can see, the linear approximation is nearly equal to the actual value in the range marked by the two black lines, from $T \approx 240\space\mathrm{K}$ to $T \approx 350\space\mathrm{K}$. If you don't care about accuracy so much, you could even stretch your definition to $T\ \epsilon\ [200\space\mathrm{K},375\space\mathrm{K}]$, as shown by the green lines. The error is: $\approx +1.3\%$ at $T=200\space\mathrm{K}$ $\approx +1.0\%$ at $T=375\space\mathrm{K}$ As seen in the following graph of the percentage error of your approximation between $173\space\mathrm{K}$ and $473\space\mathrm{K}$. Of course, at low temperatures air doesn't behave like an ideal gas, so it all breaks down, but for the purposes of this question, I believe it's a fair assumption. | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/98651', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/40343/']} | jdg_85128 |
stackexchange | llm_judgeable_groundtruth_similarity | 1980909 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was playing around with square roots today when I "discovered" this. $\sqrt{1 + \sqrt{1 + \sqrt{1 + ...}}} = x$ $\sqrt{1 + x} = x$ $1 + x = x^2$ Which, via the quadratic formula, leads me to the golden ratio. Is there any significance to this or is it just a random coincidence?
Now provide the response and nothing else.
| Any expression of the form $\sqrt{n+\sqrt{n+\sqrt{n+\ldots}}}$ will have a valueof the form $$\frac{-1\pm\sqrt{1+4n}}{2}$$so it is no coincidence that you get a simple answer like you got. As to whether it is a coincidence that this is the golden ratio, pretty much the defining expression for the golden ratio comes from a rectangle out of which a square is cut, leaving a similar rectangle -- and that diagram immediately gives you $$ \frac{1+x}{x} = \frac{x}{1} \implies 1+x = x^2$$So although a bit of opinion creeps in, I'd say this is no coincidence. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1980909', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/380229/']} | jdg_85129 |
stackexchange | llm_judgeable_groundtruth_similarity | 19202368 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
gcc 4.8 give me an error when I build #include <string.h>#include <stdio.h>static inline void toto(char str[3]){ snprintf(str, sizeof(str), "XX"); }int main(){ char str[3]; toto(str); return 0;} Here is the gcc error error: argument to ‘sizeof’ in ‘snprintf’ call is the same expression as the destination; did you mean to provide an explicit length? Note: I m using -Wall -Werror flags which convert warning to error. There is something similar here In a comment, someone answered this "For fixed length buffers, I usually use strncpy(dest, src, sizeof(dest)); dest[sizeof(dest)-1] = '\0'; That guarantees NULL termination and is just less hassle than snprintf not to mention that a lot of people use snprintf(dest, sizeof(dest), src); instead and are very surprised when their programs crash arbitrarily." But this is wrong:gcc 4.8 say "error: argument to ‘sizeof’ in ‘strncpy’ call is the same expression as the destination; did you mean to provide an explicit length? [-Werror=sizeof-pointer-memaccess]" in gcc 4.8 documentation, they are talking about this issue :they say: The behavior of -Wall has changed and now includes the new warning flag -Wsizeof-pointer-memaccess. This may result in new warnings in code that compiled cleanly with previous versions of GCC. For example, include string.hstruct A { };int main(void) { A obj; A* p1 = &obj; A p2[10]; memset(p1, 0, sizeof(p1)); // error memset(p1, 0, sizeof(*p1)); // ok, dereferenced memset(p2, 0, sizeof(p2)); // ok, array return 0;} Gives the following diagnostic:warning: argument to ‘sizeof’ in ‘void memset(void*, int, size_t)’ call is the same expression as the destination; did you mean to dereference it? [-Wsizeof-pointer-memaccess] memset(p1, 0, sizeof(p1)); // error ^Although these warnings will not result in compilation failure, often -Wall is used in conjunction with -Werror and as a result, new warnings are turned into new errors.To fix, either re-write to use memcpy or dereference the last argument in the offending memset call.* Well, in their example, it's obvious the code was wrong, but in my case, with snprintf/strncpy, I dont see why, and I think it's a false positif error of gcc. Right ? thanks for your help
Now provide the response and nothing else.
| An array decays into a pointer to the first element when you passed to a function. So what you have in static inline void toto(char str[3]) {..} is not an array but a pointer. Hence, gcc rightly warns. Whether you specify the size in the function parameter or not doesn't matter as: static inline void toto(char str[3]) and static inline void toto(char str[]) and static inline void toto(char *str) are all equivalent. Read here on this: what is array decaying? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19202368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1603778/']} | jdg_85130 |
stackexchange | llm_judgeable_groundtruth_similarity | 7880921 |
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 just want to know what is a parent table and what is a child table in databases. Can you please show me an example so I understand how it works please. Thank You
Now provide the response and nothing else.
| Child tables and parent tables are just normal database tables, but they’re linked in a way that's described by a parent–child relationship. It’s usually used to specify where one table’s value refers to the value in another table (usually a primary key of another table). For example, imagine a news article. This could be represented by a table called articles and has fields for id , headline , body , published_date and author . But instead of placing a name in the author field, you could instead put the ID value of a user in a separate table—maybe called authors —that has information on authors such as id , name , and email . Therefore, if you need to update an author’s name, you only need to do so in the authors (parent) table; because the articles (child) table only contains the ID of the corresponding author record. Hope this helps you understand better. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7880921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1096892/']} | jdg_85131 |
stackexchange | llm_judgeable_groundtruth_similarity | 45177025 |
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 having trouble writing an asynchronous function using promises function requestsPlot(plot, info) { return new Promise(function(resolve, reject) { var plotObject = fieldsObject[plot] var sqr = new Promise(function(resolve1, reject) { debugger; get(createSQRurl(plotObject.polygon)) .then(function(result) { plotObject.quality = sqrHtmlParsing(result); resolve1(); }); }); var soilType = new Promise(function(resolve2, reject) { get(createSoilTypeUrl(plotObject.polygon)) .then(function(result) { plotObject.soilType = soilTypeHtmlParsing(result); resolve2(); }); }); var distance = new Promise(function(resolve3, reject) { var start = turf.centerOfMass(plotObject.polygon).geometry.coordinates; var end = info.homeCoords; get('http://router.project-osrm.org/route/v1/driving/' + start + ';' + end + '?overview=false') .then(function(result) { var parsed = JSON.parse(result); if (parsed.code == 'Ok') { plotObject.distance = parsed.routes[0].distance / 1000; resolve3() } else { plotObject.distance = ''; resolve3() } }); }); Promise.all([sqr, soilType, distance]).then(function() { resolve('test'); }) })} The idea is to resolve the promise returned by the requestPlot function after all promises inside the function (variables sqr, soilType and distance) are resolved. However, the promise is resolved while all requests in the get function are still pending. Note that the 'get' function also returns a promise.Thanks a lot for your help! P.S. here's the get function function get(url) { var requestPromise = new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('get', url); req.onload = function() { if (req.status == 200) { resolve(req.response); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); }); return requestPromise}
Now provide the response and nothing else.
| Nesting promises within promises is a well-known anti-pattern . You don't need any of those promise constructors because you already have get which returns a promise and you can just use it directly. Here's how you can re-write your code: function requestsPlot(plot, info) { const sqr = get(createSQRurl(plotObject.polygon)) .then(sqrHtmlParsing); const soilType = get(createSoilTypeUrl(plotObject.polygon)) .then(soilTypeHtmlParsing); const start = turf.centerOfMass(plotObject.polygon).geometry.coordinates; const end = info.homeCoords; const distance = get('http://router.project-osrm.org/route/v1/driving/' + start + ';' + end + '?overview=false') .then(JSON.parse); return Promise.all([sqr, soilType, distance]) .then(([parsedSqr, parsedSoilType, parsedDistance]) => Object.assign(plotObject, { quality: parsedSqr, soilType: parsedSoilType, distance: parsedDistance.code == 'Ok' ? parsed.routes[0].distance / 1000 : '' }))} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45177025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6213343/']} | jdg_85132 |
stackexchange | llm_judgeable_groundtruth_similarity | 3639 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Does ramification have anything to do with inseparability? It feels like an extension of Q in which p ramifies should somehow correspond to an extension of F_p(t). Does totally ramified <--> purely inseparable? In fact, saying an irreducible polynomial f(x) is inseparable is the same as saying that f(x) ramifies when we extend Q[x] to L[x], where L is the splitting field of f(x). By correspond, I generally mean taking an extension of Q defined by a root of p(x)=r, where r is a rational making the extension nontrivial, and then extending F_p(t) by a root of p(x)=t. It's interesting because then this extension of F_p(t) corresponds to a number of extensions of Q (this is the same thing when you do Galois theory by looking at fundamental groups of branched coverings of C. Then do you look at etale fundamental groups of objects associated to these function fields over finite fields?).
Now provide the response and nothing else.
| Let $(A,\mathfrak{m})$ and $(B,\mathfrak{n})$ be local rings, with a local map $f : A \to B$ . (The condition that $f$ is local means that $f^{-1}(n) = m$ .) Also, assume that $f$ obeys a finiteness condition called "essentially of finite type"; I'll ignore this. By definition, $f$ is unramified if (1) $B\mathfrak m=\mathfrak n$ and (2) $B/\mathfrak n$ is a seperable extension of $A/\mathfrak m$ . Condition (1) is usually the hard part to verify, but in this answer I will concentrate on condition (2) and try to provide some intuition for why this condition is included. Let $f:A \to B$ be a map of rings. I might need some finite generation hypothesis; I'm not sure. Then f is unramified if and only if the following is true: For every prime ideal $\mathfrak p$ in $A$ , the tensor product $B \otimes_{A} \bar{\frac{A}{\mathfrak{p}}}$ is isomorphic to a direct sum of several copies of $\frac{A}{\mathfrak{p}}$ . Here the bar indicates algebraic closure. Tensoring with the algebraic closure of the residue field at a prime is called "taking the geometric fiber" over that prime, in algebraic geometry. So the geometric statement is that a map is unramified if and only if all of its geometric fibers are reduced and of dimension $0$ . (Again, modulo any finiteness hypothesis I may have forgotten.) The point here is that, if $L/K$ is a separable algebraic field extension, then $L \otimes_K \bar{K}$ is isomorphic to $\bar{K}^{[L:K]}$ . For an inseparable extension, this tensor product has nilpotents. (Specifically, if $t$ is in $L$ but not in $K$ , and $t^p=u$ is in $K$ , then $(t-u^{1/p})$ will become nilpotent in the tensor product.) So the geometric fiber will not be reduced for such an extension. While the definition of unramified requires separability, in the sense explained above, there is no implication in the other direction. I used the early parts of deJong's notes as a reference when writing this. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/3639', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1355/']} | jdg_85133 |
stackexchange | llm_judgeable_groundtruth_similarity | 134829 |
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 am using Solaris 10 and so grep options involving -f don't work. I have two pipe-separated files: file1: abc|123|BNY|apple|cab|234|cyx|orange|def|kumar|pki|bird| file 2: abc|123|kumar|pki|cab|234 I would like to compare the first two columns of file2 with file1 (search through the entire contents of file1 in first two columns) if they match print the matched line of file1. Then search for the second line of file 2 and so on. Expected Output: abc|123|BNY|apple|cab|234|cyx|orange| The files I have are huge, containing about 400,000 lines, so I would like to make the execution fast.
Now provide the response and nothing else.
| This is what awk was designed for: $ awk -F'|' 'NR==FNR{c[$1$2]++;next};c[$1$2] > 0' file2 file1abc|123|BNY|apple|cab|234|cyx|orange| Explanation -F'|' : sets the field separator to | . NR==FNR : NR is the current input line number and FNR the current file's line number. The two will be equal only while the 1st file is being read. c[$1$2]++; next : if this is the 1st file, save the 1st two fields in the c array. Then, skip to the next line so that this is only applied on the 1st file. c[$1$2]>0 : the else block will only be executed if this is the second file so we check whether fields 1 and 2 of this file have already been seen ( c[$1$2]>0 ) and if they have been, we print the line. In awk , the default action is to print the line so if c[$1$2]>0 is true, the line will be printed. Alternatively, since you tagged with Perl: perl -e 'open(A, "file2"); while(<A>){/.+?\|[^|]+/ && $k{$&}++}; while(<>){/.+?\|[^|]+/ && do{print if defined($k{$&})}}' file1 Explanation The first line will open file2 , read everything up to the 2nd | ( .+?\|[^|]+ ) and save that (the $& is the result of the last match operator) in the %k hash. The second line processes file1, uses the same regex to extract the 1st two columns and print the line if those columns are defined in the %k hash. Both of the above approaches will need to hold the 2 first columns of file2 in memory. That shouldn't be a problem if you only have a few hundred thousand lines but if it is, you could do something like cut -d'|' -f 1,2 file2 | while read pat; do grep "^$pat" file1; done But that will be slower. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/134829', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/68365/']} | jdg_85134 |
stackexchange | llm_judgeable_groundtruth_similarity | 4462074 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Jumping from article to article, I can see everywhere the expression "bulk loading". What does it really (technically) mean? What does it imply? Explanation based on use-cases is welcome.
Now provide the response and nothing else.
| Indexes are usually optimized for inserting rows one at a time. When you are adding a great deal of data at once, inserting rows one at a time may be inefficient. For instance, with a B-Tree, the optimal way to insert a single key is very poor way of adding a bunch of data to an empty index. Instead you pursue a different strategy with B-Trees. You presort all of the data, and group it in blocks. You can then build a new B-Tree by transforming the blocks into tree nodes. Although both techniques have the same asymptotic performance, O(n log(n)), the bulk-load operation has much smaller factor. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4462074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/290613/']} | jdg_85135 |
stackexchange | llm_judgeable_groundtruth_similarity | 365263 |
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:
A CentOS 7 server needs to have a new user created with a specific home directory and shell defined as follows, taken from the instructions at this link : sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucket However, when that command is run on a CentOS 7 server, the command fails with the following error: useradd: cannot create directory /opt/atlassian/bitbucket Similarly, creating the /opt/atlassian/bitbucket directory before-hand results in the following error: useradd: warning: the home directory already exists.Not copying any file from skel directory into it. What specific changes need to be made to these commands, so that the new atlbitbucket user can successfully be created? The Complete Terminal Output: The following is the complete series of commands and responses in the CentOS 7 terminal: Manually Creating The Directories: login as: [email protected]'s password:Last login: Mon May 15 14:00:18 2017[my_sudoer_user@localhost ~]$ sudo mkdir /opt/atlassian/[sudo] password for my_sudoer_user:[my_sudoer_user@localhost ~]$ sudo mkdir /opt/atlassian/bitbucket[my_sudoer_user@localhost ~]$ sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucketuseradd: warning: the home directory already exists.Not copying any file from skel directory into it.[my_sudoer_user@localhost ~]$ sudo rmdir /opt/atlassian/bitbucket[my_sudoer_user@localhost ~]$ sudo rmdir /opt/atlassian/ The Recommended useradd Syntax: [my_sudoer_user@localhost ~]$ sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucketuseradd: user 'atlbitbucket' already exists[my_sudoer_user@localhost ~]$ sudo userdel -r atlbitbucketuserdel: atlbitbucket home directory (/opt/atlassian/bitbucket) not found[my_sudoer_user@localhost ~]$ sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucketuseradd: cannot create directory /opt/atlassian/bitbucket[my_sudoer_user@localhost ~]$ adduser Instead Of useradd I then tried @terdon's suggestion from this other posting to use adduser instead, but got the same error, as follows: [my_sudoer_user@localhost ~]$ sudo userdel -r atlbitbucket[sudo] password for my_sudoer_user:userdel: atlbitbucket mail spool (/var/spool/mail/atlbitbucket) not founduserdel: atlbitbucket home directory (/opt/atlassian/bitbucket) not found[my_sudoer_user@localhost ~]$ sudo adduser --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucketadduser: cannot create directory /opt/atlassian/bitbucket[my_sudoer_user@localhost ~]$ Shorter Syntax: Then I tried @rajcoumar's suggestion from the same other posting , but got the same following results: [my_sudoer_user@localhost ~]$ sudo userdel -r atlbitbucketuserdel: atlbitbucket mail spool (/var/spool/mail/atlbitbucket) not founduserdel: atlbitbucket home directory (/opt/atlassian/bitbucket) not found[my_sudoer_user@localhost ~]$ sudo useradd -m -d /opt/atlassian/bitbucket -s /bin/bash atlbitbucketuseradd: cannot create directory /opt/atlassian/bitbucket[my_sudoer_user@localhost ~]$ Elevating To root : I even upgraded to root just to see if the problem could be resolved by running the command as root, but I still got the following error: [my_sudoer_user@localhost ~]$ su -Password:Last login: Mon May 15 14:07:11 PDT 2017 on ttyS0[root@localhost ~]# /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucketuseradd: cannot create directory /opt/atlassian/bitbucket[root@localhost ~]#
Now provide the response and nothing else.
| The useradd code calls a mkdir library function to (attempt to) create the specified directory. useradd checks the return code, but only for being non-zero; in this case, I suspect that mkdir is returning ENOENT -- A directory component in pathname does not exist or is a dangling symbolic link because the parent directory (/opt/atlassian) didn't exist, or had been removed during your attempts to add the user. As Kusalananda / roaima point out, the simplest solution here is to create the parent directory structure before calling useradd: sudo mkdir -p /opt/atlassian sudo /usr/sbin/useradd --create-home --home-dir /opt/atlassian/bitbucket --shell /bin/bash atlbitbucket | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/365263', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/92670/']} | jdg_85136 |
stackexchange | llm_judgeable_groundtruth_similarity | 68224410 |
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 display an array of text in a Crystal Reports document in the details section but I only get 1 row of the first array which I send using the .ToArray() function - these values are shown but my section doesn't extend by rows. I suspect this is my fault with the details section options, but I have wasted a lot of time trying to find the cause. Would anyone be able to help? List<string> arrayList = new List<string>();report.Load(path);report.SetParameterValue("name", arrayList.ToArray()); displaying parameter values raport result
Now provide the response and nothing else.
| You can try: library(tidyverse)dlist %>% map_df(~names(.x) %>% enframe(), .id = "id") %>% pivot_wider(names_from = name, id_cols = id)# A tibble: 3 x 5 id `1` `2` `3` `4` <chr> <chr> <chr> <chr> <chr>1 mtcars1 mpg cyl NA NA 2 mtcars2 mpg cyl disp NA 3 mtcars3 mpg cyl disp hp Or same idea in base: reshape(stack(lapply(dlist, names)), idvar = "ind", timevar = "values", direction = "wide", v.names = "values") ind values.mpg values.cyl values.disp values.hp1 mtcars1 mpg cyl <NA> <NA>3 mtcars2 mpg cyl disp <NA>6 mtcars3 mpg cyl disp hp | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/68224410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16365092/']} | jdg_85137 |
stackexchange | llm_judgeable_groundtruth_similarity | 73779 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Our security experts, database administrators, network team and infrastructure team are all saying it's OK to have the database server located in the DMZ along with the HTTP server and middle-ware server. Their reason: If the database server is compromised (because of an insecure middle tier), at least the database server is outside the internal system. If it is inside our network, the hacker can then use the database server to access other systems. What they are saying is: Let's not put the middle-ware server behind a second firewall and the database server behind a third firewall. Let's use just one firewall (the HTTP server's) in case a hacker wants to get our database's sensitive data, at least that's all they can get. The second statement was actually said... verbatim. Please note that this database server will hold sensitive information, including bank details. Now, are these experts making any sense to you? I'm a software developer, and I can't get their logic. It's like, "Put the jewelry box outside the house so that robbers won't bother getting in for the TV?"
Now provide the response and nothing else.
| SANS' "Making Your Network Safe for Databases" ( http://www.sans.org/reading-room/whitepapers/application/making-network-safe-databases-24 ) reads a little dated in some sections, but provides a decent "for dummies" level of guidance in the direction you're after. You could also exhaust yourself poking through the US NIST's resource centre ( http://csrc.nist.gov/ ). I think ISO's ISO/IEC 27033-2:2012 would be on topic too, but don't have a copy at hand to be sure. You're trying to separate/isolate the most sensitive servers (the database servers) from the most exposed (and therefore vulnerable). You're proposing a "defense in depth" approach, that seeks to a) prevent attacks where possible, and b) delay their progress (and access to the important stuff) when not. Ideally, everything is always hardened and patched, servers only listen for traffic on required ports, and only from allowed devices, all traffic "in flight" is inaccessible to unauthorized listeners (through encryption and/or isolation), and everything is monitored for intrusion and integrity. If all that is in place with 100% certainty, then great, your "opposition" have addressed point a) above, as much as is possible . Great start, but what about point b)? If a web server does get compromised, your proposed architecture is in a much better spot. Their potential attack footprint, and vector, is much larger than it needs to be. The justification for separate database from web servers is no different than the justification they've accepted for separating web servers from LAN. More bluntly: if they're so convinced a compromised web server presents no danger to other systems in the same security zone, why do they think a DMZ is required at all? It's awfully frustrating to be in your situation. At the very least, in your position I'd create a risk memo outlining your concerns and suggestions, and ensure they acknowledge it. CYA, anyway. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/73779', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/61522/']} | jdg_85138 |
stackexchange | llm_judgeable_groundtruth_similarity | 4932 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I read about perchloride in a talk and after trying to search for its chemical formula, the search results imply that perchloride is actually named perchlorate. Is this correct?
Now provide the response and nothing else.
| Short answer: Yes, sometimes "perchlorate" can be called "perchloride" in older literature, but because of the classical definition of a "perchloride", it's so confusing and technically wrong that the $\ce{ClO_4^-}$ anion should be called either "perchlorate" or "chlorate(VII)". In older naming systems, pre-IUPAC, a "per-ide" is quite simply "any substance containing an unusually high proportion of the named element". So, a " perchloride " is any substance with more chlorine than is "normal" for that mixture of elements. This name was typically given to metal halide salts where the metal has multiple possible oxidation states; the highest oxidation state of the metal forms the metal "per-X-ide". for instance, titanium perchloride aka titanium tetrachloride, $\ce{TiCl_4}$ (IUPAC name titanium(IV) chloride), as differentiated from the trichloride and dichloride salts of titanium, and iron perchloride aka ferric chloride (that name's rarely used as iron only has two stable chlorides, and so the traditional "ferric" and "ferrous" descriptors work fine). However, the perchlorate anion isn't actually a "perchloride" by that definition; it's more a "peroxide", as there's only one chlorine (which is relatively "normal") that has been "superoxidized" by four oxygens (not normal). This use of "perchloride" as a synonym for "perchlorate" is more the result of a bad simplification of the traditional naming system, where salts of "-ic" acids are "-ides". While the rule follows for the hydrohalic acids (HF, HCl, HBr, HI) and most oxoacids (which, when they end in "-ous", form "-ites", as in hypofluorous acid, chlorous acid and sulfurous acid), the highly oxygenated oxoacids like chloric, perchloric, sulfuric, nitric, phosphoric and boric acids form "-ates", not "-ides", to mirror the low-oxygen "-ous" acids and their "-ite" anions/salts. When not talking about the perchlorate anion, you sometimes hear about organic molecules that have had all their hydrogens replaced by halogens. Perchlorocarbons and perfluorocarbons are the chlorine and fluorine derivatives of hydrocarbons (for instance, the dry-cleaning chemical perchloroethylene, "Perc", and the perfluoroethylene monomer of polytetrafluoroethylene, aka Teflon). "Peroxide" has found a home in the IUPAC system as the official name of the $\ce{(O_2)^{2-}}$ anion, composed of two single-bonded oxygens (often as the related "hydroperoxide", which is an OOH functional group bound to a carbon or to hydrogen). However, because each chlorine anion in a "perchloride" is typically bound to whatever the chlorine is oxidizing, the multiple chlorides are not a single anion and so aren't named as such in IUPAC. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/4932', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/710/']} | jdg_85139 |
stackexchange | llm_judgeable_groundtruth_similarity | 11234854 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to understand whats the best way to handle exceptions in Multicast delegates ? My question is, what happens if a method throw exception in Multicast delegate execution ? Will it stop ? Continue ? How to handle ? A small program with explanation will be really helpful if somebody can share please.... thank you....
Now provide the response and nothing else.
| The exception will be propagated immediately, and any "later" actions in the delegate's invocation list will not get executed. If you want to make sure you execute all the delegates - perhaps aggregating all the exceptions together, for example - you'd need to call Delegate.GetInvocationList , cast each of those delegates to the same type as the original, and invoke them one by one, catching the exceptions as they were thrown. Here's some sample code which does this - it would be nice to do this in a more generic way, ideally building a new delegate which (when executed) would execute all of the constituent delegates and aggregate the exceptions... but this is a start. using System;using System.Collections.Generic;using System.Threading.Tasks;class Program{ public static void Main() { Action x = null; x += () => Console.WriteLine("First"); x += () => { throw new Exception("Bang 1"); }; x += () => { throw new Exception("Bang 2"); }; x += () => Console.WriteLine("Second"); try { ExecuteAll<Action>(x, action => action()); } catch (AggregateException e) { Console.WriteLine(e); } } public static void ExecuteAll<T>(Delegate multi, Action<T> invoker) { List<Exception> exceptions = new List<Exception>(); foreach (var single in multi.GetInvocationList()) { try { invoker((T)(object)single); } catch (Exception e) { exceptions.Add(e); } } if (exceptions.Count > 0) { throw new AggregateException(exceptions); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11234854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1183979/']} | jdg_85140 |
Subsets and Splits