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 | 7017 |
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:
I had thought that Lamarckian evolution had been essentially dismissed in favour of Darwinian evolution. Lamarckian evolution as I understand it is essentially the idea that the traits an organism develops in it's lifetime can then be passed to its offspring. However, Wikipedia states that it is still being considered and investigated and so has apparently not been completely dismissed. Interest in Lamarckism has recently increased, as several studies inthe field of epigenetics have highlighted the possible inheritance ofbehavioral traits acquired by the previous generation I am getting out of my depth here, however I thought epigenetics was genes being suppressed or influenced by the environment which is similar but separate from learned traits being passed on. Is Lamarckian evolution disproven and being conflated with epigenetics here, or is there still credence being given to the theory that traits acquired in a lifetime can be passed on?
Now provide the response and nothing else.
| I’m sorry, this is a long one. Unfortunately, the topic is complicated and I try to make it as understandable as possible. I’ll omit most of the technical details since they are hard to explain and don’t add a lot. Executive Summary (“tl;dr”) Epigenetic modifications do not constitute, nor enable, Lamarckian inheritance. Papers and reviews that claim this use a convoluted and ultimately useless definition of Lamarckism and inheritance. However , a paper from December 2011 does actually demonstrate a very specific case where Lamarckian inheritace does occur (without epigenetic involvement). It bears repeating that this does not in the least violate Darwinism. In fact, the results, though surprising, are entirely in line and predicted by Darwinism – the mechanism actually relies on Darwinism. Contrary to popular belief, Darwinism and Lamarckism are not actually in opposition. Preliminary The problem, as so often, is the unclear definition of terms: what, exactly, is Lamarckian inheritance ? Ask five scientists today and you will get six answers. And Lamarck himself would have disagreed with all of them. This is simply due to the fact that Lamarck wasn’t aware of a lot of mechanistic concepts that were developed long after his death – such as the distinction between somatic cells and germline. This distinction leads to the concept of the Weismann barrier and it’s of eminent importance for our modern understanding of inheritance (and hence Darwinism): simply put, the Weismann barrier postulates that in order for traits to be inheritable, they need to be carried in the germline. As a consequence, modifications in the soma (non-germline cells) are not inherited. Most scientists today see this as a direct opposition to Lamarckism. But there are of course plenty of organisms (most, in fact) that do not have a distinction between soma and germline: notably, all unicellular life. For those life-forms, all genetically acquired traits (be it through mutation or through the integration of plasmids ) are heritable. This is trivially true. Enter Epigenetics Once again, there are different definitions, but the generally agreed-on definition of epigenetics today runs something like this: Epigenetics is the study of heritable changes in cell behaviour that are not due to changes in the genetic sequence. Notice that here, “heritable” does not refer to heritability of organisms, just of cells: the daughter cells of a dividing mother cell inherit its epigenetic traits (and once again, this isn’t Lamarckism, it’s not even Darwinism, it’s on a much lower level). There are several known mechanism of epigenetics, notable among them methylation and histone modification . How exactly they work isn’t terribly relevant; what’s important is that they modify the accessibility of genes on the genome: they control whether a cell can actually read a section of the genome and use it. Cells use this to determine their specificity: how do muscle cells and brain cells know which job to do? Epigenetic modifications are (part of) the answer. How Heritable Are Epigenetics? Epigenetics are not generally heritable (due to the Weismann barrier). There have been several papers that, using similar lines of reasoning, have tried to argue that epigenetics can lead to the inheritance of acquired traits. I will showcase the argument using one well-known paper, Epigenetic programming by maternal behavior [1]. The paper examined two different groups of mice which were raised by two phenotypically different mothers. Group 1 had been licked and groomed by their mother in the first six days after their birth. Group 2 hadn’t. Female group 1 mice predominantly developed into mothers which would themselves lick and groom their offspring (“high LG/ABN”). Group 2 females developed into mothers which neglected their offspring (“low LG/ABN”), as shown in the following schematic: It was shown that the mechanism behind this is epigenetic: pups of a high LG/ABN mother had increased serotonin levels which in turn led to decreased methylation of some genetic regions which modified their behaviour. And since the behaviour is self-perpetuating, the authors argued that it’s a form of inheritance (“ soft inheritance ”). However, this is in fact not entirely true: the “inheritance chain” could be broken simply by raising the pups away from their mother for the first six days after birth. “True” inheritance would’t be broken by that. In fact, the whole argument is similar to saying that nationality is passed on by Lamarckian inheritance because children raised by, say, French parents are themselves predominantly French, and raise French kids. Other papers (such as [2]) fall prey to similar flaws. Jerry Coyne has aptly summarised the whole field as follows: In nearly all of these examples, the changes disappear after one or two generations, so they couldn’t effect permanent evolutionary change. […] I am not aware of a single case in which an adaptive change in an organism – or any change that has been fixed in a species – rests on inheritance that is not based on changes in the DNA. This is pretty damning: none of these papers demonstrate what could reasonably be termed Lamarckism. Real Lamarckism In December 2011, there has finally been a paper which convincingly demonstrated a real case of Lamarckian inheritance: Transgenerational Inheritance of an Acquired Small RNA-Based Antiviral Response in C. elegans [3]. The paper examines C. elegans (a nematode or roundworm which serves as a model organism in biology). Normally, those nematodes don’t get infected by viruses because they have developed a highly sophisticated defence mechanism called RNA interference (RNAi). This mechanism relies on so-called small-interfering RNAs (siRNAs) produced by the cell which recognise and pair up with viral RNA that has entered the cell. Those complexes are then in turn destroyed by the cell. The paper looked at nematodes where the RNAi mechanism had been knocked out (removed): the cells could no longer generate siRNAs, and hence had no defence against the virus invaders. Now, if you artificially put siRNAs into the cells, those cells can once again defend against a specific virus. The authors could show that under very specific circumstances, putting siRNAs into the cells was enough to trigger an inheritable virus resistance, even though the siRNA-generating mechanism was still knocked out. The nematodes had inherited an acquired, non-genetic trait (virus resistance) , and this inheritance was sustained over many generations. Since I’ve explicitly mentioned the Weismann barrier before, I should note that this experiment does not invalidate the Weismann barrier: this heritability only occurred in very specific circumstances, namely, when all of the cells in the nematode were provided with siRNAs. This notably includes the germline cells. Summary Despite frequent claims to the contrary, no connection between epigenetics and Lamarckism has ever been demonstrated. Inheritance of acquired traits from epigenetic modifications is transient at best, and it’s contested whether it constitutes inheritance at all. On the other hand, a clear example of Lamarckism has now been observed, albeit under very constrained, artificial circumstances. And while this is a very interesting result, it is not surprising: any competent biologist would have predicted the paper’s result, given the paper’s premises, and ignoring potential ways in which the experiment could go wrong, because its outcome is entirely predicted by modern biology. A Final Remark There are a lot of misconceptions flying around. Articles with titles like Why everything you've been told about evolution is wrong abound. There is no nice way to put it – these pronouncements are untrue. Nothing found in the papers cited here, nor in similar papers, either directly or implicitly contradicts “conventional evolution” – Darwinism. In fact, all of these studies heavily rely on predictions made by modern evolutionary theory. It’s just blatant misreporting by the media, due to two unfortunate facts: most science journalists don’t understand the science, even rudimentarily; and most scientists can’t even explain their research clearly to their colleagues, let alone lay people. [1] Ian C. G. Weaver, Nadia Cervoni & al. , Epigenetic programming by maternal behavior , Nature Neuroscience 7, 847–854 (2004) [2] Sheau-Fang Ng, Ruby C. Y. Lin & al. , Chronic high-fat diet in fathers programs β-cell dysfunction in female rat offspring , Nature 467, 963–966 (2010) [3] Oded Rechavi, Gregory Minevich & Oliver Hober, Transgenerational Inheritance of an Acquired Small RNA-Based Antiviral Response in C. elegans , Cell 147 (6) , 1248–1256 (2011) | {} | {'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/7017', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/3332/']} | jdg_86541 |
stackexchange | llm_judgeable_groundtruth_similarity | 2147280 |
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 $n\ge 4$ be give postive integers,and $x_{i}\in [0,1](i=1,2,\cdots,n)$,find the maximum of the value$$\sum_{i=1}^{n}x_{i}|x_{i}-x_{i+1}|$$where $x_{n+1}=x_{1}$ I think the maximum of the value for some $x_{i}=0$ and for some $x_{j}=1$.But How find the maximum?
Now provide the response and nothing else.
| Let $n\geq3$ be given, and denote by $X$ the set of cyclic sequences $x: \>{\mathbb Z}_n\to[0,1]$. For $x\in X$ put$$\|x\|:=\sum_{k=1}^n x_k\>|x_{k+1}-x_k|\ .$$Let $M\subset X$ be the subset of $x\in X$ with maximal norm. If $x\in M$ then $x$ is not constant, and $\max x_k=1$ (or else $\|x\|$ could be increased by adding a small constant sequence). In the following we put together some "local" properties of sequences $x\in M$. A subsequence of consecutive entries in $x$ is called a window . ${\bf 1.}$ For an $x\in M$ let $(u,v,w)$ be a window with $u\leq v\leq w$. Then $v={u+w\over2}$. Proof. Only two summands in $\|x\|$ depend on $v$. The function $\phi(v)=u(v-u)+v(w-v)$ collecting these summands is maximal at $v_*={u+w\over2}\in[u,w]$. As $x\in M$ the claim follows. ${\bf 2.}$ For an $x\in M$ one cannot have a window $(1,1)$. Proof. If there were $\geq2$ consecutive entries $1$ there would be a window $(u,1,1)$ with $u<1$. This contradicts ${\bf 1}$. ${\bf 3.}$ For an $x\in M$ let $(u,v,w)$ be a window with $u<v$, $\ v>w$. Then $v=1$. Proof. The function $\phi(v)=u(v-u)+v(v-w)$ has derivative $\phi'(v)=u+(v-w)+v>0$, hence is maximal when $v=1$. ${\bf 4.}$ If $x\in M$ then any entry $1$ in $x$ is immediately followed by a $0$. Proof. For a window $(1,v,w)$ we have$$\phi(v)=1-v+v|w-v|=1-v\bigl(1-|w-v|\bigr)\leq1\ ,$$and $\phi(v)=1$ iff $v=0$ or $|w-v|=1$. The latter implies $\{v,w\}=\{0,1\}$. Here $v=0$ is fine, whereas $v=1$ is forbidden according to ${\bf 2}$. ${\bf 5.}$ If $x_0=0$ then there is an $r\geq1$ such that$$0=x_0\leq x_1\leq x_2\leq\ldots\leq x_r,\qquad x_r>x_{r+1}\geq0\ .$$From ${\bf 1}$ it follows that there is a $t>0$ such that$$x_k=k\>t\quad(0\leq k\leq r)\ .$$This implies $x_{r-1}< x_r\>, \ x_{r+1}>x_r\,$, so that ${\bf 3}$ gives $x_r=1$, hence $t={1\over r}$. If $r\geq2$ we now have the window $\bigl(0,{1\over r},{2\over r}\bigr)$. It is easily checked that for $r\geq3$ replacing ${1\over r}$ here by $1$ increases $\|x\|$. This allows to conclude that $r\in\{1,2\}$. ${\bf 6.}$ Altogether it follows that for $x\in M$ the only possible short windows are $$(0,1)\>,\qquad\left(0,\ {1\over2},\ 1\right)\>,\qquad(1,0)\ .$$Furthermore any substring $\bigl(0,{1\over2},1,(0,1)^r,0,{1\over2},1\bigr)$ is norm-wise majorized by $(0,1)^{r+3}$. It follows that in an $x\in M$ we can have at most one substring $\bigl(0,{1\over2},1\bigr)$. The elements of $M$ can therefore be characterized as follows: If $n=2m$ is even then an $x\in M$ is $\ =(0,1)^m$, up to a rotation in ${\mathbb Z}_n$, and if $n=2m+1$ is odd then an $x\in M$ is $\ =\bigl(0,{1\over2},1,(0,1)^{m-1}\bigr)$, up to a rotation. The experimental findings of Markus Scheuer are therewith confirmed. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2147280', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58742/']} | jdg_86542 |
stackexchange | llm_judgeable_groundtruth_similarity | 22485074 |
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 running an example using log4j 2.0-rc1 and log4j.properties file, but log4j lib always runs it with the default configuration (log level, appender, etc). I also tried changing the name to log4j2.properties and nothing happened.
Now provide the response and nothing else.
| Log4j 2 doesn't support the Log4j v1 ".properties" format anymore (yet, since v2.4, Log4j supports a Property format, but its syntax is totally different from v1 format ). New formats are XML, JSON, and YAML, see the documentation (note: if you used one of these formats in a file called ".properties", it may be confusing). To specify the location of your configuration file, do you use the system property log4j.configurationFile , the Log4j class ConfigurationFactory , or something else?Did you read this manual page ? It explains that: Although the Log4j 2 configuration syntax is different than that of Log4j 1.x, most, if not all, of the same functionality is available. So it seems that a legacy Log4j1.x log4j.properties file is not supported as is, it must be migrated to v2.x format. The migration seems quite easy though, looking at the example in the link I gave above. Here is an extract: Example of Log4j v1.x config file: <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd"><log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> </layout> </appender> <category name="org.apache.log4j.xml"> <priority value="info" /> </category> <Root> <priority value ="debug" /> <appender-ref ref="STDOUT" /> </Root></log4j:configuration> Same config file migrated to Log4j v2: <?xml version="1.0" encoding="UTF-8"?><Configuration> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> </Console> </Appenders> <Loggers> <Logger name="org.apache.log4j.xml" level="info"/> <Root level="debug"> <AppenderRef ref="STDOUT"/> </Root> </Loggers></Configuration> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22485074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1392809/']} | jdg_86543 |
stackexchange | llm_judgeable_groundtruth_similarity | 45161393 |
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 wonder if there is a possibility to split jupyter classes into different cells? Lets say: #first cell:class foo(object): def __init__(self, var): self.var = var #second cell def print_var(self): print(self.var) For more complex classes its really annoying to write them into one cell.I would like to put each method in a different cell. Someone made this this last year but i wonder if there is something build in so i dont need external scripts/imports. And if not, i would like to know if there is a reason to not give the opportunity to split your code and document / debug it way easier. Thanks in advance
Now provide the response and nothing else.
| Two solutions were provided to this problem on Github issue "Define a Python class across multiple cells #1243" which can be found here: https://github.com/jupyter/notebook/issues/1243 One solution is using a magic function from a package developed for this specific case called jdc - or Jupyter dynamic classes. The documentation on how to install it and how to use can be found on package url at https://alexhagen.github.io/jdc/ The second solution was provided by Doug Blank and which just work in regular Python, without resorting to any extra magic as follows: Cell 1: class MyClass(): def method1(self): print("method1") Cell 2: class MyClass(MyClass): def method2(self): print("method2") Cell 3: instance = MyClass()instance.method1()instance.method2() I tested the second solution myself in both Jupyter Notebook and VS Code, and it worked fine in both environments, except that I got a pylint error [pylint] E0102:class already defined line 5 in VS Code, which is kind of expected but still runs fine. Moreover, VS Code was not meant to be the target environment anyway. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45161393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7408462/']} | jdg_86544 |
stackexchange | llm_judgeable_groundtruth_similarity | 21767485 |
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 deserialize json objects to specific types of objects (using Gson library) based on type field value, eg.: [ { "type": "type1", "id": "131481204101", "url": "http://something.com", "name": "BLAH BLAH", "icon": "SOME_STRING", "price": "FREE", "backgroundUrl": "SOME_STRING" }, { .... }] So type field will have different (but known) values. Based on that value I need to deserialize that json object to appropriate model object, eg.: Type1Model, Type2Model etc. I know I can easily do that before deserialization by converting it to JSONArray , iterate through it and resolve which type it should be deserialized to. But I think it's ugly approach and I'm looking for better way. Any suggestions?
Now provide the response and nothing else.
| You may implement a JsonDeserializer and use it while parsing your Json value to a Java instance. I'll try to show it with a code which is going to give you the idea: 1) Define your custom JsonDeserializer class which creates different instance of classes by incoming json value's id property: class MyTypeModelDeserializer implements JsonDeserializer<MyBaseTypeModel> { @Override public MyBaseTypeModel deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); JsonElement jsonType = jsonObject.get("type"); String type = jsonType.getAsString(); MyBaseTypeModel typeModel = null; if("type1".equals(type)) { typeModel = new Type1Model(); } else if("type2".equals(type)) { typeModel = new Type2Model(); } // TODO : set properties of type model return typeModel; }} 2) Define a base class for your different instance of java objects: class MyBaseTypeModel { private String type; // TODO : add other shared fields here} 3) Define your different instance of java objects' classes which extend your base class: class Type1Model extends MyBaseTypeModel { // TODO: add specific fields for this class}class Type2Model extends MyBaseTypeModel { // TODO: add specific fields for this class} 4) Use these classes while parsing your json value to a bean: GsonBuilder gsonBuilder = new GsonBuilder();gsonBuilder.registerTypeAdapter(MyBaseTypeModel.class, new MyTypeModelDeserializer());Gson gson = gsonBuilder.create();MyBaseTypeModel myTypeModel = gson.fromJson(myJsonString, MyBaseTypeModel.class); I can not test it right now but I hope you get the idea. Also this link would be very helpful. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21767485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1136139/']} | jdg_86545 |
stackexchange | llm_judgeable_groundtruth_similarity | 18808853 |
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 this code, @WebServlet(value="/initializeResources", loadOnStartup=1)public class InitializeResources extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("HEREEEE"); }} But the servlet doesn't start when the web application is started. How use load on startup on Servlet Annotation? My Servlet API is 3.0 and I use Tomcat 7
Now provide the response and nothing else.
| With you current code, you need to do a GET request for see the output HEREEEE . If you want to do something on the startup of the servlet (i.e. the element loadOnStartup with value greater or equal to zero, 0 ), you need put the code in a init method or in the constructor of the servlet: @Overridepublic void init() throws ServletException { System.out.println("HEREEEE");} It may be more convenient to use a listener to start a resource in the application scope (in the ServletContext ). import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.annotation.WebListener;@WebListenerpublic class InitializeListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("On start web app"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("On shutdown web app"); }} For an example, see my answer for the question Share variables between JAX-RS requests . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18808853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2780535/']} | jdg_86546 |
stackexchange | llm_judgeable_groundtruth_similarity | 59860068 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My website gathers information for Google Analytics, so I need to include a Cookie consent banner for the users to opt in/out of. I saw the plugin gatsby-plugin-gdpr-cookies and thought it looked perfect. I've followed the startup and have it inside my config file. However I'm not sure what to do next. Do I need to create a banner component and link it all up somehow? I've tried to look around for other examples but can't see any. Any help appreciated, thanks.
Now provide the response and nothing else.
| You have to combine a Gatsby plugin and build your own cookie consent banner or use a ready made component to achieve this. First as AskaNor_29 suggested you need to install and configure the gatsby-plugin-gdpr-cookies plugin. You can get the plugin here . Configure the plugin in gatsby-config.js // In your gatsby-config.jsmodule.exports = { plugins: [ { resolve: `gatsby-plugin-gdpr-cookies`, options: { googleAnalytics: { trackingId: 'YOUR_GOOGLE_ANALYTICS_TRACKING_ID', // Setting this parameter is optional anonymize: true }, facebookPixel: { pixelId: 'YOUR_FACEBOOK_PIXEL_ID' }, // Defines the environments where the tracking should be available - default is ["production"] environments: ['production', 'development'] }, }, ],} The second part is showing a cookie consent banner or modal so the user can make his choice. For this you can use the react-cookie-consent npm module. You can get the npm package here . To make it work with the gatsby-plugin-gdpr-cookies , you need to set the cookieName="gatsby-gdpr-google-analytics" prop. Then you put the CookieConsent component in your layout.js file so it's activated on any page the user visits first. <CookieConsent location="bottom" buttonText="Accept" declineButtonText="Decline" cookieName="gatsby-gdpr-google-analytics">This site uses cookies ...</CookieConsent> The component takes many props so you can tweak the behaviour and looks. If you want both Google Analytics and Facebook Pixel cookies to be set, there are callbacks for accepting/declining cookies where you can add your custom code to set both cookies. If you're interested I wrote a longer how-to describing the steps . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/59860068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5443318/']} | jdg_86547 |
stackexchange | llm_judgeable_groundtruth_similarity | 32672596 |
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 managed to get pyinstaller to run more or less correctly now, except that it opens too many windows. It's pygame project, and it keeps loading the entire thing over again every second or so. My PC fills with game windows after a few seconds and everything grinds to a halt. Running it from commandline, I can just see print outs saying the app is starting pasted over and over again in commandline window. As far as I can tell the Apps aren't closing or exiting, just spawning more and more. The command I call to start pyinstaller is this: pyinstaller --onedir main_local.py The main file looks like this: # Library importsimport pygame# Project importsfrom multiroidal_client import MultiroidalClientfrom settings import *import time# Main program functiondef main(): # Initialise game class game = MultiroidalClient(SCREEN_SIZE, ('127.0.0.1', 8080)) # Start game loop game.main_game_loop()# Execute main functionif __name__ == '__main__': main() I tried commenting out the if __ name __ ... bit to see if for some reason it was executing the main function and calling a duplicate each time by accident or something. When commented out the exec does nothing, as you might expect. Any ideas? I've not included any more code because there is loads of it, and I'm not sure which parts are relevant. Let me know if you need to see anything else. Cheers EDIT: I added a quick print after the game.main_game_loop() just to check if the script jumped out of the infinite game loop. No such luck. It's loading a parallel instances of the scripts, all running simultaneously. EDIT: I looked through the pyinstaller docs and managed to get some more debug out. Not sure if it's relevant or not, but here it is. This screen of dialog just keeps reprinting over and over again. I also tried the --noupx option which can sometimes help apparently - no such luck.
Now provide the response and nothing else.
| Multiprocessing! I tried some simpler python programs, and they packaged up all fine. So it wasn't a problem with my method it was the code. Thinking about it again, it must be some unusual or difficult to package code in the project. Hmmm, maybe threading? I've got a couple of threads running in parallel, and they are multiprocessing threads. After googling about I found this magic fix . You simply stick this line, multiprocessing.freeze_support() , straight after if __name__ == "__main__" and before you call the main() function. if __name__ == '__main__': # Pyinstaller fix multiprocessing.freeze_support() main() It looks like the guys who develop the multiprocessing module had to include a hack to allow freeze packaging (py2exe, pyinstaller etc). Seems weird it isn't included a bit more smoothly. If you leave that freeze_support() call in, it still works even when you aren't running from packaged code as opposed to standard python files. Anyway, if you are freezing/pacakaging code up and it seems to execute itself over and over, check if you are use multiprocessing. A simple google "multiprocessing pyinstaller" gave the answer. FYI this only works on --onedir mode, --onefile mode is a different story and not supported on windows. You'll have to dig around more to solve that one. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32672596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/678523/']} | jdg_86548 |
stackexchange | llm_judgeable_groundtruth_similarity | 2495402 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using the following regexp to validate numbers in my javascript file: var valid = (val.match(/^\d+$/)); It works fine for whole numbers like 100, 200, etc, however for things like 1.44, 4.11, etc, it returns false. How can I change it so numbers with a decimal are also accepted?
Now provide the response and nothing else.
| var valid = (val.match(/^\d+(?:\.\d+)?$/)); Matches: 1 : yes 1.2: yes-1.2: no+1.2: no .2: no 1. : no var valid = (val.match(/^-?\d+(?:\.\d+)?$/)); Matches: 1 : yes 1.2: yes-1.2: yes+1.2: no .2: no 1. : no var valid = (val.match(/^[-+]?\d+(?:\.\d+)?$/)); Matches: 1 : yes 1.2: yes-1.2: yes+1.2: yes .2: no 1. : no var valid = (val.match(/^[-+]?(?:\d*\.?\d+$/)); Matches: 1 : yes 1.2: yes-1.2: yes+1.2: yes .2: yes 1. : no var valid = (val.match(/^[-+]?(?:\d+\.?\d*|\.\d+)$/)); Matches: 1 : yes 1.2: yes-1.2: yes+1.2: yes .2: yes 1. : yes | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2495402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49153/']} | jdg_86549 |
stackexchange | llm_judgeable_groundtruth_similarity | 15660838 |
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 fail to compile in gcc 4.1.2 / RedHat 5 : #include <string>#include <vector>#include <map>class Toto {public: typedef std::string SegmentName;};class Titi {public: typedef Toto::SegmentName SegmentName; // import this type in our name space typedef std::vector<SegmentName> SegmentNameList; SegmentNameList segmentNames_; typedef std::map<SegmentName, int> SegmentTypeContainer; SegmentTypeContainer segmentTypes_; int getNthSegmentType(unsigned int i) const { int result = -1; if(i < segmentNames_.size()) { SegmentName name = segmentNames_[i]; result = segmentTypes_[ name ]; } return result; }}; The error is : error: no match for 'operator[]' in '(...)segmentTypes_[name]'/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_map.h:340:note: candidates are: _Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)[with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp = int, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> >] Why ? The map is rather straightforward. I guess this has to do with the typedefs, but what is wrong ? [edit] Even if I remove all the typedefs and use std::string everywhere, the problem persists... Am I misusing maps ?
Now provide the response and nothing else.
| std::map::operator[] is non-const and you're trying to use it from a const method. You could achieve this using std::map::find , which returns a const_iterator : SegmentTypeContainer::const_iterator iter = segmentTypes_.find(name); If you're using C++11, you could also use std::map::at , which will throw an exception if the key is not found in the map: result = segmentTypes_.at(name); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15660838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587407/']} | jdg_86550 |
stackexchange | llm_judgeable_groundtruth_similarity | 30504850 |
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 do have the following statement: isEnabled = false;if(foo(arg) && isEnabled) { ....}public boolean foo(arg) { some really long running code} Does it make sense to swap the statements inside the if? if(isEnabled && foo(arg)) { ... } Or does the compiler the optimization for me?
Now provide the response and nothing else.
| Note that the two expressions don't have the same behavior if foo() also has side effects . If it is manipulating the state of the program, it makes a lot of difference if you always invoke it, or if you invoke it only as a dependency of the value of isEnabled . For example, consider: boolean foo(Object arg) { someLocalVariable = arg; //do some calculation and return an answer} It matters if you always invoke foo() , or if you invoke it only in the case where isEnabled is turned on, resulting in the following two expressions to be completely different from each other: if (isEnabled && foo(arg)) { ...} //local variable changes only if isEnabled==trueif (foo(arg) && isEnabled) { ...} //local variable always changes | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30504850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1131623/']} | jdg_86551 |
stackexchange | llm_judgeable_groundtruth_similarity | 5054 |
Below is a question asked on the forum meta.mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
When I went to place my first bounty about a month ago, the question wasn't mine and I almost put up 500 rep to draw as much attention as possible figuring I'd only have to surrender said rep if someone actually came through with an answer. Lucky for me I looked into it before finalizing and found that the bounty not only wouldn't be refunded, but wouldn't even be prioritized in the 'active bounties' list over 50 point bounties since they're chronologically ordered. I went with the minimum instead and still got more views and no answers, which seems like what would have happened with 500 points anyway. Since then I've started paying attention to the active bounties tab on the home page, particularly the 500 pointers, wondering if a similar misunderstanding was taking place more broadly and leading people to lose rep they didn't expect to lose. Currently there is one bountied question that might fit the bill for what almost happened to me; the user are put up 500 bounty on a question that isn't theirs, with only 83 rep left after the bounty. There are also six other questions where users have posted bounty amounts that are around 50% of their total rep, and I suspect that some of this has to do with an expectation that rep will be refunded if the question isn't answered. I understand the philosophy that we gain extra exposure by bountying a question and that an answer isn't what we 'buy' with the bounty necessarily, but I think this should be made more explicit in the blurb we see when offering a bounty. I also think there might be some merit to (partially? 50%?) refunding bounties on questions posted by different users than the bounty placer, on the grounds that this still prevents endless promotion of ones own content while encouraging us to support one another (without punishment) in asking good questions. To respond to Martin and Gerry's comments, I am primarily taking issue with the change of phrasing implemented back in 2013: The way it is written reads to me as "this reputation is deducted immediately and cannot be refunded if you change your mind ", or in other words you can't revoke it during the 7 day period for any reason. This might just be my denseness in reading, but I think less ambiguous language would be better. For example, this reputation is deducted immediately and will not be returned to you for any reason or even better this reputation is deducted immediately and cannot be refunded, even if no answer is posted I'm not trying to die on this hill or anything, it just seems like a case of ambiguous phrasing that could use clarification.
Now provide the response and nothing else.
| The fact that the bounties are not refundable is pointed out in the help center and marked in bold: All bounties are paid for up front and non-refundable under any circumstances. Also the dialog used when offering the bounty has this information - although it is in a smaller font, the text "this reputation is deducted immediately and cannot be refunded" is contained there. I will add a screenshot taken from this answer: Point out that bounties are non-refundable . Since the text is already there, maybe you might clarify a bit what actually you want to change. (Simply change this text to a large font? Or should it be shown also in the dialog in bold ?) I'll add that the link in the text "learn more" goes to the article on bounties in the help center , which was mentioned above. EDIT: The post I linked above mentions that the wording was changed in 2013. Gerry Myerson asked in a comment about the wording before that. In the question " Why can't I offer a bounty of 50 reputation? " I was able to find a screenshot from 2012. It seems that the dialog simply said "You can start a total of 3 simultaneous bounties" - without mentioning the fact that they aren't refundable. There are also some - rather exceptional and rare - cases when the bounty is actually returned to the user who offered it. But probably the short and basic information offered in these two places isn't suitable for including all the technical details. Since you seem to be looking at the cases where large part of users' reputation was offered in bounties, I will add this SEDE query: Highest percentage of rep in bounties - only counting questions which are not deleted . I have restricted it to users with reputation at least two, so that the list is not dominated by the suspended users. (You can play around with the parameter more, if you wish to. For example, this is what you get for the default values . ) Concerning your suggestion to get partial refund of the bounty in some cases, I will add link to a feature request on Meta Stack Exchange from 2018: Partial bounty refund for good question with no answers . (At the moment, score is -10, so this idea does not seem to have much support from the community.) To some extent, also the following posts are related: Offer bounty refund on “good” question with no answers and Would it be better if bounties were NOT like ads? | {} | {'log_upvote_score': 4, 'links': ['https://meta.mathoverflow.net/questions/5054', 'https://meta.mathoverflow.net', 'https://meta.mathoverflow.net/users/92164/']} | jdg_86552 |
stackexchange | llm_judgeable_groundtruth_similarity | 1370258 |
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:
Explain why calculating values of $1 - \cos(x)$ where $x$ near zero using the trigonometric identity $1 - \cos(x) = 2\sin^2\big(\frac{x}{2}\big)$ will result in more accurate results. Is it because when we calculate $1 - \cos(x)$ for $x$ values near zero results in subtracting two nearly equal numbers and so we loose significant digits, but when we calculate $1-\cos(x)$ using the trigonometric identity $1-\cos(x)=2\sin^2\big(\frac{x}{2}\big)$ we do not subtract two nearly exact numbers? Why using the identity will be more accurate? We multiply two near zero numbers and so we will loose in this case significant digits too. Thanks for any help.
Now provide the response and nothing else.
| Multiplying numbers near $0$ is not a problem. Given two (machine) numbers $x(1+\delta)$ and $y(1+\epsilon)$, their (machine) product is $xy(1+\epsilon)(1+\delta)\simeq xy(1+\delta+\epsilon)$, so the relative rounding errors just add. If you multiply $n$ numbers like this, the relative rounding error goes like $\sqrt n$. The only problem is that you may exhaust the range of the exponent when the product gets too close to $0$, but that's unavoidable since this is the result you want, and it only happens at extremely small numbers. By contrast, if you have a machine representation of $\cos x=1-\Delta$ (where $\Delta$ is the real distance to $1$, not a rounding error) as $(1+\epsilon)(1-\Delta)$ and you subtract this from $1$, the result is $1-(1+\epsilon)(1-\Delta)=\Delta-\epsilon+\Delta\epsilon=\Delta(1-\epsilon/\Delta-\epsilon)$. So now your relative error is no longer $\epsilon$ or a small multiple of that, but $\epsilon/\Delta$, which can be much worse if $\Delta$ is, say, $10^{-6}$, a number that's very comfortably accurately represented in the other scenario. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1370258', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/108043/']} | jdg_86553 |
stackexchange | llm_judgeable_groundtruth_similarity | 29117836 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between __attribute__((const)) and __attribute__((pure)) in GNU C? __attribute__((const)) int f() { /* ... */ return 4;} vs __attribute__((pure)) int f() { /* ... */ return 4;}
Now provide the response and nothing else.
| The difference is explained in the GCC manuals . Most notably a const function may only use the arguments passed in and not any memory, whereas a pure function can access memory too, under constraints: The pure attribute prohibits a function from modifying the state of the program that is observable by means other than inspecting the function’s return value. However, functions declared with the pure attribute can safely read any non-volatile objects, and modify the value of objects in a way that does not affect their return value or the observable state of the program. The __attribute__ ((pure)) means that the function has no side effects and the value returned depends on the arguments and the state of global variables. Therefore it is safe for the optimizer to elide some calls to it, if the arguments are the same, and the caller did not do anything to change the state of the globals in between the calls . The __attribute__ ((const)) means that the return value is solely a function of the arguments, and if any of the arguments are pointers, then the pointers must not be dereferenced . A const function is always pure . Examples of const functions would be the abs functions from <stdlib.h> and some mathematical functions from <math.h> : sqrt , exp , etc. (Though they might be subject to rounding modes). Examples of pure but non-const functions would be such functions as strlen - as it dereferences the pointer passed in. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29117836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3787875/']} | jdg_86554 |
stackexchange | llm_judgeable_groundtruth_similarity | 8065097 |
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 dataframe like this: V1 V2 V3 1 1 3423086 3423685 2 1 3467184 3467723 3 1 4115236 4115672 4 1 5202437 5203057 5 2 7132558 7133089 6 2 7448688 7449283 I want to change the V1 column and add chr before the number. Just like this: V1 V2 V3 1 chr1 3423086 3423685 2 chr1 3467184 3467723 3 chr1 4115236 4115672 4 chr1 5202437 5203057 5 chr2 7132558 7133089 6 chr2 7448688 7449283 Is there a way to do this in R?
Now provide the response and nothing else.
| The regex pattern "^" (outside any character-class brackets) represents the point just before the first character of a "character"-class item (aka "string" in other computer languages). This just replaces the beginning of each "character" element in vector with a stem of "chr". It implicitly coerces a "numeric" input value to "character" so alters the mode of the result. > dat$V1 <- sub("^", "chr", dat$V1 )> dat V1 V2 V31 chr1 3423086 34236852 chr1 3467184 34677233 chr1 4115236 41156724 chr1 5202437 52030575 chr2 7132558 71330896 chr2 7448688 7449283 Could, of course, have used paste("chr", dat$V1, sep="") , but I thought a regex solution might be neater. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8065097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/670781/']} | jdg_86555 |
stackexchange | llm_judgeable_groundtruth_similarity | 24078905 |
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 successfully implemented my custom OAuthAuthorizationServerProvider . But when I log in and retrieve a token, my client doesn't have any idea of the user's roles, claims, etc. I currently added a webapi controller to return the list of the principal's claims, but I'm not really happy with that. When requesting a token, the current response looks like: { access_token: "qefelgrebjhzefilrgo4583535", token_type: "bearer", expires_in: 59} Q> How can make it return something like the following snippet? { access_token: "qefelgrebjhzefilrgo4583535", token_type: "bearer", expires_in: 59, user: { name: 'foo', role: 'bar' }} My progress so far: The documentation of OAuthAuthorizationServerProvider#TokenEndpoint(OAuthTokenEndpointContext) says: Called at the final stage of a successful Token endpoint request. An application may implement this call in order to do any final modification of the claims being used to issue access or refresh tokens. This call may also be used in order to add additional response parameters to the Token endpoint's json response body. I couldn't find any example of how to customize the response, and asp-net Identity's source code is not yet released, so I'm quite stuck.
Now provide the response and nothing else.
| May be you are looking for TokenEndpoint method override of OAuthAuthorizationServerProvider . public override Task TokenEndpoint(OAuthTokenEndpointContext context){ foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) { context.AdditionalResponseParameters.Add(property.Key, property.Value); } return Task.FromResult<object>(null);} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24078905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1725655/']} | jdg_86556 |
stackexchange | llm_judgeable_groundtruth_similarity | 68989 |
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
New cars have stop-start system (even though this has been available for a long time ). My question is: why are car companies emphasizing shutting the engine down at a traffic light, rather than making the engine run at close to zero RPM (but certainly not zero) at idle speed using the car's ECU ? My idea is that the car engine keeps running, and when the driver releases the gas pedal, the engine returns to a very low idle speed. In the manufacturer's current scenario, when the engine shuts down, the battery power is used and can put strain/stress on the battery. I see cars have RPM meter that shows rotations-per-minute in thousands. Can't engine just run at 100 RPM, drawing very much less gas/petrol? Others have similar concerns . And why don't companies make cars that have an engine that can stop just short of firing a cylinder ?
Now provide the response and nothing else.
| You are right in the thinking of using less gas and that's exactly what the purpose was to have the start/stop feature. The main goal of doing it (at least here in the States) is for zero fuel consumption/zero emissions while the engine is stopped. This provides for better overall fuel consumption numbers to meet what the EPA has mandated for companies to stay in compliance with regulations. Considering what the government mandates, zero RPM will always produce zero emissions and have less fuel consumption than will 100RPM ... it all adds up. WRT the start/stop causing wear/tear on the starter/battery which would otherwise not be there, you are accurate in thinking so. The manufacturer can do two things to help mitigate this that I can think of (whether they do them is another story): They can design in a more robust starting/battery system in the vehicle. They can (and do) engineer the engine so it stops just short of firing a cylinder. When the engine goes to start again, it fires this cylinder to assist the starter in getting the engine started, thus helping to eliminate the wear/tear on the starting system. Solar Mike is correct about V8's vs 3-cylinder engines and relative speeds to allow it to operate. This is less a function of the size (displacement or # of cylinders) of the engine, but more so to do with physics. An engine has to have enough rotating mass to continue motion (the old mass in motion tends to stay in motion kinda thing). The larger the rotating mass, the easier it is to keep things going. If mass isn't present, it needs to spin faster to be kept in motion. Secondary to that is the # of cylinders and how many cylinders fire per revolution of the crank. A V8 fires four cylinders every revolution (every 90° of crank rotation), while a 3-cylinder only fires a cylinder every 240° of crank rotation (given both are 4-stroke engines). The reason I point this out is with larger engines, such as those which are used in large cargo ships, run at full speed ~120RPM. Idle would be something much lower. Point is, the rotating mass of the engine allows it to run much lower in RPM. You can't fit a Wartsila engine in a car, though. | {} | {'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/68989', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/48571/']} | jdg_86557 |
stackexchange | llm_judgeable_groundtruth_similarity | 27785 |
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:
I found this on Facebook: It claims that: During his presidency, John F. Kennedy never collected his salary of $150,000 a year. Instead, he donated the full amount to charity. Initial googling seems to support his charity, but that amount seems to me like a rather high salary for the 1960s.
Now provide the response and nothing else.
| Drexel University validates the amount: Presidential Salary: $100,000/year + $50,000 expense account (refused by Kennedy) As DavePhD pointed out, that $50,000 could only be spent on presidential business, so the full amount that JFK could donate from his presidential salary was 100,000 minus taxes. The History Channel backs up the claim that he donated his full presidential income: 6. He donated his congressional and presidential salaries to charity. Kennedy’s father built a family fortune, and when the young politician entered Congress in 1947, he earned sufficiently ample annual income from trusts established by his father that he decided to donate his entire legislative salary to various charities. Kennedy quietly maintained the practice as president after becoming the richest man to ever take the oath of office. As The History Channel isn't focused on facts anymore , here's a list of supporting book quotes from this page : "A millionaire by age twenty-one, Kennedy was our wealthiest President. The only President besides George Washington to decline his salary, he donated his to the Boy Scouts and Girl Scouts, the United Negro College Fund and Jewish organizations." From: Page 67 "Lives of the Presidents: Fame, Shame (and What the Neighbors Thought)" by Kathleen Krull, read using the "search inside" feature at Amazon.com: http://www.amazon.com/exec/obidos/tg/detail/-/015200808X/ "His $100,000 salary as President was being divided, after taxes, among two dozen charities, including the Boy Scouts and Girl Scouts of America, the United Negro College Fund, and the Federation of Jewish Philanthropies. The schedule of contributions was worked out each year during a short money meeting Kennedy had with a family accountant named Thomas Walsh." From: Page 428 "PRESIDENT KENNEDY: PROFILE OF POWER" by Richard Reeves, read using the "search inside" feature at Amazon.com: http://www.amazon.com/exec/obidos/tg/detail/-/0671892894/ "He donated his entire presidential salary of $100,000 to charity, ranging from hospitals to the Boy and Girl Scouts, to Jewish philanthropies and retarded children's associations. In 1962, however, he chose to make what were clearly strategically political contributions with his private funds?the United Negro College Fund and the Cuban Families Committee." From: Page 95 "The Kennedy White House : Family Life and Pictures, 1961-1963" by Carl Sferrazza Anthony, read using the "search inside" feature at Amazon.com: http://www.amazon.com/exec/obidos/tg/detail/-/0743214730/ As for being a lot of money for that time: 100,000 USD in 1962 would have the same purchasing power as 783,894 USD in 2014. Yet nominally , it would still be worth only 100,000 USD. | {} | {'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/27785', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/5079/']} | jdg_86558 |
stackexchange | llm_judgeable_groundtruth_similarity | 14867981 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I create a migration with two fields that reference the same table? I have tables A, and image. A.image1_id will reference image, and A.image2_id will reference image also. There are only 2 images, not many. If I use class AddFields < ActiveRecord::Migration def change change_table(:ticket) do |t| t.references :image1_id t.references :image2_id end endend I don't think that will work because it will add another _id to the end and probably won't know to use the 'image' model. I also thought about change_table(:ticket) do |t| t.references :image But then how do I add two of those? I also thought about adding create_table :images do |t| t.belongs_to :ticket t.string :file But I only want 2, not many, and this doesn't appear to allow getting to the image from the ticket, like ticket.image1 or ticket.image2 . According to this documentation http://apidock.com/rails/v3.2.8/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table which is all I could find, t.references doesn't appear to take any arguments either. change_table(:suppliers) do |t| t.references :companyend
Now provide the response and nothing else.
| You can do this simply with the add_column method in your migrations and set up the proper associations in your classes: class AddFields < ActiveRecord::Migration def change add_column :tickets, :image_1_id, :integer add_column :tickets, :image_2_id, :integer endendclass Ticket < ActiveRecord::Base belongs_to :image_1, :class_name => "Image" belongs_to :image_2, :class_name => "Image"endclass Image < ActiveRecord::Base has_many :primary_tickets, :class_name => "Ticket", :foreign_key => "image_1_id" has_many :secondary_tickets, :class_name => "Ticket", :foreign_key => "image_2_id"end This blog post, Creating Multiple Associations with the Same Table , goes into more detail. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14867981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148844/']} | jdg_86559 |
stackexchange | llm_judgeable_groundtruth_similarity | 403783 |
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:
The echo one; echo two > >(cat); echo three; command gives unexpected output. I read this: How process substitution is implemented in bash? and many other articles about process substitution on the internet, but don't understand why it behaves this way. Expected output: onetwothree Real output: prompt$ echo one; echo two > >(cat); echo three;onethreeprompt$ two Also, this two commands should be equivalent from my point of view, but they don't: ##### first command - the pipe is used.prompt$ seq 1 5 | cat12345##### second command - the process substitution and redirection are used.prompt$ seq 1 5 > >(cat)prompt$ 12345 Why I think, they should be the same? Because, both connects the seq output to the cat input through the anonymous pipe - Wikipedia, Process substitution . Question: Why it behaves this way? Where is my error? The comprehensive answer is desired (with explanation of how the bash does it under the hood).
Now provide the response and nothing else.
| Yes, in bash like in ksh (where the feature comes from), the processes inside the process substitution are not waited for (before running the next command in the script). for a <(...) one, that's usually fine as in: cmd1 <(cmd2) the shell will be waiting for cmd1 and cmd1 will be typically waiting for cmd2 by virtue of it reading until end-of-file on the pipe that is substituted, and that end-of-file typically happens when cmd2 dies. That's the same reason several shells (not bash ) don't bother waiting for cmd2 in cmd2 | cmd1 . For cmd1 >(cmd2) , however, that's generally not the case, as it's more cmd2 that typically waits for cmd1 there so will generally exit after. That's fixed in zsh that waits for cmd2 there (but not if you write it as cmd1 > >(cmd2) and cmd1 is not builtin, use {cmd1} > >(cmd2) instead as documented ). ksh doesn't wait by default, but lets you wait for it with the wait builtin (it also makes the pid available in $! , though that doesn't help if you do cmd1 >(cmd2) >(cmd3) ) rc (with the cmd1 >{cmd2} syntax), same as ksh except you can get the pids of all the background processes with $apids . es (also with cmd1 >{cmd2} ) waits for cmd2 like in zsh , and also waits for cmd2 in <{cmd2} process redirections. bash does make the pid of cmd2 (or more exactly of the subshell as it does run cmd2 in a child process of that subshell even though it's the last command there) available in $! , but doesn't let you wait for it. If you do have to use bash , you can work around the problem by using a command that will wait for both commands with: { { cmd1 >(cmd2); } 3>&1 >&4 4>&- | cat; } 4>&1 That makes both cmd1 and cmd2 have their fd 3 open to a pipe. cat will wait for end-of-file at the other end, so will typically only exit when both cmd1 and cmd2 are dead. And the shell will wait for that cat command. You could see that as a net to catch the termination of all background processes (you can use it for other things started in background like with & , coprocs or even commands that background themselves provided they don't close all their file descriptors like daemons typically do). Note that thanks to that wasted subshell process mentioned above, it works even if cmd2 closes its fd 3 (commands usually don't do that, but some like sudo or ssh do). Future versions of bash may eventually do the optimisation there like in other shells. Then you'd need something like: { { cmd1 >(sudo cmd2; exit); } 3>&1 >&4 4>&- | cat; } 4>&1 To make sure there's still an extra shell process with that fd 3 open waiting for that sudo command. Note that cat won't read anything (since the processes don't write on their fd 3). It's just there for synchronisation. It will do just one read() system call that will return with nothing at the end. You can actually avoid running cat by using a command substitution to do the pipe synchronisation: { unused=$( { cmd1 >(cmd2); } 3>&1 >&4 4>&-); } 4>&1 This time, it's the shell instead of cat that is reading from the pipe whose other end is open on fd 3 of cmd1 and cmd2 . We're using a variable assignment so the exit status of cmd1 is available in $? . Or you could do the process substitution by hand, and then you could even use your system's sh as that would become standard shell syntax: { cmd1 /dev/fd/3 3>&1 >&4 4>&- | cmd2 4>&-; } 4>&1 though note as noted earlier that not all sh implementations would wait for cmd1 after cmd2 has finished (though that's better than the other way round). That time, $? contains the exit status of cmd2 ; though bash and zsh make cmd1 's exit status available in ${PIPESTATUS[0]} and $pipestatus[1] respectively (see also the pipefail option in a few shells so $? can report the failure of pipe components other than the last) Note that yash has similar issues with its process redirection feature. cmd1 >(cmd2) would be written cmd1 /dev/fd/3 3>(cmd2) there. But cmd2 is not waited for and you can't use wait to wait for it either and its pid is not made available in the $! variable either. You'd use the same work arounds as for bash . | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/403783', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/109397/']} | jdg_86560 |
stackexchange | llm_judgeable_groundtruth_similarity | 1486514 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As I move through the iterations on my application*(s) I accumulate migrations. As of just now there are 48 such files, spanning about 24 months' activity. I'm considering taking my current schema.rb and making that the baseline. I'm also considering deleting (subject to source control, of course) the existing migrations and creating a nice shiny new single migration from my my current schema? Migrations tend to like symbols, but rake db:schema:dump uses strings: should I care? Does that seem sensible? If so, at what sort of interval would such an exercise make sense?If not, why not? And am I missing some (rake?) task that would do this for me? * In my case, all apps are Rails-based, but anything that uses ActiveRecord migrations would seem to fit the question.
Now provide the response and nothing else.
| Yes, this makes sense. There is a practice of consolidating migrations. To do this, simply copy the current schema into a migration, and delete all the earlier migrations. Then you have fewer files to manage, and the tests can run faster. You need to be careful doing this , especially if you have migrations running automatically on production. I generally replace a migration that I know everyone has run with the new schema one. Other people have slightly different ways to do this. I generally haven't done this until we had over 100 migrations, but we can hit this after a few months of development. As the project matures, though, migrations come less and less often, so you may not have to do it again. This does go against a best practice: Once you check in a migration to source control, don't alter it. I make a rare exception if there is a bug in one, but this is quite rare (1 in 100 maybe). The reason is that once they are out in the wild, some people may have run them. They are recorded as being completed in the db. If you change them and check in a new version, other people will not get the benefit of the change. You can ask people to roll back certain changes, and re-run them, but that defeats the purpose of the automation. Done often, it becomes a mess. It's better left alone. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1486514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1060/']} | jdg_86561 |
stackexchange | llm_judgeable_groundtruth_similarity | 3174358 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
the code I'm dealing with has loops like the following: bistar = zeros(numdims,numcases); parfor hh=1:nt bistar = bistar + A(:,:,hh)*data(:,:,hh+1)' ;end for small nt (10). After timing it, it is actually 100 times slower than using the regular loop!!! I know that parfor can do parallel sums, so I'm not sure why this isn't working. I run matlabpool with the out-of-the-box configurations before running my code. I'm relatively new to matlab, and just started to use the parallel features, so please don't assume that I'm am not doing something stupid. Thanks! PS: I'm running the code on a quad core so I would expect to see some improvements.
Now provide the response and nothing else.
| Making the partitioning and grouping the results (overhead in dividing the work and gathering results from the several threads/cores) is high for small values of nt . This is normal, you would not partition data for easy tasks that can be performed quickly in a simple loop. Always perform something challenging inside the loop that is worth the partitioning overhead. Here is a nice introduction to parallel programming . The threads come from a thread pool so the overhead of creating the threads should not be there. But in order to create the partial results n matrices from the bistar size must be created, all the partial results computed and then all these partial results have to be added (recombining). In a straight loop, this is with a high probability done in-place, no allocations take place. The complete statement in the help (thanks for your link hereunder) is: If the time to compute f, g, and h is large , parfor will be significantly faster than the corresponding for statement, even if n is relatively small. So you see they mean exactly the same as what I mean, the overhead for small n values is only worth the effort if what you do in the loop is complex/time consuming enough. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3174358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130152/']} | jdg_86562 |
stackexchange | llm_judgeable_groundtruth_similarity | 830757 |
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:
There are 20 conplanar points of which 5 are collinear. How many straight line segments and how many triangles can be made using these points? I understand it belongs to combination. But there are both collinear and non collinear points. I don't know how to proceed.
Now provide the response and nothing else.
| $\newcommand{\+}{^{\dagger}} \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle} \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack} \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,} \newcommand{\dd}{{\rm d}} \newcommand{\down}{\downarrow} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,{\rm e}^{#1}\,} \newcommand{\fermi}{\,{\rm f}} \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,} \newcommand{\half}{{1 \over 2}} \newcommand{\ic}{{\rm i}} \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow} \newcommand{\isdiv}{\,\left.\right\vert\,} \newcommand{\ket}[1]{\left\vert #1\right\rangle} \newcommand{\ol}[1]{\overline{#1}} \newcommand{\pars}[1]{\left(\, #1 \,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\pp}{{\cal P}} \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,} \newcommand{\sech}{\,{\rm sech}} \newcommand{\sgn}{\,{\rm sgn}} \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\ul}[1]{\underline{#1}} \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert} \newcommand{\wt}[1]{\widetilde{#1}}$ $\ds{\int_{0}^{\infty}\int_{0}^{\infty}\expo{-\pars{x + y}^{2}}\,\dd y\,\dd x:\ {\large ?}}$ \begin{align}&\color{#66f}{\large%\int_{0}^{\infty}\int_{0}^{\infty}\expo{-\pars{x + y}^{2}}\,\dd y\,\dd x}\\[5mm] = &\\int_{0}^{\infty}\int_{x}^{\infty}\expo{-y^{2}}\,\dd y\,\dd x=\left.\int_{0}^{\infty}\int_{0}^{\infty}\expo{-y^{2}}\,\dd y\,\dd x\right\vert_{y\ >\ x}\\[3mm]&=\left.\int_{0}^{\infty}\expo{-y^{2}}\int_{0}^{\infty}\,\dd x\,\dd y\right\vert_{x\ <\ y}=\int_{0}^{\infty}\expo{-y^{2}}\int_{0}^{y}\,\dd x\,\dd y=\int_{0}^{\infty}y\expo{-y^{2}}\,\dd y\\[5mm] = &\\left.-\,\half\,\expo{-y^{2}}\right\vert_{0}^{\infty} =\color{#66f}{\Large\half}\end{align} | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/830757', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/86508/']} | jdg_86563 |
stackexchange | llm_judgeable_groundtruth_similarity | 9502548 |
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 going to be working on a project that involves a number of elements: ASP.NET MVC website C# console application iPhone App To get all these separate applications talking to the database, my immediate thought was to use a WCF Service. However, I now need to add an API to the site to allow third parties to select, insert and update records from their own applications. In my mind, I would just create a separate RESTful service endpoint on my WCF Service which would be locked down using authentication and would only give access to certain methods. However, I've been reading today about the Web API feature in MVC 4 which is meant to be the latest thing for RESTful APIs? Should I be going along the line of using the Web API? or because my other applications need a web service, should I stick with a WCF Service?
Now provide the response and nothing else.
| If you intend to do RESTful development then you will definitely want to use the ASP.Net Web Api (which was originally called WCF Web Api and created with the goal of "Making REST a first class citizen in .NET" . Another thing to consider is that the WCF REST Starter kit is no longer supported . Note that using Web Api doesn't mean you have to use ASP.Net MVC or IIS even as it can be self hosted . For handling operations which are non-CRUD in nature I'd recommend Googling "REST non-CRUD". I found this blog post RESTful URLs for non-CRUD operations (and particularly the comments interesting). If you decide you NEED to have RPC calls then those may have to be done with WCF. That said since WCF REST is being killed off I'm not sure what the best solution is going to be. Having both is probably the best answer but at the same time it's not necessarily a good answer. Another alternative would be a WCF OData Service but I'm not sure if that gets any support from an iPhone. One last point to make (that can be deleted in the future as this is time sensitive) Microsoft has provided a Go Live license with the beta which means that it is supported by Microsoft and you shouldn't have any problems upgrading to the file RTM. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9502548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/648938/']} | jdg_86564 |
stackexchange | llm_judgeable_groundtruth_similarity | 26130 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Every job offer I receive comes with the provision that I pass a background check, to which I have no choice but submit. It was said of one politician that they wouldn't be allowed to work at a 7-Eleven yet they were running for highest office in the land. Another example was a NYC mayoral candidate who committed lewd acts with children and by his candidacy was proposing to have the public school system accountable to him. Is there any equivalent to the background checks required in professional spheres for those who seek public office?
Now provide the response and nothing else.
| In general, the point of electing someone is that the voters are supposed to decide their qualifications. When there are restrictions on who can hold an office, the restrictions tend to be very simple -- are you a citizen, are you a resident of the area, have you been convicted of a felony, etc. Some positions might require certain professional qualifications (e.g. requiring a prosecutor to be a licensed lawyer), but again, those are fairly simple yes/no questions and are requirements you'd probably have met long before running for office. At the federal level, the only background requirements are those set out in the Constitution. Representatives must be at least 25, Senators at least 30, Presidents at least 35; Representatives must have been a citizen for 7 years, Senators 9, Presidents their whole life; Representatives and Senators must be residents of the state they represent; someone who swore to uphold the Constitution and then took part in a rebellion against it can't hold any office at any level of government; and someone who's been impeached and removed from federal office can be barred by the Senate from ever holding any federal office again (I don't think this applies to being in Congress but does apply to being President, but am unsure). Per Powell v. McCormack , the constitutional requirements for Congress are the only requirements for Congress; I believe the same logic would be extended to the Presidency if it ever came up. The kind of background check a private company does, where they subjectively decide based on your full background whether or not you're suitable, is not used for elective office. The closest you'd get is if you need a professional license (like a prosecutor needing to be a lawyer), where the license might have some subjective "good moral character" requirement, the only requirement for the office is that the licensing agency has licensed you. That's not to say there's no subjective background component. Both the opposition and the press are able to dig into your background and report whatever they find. That lets the voters decide whether or not your background is disqualifying. The whole point of putting an office up to a vote is that you trust the voters to decide who is suited to hold that office. For instance, at the time I'm writing this US Senate candidate Roy Moore has been accused of sexual misconduct back in the 1970s. This is the sort of thing that will basically never show up on a normal background check; however, the media attention on the Senate race meant people were probing deeply into his history, resulting in accusers coming forwards. Now that the allegations are public, the voters of Alabama get to decide whether or not they want to elect someone who's been accused of these things. | {} | {'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/26130', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/12367/']} | jdg_86565 |
stackexchange | llm_judgeable_groundtruth_similarity | 1476950 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $a$ and $b$ and $c$ are parameters, how many solutions for: $$\frac{(x-b)(x-c)}{(a-b)(a-c)} + \frac{(x-a)(x-c)}{(b-a)(b-c)} + \frac{(x-a)(x-b)}{(c-a)(c-b)} = 1$$ I would say $3 \implies x = \{a, b, c\}$ But the answer is apparently $\infty$ . I am confused?
Now provide the response and nothing else.
| You observed that $a$, $b$, and $c$ are solutions. But if a polynomial of degree $\le 2$ has at least $3$ zeros, then it is the identically $0$ polynomial. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1476950', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/279621/']} | jdg_86566 |
stackexchange | llm_judgeable_groundtruth_similarity | 33058717 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The examples I've seen of unrestricted unions always seem to use placement new when constructing. The Wikipedia article for C++11 features uses placement new in the constructor of a union. https://en.wikipedia.org/wiki/C%2B%2B11#Unrestricted_unions #include <new> // Required for placement 'new'.struct Point { Point() {} Point(int x, int y): x_(x), y_(y) {} int x_, y_;};union U { int z; double w; Point p; // Illegal in C++03; legal in C++11. U() {new(&p) Point();} // Due to the Point member, a constructor definition is now required.}; Is it necessary to use placement new here? For example, this piece of code compiles without warnings with gcc and valgrind shows no memory leaks when the union is used to hold a string: struct HasUnresUnion{ enum { Int, String } tag; HasUnresUnion(int i) : tag(Int), as_int(i) {} HasUnresUnion(std::string str) : tag(String), as_str(std::move(str)) {} ~HasUnresUnion() { using std::string; if (tag == String) as_str.~string(); } union { int as_int; std::string as_str; };}; It doesn't seem like there's any ambiguity here so I don't see why the standard would outlaw this. Is this legal code? Is placement new necessary when the union is uninitialized (rather than being assigned to)? Is the constructor in the union required? I've definitely seen unrestricted unions without their own constructors but Wikipedia explicitly states it's required.
Now provide the response and nothing else.
| Introduction The snippet you have shown is perfectly safe; you are legally allowed to initialize one non-static data-member when initializing your union-like class . Example The wikipedia article has an example where placement-new is used because they are writing to a member after the point in which it is possible to directly initialize a certain member. union A { A () { new (&s1) std::string ("hello world"); } ~A () { s1.~basic_string<char> (); } int n1; std::string s1;}; The previous snippet is however semantically equivalent to the following, where we explicitly state that A::s1 shall be initialized when constructing A . union A { A () : s1 ("hello world") { } ~A () { s1.~basic_string<char> (); } int n1; std::string s1;}; Elaboration In your snippet you have an anonymous union inside your class (which makes your class a union-like class ), which means that unless you initialize one of the members of the union during initialization of the class — you must use placement-new to initialize them at a later time. What does the Standard say? 9.5/1 -- Unions -- [class.union]p1 In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time. 3.8/1 -- Object lifetime -- [basic.life]p1 [...] The lifetime of an object of type T begins when: storage with the proper alignment and size for type T is obtained, and if the object has non-trivial initialization, its initialization is complete. The lifetime of an object of type T ends when: if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or the storage which the object occupies is reused or released. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33058717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1128289/']} | jdg_86567 |
stackexchange | llm_judgeable_groundtruth_similarity | 36094183 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a root absolute directory path. How do I generate a dendrogram object of all path's below it so that I can visualize the directory tree with R? Suppose the following call returned the following leaf nodes. list.files(path, full.names = TRUE, recursive = TRUE ) root/a/some/file.Rroot/a/another/file.Rroot/a/another/cool/file.Rroot/b/some/data.csvroot/b/more/data.csv I'd like to make a plot in R like the output of the unix tree program: root├── a│ ├── another│ │ ├── cool│ │ │ └── file.R│ │ └── file.R│ └── some│ └── file.R└── b ├── more │ └── data.csv └── some └── data.csv It would be especially useful if the solution involved decomposing the file system tree into two data.frame 's: a table of nodes (with which I could include attributes such as modification date) and a table of edges (also with attributes) And then building the dendrogram object from those two data.frame s.
Now provide the response and nothing else.
| Here's a possible approach to get what you originally asked for which is a system like tree. This will give a data.tree object that's pretty flexible and could be made to plot like you might want but it's not entirely clear to me what you want: path <- c( "root/a/some/file.R", "root/a/another/file.R", "root/a/another/cool/file.R", "root/b/some/data.csv", "root/b/more/data.csv")library(data.tree); library(plyr)x <- lapply(strsplit(path, "/"), function(z) as.data.frame(t(z)))x <- rbind.fill(x)x$pathString <- apply(x, 1, function(x) paste(trimws(na.omit(x)), collapse="/"))(mytree <- data.tree::as.Node(x))1 root 2 ¦--a 3 ¦ ¦--some 4 ¦ ¦ °--file.R 5 ¦ °--another 6 ¦ ¦--file.R 7 ¦ °--cool 8 ¦ °--file.R9 °--b 10 ¦--some 11 ¦ °--data.csv 12 °--more 13 °--data.csv plot(mytree) You can get the parts you want (I think) but it'll require you to do the leg work and figure out conversion between data types in data.tree : https://cran.r-project.org/web/packages/data.tree/vignettes/data.tree.html#tree-conversion I use this approach in my pathr package's tree function when use.data.tree = TRUE https://github.com/trinker/pathr#tree EDIT Per@Luke's comment below... data.tree::as.Node takes a path directly: (mytree <- data.tree::as.Node(data.frame(pathString = path))) levelName1 root2 2 ¦--a 3 ¦ ¦--some 4 ¦ ¦ °--file.R 5 ¦ °--another 6 ¦ ¦--file.R 7 ¦ °--cool 8 ¦ °--file.R9 °--b 10 ¦--some 11 ¦ °--data.csv 12 °--more 13 °--data.csv | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36094183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552650/']} | jdg_86568 |
stackexchange | llm_judgeable_groundtruth_similarity | 174676 |
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:
When I am faced with a simple linear congruence such as $$9x \equiv 7 \pmod{13}$$and I am working without any calculating aid handy, I tend to do something like the following: "Notice" that adding $13$ on the right and subtracting $13x$ on the left gives:$$-4x \equiv 20 \pmod{13}$$ so that $$x \equiv -5 \equiv 8 \pmod{13}.$$ Clearly this process works and is easy to justify (apart from not having an algorithm for "noticing"), but my question is this: I have a vague recollection of reading somewhere this sort of process was the preferred method of C. F. Gauss, but I cannot find any evidence for this now, so does anyone know anything about this, or could provide a reference? (Or have I just imagined it all?) I would also be interested to hear if anyone else does anything similar.
Now provide the response and nothing else.
| $bx\equiv a\pmod{\!m}$ has a unique solution $\!\iff\!b\,$ is coprime to the modulus $m$ . If so, by Bezout $\,b\,$ is invertible $\!\bmod m,\,$ so scaling $\,bx\equiv a\,$ by $\,b^{-1}\,$ we obtain the unique solution $\,x\equiv b^{-1}a =: a/b.\,$ We can quickly compute $\,b^{-1}\pmod{\!m}\,$ by the extended Euclidean algorithm , but there are often more convenient ways for smaller numbers (e.g. here and here are a handful of methods applied).We describe a few such methods below, viewing $\, x\equiv b^{-1}a \equiv a/b\,$ as a modular fraction. [See here for the general method when the solution is not unique , i.e. when $\gcd(b,m)>1$ ]. The first, Gauss's algorithm , is based on Gauss's proof of Euclid's lemma via the descent $\,p\mid ab\,\Rightarrow\, p\mid a(p\bmod b).\,$ Generally it only works for prime moduli, but we can also execute the general extended Euclidean algorithm in fraction form too (using multi-valued "fractions"). It works by repeatedly scaling $\rm\:\color{#C00}{\frac{A}B}\overset{\times\ N} \to \frac{AN}{BN}\: $ by the least $\rm\,N\,$ with $\rm\, BN \ge 13,\, $ then reducing mod $13$ $$\rm\displaystyle \ mod\ 13\!:\,\ \color{#C00}{\frac{7}9} \,\overset{\times\ 2}\equiv\, \frac{14}{18}\, \equiv\, \color{#C00}{\frac{1}5}\,\overset{\times \ 3}\equiv\, \frac{3}{15}\,\equiv\, \color{#C00}{\frac{3}2} \,\overset{\times\ 7}\equiv\, \frac{21}{14} \,\equiv\, \color{#C00}{\frac{8}1}\qquad\!\! $$ Denominators of the $\color{#c00}{\rm reduced}$ fractions decrease $\,\color{#C00}{ 9 > 5 > 2> \ldots}\,$ so reach $\color{#C00}{1}\,$ (not $\,0\,$ else the denominator would be a proper factor of the prime modulus; it may fail for composite modulus) Simpler: $ $ using $\rm\color{#0a0}{least}$ residues: $\displaystyle\ \ \frac{7}9\,\equiv\, \frac{7}{\!\color{#0a0}{-4}\!\ \,}\,\overset{\times\ 3}\equiv\,\frac{21}{\!\!-12\ \ \ \!\!}\,\equiv\, \color{#c00}{\frac{8}1}$ This optimization using $\rm\color{#0a0}{least\ magnitude}$ residues $\,0,\pm 1, \pm 2.\ldots$ often simplifies mod arithmetic. Here we can also optimize by (sometimes) cancelling obvious common factors, or by pulling out obvious factors of denominators, etc. For example $$\frac{7}9\,\equiv\, \frac{\!-6\,}{\!-4\,}\,\equiv\frac{\!-3\,}{\!-2\,}\,\equiv\frac{10}{\!-2\,}\,\equiv\,-5$$ $$\frac{7}9\,\equiv\,\frac{\!-1\cdot 6}{\ \ 3\cdot 3}\,\equiv\,\frac{\!\,12\cdot 6\!}{\ \ \,3\cdot 3}\,\equiv\, 4\cdot 2$$ Or twiddle it as you did: $ $ check if quotient $\rm a/b\equiv (a\pm\!13\,i)/(b\pm\!13\,j)\,$ is exact for small $\rm\,i,j,\,$ e.g. $$ \frac{1}7\,\equiv \frac{\!-12}{-6}\,\equiv\, 2;\ \ \ \frac{5}7\,\equiv\,\frac{18}{\!-6\!\,}\,\equiv -3$$ When working with smaller numbers there is a higher probability of such optimizations being applicable (the law of small numbers), so it's well-worth looking for such in manual calculations. Generally we can choose a congruent numerator giving an exact quotient by Inverse Reciprocity . $\bmod 13\!:\ \dfrac{a}{b}\equiv \dfrac{a-13\left[\color{#0a0}{\dfrac{a}{13}}\bmod b\right]}b\,\ $ e.g. $\,\ \dfrac{8}9\equiv \dfrac{8-13\overbrace{\left[\dfrac{8}{\color{#c00}{13}}\bmod 9\right]}^{\large\color{#c00}{ 13\ \,\equiv\,\ 4\ }}}9\equiv\dfrac{8-13[2]}9\equiv-2$ Note that the value $\,\color{#0a0}{x\equiv a/13}\,$ is exactly what we need to make the numerator divisible by $b,\,$ i.e. $\qquad\quad\bmod b\!:\,\ a-13\,[\color{#0a0}x]\equiv 0\iff 13x\equiv a\iff \color{#0a0}{x\equiv a/13}$ This is essentially an optimization of the Extended Euclidean Algorithm (when it takes two steps). Note $ $ Gauss' algorithm is my name for a special case of the Euclidean algorithm that's implicit in Gauss' Disquisitiones Arithmeticae, Art. 13, 1801 . I don't know if Gauss explicitly used this algorithm elsewhere (apparently he chose to avoid use or mention of the Euclidean algorithm in Disq. Arith. ). Gauss does briefly mention modular fractions in Art. 31 in Disq. Arith . The reformulation above in terms of fractions does not occur in Gauss' work as far as I know. I devised it in my youth before I had perused Disq. Arith. It is likely very old but I don't recall seeing it in any literature. I'd be very grateful for any historical references. See here for further discussion, including a detailed comparison with the descent employed by Gauss, and a formal proof of correctness of the algorithm. Beware $ $ Modular fraction arithmetic is valid only for fractions with denominator coprime to the modulus. See here for further discussion. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/174676', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32441/']} | jdg_86569 |
stackexchange | llm_judgeable_groundtruth_similarity | 11072407 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Assume p is a integer pointer and i is an integer: *p++ gives an integer value corresponding to p . i++ gives an integer value incremented by 1 Since by behavior, both the above yields integer, ++*p++ and ++i++ shouldn't have same error reported? But why ++*p++ works while ++i++ gives compiler error? int main(){int a[10] = {0};int *p = (int*)&a;int i = 0;// printf("%d", ++i++); -- FAILS error: lvalue required as increment operand printf("%d\n", ++*p++ ); // Prints 1return 0;} EDIT ++i++ is decomposed as following: i++++(result) This is exactly where I am confused :In the same way we can decompose ++*p++ as *p++ ++(result). *p++ returns a value (rvalue) , not a pointer. So why the difference ?
Now provide the response and nothing else.
| The result of post-increment is an rvalue. You're not allowed to modify it. ++i++ attempts to modify that rvalue, which the compiler rejects. p++ produces an rvalue, but it's of pointer type. You're not allowed to modify it, but you are allowed to dereference it. *p++ dereferences that rvalue. This gives you the value it points at, as an lvalue . The pre-increment then modifies the lvalue it points at, not the rvalue that was produced by the post-increment. Edit: I should probably also add one more point: even if ++i++ was allowed by the compiler, the result would be undefined behavior, because it attempts to modify i twice without an intervening sequence point. In the case of ++*p++ , that doesn't happen either -- the post increment modifies the pointer itself, while the pre-increment modifies what the pointer pointed at (before it was incremented). Since we're modifying two entirely different locations, the result in not undefined behavior. If you wanted to badly enough, you could still get undefined behavior by initializing the pointer to point at itself, in which case both increments would attempt to modify the pointer. The committee didn't work very hard at preventing this, probably because only the truly pedantic would be at all likely to even think of such an insane thing. Bottom line: in this case, the compiler is mostly trying to protect you from yourself, though you can still shoot yourself in the foot if you try hard enough. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11072407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/986020/']} | jdg_86570 |
stackexchange | llm_judgeable_groundtruth_similarity | 103387 |
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:
Some topics here have touched on this before (see 1 , 2 , 3 ), but I haven't found a clear definition yet. I would like to know what exact property of the wave function these terms refer to. It would also be helpful to have a clear definition of 'reference' and 'configuration'. I'll try to explain below where my problems are in clearly understanding/defining these terms: Starting with Hartree-Fock, it is obvious that the wave function in HF is both single-reference and 'single-configurational': there is only one Slater determinant. Going to configuration interaction methods, the wave function now becomes a linear combination of several Slater determinants. The additional Slater determinants are excitations of the ground state determinant: virtual orbitals from HF are taken and replace previously occupied orbitals in the determinant. However, these orbitals still have the same coefficients as in HF - only the coefficients in front of the Slater determinants are optimized for the linear combination. If I'm correct, 'configuration' here refers to one particular Slater determinant - a method is, therefore 'multi-configurational' if the wave function that is used has two or more (different) Slater determinants, correct? That also means that none of the CI methods (be it CIS, CISD,..., or Full CI) are multireference methods? Continuing with CASSCF, this method is basically Full CI limited to the chosen active space of orbitals. It is therefore multi-configurational. At the same time, it is also often referred to as being 'multireference'. The only difference to CI, however, seems to be the optimization of the coefficients in the Slater determinants themselves, hence, this must be the defining criterion for 'multireference'? What does 'reference' here refer to? Now there is also multireference-CI. From the above definition, I would expect this to be a form of CI where I also optimize the orbitals, but that does not seem to be the case. The Wikipedia article on MRCI starts with: In quantum chemistry, the multireference configuration interaction (MRCI) method consists of a configuration interaction expansion of the eigenstates of the electronic molecular Hamiltonian in a set of Slater determinants which correspond to excitations of the ground state electronic configuration but also of some excited states. The Slater determinants from which the excitations are performed are called reference determinants. This is confusing to me: Is 'excitation of the ground state electronic configuration' vs. 'excited states' referring to the optimization of the Slater determinants themselves? Or does 'excited state' refer to configurations with different total spin? That would be a different definition of 'reference', but then CASSCF would only be a multireference method if it uses the corresponding SA-CSFs, regardless whether the Slater determinants are optimized or not?
Now provide the response and nothing else.
| Your problem seems to be with the terminology used in CI methods, so let me go through the different terms you mentioned: A configuration is a certain occupation of (molecular) orbitals. Mathematically configurations can be represented in 2 ways. The first one is the Slater Determinant (SD), an anti-symmetrized product of spin-orbitals. Slater Determinants, however, are not eigenfunctions of the spin operator $\hat S^2$ , but the electronic wave function needs to fulfill this requirement. Therefore one constructs spin-adapted Configuration State Functions (CSF) as certain linear-combinations of SDs. Using CSFs instead of SDs usually makes a calculation more stable. "Configuration" is a more general term, which does not explicitly say whether an SD or CSF is considered. Multi-configurational just means the method considers more than one configuration. Reference means we have a designated configuration from which the excitations are generated. Single-reference thus means we only have one such configurations (usually the HF configuration), e.g. in CISD or CCSD. Multi-reference means we have more than one configurations to generate excitations from. So multi-configurational just means we have many configurations, while single-/multireference says something about how those configurations are selected/generated. How does single-/multireference apply to the different methods? In HF we do not generate any excitations, therefore this concept does not really apply here. But I think one could still call it single-reference and single-configurational. CISD and CCSD are the typical examples of single-reference methods. Nothing special here. In FCI and CASCI we don't restrict the excitations to certain degrees (Single, Double, etc.), instead, we just take all of them. The concept of having one (or more) reference configurations is a possible perspective, but it is not really necessary. FCI can be viewed as having one reference configuration and taking all excitation degrees (up to the number of electrons available), which would make it single-reference. But from another perspective, we can argue that every MRCI wave function is just a truncation of the corresponding FCI wave function. So if FCI covers everything and more than MRCI does, would it not be multi-reference as well? Again, I would just say the concept does not apply here. MCSCF (CASSCF) is a combination of CI (CASCI) and SCF, where SCF means we optimize the orbitals as well. This is not done in CI(SD...), CC(SD...), MRCI, etc. Other than that, the above arguments apply in the same way to the CI space as before. Multi-Reference CI and CASSCF As argued above, personally I would not consider CASSCF to be multi-reference, as the concept does not really apply. But I can see why people would consider it as such. One usually does CASSCF because single-reference methods fall short of describing the wave function correctly, in a qualitative way. Such systems are then called strongly correlated and CASSCF can treat that strong correlation (also called static correlation ) which is missing in single-reference calculations. In turn, however, CASSCF is missing that kind of correlation single-reference method can treat well, called weak or dynamic correlation. Multi-reference is now the approach to combine both, strong and weak correlation, by doing first a CASSCF, and then using those configurations as a reference space , to generate all the excitations from. Orbital optimization, however, is usually not feasible for dynamic correlation, because dynamic correlation usually means to have a lot of configurations and therefore huge CI space. With static correlation there are much fewer configurations, so doing orbital optimization additional to CI optimization is feasible and yields qualitative improvements of the orbitals. Therefore this is done in CASSCF, but not in MRCI. "Excited states" in MRCI What is meant here by "excited states" are actually "excited configurations" (with respect to the HF configuration). If you, for example, choose a CAS as your reference space, then all configurations, except for the HF configuration itself, are excited configurations. Please note, that "excited state" is not a good choice of words here since it is actually something different: a state is a result of a CI calculation and is physically observable. On the other hand, a configuration is a basis function you put in a CI calculation and therefore is more of an abstract mathematical tool. However, you can approximate a state as a configuration to some extent, this is for example done in HF. | {} | {'log_upvote_score': 6, 'links': ['https://chemistry.stackexchange.com/questions/103387', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/17102/']} | jdg_86571 |
stackexchange | llm_judgeable_groundtruth_similarity | 3211566 |
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 C++, function() = 10; works if the function returns a variable by reference. What are the use cases of it?
Now provide the response and nothing else.
| The commonest case is to implement things like operator[]. struct A { int data[10]; int & operator[]( int i ) { return data[i]; }}; Another is to return a big object from a class via an accesor function: struct b { SomeBigThing big; const SomeBigThing & MyBig() const { return big; }}; in order to avoid the copying overhead. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3211566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/387587/']} | jdg_86572 |
stackexchange | llm_judgeable_groundtruth_similarity | 267167 |
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 nested list with sublists of varying lengths like this: list={{a,b,c,d},{e,f},{g,h,i},{j},{k,l},{m,n,o}} How can I join the 4th and 5th sublists based on their position to give me: {{a,b,c,d},{e,f},{g,h,i},{j,k,l},{m,n,o}} The closest I have managed to get is using: FlattenAt[list, {{4}, {5}}] But this gives: {{a, b, c, d}, {e, f}, {g, h, i}, j, k, l, {m, n, o}} Thanks in advance.
Now provide the response and nothing else.
| You could use SubsetMap (available from version 12.0), but since it requires you to return the same size you get, we could trick it by Hold and Nothing : ReleaseHold @ SubsetMap[{Join @@ #, Hold @ Nothing} &, list, {4, 5}](* Out: {{a, b, c, d}, {e, f}, {g, h, i}, {j, k, l}, {m, n, o}} *) | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/267167', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/84566/']} | jdg_86573 |
stackexchange | llm_judgeable_groundtruth_similarity | 45745661 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I do a case-insensitive string comparison? From what I understood from Google and the link above that both functions: lower() and casefold() will convert the string to lowercase, but casefold() will convert even the caseless letters such as the ß in German to ss . All of that about Greek letters, but my question in general: are there any other differences? which one is better to convert to lowercase? which one is better to check the matching strings? Part 2: firstString = "der Fluß"secondString = "der Fluss"# ß is equivalent to ssif firstString.casefold() == secondString.casefold(): print('The strings are equal.')else: print('The strings are not equal.') In the example above should I use: lower() # the result is not equal which make sense to me Or: casefold() # which ß is ss and result is the # strings are equal. (since I am a beginner that still does not # make sense to me. I see different strings).
Now provide the response and nothing else.
| TL;DR Purely ASCII Text -> lower() Unicode text/user input -> casefold() Casefolding is a more aggressive version of lower() that is set up to make many of the more unique unicode characters more comparable. It is another form of normalizing text that may initially appear to be very different, but it takes characters of many different languages into account. I suggest you take a closer look into what case folding actually is, so here's a good start: W3 Case Folding Wiki To answer your other two questions, if you are working strictly in the English language, lower() and casefold() should be yielding exactly the same results.However, if you are trying to normalize text from other languages that use more than our simple 26-letter alphabet (using only ASCII), I would use casefold() to compare your strings, as it will yield more consistent results. Another source: Elastic.co Case Folding Edit: I just recently found another very good related answer to a slightly different question here on SO (doing a case-insensitive string comparison) Another Edit: @Voo's comments have been bouncing around in the back of my mind for a few months, so here are some further thoughts: As Voo mentioned, there aren't any languages that never use text outside the standard ASCII values. That's pretty much why Unicode exists. With that in mind, it makes more sense to me to use casefold() on anything that is user-entered that can contain non-ascii values. This might end up excluding some text that might come from a database that strictly deals with ASCII, but, in general, probably most user input would be dealt with using casefold() because it has the logic to properly de-uppercase all of the characters. On the other hand, values that are known to be generated into the ASCII character space like hex UUIDs or something like that should be normalized with lower() because it is a much simpler transformation. Simply put, lower() will require less memory or less time because there are no lookups, and it's only dealing with 26 characters it has to transform. Additionally, if you know that the source of your information is coming from a CHAR or VARCHAR (SQL Server fields) database field, you can similarly just use lower because Unicode characters can't be entered into those fields. So really, this question comes down to knowing the source of your data, and when in doubt about your user-entered information, just casefold() . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45745661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_86574 |
stackexchange | llm_judgeable_groundtruth_similarity | 2191120 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While converting .NET DateTime (when is default(DateTime)) to SqlDateTime should I always check if the .NET date is between SqlDateTime.MinValue and SqlDateTime.MaxValue [or] Is there a good way to do this.
Now provide the response and nothing else.
| Is it possible that the date could actually be outside that range? Does it come from user input? If the answer to either of these questions is yes, then you should always check - otherwise you're leaving your application prone to error. You can format your date for inclusion in an SQL statement rather easily: var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss"); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2191120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85952/']} | jdg_86575 |
stackexchange | llm_judgeable_groundtruth_similarity | 37625480 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How does Go calculate a hash for keys in a map? Is it truly unique and is it available for use in other structures? I imagine it's easy for primitive keys like int or immutable string but it seems nontrivial for composite structures.
Now provide the response and nothing else.
| The language spec doesn't say, which means that it's free to change at any time, or differ between implementations. The hash algorithm varies somewhat between types and platforms. As of now: On x86 (32 or 64 bit) if the CPU supports AES instructions, the runtime uses aeshash , a hash built on AES primitives, otherwise it uses a function "inspired by" xxHash and cityhash, but different from either. There are different variants for 32-bit and 64-bit systems. Most types use a simple hash of their memory contents, but floating-point types have code to ensure that 0 and -0 hash equally (since they compare equally) and NaNs hash randomly (since two NaNs are never equal). Since complex types are built from floats, their hashes are composed from the hashes of their two floating-point parts. And an interface's hash is the hash of the value stored in the interface, and not the interface header itself. All of this stuff is in private functions, so no, you can't access Go's internal hash for a value in your own code. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37625480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717318/']} | jdg_86576 |
stackexchange | llm_judgeable_groundtruth_similarity | 3994928 |
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:
What is the volume of a solid enclosed by $y = (x-1)^2$ and $y = 4$ revolved around $x = - 3$ ? I tried the washer method and the shell method and got different answers each time and I'm really confused please help! My set up for the washer method was: $$ \pi \int_0^4 {(4 + \sqrt{y} + 1)^2 - 4^2 \ \ dy} $$ My set up for the shell method was: $$ 2 \pi \int_{-1}^3 {(x + 3)(4 - \sqrt{x} + 1)^2} \ \ dx $$
Now provide the response and nothing else.
| Washer Method The larger radius comes from the right side of the parabola $y = (x - 1)^2$ , while the smaller radius comes from the left side of that parabola. Rewriting that parabola in terms of $x$ , we have: $$ y = (x - 1)^2 \Rightarrow x = 1 \pm \sqrt{y} . $$ Then, $ R(y) = (1 + \sqrt{y}) - (-3) $ and $ r(y) = (1 - \sqrt{y}) - (-3) $ , where in both functions, the $ - (-3) $ comes from rotating about $x = -3$ . These radii are also a bit easier to see graphically . Then we have $$ R(y) = 4 + \sqrt{y} , $$ $$ r(y) = 4 - \sqrt{y} . $$ Then, our formula for the volume is $$ V_w = \pi \int_0^4 {R(y)^2 - r(y)^2 \ dy} $$ $$ = \pi \int_0^4 {(4 + \sqrt{y})^2 - (4 - \sqrt{y})^2 \ dy} $$ $$ = \frac{256\pi}{3} . $$ Shell Method You've set up the radius of your cylindrical shells correctly: $$ r(x) = x + 3 . $$ But, the height is just the difference in the $y$ -coordinates of the two curves bounding your region: $$ h(x) = 4 - (x - 1)^2 . $$ So, our volume is then $$ V_s = 2 \pi \int_{-1}^3 {r(x)h(x) \ dx} $$ $$ = 2 \pi \int_{-1}^3 {(x + 3)(4 - (x - 1)^2) \ dx} $$ $$ = \frac{256\pi}{3} . $$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3994928', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/877317/']} | jdg_86577 |
stackexchange | llm_judgeable_groundtruth_similarity | 15410486 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
<h:selectOneMenu id="dropdownDevice" value="#{skinningBean.currentDevice}" converter="SkinConverter"> <f:selectItems value="#{skinningBean.myDevicesSI}" var="c" itemValue="#{c}" /> <f:ajax event="change" render="preview" /></h:selectOneMenu> Is it possible to reload the whole page within this dropdown? i need this because, I also need to reload a javascript when another device was selected.
Now provide the response and nothing else.
| You're not clear on if you would like to perform it synchronously or asynchronously. If asynchronously, specify a render of @all . <f:ajax ... render="@all" /> If synchronously, replace <f:ajax> by JS form.submit() call. <h:selectOneMenu ... onchange="this.form.submit()"> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15410486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1177083/']} | jdg_86578 |
stackexchange | llm_judgeable_groundtruth_similarity | 370283 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a script that runs several different psql statements. I'm trying to capture the error output from psql when password entered is incorrect.The password is entered in before the check (and when correct, the psql statements execute successfully) I've tried the following: pwcheck=`psql -q -U postgres -h $ip -d $database;`echo "error message: $pwcheck" When I enter an incorrect password to check it, the error messages are output but the variable is empty. psql: FATAL: password authentication failed for user "postgres"FATAL: password authentication failed for user "postgres"error message: Ideally, I'd like to save the error message to a variable and not print my own error message/prompt and not display the psql errors at all. How can I store either of these error messages in a bash variable?
Now provide the response and nothing else.
| You can't, directly. At least, not without either commingling it with or discarding standard output. However, there is a way! #!/bin/basherrorlog=$(mktemp)trap 'rm -f "$errorlog"' EXITpwcheck="$(psql -q -U postgres -h $ip -d $database 2> "$errorlog")"if [[ 0 -ne $? ]]; then echo "Something went wrong; error log follows:" cat "$errorlog"fi | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/370283', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/218603/']} | jdg_86579 |
stackexchange | llm_judgeable_groundtruth_similarity | 3627793 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Lately, I've had lots of trouble with __repr__() , format() , and encodings. Should the output of __repr__() be encoded or be a unicode string? Is there a best encoding for the result of __repr__() in Python? What I want to output does have non-ASCII characters. I use Python 2.x, and want to write code that can easily be adapted to Python 3. The program thus uses # -*- coding: utf-8 -*-from __future__ import unicode_literals, print_function # The 'Hello' literal represents a Unicode object Here are some additional problems that have been bothering me, and I'm looking for a solution that solves them: Printing to an UTF-8 terminal should work (I have sys.stdout.encoding set to UTF-8 , but it would be best if other cases worked too). Piping the output to a file (encoded in UTF-8) should work (in this case, sys.stdout.encoding is None ). My code for many __repr__() functions currently has many return ….encode('utf-8') , and that's heavy. Is there anything robust and lighter? In some cases, I even have ugly beasts like return ('<{}>'.format(repr(x).decode('utf-8'))).encode('utf-8') , i.e., the representation of objects is decoded, put into a formatting string, and then re-encoded. I would like to avoid such convoluted transformations. What would you recommend to do in order to write simple __repr__() functions that behave nicely with respect to these encoding questions?
Now provide the response and nothing else.
| In Python2, __repr__ (and __str__ ) must return a string object, not aunicode object. In Python3, the situation is reversed, __repr__ and __str__ must return unicode objects, not byte (née string) objects: class Foo(object): def __repr__(self): return u'\N{WHITE SMILING FACE}' class Bar(object): def __repr__(self): return u'\N{WHITE SMILING FACE}'.encode('utf8')repr(Bar())# ☺repr(Foo())# UnicodeEncodeError: 'ascii' codec can't encode character u'\u263a' in position 0: ordinal not in range(128) In Python2, you don't really have a choice. You have to pick an encoding for thereturn value of __repr__ . By the way, have you read the PrintFails wiki ? It may not directly answeryour other questions, but I did find it helpful in illuminating why certainerrors occur. When using from __future__ import unicode_literals , '<{}>'.format(repr(x).decode('utf-8'))).encode('utf-8') can be more simply written as str('<{}>').format(repr(x)) assuming str encodes to utf-8 on your system. Without from __future__ import unicode_literals , the expression can be written as: '<{}>'.format(repr(x)) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3627793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42973/']} | jdg_86580 |
stackexchange | llm_judgeable_groundtruth_similarity | 16819 |
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 planning on doing a large project that would include an ARM microcontroller @ 50 MHz interfacing with a graphic LCD, user buttons, some sensors and some actuators (DC motors, valves) controlled through relays. I want to design a robust and durable power supply for this project that must have a 10+ years lifetime.I have a 24V power supply and I have to design the circuit that will give me 3.3V/5V and at least 1A. What protection components should I include in the circuit?Where does all this components come into place: PTCs, ferrite beads, filter capacitors, EMI filters, fuses etc.?Could you give me a block diagram of such a circuit?
Now provide the response and nothing else.
| Sounds like a homework question :-). If you need to ask at the level of detail you are asking you will need more input and learning than you will get in a single answer here. If this is a real project that is worth money then that is the sort of task that is worth spending money on the design of for professional input. But: Assume design life is 100,000 hours = 11.4 years x 8765 hrs pa. Capacitors can be aluminum electrolytic IF you design properly.A 2000 hour capacitor will need to be run at 60C under rated temperature . So 105C caps need 105C - 60 = 45C ambient or less and preferably much less. That sounds easy but must account for local temperature + enclosure rise + self heating + radiation from other components + any local hot spotting from other air flow. Care will be needed. 3000 or 4000 hour caps will help. Be aware that aluminium wet electrolytic caps die FASTER at a given temperature when unpowered than when powered (due to dryout). Solid Aluminum caps will be easier to use where size and price allows. Tantalum caps are tempting and work well if design is immaculate and if reality follows theory. If this is in a game it's worth the risk, perhaps. If it's in a sub or spacecraft then send tantalum packing now. Understand temperature derating, ripple current derating. Buy components of known trustable brands AND ensure that what you buy is what it claims to be. Incoming inspect as much as needed to maintain certainty. Properly manage ESD issues (electrostatic discharge), if it says don't bend closer to xxx from seal then don't, if it says clamp lead to prevent shock damage while cutting or bending then do. Similarly take proper note of manufacturers advice re max storage time at xx% RH, retreatment required for packages open too long, reflow soldering temperature profiles, advice that part may not be solder by means of xxx, ultrasonic cleaning warnings, solvent cleaning warnings, do not stack xxx way, do not apply force to xxx, ... manufacturers advice. Design properly. Use worst case parameters, pore data sheet for exceptions and special requirements. err on conservative side. For any of the following that you wish to be protect from take due note: Assume worst worst case mains transients, sags, brownout, lightning strike, acts of God, acts of children, acts of drunks and people of low IQ, acts of mice rats ants and cockroaches (gnawing, urinating, defecating, nesting, dying, ...), 100% condensing atmospheres, low humidity, air conditioning failure, coffee spills, Coke spills ... . If you care, assume that 110 VAC equipment will be plugged into 230 VAC mains. Assume that 60 Hz equipment will be plugged into 50 Hz (iron cored transformers care, other things may) and vice versa. Understand longitudinal and transverse mains filters. Understand X & Y filter capacitor ratings. Realise that mains to output ground Y caps can produce destructive output voltages(typically half mans voltage). Allow component degradations and changes of characteristics with time - capacitor dryout, LED degradation (especially including opto couplers), iron cored coil binder thermal degradation, ... . Be aware of why components have rated values - voltage ratings for resistors, surge (not fusing) ratings for fuses, temperature rise for tracks, resistor current as opposed to power ratings, power semiconductor peak vs max operating ratings, dV/dT opto ratings ... . That's a once over lightly out of my head start. There can be much more. Skimp on or ignore almost any of these and your 10 year lifetime is suspect. 100,000 hours is a long time. Survival is usually via gross dumb overkill or skilled design but seldom due to luck. If you are feeling lucky you probably wont be. Produce a total picture of what you wish to do, known hazards, know mitigations, sensible solutions. Worry it to dearth if you don't want it to die. More ... ___________________________________ This superb reference, supplied by @davidcarey, is essential readung. Underestimating Complexity of Power Supply Design - Underestimating the complexity of power supply design can lead to schedule slips, cost overruns, and excessive field failures. Useful: Best manufacturing practices site - Reliability and their download list - some relevant. MORE POWER FOR THE DOLLAR 149 pages Price vs Value - A Technical Guide NAVSO P-3641A (Replaces NAVMAT P-4855-1A) October 1999 Power Supply Standards | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/16819', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4906/']} | jdg_86581 |
stackexchange | llm_judgeable_groundtruth_similarity | 16176701 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to make a Java program in JavaFX using FXML. However i'm having trouble with the layout management. I want to switch between Panes, just as i'm used to with CardLayout in swing, but i can't seem to get it. I googled around and didn't find any answers. Is there any CardLayout equivalent in JavaFX? and if so, can you provide me of an example? That would help my evening a lot! Here is my FXML code <AnchorPane id="anchorPane" prefHeight="324.0" prefWidth="530.0" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication2.SampleController"> <children> <Pane fx:id="mainScreen" layoutX="6.0" prefHeight="324.0" prefWidth="518.0"> <children> <Button layoutX="254.0" layoutY="37.0" mnemonicParsing="false" text="Button" /> </children> </Pane> <Pane fx:id="loginScreen" prefHeight="324.0" prefWidth="530.0"> <children> <TextField id="password" fx:id="username" layoutX="142.0" layoutY="106.0" prefWidth="200.0" /> <TextField fx:id="password" layoutX="142.0" layoutY="140.0" prefWidth="200.0" /> <Label fx:id="label" layoutX="126.0" layoutY="120.0" minHeight="16.0" minWidth="69.0" /> <Button fx:id="button" layoutX="213.0" layoutY="196.0" onAction="#handleButtonAction" onKeyPressed="#handleButtonAction" text="Login" /> </children> </Pane> </children></AnchorPane>
Now provide the response and nothing else.
| Non-animated transitions If you don't need animated transitions between your panes, then you can: Replace the whole scene by creating a new scene and set that scene on your Stage OR Replace just a specific pane in a parent layout, by removing the old pane from it's parent and adding your new pane (by manipulating the parent's children list ) OR Place all your Panes in a StackPane and move the pane you want to display to the top of the stack's child list . Animated transitions If you would like animated transtions between your panes, then see Angela Caicedo's two part series on managing multiple screens in JavaFX: Part I Part II Angela's solution is to use a StackPane with a separate custom ScreenController class for managing Transitions or animations between panes in the stack. Frameworks Frameworks like JFXFlow and WebFX can also provide a browser style interface for your app, allowing users to switch back and forth between screens using back and forward buttons and a history list. Update 2017 I think development on both referenced frameworks above is now defunct. Other frameworks which are under development are: TornadoFX JRebirth afterburner.fx And numerous others (I won't provide a comprehensive list here). Related Loading new fxml in the same scene | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16176701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1290601/']} | jdg_86582 |
stackexchange | llm_judgeable_groundtruth_similarity | 414831 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This question led me to the following: Prove that $\mathbb C[X]/(X^2)$ is isomorphic to $\mathbb R[Y]/((Y^2+1)^2)$.
Now provide the response and nothing else.
| Try to write down a ring homomorphism ${\mathbf R}[y] \rightarrow {\mathbf C}[x]/(x^2)$ with kernel $((y^2+1)^2)$. Build it as a substitution map (evaluation of polynomials in ${\mathbf R}[y]$ at some element of ${\mathbf C}[x]/(x^2)$). Since you want to kill off $(y^2+1)^2$ but not $y^2+1$, you'd like to send $y^2 + 1$ to $x$ (or to any nonzero scalar multiple of $x$), and you need to figure out, with that goal in mind, where $y$ itself ought to be sent. (Hint: think about the first few terms of the Taylor expansion of $\sqrt{1+t}$.) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/414831', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_86583 |
stackexchange | llm_judgeable_groundtruth_similarity | 1514120 |
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 an Object Pool , and rather than implement it myself, I thought I would look around for a ready-made and tested Python library. What I found was plenty of other people looking , but not getting many straight answers, so I have brought it over here to Stack Overflow. In my case, I have a large number of threads (using the threading module), which need to occasionally call a remote SOAP-based server. They could each establish their own connection to the server, but setting up a socket and completing the authentication process is expensive (it is throttled by the server), so I want to share a pool of connections, creating more only as needed. If the items to pool were worker subprocesses, I might have chosen multiprocessing.pool , but they are not. If they were worker threads, I might have chosen this implementation , but they are not. If they were MySQL connections, I might have chosen pysqlpool , but they are not. Similarly the SQLAlchemy Pool is out. If there was one thread, using a variable number of connections/objects, I would consider this implementation , but I need it to be thread-safe. I know I could implement this again fairly quickly, but given there are many people looking for it, I thought a canonical answer on Stack Overflow would be nice.
Now provide the response and nothing else.
| It seems to me, from your description, that what you need is a pool of connections , not of objects. For simple thread-safety, just keep the reusable connections in a Queue.Queue instance, call it pool . When a thread instantiates a connection-wrapping object, the object gets its connection via pool.get() (which automaticaly enqueues it to wait if there are no connections currently availabe and dequeues it when a connection's ready for it); when the object's done using its connection, it puts it back in the pool via pool.put . There's so little universally-required, general-purpose functionality in this, beyond what Queue.Queue already gives you, that it's not surprising no module providing it is well known or popular -- hard to make a module widespread when it has about 6 lines of functional code in all (e.g. to call a user-supplied connection factory to populate the queue either in advance or just-in-time up to some maximum number -- not a big added value generally, anyway). "Thick glue", thickly wrapping the underlying functionality from a standard library module without substantial added value, is an architectural minus, after all;-). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1514120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8014/']} | jdg_86584 |
stackexchange | llm_judgeable_groundtruth_similarity | 34964453 |
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 for a way, either in Ruby or Javascript, that will give me all matches, possibly overlapping, within a string against a regexp. Let's say I have str = "abcadc" , and I want to find occurrences of a followed by any number of characters, followed by c . The result I'm looking for is ["abc", "adc", "abcadc"] . Any ideas on how I can accomplish this? str.scan(/a.*c/) will give me ["abcadc"] , str.scan(/(?=(a.*c))/).flatten will give me ["abcadc", "adc"] .
Now provide the response and nothing else.
| def matching_substrings(string, regex) string.size.times.each_with_object([]) do |start_index, maching_substrings| start_index.upto(string.size.pred) do |end_index| substring = string[start_index..end_index] maching_substrings.push(substring) if substring =~ /^#{regex}$/ end endendmatching_substrings('abcadc', /a.*c/) # => ["abc", "abcadc", "adc"]matching_substrings('foobarfoo', /(\w+).*\1/) # => ["foobarf", # "foobarfo", # "foobarfoo", # "oo", # "oobarfo", # "oobarfoo", # "obarfo", # "obarfoo", # "oo"]matching_substrings('why is this downvoted?', /why.*/) # => ["why", # "why ", # "why i", # "why is", # "why is ", # "why is t", # "why is th", # "why is thi", # "why is this", # "why is this ", # "why is this d", # "why is this do", # "why is this dow", # "why is this down", # "why is this downv", # "why is this downvo", # "why is this downvot", # "why is this downvote", # "why is this downvoted", # "why is this downvoted?"] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34964453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5830265/']} | jdg_86585 |
stackexchange | llm_judgeable_groundtruth_similarity | 11064473 |
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, myTable that has two fields in it ID and patientID . The same patientID can be in the table more than once with a different ID. How can I make sure that I get only ONE instance of every patientID .? EDIT: I know this isn't perfect design, but I need to get some info out of the database and today and then fix it later.
Now provide the response and nothing else.
| You could use a CTE with ROW_NUMBER function: WITH CTE AS( SELECT myTable.* , RN = ROW_NUMBER()OVER(PARTITION BY patientID ORDER BY ID) FROM myTable )SELECT * FROM CTEWHERE RN = 1 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11064473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/645070/']} | jdg_86586 |
stackexchange | llm_judgeable_groundtruth_similarity | 57805276 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a functional difference between declaring a property in TypeScript as readonly vs creating it through a get() ? Both behave the same, but it'd be good to know if there is a reason to use one over the other besides preference.
Now provide the response and nothing else.
| It makes a difference to the generated JavaScript: The getter will be an accessor property (e.g., function), the readonly property will be a data property. This: class Example { get foo(): string { return "foo"; } readonly bar: string = "bar";} converts to this if you target ES2015+: "use strict";class Example { constructor() { this.bar = "bar"; } get foo() { return "foo"; }} Live on the playground or to this if you target ES5+: "use strict";var Example = /** @class */ (function () { function Example() { this.bar = "bar"; } Object.defineProperty(Example.prototype, "foo", { get: function () { return "foo"; }, enumerable: true, configurable: true }); return Example;}()); Live on the playground Notice that although TypeScript considers bar read-only, nothing enforces that at runtime. foo , on the other hand, is read-only even at runtime. (Although if you really wanted to, you could use Object.defineProperty to defeat it by reconfiguring the property.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57805276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1195056/']} | jdg_86587 |
stackexchange | llm_judgeable_groundtruth_similarity | 45197566 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following dataframe df: Customer_ID | 2015 | 2016 |2017 | Year_joined_mailingABC 5 6 10 2015BCD 6 7 3 2016 DEF 10 4 5 2017GHI 8 7 10 2016 I would like to look up the value of the customer in the year they joined the mailing list and save it in a new column. Output would be: Customer_ID | 2015 | 2016 |2017 | Year_joined_mailing | Purchases_1st_yearABC 5 6 10 2015 5BCD 6 7 3 2016 7 DEF 10 4 5 2017 5GHI 8 9 10 2016 9 I have found some solutions for match vlookup in python, but none that would use the headers of other columns.
Now provide the response and nothing else.
| Deprecation Notice : lookup was deprecated in v1.2.0 Use pd.DataFrame.lookup Keep in mind that I'm assuming Customer_ID is the index. df.lookup(df.index, df.Year_joined_mailing)array([5, 7, 5, 7]) df.assign( Purchases_1st_year=df.lookup(df.index, df.Year_joined_mailing)) 2015 2016 2017 Year_joined_mailing Purchases_1st_yearCustomer_ID ABC 5 6 10 2015 5BCD 6 7 3 2016 7DEF 10 4 5 2017 5GHI 8 7 10 2016 7 However, you have to be careful with comparing possible strings in the column names and integers in the first year column... Nuclear option to ensure type comparisons are respected. df.assign( Purchases_1st_year=df.rename(columns=str).lookup( df.index, df.Year_joined_mailing.astype(str) )) 2015 2016 2017 Year_joined_mailing Purchases_1st_yearCustomer_ID ABC 5 6 10 2015 5BCD 6 7 3 2016 7DEF 10 4 5 2017 5GHI 8 7 10 2016 7 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45197566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5187157/']} | jdg_86588 |
stackexchange | llm_judgeable_groundtruth_similarity | 1534810 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently having a really weird issue and I can't seem to figure out how to resolve it. I've got a fairly complex type which I'm trying to serialize using the XmlSerializer class. This actually functions fine and the type serializes properly, but seems to take a very long time in doing so; around 5 seconds depending on the data in the object. After a bit of profiling I've narrowed the issue down - bizarrely - to specifying an XmlRootAttribute when calling XmlSerializer.Serialize. I do this to change the name of a collection being serialized from ArrayOf to something a bit more meaningful. Once I remove the parameter the operation is almost instant! Any thoughts or suggestions would be excellent as I'm entirely stumped on this one!
Now provide the response and nothing else.
| Just for anyone else who runs into this problem; armed with the answer above and the example from MSDN I managed to resolve this issue using the following class: public static class XmlSerializerCache{ private static readonly Dictionary<string, XmlSerializer> cache = new Dictionary<string, XmlSerializer>(); public static XmlSerializer Create(Type type, XmlRootAttribute root) { var key = String.Format( CultureInfo.InvariantCulture, "{0}:{1}", type, root.ElementName); if (!cache.ContainsKey(key)) { cache.Add(key, new XmlSerializer(type, root)); } return cache[key]; }} Then instead of using the default XmlSerializer constructor which takes an XmlRootAttribute, I use the following instead: var xmlRootAttribute = new XmlRootAttribute("ExampleElement");var serializer = XmlSerializerCache.Create(target.GetType(), xmlRootAttribute); My application is now performing again! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1534810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/186017/']} | jdg_86589 |
stackexchange | llm_judgeable_groundtruth_similarity | 30669854 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am a beginner of the neural network. I am very confused about the word feature . Can you give me a defintion of feature ? Are the features the neurons in the hidden layers?
Now provide the response and nothing else.
| The features are the elements of your input vectors. The number of features is equal to the number of nodes in the input layer of the network. If you were using a neural network to classify people as either men or women, the features would be things like height, weight, hair length etc. Each of these would have an initial value in meters, kilograms and so on, and would then be normalized and centered at zero (within-feature) prior to presentation to the system. So this guy: height: 1.5m weight: 70kg hair length: 0.1m Would be initially represented by the vector [1.5, 70, 0.1] and then after preprocessing (there would have to be other items in the dataset...) by something like [-0.2, 0.4, .05] The features of an image of a letter could be as simple as the greyscale values of pixels. Other features could be generated by processing the images and extracting parameters from power spectra, or finding edges, etc. To learn more about this, seek out information about image processing and feature extraction. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30669854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3279996/']} | jdg_86590 |
stackexchange | llm_judgeable_groundtruth_similarity | 6398937 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I have a folder in my "Resources" folder of my iPhone application called "Documents". Is there a way that I can get an array or some type of list of all the files included in that folder at run time? So, in code, it would look like: NSMutableArray *myFiles = [...get a list of files in Resources/Documents...]; Is this possible?
Now provide the response and nothing else.
| You can get the path to the Resources directory like this, NSString * resourcePath = [[NSBundle mainBundle] resourcePath]; Then append the Documents to the path, NSString * documentsPath = [resourcePath stringByAppendingPathComponent:@"Documents"]; Then you can use any of the directory listing APIs of NSFileManager . NSError * error;NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error]; Note : When adding source folder into the bundle make sure you select "Create folder references for any added folders option when copying" | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6398937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/412082/']} | jdg_86591 |
stackexchange | llm_judgeable_groundtruth_similarity | 290913 |
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 C++, is it possible to have a base plus derived class implement a single interface? For example: class Interface{ public: virtual void BaseFunction() = 0; virtual void DerivedFunction() = 0;};class Base{ public: virtual void BaseFunction(){}};class Derived : public Base, public Interface{ public: void DerivedFunction(){}};void main(){ Derived derived;} This fails because Derived can not be instantiated. As far as the compiler is concerned Interface::BaseFunction is never defined. So far the only solution I've found would be to declare a pass through function in Derived class Derived : public Base, public Interface{ public: void DerivedFunction(){} void BaseFunction(){ Base::BaseFunction(); }}; Is there any better solution? EDIT: If it matters, here is a real world problem I had using MFC dialogs. I have a dialog class (MyDialog lets say) that derives from CDialog. Due to dependency issues, I need to create an abstract interface (MyDialogInterface). The class that uses MyDialogInterface needs to use the methods specific to MyDialog, but also needs to call CDialog::SetParent. I just solved it by creating MyDialog::SetParent and having it pass through to CDialog::SetParent, but was wondering if there was a better way.
Now provide the response and nothing else.
| C++ doesn't notice the function inherited from Base already implements BaseFunction : The function has to be implemented explicitly in a class derived from Interface . Change it this way: class Interface{ public: virtual void BaseFunction() = 0; virtual void DerivedFunction() = 0;};class Base : public Interface{ public: virtual void BaseFunction(){}};class Derived : public Base{ public: virtual void DerivedFunction(){}};int main(){ Derived derived;} If you want to be able to get away with only implementing one of them, split Interface up into two interfaces: class DerivedInterface{ public: virtual void DerivedFunction() = 0;};class BaseInterface{ public: virtual void BaseFunction() = 0;};class Base : public BaseInterface{ public: virtual void BaseFunction(){}};class Derived : public DerivedInterface{ public: virtual void DerivedFunction(){}}; class Both : public DerivedInterface, public Base { public: virtual void DerivedFunction(){}};int main(){ Derived derived; Base base; Both both;} Note: main must return int Note: it's good practise to keep virtual in front of member functions in the derived that were virtual in the base, even if it's not strictly required. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/290913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12567/']} | jdg_86592 |
stackexchange | llm_judgeable_groundtruth_similarity | 50218376 |
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 Kubernetes based application consisting of multiple services (and pods) managed with helm chart. Postgres is used as a database for all services. When application is upgraded to a newer version, I am running a db migration script via initContainers . The problem occurs when migration scripts require an exclusive access to DB (all other connections should be terminated), otherwise the script is blocked. Ideal solution would be to stop all pods, run the migration and recreate them. But I am not sure how to achieve it properly with Kubernetes. Tnx
Now provide the response and nothing else.
| Ideal solution would be to stop all pods, run the migration andrecreate them. But I am not sure how to achieve it properly withKubernetes. I see from one of the comments that you use Helm, so I'd like to propose a solution leveraging Helm's hooks: Helm provides a hook mechanism to allow chart developers to interveneat certain points in a release's life cycle. For example, you can usehooks to: Load a ConfigMap or Secret during install before any other charts areloaded. Execute a Job to back up a database before installing a newchart, and then execute a second job after the upgrade in order torestore data. Run a Job before deleting a release to gracefully take aservice out of rotation before removing it. https://helm.sh/docs/topics/charts_hooks/ You could package your migration as a k8s Job and leverage the pre-install or pre-upgrade hook to run the job. These hooks runs after templates are rendered, but before any new resources are created in Kubernetes. Thus, your migrations will run before your Pods are deployed. To delete the deployments prior to running your migrations, create a second pre-install/pre-upgrade hook with a lower helm.sh/hook-weight that deletes the target deployments: apiVersion: batch/v1kind: Jobmetadata: name: "pre-upgrade-hook1" annotations: "helm.sh/hook": pre-upgrade "helm.sh/hook-weight": "-1" "helm.sh/hook-delete-policy": hook-succeededspec: template: metadata: name: "pre-upgrade-hook1" spec: restartPolicy: Never serviceAccountName: "<an SA with delete RBAC permissions>" containers: - name: kubectl image: "lachlanevenson/k8s-kubectl:latest" command: ["delete","deployment","deploy1","deploy2"] The lower hook-weight will ensure this job runs prior to the migration job. This will ensure the following series of events: You run helm upgrade The helm hook with the lowest hook-weight runs and deletes the relevant deployments The second hook runs and runs your migrations Your Chart will install with new Deployments, Pods, etc. Just make sure to keep all of the relevant Deployments in the same Chart. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50218376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1349428/']} | jdg_86593 |
stackexchange | llm_judgeable_groundtruth_similarity | 14091387 |
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 take input from a CSV file and then push it into a dictionary format (I am using Python 3.x). I use the code below to read in the CSV file and that works: import csvreader = csv.reader(open('C:\\Users\\Chris\\Desktop\\test.csv'), delimiter=',', quotechar='|')for row in reader: print(', '.join(row)) But now I want to place the results into a dictionary. I would like the first row of the CSV file to be used as the "key" field for the dictionary with the subsequent rows in the CSV file filling out the data portion. Sample data: Date First Name Last Name Score12/28/2012 15:15 John Smith 2012/29/2012 15:15 Alex Jones 3812/30/2012 15:15 Michael Carpenter 25 How can I get the dictionary to work?
Now provide the response and nothing else.
| Create a dictionary, then iterate over the result and stuff the rows in the dictionary. Note that if you encounter a row with a duplicate date, you will have to decide what to do (raise an exception, replace the previous row, discard the later row, etc...) Here's test.csv: Date,Foo,Bar123,456,789abc,def,ghi and the corresponding program: import csvreader = csv.reader(open('test.csv'))result = {}for row in reader: key = row[0] if key in result: # implement your duplicate row handling here pass result[key] = row[1:]print(result) yields: {'Date': ['Foo', 'Bar'], '123': ['456', '789'], 'abc': ['def', 'ghi']} or, with DictReader: import csvreader = csv.DictReader(open('test.csv'))result = {}for row in reader: key = row.pop('Date') if key in result: # implement your duplicate row handling here pass result[key] = rowprint(result) results in: {'123': {'Foo': '456', 'Bar': '789'}, 'abc': {'Foo': 'def', 'Bar': 'ghi'}} Or perhaps you want to map the column headings to a list of values for that column: import csvreader = csv.DictReader(open('test.csv'))result = {}for row in reader: for column, value in row.items(): # consider .iteritems() for Python 2 result.setdefault(column, []).append(value)print(result) That yields: {'Date': ['123', 'abc'], 'Foo': ['456', 'def'], 'Bar': ['789', 'ghi']} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14091387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1937972/']} | jdg_86594 |
stackexchange | llm_judgeable_groundtruth_similarity | 22186626 |
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 we write: //in mainFILE *p = fopen("filename", "anymode"); My question is: to what is p pointing?
Now provide the response and nothing else.
| The file pointer p is pointing a structure handled by the C library that manages I/O functionality for the named file in the given open mode. You can't tell, a priori, whether what it points at is statically allocated memory or dynamically allocated memory; you don't need to know. You treat it as an opaque pointer. Note that the standard says: ISO/IEC 9899:2011 7.21.3 Files The address of the FILE object used to control a stream may be significant; a copy of a FILE object need not serve in place of the original. This says (roughly): Don't futz around with the pointer; pass it to the functions that need it and otherwise leave well alone. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22186626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3287033/']} | jdg_86595 |
stackexchange | llm_judgeable_groundtruth_similarity | 5724761 |
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 now doing it this way: [root@~]# echo Aa|hexdump -v0000000 6141 000a 0000003[root@~]# echo -e "\x41\x41\x41\x41"AAAA But it's not exactly behaving as I wanted, the hex form of Aa should be 4161 ,but the output is 6141 000a ,which seems not making sense. and when performing hex to ascii,is there another utility so that I don't need the prefix \x ?
Now provide the response and nothing else.
| The reason is because hexdump by default prints out 16-bit integers, not bytes. If your system has them, hd (or hexdump -C ) or xxd will provide less surprising outputs - if not, od -t x1 is a POSIX-standard way to get byte-by-byte hex output. You can use od -t x1c to show both the byte hex values and the corresponding letters. If you have xxd (which ships with vim), you can use xxd -r to convert back from hex (from the same format xxd produces). If you just have plain hex (just the '4161', which is produced by xxd -p ) you can use xxd -r -p to convert back. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5724761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/681256/']} | jdg_86596 |
stackexchange | llm_judgeable_groundtruth_similarity | 35030642 |
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 JavaScript, is the following code: window.onresize = function() { // Do something.} The same as: $(window).on('resize', function () { // Do something.}); Are the two code blocks above equal, functionality-wise? Is there any advantage or disadvantage (however minor) using one or the other? What about: window.addEventListener('resize', function(event) { // Do something.});
Now provide the response and nothing else.
| They aren't the same, in the first example, you're affecting an event to the dom object onresize handler. The jQuery version is probably doing something different behind the scene. Without looking into the source code, it is probably simply doing: window.addEventListener('resize', function () {...}) That said, the jQuery version and the native addEventListener are still different because jQuery is also adding some magic to the event handler. And addEventListenener is probably the prefered way to add event to a DOM object, because you can add multiple events but with the dom attribute on[event] you're limited to one event. Here's a bit more about it: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener While you're at it, you could also read about the addEventListener friend: removeEventListener . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35030642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1744104/']} | jdg_86597 |
stackexchange | llm_judgeable_groundtruth_similarity | 5695810 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I store a credit card's expiration date if it only consists of the month and year? The date field in mysql accepts the following format: yyyy-mm-dd. An expiration date without a day is not invalid using that format. Do I use varchar, instead? And does that not prevent me from making calculations to determine when cards expire and what not?
Now provide the response and nothing else.
| For Jan 2014: 2014-01-00 It's common to use 00 for month and day that are undefined. From the MySQL reference manual : Some date functions can be used with “zero” dates or incomplete dates such as '2001-11-00', whereas others cannot. Functions that extract parts of dates typically work with incomplete dates and thus can return 0 when you might otherwise expect a nonzero value. For example: mysql> SELECT DAYOFMONTH('2001-11-00'), MONTH('2005-00-00'); -> 0, 0 and later on in the manual for DATE_FORMAT : Ranges for the month and day specifiers begin with zero due to the fact that MySQL permits the storing of incomplete dates such as '2014-00-00'. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5695810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/276959/']} | jdg_86598 |
stackexchange | llm_judgeable_groundtruth_similarity | 443226 |
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:
What determines which Linux commands require root access? I understand the reasons why it is desirable that, say, apt-get should require root privilege; but what distinguishes these commands from the rest? Is it simply a matter of the ownership and execute permissions of the executable?
Now provide the response and nothing else.
| It's mainly a matter of what the tool or program does . Keeping in mind that a non-superuser can only touch files that it owns or has access to, any tool that needs to be able to get its fingers into everything will require superuser access in order to do the thing which it does. A quick sample of Things that might require superuser access include, but are not limited to: Opening a listening TCP socket on a port below 1024 Changing system configurations (e. g. anything in /etc ) Adding new globally-accessible libraries ( /lib and /usr/lib ) or binaries ( /bin , /usr/bin ) Touching any files not owned by the user who is doing the touching which don't have a sufficiently permissive mode Changing other users' files' ownership Escelating process priorities (e. g. renice ) Starting or stopping most services Kernel configuration (e. g. adjusting swappiness) Adjusting filesystem quotas Writing to "full" disks (most filesystems reserve some space for the root user) Performing actions as other users | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/443226', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/290445/']} | jdg_86599 |
stackexchange | llm_judgeable_groundtruth_similarity | 6852763 |
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 the following mapping: map <F4> :execute "vimgrep /" .expand("<cword>") . "/j **" <Bar> cw<CR> which (recursively) greps the current directory for instances of the word under the cursor and opens these files in the quickfix list window. From the quickfix window, how do I launch the file that I open into a new tab? Enter just changes my current buffer in the window to that new file.
Now provide the response and nothing else.
| Quickfix-window commands respect the switchbuf option when creatingthe buffer. The switchbuf option has the newtab specifier thatinstructs Vim to open a new tab page before loading the buffer toswitch to. If one adds this key to the option via :set switchbuf+=newtab the entries in the quickfix window will be opened in separate tabpages. There is the usetab specifier that also might be useful in thiscase. It prescribes Vim to switch to an existing tab page if itcontains a window displaying the target buffer, instead of duplicatingit in a new tab. :set switchbuf+=usetab,newtab The value of switchbuf also (partially) affects otherbuffer-switching commands, such as :bfirst , :blast , :sbuffer , :sbnext , and :sbprevious . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6852763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61410/']} | jdg_86600 |
stackexchange | llm_judgeable_groundtruth_similarity | 16138766 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Going by the instructions both here: http://lokeshdhakar.com/projects/lightbox2/ and in the book "Murach's JavaScript and jQuery" (on pages 320 and 321), I'm trying to add lightbox functionality to my site. I added lightbox.css (and screen.css, thtinking that might also be required) to my Content folder, and both lightbox.js and jquery.smooth-scroll.min.js (because it was included in the lightbox download, and I figured lightbox needed it) to my Scripts folder. I also added to my Images folder the following images included in the lightbox download: close.png, loading.gif, next.png, and prev.png. I've got this html and jQuery code (this is the entire Default.cshtml at this point): @{ Layout = "~/_SiteLayout.cshtml"; Page.Title = "el Garrapata - Spoon!!!";}<div id="tabs"> <ul> <li><a href="#tabs-1">Spring</a></li> <li><a href="#tabs-2">Summer</a></li> <li><a href="#tabs-3">Fall</a></li> <li><a href="#tabs-4">Winter</a></li> </ul> <div id="tabs-1"> <a href="Images/Fullsize/Landscapes/Spring_2013 04 06_2293.jpg" rel="lightbox" ><img src="Images/Thumbnails/Landscapes/Spring_2013 04 06_2293_th.jpg" width="300" height="200"></a> </div> <div id="tabs-2"> </div> <div id="tabs-3"> </div> <div id="tabs-4"> </div></div> <script type="text/javascript"> $(document).ready(function () { $("#tabs").tabs(); }); </script> ...but it doesn't work: although that one thumbnail image displays in the "Spring" tab, clicking it simply causes the screen to go mostly dark - it becomes "grayed out" to the point of almost opaqueness. The lightbox download also includes jquery-1.7.2.min.js and jquery-ui-1.8.18.custom.min.js I'm referencing newer versions in _SiteLayout.cshtml: <script src="~/Scripts/jquery-2.0.0.min.js"></script><script src="~/Scripts/jquery-ui-1.9.2.min.js"></script> Could this be the problem? Am I "stuck" using older versions of jQuery and jQueryUI if I want to use lightbox? BTW, I tried to post this at lightbox's internal forum, but was unable to log in, neither with Fakebook or Google (although I have (reluctantly in the case of the former) accounts with both; also the OpenID jazz I tried, but it seems to expect an URL...???) UPDATE Note: I am going to bountify this question for 100 points ASAP. If I get an answer prior to that, I will award the bounty post-answer. UPDATE 2 I've switched to fancyBox, but the large (href) image still hugs the left side of the page when clicking on the "thumbnail", not the center. Here's all the Razor, HTML, and jQuery (some of the image code elided for brevity): selected from _SiteLayout.cshtml: <link rel="stylesheet" href="/fancybox/source/jquery.fancybox.css?v=2.1.4" type="text/css" media="screen" /><script src="~/Scripts/jquery-2.0.0.min.js"></script><!-- May want to replace the above before deploying with use of a CDN:<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>OR: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>..and similar for jquery-ui --><script src="~/Scripts/jquery-ui-1.9.2.min.js"></script><script type="text/javascript" src="/fancybox/source/jquery.fancybox.pack.js?v=2.1.4"></script> from Default.cshtml: @{ Layout = "~/_SiteLayout.cshtml"; Page.Title = "Garrapata";}<div id="tabs"> <ul> <li><a href="#tabs-1">Spring</a></li> <li><a href="#tabs-2">Summer</a></li> <li><a href="#tabs-3">Fall</a></li> <li><a href="#tabs-4">Winter</a></li> </ul> <div id="tabs-1"> <a class="fancybox" rel="group" href="Images/Fullsize/Landscapes/Spring_2013 04 06_2293.jpg"><img src="Images/Thumbnails/Landscapes/Spring_2013 04 06_2293_th.jpg" width="294" height="196" alt="" /></a> <a class="fancybox" rel="group" href="Images/Fullsize/Landscapes/Spring_2013 04 06_2295.jpg"><img src="Images/Thumbnails/Landscapes/Spring_2013 04 06_2295_th.jpg" width="294" height="196" alt="" /></a> </div> <div id="tabs-2"> </div> <div id="tabs-3"> </div> <div id="tabs-4"> </div></div> <script type="text/javascript"> $(document).ready(function () { $("#tabs").tabs(); $(".fancybox").fancybox({ openEffect : 'elastic', closeEffect : 'elastic' }); }); </script> Also, I don't see the "Close" button in the NE corner - perhaps because the large image, taking up all the "top" space, has not left room for it to be visible. UPDATE 3 Now I see that the .css and .js files I was referencing in _SiteLayout.cshtml are supposed to be in /fancybox/source It seems like instead of what I have now, namely: <link rel="stylesheet" href="/fancybox/source/jquery.fancybox.css?v=2.1.4" type="text/css" media="screen" /><script type="text/javascript" src="/fancybox/source/jquery.fancybox.pack.js?v=2.1.4"></script> ...what should work would be: <link rel="stylesheet" href="~/Content/jquery.fancybox.css" type="text/css" media="screen" /><script type="text/javascript" src="~/Scripts/jquery.fancybox.js"></script> ...as I have copied those files into those locations. Does it really have to be that particular (and, it seems to me, rather peculiar) way you mentioned? Since it would seem based on what I've got that the css and js would not be found at all, I'm surprised it even works as well as it does...
Now provide the response and nothing else.
| The lightbox you're trying to implement only works with jQuery jquery-1.7.2 or below and also you don't need jquery-ui-1.9.2.min.js in order for the Lightbox to work. For this version of lightbox to work, you need lightbox.css , jquery-1.7.2.js and lightbox.js . Shown below is a sample code similar to your one where the Lightbox is working. ( Paste this code on a Text editor, save it as a HTML page and open it using your Web Browser ) <html><head> <!-- **** Things you need to do**** 1. SPECIFY LIGHTBOX CSS FILE 2. SPECIFY JQUERY JS (jquery-1.7.2) FILE 3. SPECIFY LIGHTBOX JS FILE --> <link rel="stylesheet" href="http://lokeshdhakar.com/projects/lightbox2/css/lightbox.css" type="text/css" media="screen" /> <script src="http://lokeshdhakar.com/projects/lightbox2/js/jquery-1.7.2.min.js"></script> <script src="http://lokeshdhakar.com/projects/lightbox2/js/lightbox.js"></script> </head><body><div id="tabs"> <ul> <li><a href="#tabs-1">Spring</a></li> <li><a href="#tabs-2">Summer</a></li> <li><a href="#tabs-3">Fall</a></li> <li><a href="#tabs-4">Winter</a></li> </ul> <div id="tabs-1"> <a href="http://pages.swcp.com/~jamii/OtherCats/coco.jpg" rel="lightbox" > <img src="http://pages.swcp.com/~jamii/OtherCats/coco.jpg" width="300" height="200"> </a> </div></div></body></html> You can use fancybox instead of lightbox, which works with the latest jQuery versions. The latest version of Fancybox is Fancybox 2 , You can download it from this Site - http://fancyapps.com/fancybox/ Code for implementing Fancybox 2 <html><head> <!-- Add jquery library --> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js"></script> <link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css" media="screen" /> <script> $(document).ready(function(){ $(".fancybox").fancybox({ openEffect : 'elastic', closeEffect : 'elastic' }); }); </script></head><body><div id="tabs"> <ul> <li><a href="#tabs-1">Spring</a></li> <li><a href="#tabs-2">Summer</a></li> <li><a href="#tabs-3">Fall</a></li> <li><a href="#tabs-4">Winter</a></li> </ul> <div id="tabs-1"> <a class="fancybox" href="http://pages.swcp.com/~jamii/OtherCats/coco.jpg" rel="lightbox" > <!--Add class "fancybox"--> <img src="http://pages.swcp.com/~jamii/OtherCats/coco.jpg" width="300" height="200"> </a> </div></div></body></html> UPDATE #1 You need all the files in the source folder to implement fancybox (helpers folder is optional). You need to keep the fancybox css, js and images in one location. What you can do is copy the source folder into your web app directory and rename it to fancybox . Then you can call the css file, js files from your html page. eg: <link rel="stylesheet" href="../fancybox/jquery.fancybox.css" type="text/css" media="screen" /><script type="text/javascript" src="../fancybox/jquery.fancybox.pack.js"></script> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16138766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/875317/']} | jdg_86601 |
stackexchange | llm_judgeable_groundtruth_similarity | 31200680 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please refer to below code. #import "RecipeDetail.h"#import "Recipe.h"@implementation RecipeDetail@synthesize recipeLabel;@synthesize recipeName;- (void)viewDidLoad{ [super viewDidLoad]; self.title = recipe.name; self.prepTimeLabel.text = recipe.prepTime; self.recipePhoto.image = [UIImage imageNamed:recipe.imageFile]; NSMutableString *ingredientText = [NSMutableString string]; for (NSString* ingredient in recipe.ingredients) { [ingredientText appendFormat:@"%@\n", ingredient]; } self.ingredientTextView.text = ingredientText;}
Now provide the response and nothing else.
| Instead of animating two attributes simultaneously, I think you'll find it much easier to use a transform attribute to get the coordinate system you wanted in the first place. In this example, the animated <rect> elements are wrapped in the following <g> element: <g transform="scale(1,-1) translate(0,-200)"> ...</g> The scale transform turns all the y coordinates upside down, and the translate transform shifts the coordinates so that y=0 is at the bottom of the SVG canvas. <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="400" height="200" viewBox="0 0 400 200"> <g transform="scale(1,-1) translate(0,-200)"> <rect x="50" y="0" fill="#f00" width="100" height="100"> <animate attributeName="height" from="0" to="100" dur="0.5s" fill="freeze" /> </rect> <rect x="150" y="0" fill="#f70" width="100" height="200"> <animate attributeName="height" from="0" to="200" dur="0.5s" fill="freeze" /> </rect> <rect x="250" y="0" fill="#ec0" width="100" height="150"> <animate attributeName="height" from="0" to="150" dur="0.5s" fill="freeze" /> </rect> </g></svg> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31200680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5047304/']} | jdg_86602 |
stackexchange | llm_judgeable_groundtruth_similarity | 52508038 |
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 upgraded an EC2 instance from m4 to m5, and now I want to increase the volume. I did perform this command and got the error: growpart /dev/nvme0n1 p1FAILED: partition-number must be a number Can't find instruction from AWS docs and forums. Any idea how to increase NVME disk ?
Now provide the response and nothing else.
| ERROR: type should be string, got "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recognize-expanded-volume-linux.html growpart [OPTIONS] DISK PARTITION-NUMBER $ lsblkNAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTnvme0n1 259:0 0 16G 0 disk ├─nvme0n1p1 259:1 0 8G 0 part /└─nvme0n1p128 259:2 0 1M 0 part So to grow the partition, we use the diskname nvme0n1 (see disk under TYPE ) and desired partition is 1 sudo growpart /dev/nvme0n1 1 And then to extend the fs - resize2fs device [ size ] (device refers to the location of the target filesystem) $ df -hFilesystem Size Used Avail Use% Mounted ondevtmpfs 470M 52K 470M 1% /devtmpfs 480M 0 480M 0% /dev/shm/dev/nvme0n1p1 7.8G 7.7G 3.1M 100% / So to extend the fs, we use the device name /dev/nvme01np1 : sudo resize2fs /dev/nvme0n1p1 Voila! $ df -hFilesystem Size Used Avail Use% Mounted ondevtmpfs 470M 52K 470M 1% /devtmpfs 480M 0 480M 0% /dev/shm/dev/nvme0n1p1 16G 7.7G 7.9G 50% /" | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/52508038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7882462/']} | jdg_86603 |
stackexchange | llm_judgeable_groundtruth_similarity | 14096656 |
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 working through "Learn Prolog now" online book for fun. I'm trying to write a predicate that goes through each member of a list and adds one to it, using accumulators. I have already done it easily without tail recursion. addone([],[]).addone([X|Xs],[Y|Ys]) :- Y is X+1, addone(Xs,Ys). But I have read that it is better to avoid this type of recursion for performance reasons. Is this true? Is it considered 'good practice' to use tail recursion always? Will it be worth the effort to use accumulators to get into a good habit? I have tried to change this example into using accumulators, but it reverses the list. How can I avoid this? accAddOne([X|Xs],Acc,Result) :- Xnew is X+1, accAddOne(Xs,[Xnew|Acc],Result).accAddOne([],A,A).addone(List,Result) :- accAddOne(List,[],Result).
Now provide the response and nothing else.
| Short answer: Tail recursion is desirable, but don't over-emphasize it. Your original program is as tail recursive as you can get in Prolog. But there are more important issues: Correctness and termination. In fact, many implementations are more than willing to sacrifice tail-recursiveness for other properties they consider more important. For example steadfastness . But your attempted optimization has some point. At least from a historical perspective. Back in the 1970s, the major AI language was LISP. And the corresponding definition would have been (defun addone (xs) (cond ((null xs) nil) (t (cons (+ 1 (car xs)) (addone (cdr xs)))))) which is not directly tail-recursive: The reason is the cons : In implementations of that time, its arguments were evaluated first, only then, the cons could be executed. So rewriting this as you have indicated (and reversing the resulting list) was a possible optimization technique. In Prolog, however, you can create the cons prior to knowing the actual values, thanks to logic variables. So many programs that were not tail-recursive in LISP, translated to tail-recursive programs in Prolog. The repercussions of this can still be found in many Prolog textbooks. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14096656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1699048/']} | jdg_86604 |
stackexchange | llm_judgeable_groundtruth_similarity | 31471 |
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:
Fresh ice cubes are almost instantly sticky and easily cling on to fabric and other similarly rough surfaces. A few minutes later, however, the effect almost completely disappears. What is the cause of this adhesion? Why does the effect vanish after some time?
Now provide the response and nothing else.
| Whether or not the ice cube will adhere to something is dependent on the temperature of the ice, the state of the surface of the ice, and the moisture content of the material. The temperature of an ice cube can range from the freezing point of water ($0\ \mathrm{^\circ C}$) to well below this temperature. Typically most materials have a small degree of moisture regardless of whether they are “wet” or not. If the ice cube is cold enough, it will freeze the water present in the material. The giant covalent network structure of the ice extends into the material, accounting for why it sticks to the ice—the moisture in the material has become part of the ice cube. If the surface of the ice cube is has melted, it will not be able to freeze the water in the material any more than it will be able to freeze the ice already melted on its surface. No giant covalent network solid will form, and the ice will not stick to the material. | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/31471', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/15508/']} | jdg_86605 |
stackexchange | llm_judgeable_groundtruth_similarity | 13125944 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Usually we can define a variable for a C++ struct, as in struct foo { int bar;}; Can we also define functions for a struct? How would we use those functions?
Now provide the response and nothing else.
| Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template) Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class. struct foo { int bar; foo() : bar(3) {} //look, a constructor int getBar() { return bar; }};foo f;int y = f.getBar(); // y is 3 | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13125944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1736691/']} | jdg_86606 |
stackexchange | llm_judgeable_groundtruth_similarity | 34675659 |
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 nodejs app in typescript in which i have wrote a file server.js as fallow : import express = require('express');import mongoose = require('mongoose');let app=express();app.set('port', process.env.PORT || 3000); // Set port to 3000 or the provided PORT variable/** * Start app */app.listen(app.get('port'), function() { console.log(`App listening on port ${app.get('port')}!`);}); i have use the gulp to traspile it which generate js file as define(["require", "exports", 'express'], function (require, exports, express) { var app = express(); app.set('port', process.env.PORT || 3000); // Set port to 3000 or the provided PORT variable /** * Start app */ app.listen(app.get('port'), function () { console.log("App listening on port " + app.get('port') + "!"); });});//# sourceMappingURL=../map/server.js.map but when i run this file am getting error define is not define. Please correct me if i am doing any mistake.
Now provide the response and nothing else.
| If you are writing an application that will run purely in Node.js, you should be using "commonjs" modules, not AMD modules, when you compile your TypeScript files. If you are writing an application that will run both in Node.js and in the browser, you should be using "umd" modules, not AMD modules, when you compile your TypeScript files. So, you need to change your the configuration object you pass to the Gulp TypeScript compiler to use { module: "commonjs" } or { module: "umd" } . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34675659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2170891/']} | jdg_86607 |
stackexchange | llm_judgeable_groundtruth_similarity | 347476 |
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 virtual host running on my local copy of Apache. It has an alias. <VirtualHost 127.0.0.1> ServerName oliverash.me.dev DocumentRoot "/usr/docs/oliverash.me/public" Alias /mayor "/usr/docs/uni/tmosct/public"</VirtualHost> This works fine. I can access the alias by going to oliverash.me.dev/mayor in my browser. However, I have a simple .htaccess rewrite in that alias' folder, which rewrites everything (except folders) to the index.php page. This rewrite is working fine. Although the rewrite is working, the rewrite returns with a 404 Not Found error. For instance, if I go to oliverash.me.dev/mayor/abcdefg , that rewrites to the index.php file, but I get this error: "The requested URL /usr/docs/uni/tmosct/public/index.php was not found on this server." This file does actually exist. I can access it directly. When I use the same alias but for localhost instead of just this virtual host, the rewrite works fine, and the index.php returns with the actual file, and not the 404. This makes me think it is something to do with the permissions of my virtual host. So I tried to add this beneath my httpd-vhosts.conf (with no luck): <Directory "/usr/docs/oliverash.me/public"> AllowOverride All Order allow,deny Allow from all</Directory> These are the same settings that are used on the localhost 's DocumentRoot , so I don't see why it's not helping. UPDATE: So I checked the Apache error_log. Turns out that the rewrites for this alias are actually relative to the document root of this virtual host. [Fri Jan 06 22:30:57 2012] [error] [client 127.0.0.1] File does not exist: /usr/docs/oliverash.me.dev/usr This rewrite is actually looking in /usr/docs/oliverash.me.dev/public/usr/docs/uni/tmosct/public for index.php. Hopefully it is obvious that it should be looking in /usr/docs/oliverash.me.dev . UPDATE 2: Okay, this is a problem I'm experiencing a local copy of Apache. However, I've just run into exactly the same problem for an alias on my live Web server. This isn't using any kind of virtual host. [Sat Jan 07 02:41:51 2012] [error] [client 86.11.223.135] File does not exist: /var/www/html/var Again, the path is relative to the DocumentRoot. It should be an absolute path. Kinda annoying :( UPDATE 3: This is exactly the problem I am having, but perhaps much better phrased: http://forums.devshed.com/apache-development-15/rewritebase-alias-and-rewriterule-are-not-rooting-to-required-file-395917.html
Now provide the response and nothing else.
| Solution : The RewriteBase have to be the same as the Alias definition, not the physical path/directory in the filesystem! Check the RewriteBase directive for mod_rewrite, it sounds like it could be related to that.Read about it at: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase Edit 1 : To try this out I setup a clean fresh Ubuntu in VMware, a clean apache2 installation and created a new folder out of the normal path, then setup a .htaccess and I made it work with a proper RewriteBase rule. The default DocumentRoot is /var/www, I put a index.php in there just to show me where I am. It echoes out "I am index.php in default!". Then I created this Alias in Apaches configuration: Alias /testberg /home/www/testberg<Directory "/home/www/testberg"> Options +Indexes AllowOverride All</Directory> And in there I put another index.php saying "I am index.php in testberg!". Under /home/www/testberg I created a .htaccess with the following contents: RewriteEngine OnRewriteBase /testbergRewriteRule ^apa.test$ index.php When I browse to http://192.168.100.183/testberg/apa.test I now see: "I am index.php in testberg!" and no errors in Apaches logfile, etc. Isn't this what you wanted to accomplish? Edit 2 : Trying with a different virtual host. On my Windows desktop I pointed ahntest.net to my VMware IP in c:\windows\system32\drivers\etc\hosts . On my VMware server I created /home/www/ahntest.net and put a modified index.php there to echo "I am index.php in ahntest.net!" and created the following virtual host: <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName ahntest.net DocumentRoot /home/www/ahntest.net Alias /testberg /home/www/testberg <Directory "/home/www/testberg"> Options +Indexes AllowOverride All </Directory></VirtualHost> Browsing to http://ahntest.net gives me "I am index.php in ahntest.net!", browsing to http://ahntest.net/testberg gives me "I am index.php in testberg!" and finally browsing to http://ahntest.net/testberg/apa.test gives me "I am index.php in testberg!" so it works just fine here too from what I can tell. The .htaccess/patch in Edit 2 is the same as under Edit 1 above. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/347476', 'https://serverfault.com', 'https://serverfault.com/users/106210/']} | jdg_86608 |
stackexchange | llm_judgeable_groundtruth_similarity | 19677879 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
→ jsFiddle function f1(){ var n=999; nAdd=function(){n+=1;}; function f2(){ alert(n); } return f2;}var result = f1();var result2 = f1();result(); // 999nAdd();result2(); // 1000result2(); // 1000result(); // 999 I am trying to learn JavaScript closures, but the code above just got me confused.When the first time result() is called , it's 999. That's ok for me. After nAdd() is called, result2() shows 1000. And I think this is due to function result2() and function result() are equals to function f1() . But why does the last result() show 999 instead of 1000?
Now provide the response and nothing else.
| Each time f1() is called that creates a new closure with its own local n variable. However, the nAdd variable is global, and so gets overwritten every time f1() is called - which means calling nAdd() will only ever add to the n variable in the last closure. UPDATE: If you want to be able to increment the values of n in each closure independently you could do something like this: function f1(){ var n=999; return { incrementN : function(){n+=1;}, getN : function f2(){console.log(n);} }} var result = f1();var result2 = f1();result.getN(); // 999result.incrementN();result2.getN();//999result2.incrementN();result2.getN();//1000result.getN();//1000 That is, have f1() return an object containing two methods that are not declared as globals, and that both operate on the local n variable from the closure they belong to. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19677879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2935499/']} | jdg_86609 |
stackexchange | llm_judgeable_groundtruth_similarity | 10016550 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Instead of throwing new Exception("Some message", maybeSomeCause) , which means that all callers of my method will need to catch Exception (which can include RuntimeExceptions), I'd like to throw a more specific type of exception when a problem occurs. I can create my own exception types which extend Exception or another exception type, but I am curious if it is a good idea to re-use some exceptions that come with core Java language, such as: IllegalArgumentException UnsupportedOperationException IOException Others? Are there others that I am missing? I found a basic list of the 'core' exceptions here: http://rymden.nu/exceptions.html , with humous explanations. Thanks! Edit: Is there a good list of 'core' exceptions? List so far: http://rymden.nu/exceptions.html Java 7 Exception class API
Now provide the response and nothing else.
| Yes, it's very good to do that. In fact, it's even written about in Effective Java, 2nd ed. See item 60 on page 248: "Favor the use of standard exceptions" Reusing preexisting exceptions has several benefits. Chief among these, it makes your API easier to learn and use because it matches established conventions with which programmers are already familiar. A close second is that programs using your API are easier to read because they aren’t cluttered with unfamiliar exceptions. Last (and least), fewer exception classes mean a smaller memory footprint and less time spent loading classes. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10016550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132374/']} | jdg_86610 |
stackexchange | llm_judgeable_groundtruth_similarity | 17878632 |
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 recently noticed that the following expression compiles in my compiler (Clang): float a;if (0.0 < a < 1.0) { ... } Does this do what I expect? I would expect that it evaluates identically to this condition: if (0.0 < a && a < 1.0) { ... } If it is so, since when and with which other compilers it is possible to write conditions in this short form?
Now provide the response and nothing else.
| Because of left-to-right associativity of < operator the expression condition (0.0 < a < 1.0) means ((0.0 < a) < 1.0) == 1 < 1.0 or 0 < 1.0 depending on value of a . So no, its not identical to if (0.0 < a && a < 1.0) (perhaps you might confusing from Python compassion rule) but in C it will be interpenetrated as I explained above. A difference you can observe in an example --- 0.0 < a < 1.0 == true when a == 0.0 , where as (0.0 < a && a < 1.0) == false, for a == 0.0 , below is my code (read comments): #include<stdio.h>void print_(int c){ c ? printf("True \n"): printf("False \n");}int main(void){ float a = 0.0f; print_(0.0f < a < 1.0f); // 0.0 < 0.0 < 1.0f == 0 < 1.0f == True print_(0.0f < a && a < 1.0f); // 0.0f < 0.0f && ... == False && ... = False return 0;} output: True False Check its working @ Ideone | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17878632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242446/']} | jdg_86611 |
stackexchange | llm_judgeable_groundtruth_similarity | 1196570 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to know how this can be achieved. Assume: That there's a lot of html code containing tables, divs, images, etc. Problem: How can I get matches of all occurances. More over, to be specific, how can I get the img tag source (src = ?). example: <img src="http://example.com/g.jpg" alt="" /> How can I print out http://example.com/g.jpg in this case. I want to assume that there are also other tags in the html code as i mentioned, and possibly more than one image. Would it be possible to have an array of all images sources in html code? I know this can be achieved way or another with regular expressions, but I can't get the hang of it. Any help is greatly appreciated.
Now provide the response and nothing else.
| While regular expressions can be good for a large variety of tasks, I find it usually falls short when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately (and by accurately I mean 100% success rate with no false positive) extract a tag. What I recommend you do is use a DOM parser such as SimpleHTML and use it as such: function get_first_image($html) { require_once('SimpleHTML.class.php') $post_html = str_get_html($html); $first_img = $post_html->find('img', 0); if($first_img !== null) { return $first_img->src; } return null;} Some may think this is overkill, but in the end, it will be easier to maintain and also allows for more extensibility. For example, using the DOM parser, I can also get the alt attribute. A regular expression could be devised to achieve the same goal but would be limited in such way that it would force the alt attribute to be after the src or the opposite, and to overcome this limitation would add more complexity to the regular expression. Also, consider the following. To properly match an <img> tag using regular expressions and to get only the src attribute (captured in group 2), you need the following regular expression: <\s*?img\s+[^>]*?\s*src\s*=\s*(["'])((\\?+.)*?)\1[^>]*?> And then again, the above can fail if: The attribute or tag name is in capital and the i modifier is not used. Quotes are not used around the src attribute. Another attribute then src uses the > character somewhere in their value. Some other reason I have not foreseen. So again, simply don't use regular expressions to parse a dom document. EDIT: If you want all the images: function get_images($html){ require_once('SimpleHTML.class.php') $post_dom = str_get_dom($html); $img_tags = $post_dom->find('img'); $images = array(); foreach($img_tags as $image) { $images[] = $image->src; } return $images;} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1196570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/77762/']} | jdg_86612 |
stackexchange | llm_judgeable_groundtruth_similarity | 330316 |
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:
In answers to this question, the general consensus was that static methods are not meant to be overridden (and thus static functions in C# cannot be virtual or abstract). This is not only the case in C#, though; Java also forbids this and C++ doesn't seem to like it either. However, I can think of many examples of static functions that I'd want to override in a child class (for example, factory methods). While in theory, there are ways to get around them, none of them are clean or simple. Why shouldn't static functions be overrideable?
Now provide the response and nothing else.
| With the static methods, there is no object to provide proper control of the override mechanism. The normal class/instance virtual method mechanism allows for finely tuned control of overrides as follows: each real object is an instance of exactly one class. That class determines the behavior of the overrides; it always gets the first crack at virtual methods. It can then choose to call parent method at the right time for it's implementation. Each parent method then also gets its turn to invoke its parent method. This results in a nice cascade of parent invocations, which accomplishes one of the notions of reuse of code that object orientation is known for. (Here the base/super classes' code are being reused in a relatively complex way; another orthogonal notion of code reuse in OOP is simply having multiple object of the same class.) Base classes can get reused by various subclasses, and each can coexist comfortably. Each class that is used to instantiate objects dictating its own behavior, peacefully and simultaneously coexisting with the others. The client has control over which behaviors it wants and when by choosing which class to use to instantiate an object and pass around to others as desired. (This is not a perfect mechanism, as one can always identify capabilities that are not supported, of course, which is why patterns like factory method and dependency injection are layered on top.) So, if we were to make an override capability for statics without changing anything else, we would have difficulty ordering the overrides. It would be hard to define a limited context for the applicability of the override, so you would get the override globally rather than more locally like with objects. There is no instance object to switch the behavior. So, if someone invoked the static method that happened to have been overridden by another class, should the override get control or not? If there are multiple such overrides, who gets control first? second? With instance object overrides, these questions all have meaningful and well-reasoned answers, but with statics they do not. Overrides for statics would be substantially chaotic, and, things like this have been done before. For example, the Mac OS System 7 and prior used a trap patching mechanism for extending the system by getting control of application-made system calls before the operating system. You could think of the system call patch table as an array of function pointers, much like a vtable for instance objects, except that it was a single global table. This caused untold grief for programmers because of the unordered nature of the trap patching. Whoever got to patch the trap last basically won, even if they didn't want to. Each patcher of the trap would capture the previous trap value for a sort-of parent call capability, which was extremely fragile. Removing a trap patch, say when you no longer needed to know about a system call was considered bad form as you didn't really have the information needed to remove your patch (if you did it you would also unpatch any other patches that had followed you). This is not to say that it would be impossible to create a mechanism for overrides of statics, but what I would probably prefer to do instead is turn the static fields and static methods into instances fields and instance methods of metaclasses, so that the normal object orientation techniques would then apply. Note that there are systems that do this as well: CSE 341: Smalltalk classes and metaclasses ; See also: What is the Smalltalk equivalent of Java's static? I'm trying to say that you would have to do some serious language feature design to make it work even reasonably well. For one example, a naive approach was done, did limp along, but was very problematic, and arguably (i.e. I would argue) architecturally flawed by providing an incomplete and difficult to use abstraction. By the time you're done designing the static overrides feature to work nicely you might have just invented some form of metaclasses, which is a natural extension of OOP into/for class-based methods. So, there is no reason not to do this -- and some languages actually do. Perhaps it is just a bit more of a fringe requirement that a number of languages choose not to do. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/330316', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/95094/']} | jdg_86613 |
stackexchange | llm_judgeable_groundtruth_similarity | 16508195 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For my app I'm implementing the same security as shown in the zentask. public class Secured extends Authenticator {@Overridepublic String getUsername(Context ctx) { return ctx.session().get("email");}@Overridepublic Result onUnauthorized(Context ctx) { ctx.flash().put("error", "please login to proceed"); return redirect(routes.Application.index());}} When a user is authenticated isuser session().put("email", email) ; I have two problems. First: how you invalidate a session when user leaves the app without using the logout? Second more serious one is that I examined the cookie using firefox plugin cookies manager+ and I can copy a cookie and later paste it thus I can access methods without having to first login, basically I can steal sessions
Now provide the response and nothing else.
| Play Framework uses stateless sessions. There is no state stored on the server side, rather, all the state is stored in the session cookie. To validate a session, Play signs the sessions using a secret key, and validates the signature when a request with a session cookie arrives. If a user was to tamper with the session data, for example, if they changed the email address in the session to someone else's email address, then the signature would not match, and so Play would reject the session cookie. Yes, you can copy the cookie and use it later. But you can't change the cookie. This means the only cookie that you can "steal" is your own, but stealing from yourself is not really stealing. So no, you can't steal sessions, except through exploiting other vulnerabilities such as XSS, but session tokens are vulnerable to this too. By default, Play is configured to create "session" cookies, ie, cookies that expire when you close the browser. So if a user quits out of their browser, the browser will delete all the session cookies, and the user will not be logged in anymore. This is the same for session tokens. There is one consideration to be aware of, and that is that session tokens also expire on the server because the server holds state. Stateless signed sessions, such as those used in Play, don't. However, you can implement an expiration mechanism yourself, by storing a timestamp inside the session when it is created, and verifying that that timestamp is no older than a configured expiration period in the getUsername() method. Since the timestamp is stored in the session, which is signed, the timestamp can't be tampered with without changing the signature, so this simple mechanism is quite safe. A more advanced solution might be to implement a filter that updated that timestamp each time a request came in, so that expiration could be based on last accessed, rather than when the user logged in. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16508195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1832932/']} | jdg_86614 |
stackexchange | llm_judgeable_groundtruth_similarity | 48151388 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are using the kubernetes python client (4.0.0) in combination with google's kubernetes engine (master + nodepools run k8s 1.8.4) to periodically schedule workloads on kubernetes. The simplified version of the script we use to creates the pod, attach to the the logs and report the end status of the pod looks as follows: config.load_kube_config(persist_config=False)v1 = client.CoreV1Api()v1.create_namespaced_pod(body=pod_specs_dict, namespace=args.namespace)logging_response = v1.read_namespaced_pod_log( name=pod_name, namespace=args.namespace, follow=True, _preload_content=False)for line in logging_response: line = line.rstrip() logging.info(line)status_response = v1.read_namespaced_pod_status(pod_name, namespace=args.namespace)print("Pod ended in status: {}".format(status_response.status.phase)) Everything works pretty fine, however we are experiencing some authentication issues. Authentication happens through the default gcp auth-provider, for which I obtained the initial access token by running a kubectl container cluster get-credentials manually on the scheduler. At some random timeframes, some API calls result in a 401 response from the API server. My guess is that this happens whenever the access token is expired, and the script tries to obtain a new access token. However it happens that multiple scripts are running concurrently on the scheduler, resulting in obtaining a new API key multiple times of which only one is still valid. I tried out multiple ways to fix the issue (use persist_config=True , retry 401's after reloading the config,...) without any success. As I am not completely aware how the gcp authentication and the kubernetes python client config work (and docs for both are rather scarce), I am a bit left in the dark. Should we use another authentication method instead of the gcp auth-provider? Is this a bug in the kubernetes python client? Should we use multiple config files?
Now provide the response and nothing else.
| In the end we have solved this by using bearer token authentication, instead of relying on the default gcloud authentication method. Here are the steps that I did to achieve this. First create a service account in the desired namespace, by creating a file with the following content. apiVersion: v1kind: ServiceAccountmetadata: name: <name_of_service_account> Then use this file to create the service account kubectl create -f <path_to_file> --namespace=<namespace_name> Each service account has a bearer token linked to it, which can be used for authentication. This bearer token is automatically mounted as a secret into the namespace. To find out what this token is, first find the name of the secret (is of the form <service_account_name>-token-<random_string> ) and then use that name to get to content. # To search for out service account's token namekubectl get secrets --namespace=<namespace_name># To find the token namekubectl describe secret/<secret_name> After this you should find out the ip address of the API server, and the Cluster CA certificate of the kubernetes cluster. This can be done by going to the kubernetes engine detail page on google cloud console. Copy the content of the certificate into a local file. You can now use the bearer token to authenticate via the kubernetes python client, as follows: from kubernetes import clientconfiguration = client.Configuration()configuration.api_key["authorization"] = '<bearer_token>'configuration.api_key_prefix['authorization'] = 'Bearer'configuration.host = 'https://<ip_of_api_server>'configuration.ssl_ca_cert = '<path_to_cluster_ca_certificate>'v1 = client.CoreV1Api(client.ApiClient(configuration)) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48151388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5260676/']} | jdg_86615 |
stackexchange | llm_judgeable_groundtruth_similarity | 187713 |
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 C++, what's the generic way to convert any floating point value (float) to fixed point (int, 16:16 or 24:8)? EDIT: For clarification, fixed-point values have two parts to them: an integer part and a fractional part. The integer part can be represented by a signed or unsigned integer data type. The fractional part is represented by an unsigned data integer data type. Let's make an analogy with money for the sake of clarity. The fractional part may represent cents -- a fractional part of a dollar. The range of the 'cents' data type would be 0 to 99. If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts. I hope that clears things up.
Now provide the response and nothing else.
| Here you go: // A signed fixed-point 16:16 classclass FixedPoint_16_16{ short intPart; unsigned short fracPart;public: FixedPoint_16_16(double d) { *this = d; // calls operator= } FixedPoint_16_16& operator=(double d) { intPart = static_cast<short>(d); fracPart = static_cast<unsigned short> (numeric_limits<unsigned short> + 1.0)*d); return *this; } // Other operators can be defined here}; EDIT: Here's a more general class based on anothercommon way to deal with fixed-point numbers (and which KPexEA pointed out): template <class BaseType, size_t FracDigits>class fixed_point{ const static BaseType factor = 1 << FracDigits; BaseType data;public: fixed_point(double d) { *this = d; // calls operator= } fixed_point& operator=(double d) { data = static_cast<BaseType>(d*factor); return *this; } BaseType raw_data() const { return data; } // Other operators can be defined here};fixed_point<int, 8> fp1; // Will be signed 24:8 (if int is 32-bits)fixed_point<unsigned int, 16> fp1; // Will be unsigned 16:16 (if int is 32-bits) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/187713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/209/']} | jdg_86616 |
stackexchange | llm_judgeable_groundtruth_similarity | 136266 |
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:
An organic compound A $(\ce{C10H14O})$ exhibits following characteristics. A) It reacts with metallic sodium to give a colorless odorless gas. B) It is oxidized by $\ce{KMnO4}$ to benzoic acid. C) It can be resolved. D) It does not give precipitate with iodine in presence of $\ce{NaOH}.$ E) It changes the color of acidified potassium dichromate from orange to bluishgreen, and gives a chiral compound. How many of the following compounds satisfy all the five criteria from A to E? The given answer is the compounds 4 , 5 , 10 satisfy the criteria but I think the compounds 5 , 6 , 12 satisfy the criteria. From statement A, we come to know it's an alcohol (which is common to every compound). From statement B, we come to know that it has a benzylic hydrogen (which rules out the compound 11 ). From statement C, we come to know that it has a chiral carbon. (which rules out options 4 , 7 , 9 ). From statement D, we come to know that $\ce{OH}$ group is not attached to a methyl group (which rules out options 3 , 10 ). For statement E, I guess potassium dichromate will oxidise 2° alcohol to ketone and 1° alcohol to carboxylic acid and the compound still remains chiral (which rules out options 1 , 2 , 8 ). So where's the mistake?
Now provide the response and nothing else.
| I think that correct answer should be 5 and 6 only, because: 12 will produce terephthalic acid , instead of benzoic acid as it possess two benzylic-H (also given by 7). 4 and 10 doesn't satisfy statement C and D, as you've mentioned. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/136266', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/95340/']} | jdg_86617 |
stackexchange | llm_judgeable_groundtruth_similarity | 12034840 |
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 not well versed in event-based programming. Basically, I'm still stumbling around with it. I'm trying to get something set up, but even with the tutorials, I can't wrap my head around it. What I would like to do (in words) is the following: I have a dataobject where a property changes. I notice this in the setter of the property, and want to raise an event that the property has changed. Elsewhere (in a different class entirely), I want to know that the property on this object has changed, and take some action. Now I'm sure this is a common enough scenario, but my google-fu is letting me down. I'm simply not understanding http://msdn.microsoft.com/en-us/library/ms743695.aspx . I have this: public class ChattyClass { private int someMember; public event PropertyChangedEventHandler PropertyChanged; public int SomeMember { get { return this.someMember; } set { if (this.someMember != value){ someMember = value; // Raise event/fire handlers. But how? } }}public class NosyClass{ private List<ChattyClass> myChatters; public void addChatter(ChattyClass chatter){ myChatters.add(chatter); // Start listening to property changed events } private void listner(){ // I want this to be called when the PropertyChangedEvent is called Console.WriteLine("Hey! Hey! Listen! A property of a chatter in my list has changed!"); }} What do I do to wire this up? Concerning the comment pointing me back to the link: In the example I see: protected void OnPropertyChanged(string name){ PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); }} What I'm not understanding: Why isn't this just calling PropertyChanged(this, new PropertyCHangedEventArgs(name)) Where does PropertyChanged get assigned? What does the assignment look like?
Now provide the response and nothing else.
| You have to fire the event. In the example on MSDN, they made a protected method OnPropertyChanged to handle this easier (and to avoid duplicate code). // Create the OnPropertyChanged method to raise the event protected void OnPropertyChanged(string name){ PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); }} What this method does, is look whether there is an event handler assigned or not (if it is not assigned and you just call it, you'll get a NullReferenceException ). If there is one assigned, call this event handler. The event handler provided, has to have the signature of the PropertyChangedEventHandler delegate. This signature is: void MyMethod(object sender, PropertyChangedEventArgs e) Where the first parameter has to be of the type object and represents the object that fires the event, and the second parameter contains the arguments of this event. In this case, your own class fires the event and thus give this as parameter sender . The second parameter contains the name of the property that has changed. Now to be able to react upon the firing of the event, you have to assign an event handler to the class. In this case, you'll have to assign this in your addChatter method. Apart from that, you'll have to first define your handler. In your NosyClass you'll have to add a method to do this, for example: private void chatter_PropertyChanged(object sender, PropertyChangedEventArgs e){ Console.WriteLine("A property has changed: " + e.PropertyName);} As you can see, this method corresponds to the signature I explained before. In the second parameter, you'll be able to find the information of which parameter has been changed. Last thing to do, is add the event handler. Now in your addChatter method, you'll have to assign this: public void AddChatter(ChattyClass chatter){ myChatters.Add(chatter); // Assign the event handler chatter.PropertyChanged += new PropertyChangedEventHandler(chatter_PropertyChanged);} I would suggest you to read something about events in .NET / C#: http://msdn.microsoft.com/en-us/library/awbftdfh . I think after reading/learning this, things will be more clear to you. You can find a console application here on pastebin if you would like to test it quickly (just copy/paste into a new console application). With newer versions of C#, you can inline the call to the event handler: // inside your setterPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyProperty))); You could also use something like Fody PropertyChanged to automatically generated the necessary code (visit the link to their GitHub page, with samples). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12034840', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/381801/']} | jdg_86618 |
stackexchange | llm_judgeable_groundtruth_similarity | 32499382 |
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 html code that describes about the community members like "K S Lenscapes" and "Venky P G" which onclick calls a modal popup #visit <div class="portfolio-info"> <a href="#visit" id="ks" ><h3>K S Lenscapes</h3></a></div><div class="portfolio-info"> <a href="#visit" id="vpg"><h3>Venky P G</h3></a></div> This is #visit code : <div id="visit" class="modalDialog"> <div> <a href="#close" title="Close" class="close">X</a><br><br> <div class="text-center"> <p><a class="btn btn-primary btn-lg" href="#" id="ba">Book Appointment</a></p> </div> </div></div> I need "Book Appointment" button of #visit to recognize from which anchor tag it is requested and send mail to corresponding portfolio taking its email from a file or databse. I have no idea how to do this, Please help me out with this.
Now provide the response and nothing else.
| "Except numbers that are divisible by 3 and 7 at the same time" can be broken down as follows: "divisible by 3 and 7 at the same time" can be expressed as: "(divisible by 3 and divisible by 7)" "Except" can be expressed as "Not" . So you get: Not (divisible by 3 and divisible by 7) "divisible by 3" is (a % 3) == 0 "divisible by 7" is (a % 7) == 0 Giving: Not ( (a % 3) == 0 and (a % 7) == 0) In C# Not becomes ! and and becomes && , so you can write the whole thing in C# as: if (!((a % 3) == 0 && (a % 7) == 0)) Compare with your incorrect: if (a % 3 != 0 && a % 7 != 0) This latter is incorrect because it means: if (the number is not divisible by 3) and (the number is not divisible by 7 ). i.e. it means "Print the number if it is neither divisible by 3 nor divisible by 7" , which means "don't print the number if it's divisible by 3 or 7" . To see why, first consider the number 6: 6 is not divisible by 3? = false (because 6 *is* divisible by 3)6 is not divisible by 7? = true (because 6 is *not* divisible by 7) So this resolves to if false and true which is, of course, false . This result also applies to any other number divisible by 3, so no numbers divisible by 3 will be printed. Now consider the number 14: 14 is not divisible by 3? = true (because 14 is *not* divisible by 3)14 is not divisible by 7? = false (because 14 *is* divisible by 7) So this resolves to if true and false which is, of course, false . This result also applies to any other number divisible by 7, so no numbers divisible by 7 will be printed. Hopefully you can see why it's wrong now. If not, consider this equivalent example: Suppose we have four people, Tom the Carpenter, Dick the Carpenter, Harry the Butcher and Tom the Butcher. This question is equivalent to the one you're asking: Name every person who is (not called Tom and is not a Butcher) And you should be able to see that this the same as asking: Name every person except (anyone called Tom or anyone who is a Butcher) In both cases, the answer is Dick the Carpenter. The question you should have asked is: Name every person except (anyone called Tom who is also a butcher) To which the answer is Tom the Carpenter, Dick the Carpenter and Harry the Butcher. Footnote : De Morgan's laws The second law states that: "not (A or B)" is the same as "(not A) and (not B)" This is the equivalent of my example above where: Name every person except (anyone called Tom or anyone who is a Butcher) is the equivalent to: Name every person who is (not called Tom and is not a Butcher) where A is anyone called Tom and B is anyone who is a butcher and not is written as except . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32499382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5320696/']} | jdg_86619 |
stackexchange | llm_judgeable_groundtruth_similarity | 49900770 |
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 a Q/A on how to handle the opacity of overlapping elements and make it consistent while hover, with a JS solution. Requirement The requirement is to develop two elements, which are transparent and overlapping, like the two red boxes below. These need to be transparent so that the background contents are visible. Now, while hover on any of these elements, the particular element should turn opaque like below.
Now provide the response and nothing else.
| There's a CSS only solution, which makes it a bit more efficient. Like this for example: body { background-image: linear-gradient(45deg, transparent 50%, #aaa 75%); background-size: 20px 20px;}#a { position: absolute; width: 150px; height: 150px; top: 50px; left: 50px; background: rgba(255, 0, 0, 1);}#b { position: absolute; width: 150px; height: 150px; top: 125px; left: 125px; background: rgba(255, 0, 0, 1);}#wrapper { opacity: 0.5;}/* instead of changing the classes, you can use selectors like this:*/#wrapper:hover #a:hover,#wrapper:hover #b:hover { opacity: 1; z-index: 10;}#wrapper:hover { opacity: 1;}#wrapper:hover #b,#wrapper:hover #a { opacity: 0.5; z-index: -1;} <div id=wrapper> <div id="a"> </div> <div id="b"> </div></div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49900770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7527037/']} | jdg_86620 |
stackexchange | llm_judgeable_groundtruth_similarity | 24858 |
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:
The distant an interstellar object is, the more time is required for light to travel, which is known, measured as light years. So are the farthest stars and gas clusters in the Milky Way seen as how they looked millions of years ago & not how as they look today?
Now provide the response and nothing else.
| Most of the matter in the Milky Way is contained within a radius of 100,000 light-years from the galactic center. This encompasses the disk and most of the halo, including halo stars and globular clusters. It also includes quite a few (though not all) of the Milky Way's satellite galaxies . This is rather large - the Sun is only about 25,000 light-years from the galactic center - but not truly inter-galactic scales. Andromeda, the nearest large spiral galaxy , is 2.5 million light-years away, and so we see it as it was 2.5 million years ago. However, we see most of the objects in the Milky Way as they were no more than 100-200,000 years ago, usually much closer to the present day. It's true that some galaxies are a couple million light-years across , but they are quite rare. In fact, the largest known spiral galaxy, Malin 1 , is a mere 650,000 light-years in diameter. I should make it clear, though, that most of these galaxies are large because they have extremely large halos , consisting of gas, pockets of stars, and dark matter. Most matter is not contained in the halo. Additionally, it is not always clear where a galaxy ends and where the intergalactic medium begins. | {} | {'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/24858', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/20219/']} | jdg_86621 |
stackexchange | llm_judgeable_groundtruth_similarity | 2024923 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When it comes to adding gems/plugins I notice that sometimes the author name is prepended to the gem/plugin name, whereas other times it isn't. Is there any reasoning behind this? Example: config.gem "thoughtbot-factory_girl", :source => "http://gems.github.com" Why not have it as: config.gem "factory_girl", :source => "http://gems.github.com" When do you differentiate between the two?
Now provide the response and nothing else.
| When GitHub used to auto-build and host gems, they enforced a namespacing scheme by username. This is why github gems are prefixed with a username. GitHub embraces forking projects; hence the need for the prefixed usernames. GitHub was never really a good place for the canonical gem names, so they decided to drop their automatic gem hosting * when Gemcutter launched. Since then, even the original host of canonical gems, RubyForge , stopped hosting gems in favor of Gemcutter. Gemcutter is now the canonical source for all gems. To make this easy for everyone, http://gems.rubyforge.org now points to http://gemcutter.org . *GitHub announced that they would continue to host all old username namespaced gems for at least one more year. With regards to factory_girl , that too is now hosted on Gemcutter. Your config only needs to look like this now: config.gem "factory_girl" ...but I suggest also adding a version number for your projects (you'll thank me when you come back to a stale project later): config.gem "factory_girl", :version => "1.2.3" | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2024923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_86622 |
stackexchange | llm_judgeable_groundtruth_similarity | 6542339 |
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 multiple images taken simultaneously pointing at the same direction from the same starting location. However, there is still a slight offset because these cameras were not in the exact same place when the picture was taking. I'm looking for a way to calculate the optimal translation/shear/skew/rotation needed to apply to match one image to another so that they overlay (almost) perfectly. The images are in a .raw format which I am reading in 16 bits at a time. I have been suggested (by my employer who is not a programmer [I'm an intern btw]) to take a portion of the source image (not at the edges) and brute-force search for a same-sized portion with a high correlation in data values. I'm hoping there is a less-wasteful algorithm.
Now provide the response and nothing else.
| Here is a short code that does what you want (I use openCV 2.2): Suppose you have 2 images: srcImage,dstImage, and you want to align them The code is very simple. Use it as basis for your algorithm. Code: // Detect special points on each image that can be corresponded Ptr<FeatureDetector> detector = new SurfFeatureDetector(2000); // Detector for featuresvector<KeyPoint> srcFeatures; // Detected key points on first imagevector<KeyPoint> dstFeatures;detector->detect(srcImage,srcFeatures);detector->detect(dstImage,dstFeatures); // Extract descriptors of the featuresSurfDescriptorExtractor extractor; Mat projDescriptors, camDescriptors;extractor.compute(srcImage, srcFeatures, srcDescriptors);extractor.compute(dstImage , dstFeatures, dstDescriptors );// Match descriptors of 2 images (find pairs of corresponding points)BruteForceMatcher<L2<float>> matcher; // Use FlannBasedMatcher matcher. It is bettervector<DMatch> matches;matcher.match(srcDescriptors, dstDescriptors, matches); // Extract pairs of pointsvector<int> pairOfsrcKP(matches.size()), pairOfdstKP(matches.size());for( size_t i = 0; i < matches.size(); i++ ){ pairOfsrcKP[i] = matches[i].queryIdx; pairOfdstKP[i] = matches[i].trainIdx;}vector<Point2f> sPoints; KeyPoint::convert(srcFeatures, sPoints,pairOfsrcKP);vector<Point2f> dPoints; KeyPoint::convert(dstFeatures, dPoints,pairOfdstKP);// Matched pairs of 2D points. Those pairs will be used to calculate homographyMat src2Dfeatures;Mat dst2Dfeatures;Mat(sPoints).copyTo(src2Dfeatures);Mat(dPoints).copyTo(dst2Dfeatures);// Calculate homographyvector<uchar> outlierMask;Mat H;H = findHomography( src2Dfeatures, dst2Dfeatures, outlierMask, RANSAC, 3);// Show the result (only for debug)if (debug){ Mat outimg; drawMatches(srcImage, srcFeatures,dstImage, dstFeatures, matches, outimg, Scalar::all(-1), Scalar::all(-1), reinterpret_cast<const vector<char>&> (outlierMask)); imshow("Matches: Src image (left) to dst (right)", outimg); cvWaitKey(0);}// Now you have the resulting homography. I mean that: H(srcImage) is alligned to dstImage. Apply H using the below codeMat AlignedSrcImage;warpPerspective(srcImage,AlignedSrcImage,H,dstImage.Size(),INTER_LINEAR,BORDER_CONSTANT);Mat AlignedDstImageToSrc;warpPerspective(dstImage,AlignedDstImageToSrc,H.inv(),srcImage.Size(),INTER_LINEAR,BORDER_CONSTANT); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6542339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/567558/']} | jdg_86623 |
stackexchange | llm_judgeable_groundtruth_similarity | 161652 |
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 just ran into a problem with GraphicsRow . Here an example (I want to combine a BarChart and a PairedBarChart ), so... {l1, l2} = RandomInteger[#, 20] & /@ {10, 10}; and: g1 = BarChart[l1, BarOrigin -> Left] and g2 = PairedBarChart[l1, l2, ChartLabels -> Range[20], AxesLabel -> {"Horizontal", "Vertical"} ] Then GraphicsRow delivers: GraphicsRow[{g1, g2}] Output (look at the borders of GraphicsRow ): Now the graphs are not aligned, so I used an alignment ( Bottom in GraphicsRow ), and got: GraphicsRow[{g1, g2}, Alignment -> Bottom] O.K. the graphs are aligned, but why this large surrounding box? Update... If I add a frame, everything is fine???
Now provide the response and nothing else.
| If you use AspectRatio->Full then it works without having to use Frame nor Alignment {l1,l2} = RandomInteger[#,20]&/@{10,10};g1 = BarChart[l1,BarOrigin->Left,AspectRatio->Full]g2 = PairedBarChart[l1,l2,ChartLabels->Range[20], AxesLabel->{"Horizontal","Vertical"},AspectRatio->Full] Now GraphicsRow[{g1,g2},ImageSize->700] fyi, I noticed with this method, if the final imagesize is small, the numerical values in the right images in the middle there (the ones from 1..20, become harder to read as they do not scale. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/161652', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/19726/']} | jdg_86624 |
stackexchange | llm_judgeable_groundtruth_similarity | 8619167 |
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 confronted to a weird situation that I can't explain. Here is my test timing the generation of a large list of tuples: In [1]: def get_list_of_tuples(): ...: return [(i,) for i in range(10**6)] ...:In [2]: %time res = get_list_of_tuples()CPU times: user 0.93 s, sys: 0.08 s, total: 1.01 sWall time: 0.98 sIn [3]: %timeit res = get_list_of_tuples()1 loops, best of 3: 92.1 ms per loop As you can see, the generation of this large list of tuples takes just below a second. timeit reports the execution time to be around 0.1 second. Why is there such a big difference in the two reports? (Tested on IPython 0.11, Python 2.6.5.)
Now provide the response and nothing else.
| The main difference is because " by default, timeit() temporarily turns off garbage collection during the timing ". Turning the garbage collection returns results similar to the one shown in the question, i.e. the time of execution with garbage collection is magnitude bigger than the one without: In [1]: import timeit# Garbage collection on.In [2]: N = 10; timeit.timeit('[(i,) for i in range(10**6)]', 'gc.enable()', number=N) / NOut[2]: 0.74884700775146484# 749 ms per loop.# Garbage collection off.In [3]: N = 10; timeit.timeit('[(i,) for i in range(10**6)]', number=N) / NOut[3]: 0.15906109809875488# 159 ms per loop. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8619167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/787802/']} | jdg_86625 |
stackexchange | llm_judgeable_groundtruth_similarity | 19943531 |
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 viewing this post while trying to get started Node.js, and I started working with this guide to learn the basics. The code for my server is : var http = require('http');http.createServer(function (request, response) { request.on('end', function() { response.writeHead(200, { 'Content-Type' : 'text/plain' }); response.end('Hello HTTP!'); });}).listen(8080); When I go to localhost:8080 (per the guide), I get a 'No Data Received' error. I've seen some pages that say https:// are required, but that returns a 'SSL Connection Error'. I can't figure out what I'm missing.
Now provide the response and nothing else.
| The problem in your code is that "end" event is never fired because you are using Stream2 request stream as if it's Stream1. Read migration tutorial - http://blog.nodejs.org/2012/12/20/streams2/ To convert it to "old mode stream behavior" you can add "data" event handler or '.resume()' call: var http = require('http');http.createServer(function (request, response) { request.resume(); request.on('end', function() { response.writeHead(200, { 'Content-Type' : 'text/plain' }); response.end('Hello HTTP!'); });}).listen(8080); If your example is http GET handler you already have all headers and don't need to wait for body: var http = require('http');http.createServer(function (request, response) { response.writeHead(200, { 'Content-Type' : 'text/plain' }); response.end('Hello HTTP!');}).listen(8080); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19943531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2308004/']} | jdg_86626 |
stackexchange | llm_judgeable_groundtruth_similarity | 6202726 |
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 push user account data from an Active Directory to our MySQL-Server. This works flawlessly but somehow the strings end up showing an encoded version of umlauts and other special characters. The Active Directory returns a string using this sample format: M\xc3\xbcller This actually is the UTF-8 encoding for Müller , but I want to write Müller to my database not M\xc3\xbcller . I tried converting the string with this line, but it results in the same string in the database: tempEntry[1] = tempEntry[1].decode("utf-8") If I run print "M\xc3\xbcller".decode("utf-8") in the python console the output is correct. Is there any way to insert this string the right way? I need this specific format for a web developer who wants to have this exact format, I don't know why he is not able to convert the string using PHP directly. Additional info: I am using MySQLdb; The table and column encoding is utf8_general_ci
Now provide the response and nothing else.
| As @marr75 suggests, make sure you set charset='utf8' on your connections. Setting use_unicode=True is not strictly necessary as it is implied by setting the charset. Then make sure you are passing unicode objects to your db connection as it will encode it using the charset you passed to the cursor. If you are passing a utf8-encoded string, it will be doubly encoded when it reaches the database. So, something like: conn = MySQLdb.connect(host="localhost", user='root', password='', db='', charset='utf8')data_from_ldap = 'M\xc3\xbcller'name = data_from_ldap.decode('utf8')cursor = conn.cursor()cursor.execute(u"INSERT INTO mytable SET name = %s", (name,)) You may also try forcing the connection to use utf8 by passing the init_command param, though I'm unsure if this is required. 5 mins testing should help you decide. conn = MySQLdb.connect(charset='utf8', init_command='SET NAMES UTF8') Also, and this is barely worth mentioning as 4.1 is so old, make sure you are using MySQL >= 4.1 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6202726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/452130/']} | jdg_86627 |
stackexchange | llm_judgeable_groundtruth_similarity | 12603700 |
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 add a new line Javascript alert message. I tried '\n' and 'Environment.NewLine'. I am getting Unterminated string constant error. Could you please let me know what could be the problem? I appreciate any help. I also tried \r\n. string msg = "Your session will expire in 10 minutes. \n Please save your work to avoid this.";if (!this.ClientScript.IsStartupScriptRegistered(ID)) this.ClientScript.RegisterStartupScript(GetType(), ID, String.Format("<script language=JavaScript>setTimeout(\'alert(\"{1}\");\',{0}*1000);</script>", sTime, msg));
Now provide the response and nothing else.
| I would suspect that you need to change your code to; string msg = "Your session will expire in 10 minutes. \\n Please save your work to avoid this."; And escape the \n otherwise your code outputted would actually include the line break rather than \n Your output code would look like: setTimeout('alert("Your Session.... Please save your work to ....");', 1000); Rather than: setTimeout('alert("Your Session....\n Please save your work to ....");', 1000); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12603700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/949512/']} | jdg_86628 |
stackexchange | llm_judgeable_groundtruth_similarity | 25967792 |
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 create and app which will run on iPhone 4S, 5,5S, 6, 6+ and the deployment target will be iOS 7.1. I saw Apple introduced LauchScreens.xib for creating the launch screen (Splash Screen) and also there is an Image Assets in which I can provide the Launch Images screens. See image below: So my questions is how can I use the splash screen for all the iPhones? Or I should say, what is the standard way to to do that when I am using Xcode 6? I have been looking for the answers and reading blogs and Apple's Documents as well but I didn't find anything. Everything was singing its own song but not the answer.
Now provide the response and nothing else.
| In Xcode6 for all devices splash screen you need to make splash image for each device size retina and non retina. Best way of done this thng use asset Catalog from target-->general like following screenshot: when you tap the right small arrow near of launchImage (->) you can see the following window: Currently there is empty because from right side there is no any target selected so if your deployment target is 6.0 you need to set check mark like following screenshot so you can see the all image need box : See when you add wrong dimension image in catalog you can get warning at top right corner and when you tap on this warning you can get actually dimension. see the following screenshot for: So from the warning log you can know which dimension image need for which splash screen. Other way No need to use Asses Catalog and no need to use LaunchScreen.xib you can still use old way: create splash screen image with following size: Default-568h.png 320 x 568 [email protected] 640 x [email protected] 750 x [email protected] 1242 x 2208Default.png 320 x [email protected] 640 x 960 Now in plist you need to add following data: Add one row by tap (+) its called UILaunchImages and you need to fill this row like following that's it no need to do any thing hope that answer helps to other as well. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25967792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/390423/']} | jdg_86629 |
stackexchange | llm_judgeable_groundtruth_similarity | 30215 |
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:
I'm trying to learn about the Bell state $\frac{1}{\sqrt{2}}|00\rangle+\frac{1}{\sqrt{2}}|11\rangle$. Question 10.1 in Algorithms asks us to show that this cannot be decomposed into the tensor product of two single qubits' states. It seems to me however that this can be decomposed while still obeying the basic rules. Wolfram Alpha lists some solutions. What am I doing wrong?
Now provide the response and nothing else.
| All you need to show is that there do not exist any $a,b,c$ or $d$ satisfying the conditions $\frac{1}{\sqrt{2}}(|00\rangle)+|11\rangle)=(a|0\rangle+b|1\rangle)\otimes(c|0\rangle+d|1\rangle)$ and $|a|^2+|b|^2=|c|^2+|d|^2=1$. You should be able to do this quite easily! | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/30215', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/5387/']} | jdg_86630 |
stackexchange | llm_judgeable_groundtruth_similarity | 7368522 |
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 python 2.6: [x() for x in [lambda: m for m in [1,2,3]]] results in: [3, 3, 3] I would expect the output to be [1, 2, 3]. I get the exact same problem even with a non list comprehension approach. And even after I copy m into a different variable. What am I missing?
Now provide the response and nothing else.
| To make the lambdas remember the value of m , you could use an argument with a default value: [x() for x in [lambda m=m: m for m in [1,2,3]]]# [1, 2, 3] This works because default values are set once, at definition time. Each lambda now uses its own default value of m instead of looking for m 's value in an outer scope at lambda execution time. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7368522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/515288/']} | jdg_86631 |
stackexchange | llm_judgeable_groundtruth_similarity | 10630737 |
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 created class by implementing runnable interface and then created many threads(nearly 10) in some other class of my project. How to stop some of those threads?
Now provide the response and nothing else.
| The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true , and may also throw an InterruptedException under certain circumstances where the Thread is waiting , for example Thread.sleep() , otherThread.join() , object.wait() etc. Inside the run() method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted() value and do something (for example, break out). Note: Although Thread.interrupted() seems the same as isInterrupted() , it has a nasty side effect: Calling interrupted() clears the interrupted flag, whereas calling isInterrupted() does not. Other non-interrupting methods involve the use of "stop" ( volatile ) flags that the running Thread monitors. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10630737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114387/']} | jdg_86632 |
stackexchange | llm_judgeable_groundtruth_similarity | 16510234 |
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 a bit puzzled by the following: Let's say I've got a paragraph element with the id of para . Using Chromes console, if I say document.getElementById("para") I'm returned with the HTML snippet <p id="para">....</p> , whereas if I use for instance the Javascript library D3's selection method and say d3.select("#para") I'm returned with the DOM node and can access all the properties and methods of the paragraph element. Why this difference?
Now provide the response and nothing else.
| By default, when logging a DOM node in Chrome, it displays as markup. To log the DOM node as a normal object use console.dir . The reason d3.select("#para") shows as a normal object is that this method probably doesn't return a DOM node, but an object that wraps over the DOM node. console.dir(document.getElementById("para")); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16510234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_86633 |
stackexchange | llm_judgeable_groundtruth_similarity | 4522572 |
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 equation $$x^6-2x^5+3x^4-3x^2+2x-1=0$$ Let's divide both sides of the equation by $x^3\ne0$ (as $x=0$ is obviously not a solution, we can consider $x\ne0$ ). Then we have $$x^3-2x^2+3x-3\cdot\dfrac{1}{x}+2\cdot\dfrac{1}{x^2}-\dfrac{1}{x^3}=0\\\left(x^3-\dfrac{1}{x^3}\right)-2\left(x^2-\dfrac{1}{x^2}\right)+3\left(x-\dfrac{1}{x}\right)=0$$ What do we do now? If we say $y=x-\dfrac{1}{x}$ , we won't be able to express $\left(x^2-\dfrac{1}{x^2}\right)$ in terms of $y$ because of the minus sign as $(a-b)^2=a^2-2ab\color{red}{+b^2}$ . On the other side, $$y^3=x^3-\dfrac{1}{x^3}-3\left(x-\dfrac{1}{x}\right)\\x^3-\dfrac{1}{x^3}=y^3+3y$$ I think this is a traditional issue when solving reciprocal equations, but I can't figure out how to deal with it.
Now provide the response and nothing else.
| Noticing that $x=1$ and $x=-1$ are roots and by long division, you'll get $x^6-2x^5+3x^4-3x^2+2x-1=(x-1)(x+1)(x^4-2x^3+4x^2-2x+1)$ Considering $x^4-2x^3+4x^2-2x+1=0$ , you now divide by $x^2$ and you'll get $x^2+\frac{1}{x^2}-2(x+\frac{1}{x})+4=0$ which, using the substitution $y=x+\frac{1}{x}$ , gives $y^2-2y+2=0$ . I believe you can finish this from here :) | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4522572', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1091115/']} | jdg_86634 |
stackexchange | llm_judgeable_groundtruth_similarity | 2093 |
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 use a power relay ( PR26MF ) to turn on and off a device. The device takes a 9v supply and typically draws ~250mA. I'm finding that the relay turns on just fine, but when I try to turn it off, it won't: it remains latched in the on state. The datasheet mentions that a snubber circuit across the load may be necessary. I tried adding one (with a ~2ms time constant). It had no effect. I measured the resistance across the output port of the relay without the load attached; it works as you would expect: ~inf resistance when it's off and low resistance when on. It seems to turn on and off just fine in that setup. I tried a different load - using the SSR to drive a 5V mechanical relay. The SSR still exhibited the latching behavior.
Now provide the response and nothing else.
| One big question is whether this is an AC load or not. The solid state relay you are using is meant to switch AC loads only and WILL NOT shut off until the zero crossing occurs. If you are using it for a DC load, then it'll stay on once switched on, and will not turn off until the current goes to 0 (usually at zero crossing with an AC power supply). If it is an AC load, then you may need to design your snubber more carefully to match your load and power supply. You haven't given us enough information to help you with that part, though. If you are trying to switch a DC load, then you need a different type of solid state relay. | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/2093', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1199/']} | jdg_86635 |
stackexchange | llm_judgeable_groundtruth_similarity | 13355534 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have the a document c:\temp\temp.txt with contents line 1line 2 and I create the following function PS>function wrapit($text) {@"---Start---$text---End---"@} Then running PS> wrapit((Get-Content c:\temp\temp.txt)) will output ---Start---line 1 line 2---End--- How do I preserve newlines? Appending versus interpolating doesn't help. I found this related question , but here they are using a string array. I am using a single string which has newline characters in it (you can see them if you output the string directly from inside the function without concatenating and $text | gm confirms I'm working with a string, not an array). I can do all the string parsing in the world to hammer it into place, but that seems like I'd be banging a square peg in a round hole. What is the concept that I'm missing?
Now provide the response and nothing else.
| A simple way to do what you want is: wrapit((Get-Content c:\temp\temp.txt | out-string)) Now the explanation: Here-strings @"" just behave like strings "" and the result is due to the PowerShell behaviour in variables expansion. Just try: $a = Get-Content c:\temp\temp.txt"$a" Regarding your comment: $a | Get-MemberTypeName: System.String... But Get-Member -InputObject $aTypeName: System.Object[]... The first answer is OK (it receives strings). It just does not repeat System.string each time. In the second it receive an array as parameter. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13355534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5056/']} | jdg_86636 |
stackexchange | llm_judgeable_groundtruth_similarity | 28827593 |
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 Gradle to build an Android library project and deploy it to maven repository as an aar. The library has some dependencies, which should be included in the POM With apply plugin: 'maven' no POM file is present, just the artifact With apply plugin: 'maven-publish' a POM file is generated, but it does not include any dependencies Any ideas? Is this just not supported? Gradle 2.2 and Android Gradle Plugin 1.1.0 First approach: configurations { archives { extendsFrom configurations.default }}afterEvaluate { project -> uploadArchives { configuration = configurations.archives repositories { mavenDeployer { repository(url: "http://nexus-url") { authentication(userName: nexusUsername, password: nexusPassword) pom.groupId = 'com.example' pom.version = '123-SNAPSHOT' pom.artifactId = 'foo' pom.packaging = 'aar' pom.project { artifactId = 'bar' packaging 'aar' description 'baz' } } }} Also tried it without wrapping it in afterEvaluate Second approach: publishing { publications { sdk(MavenPublication) { groupId 'com.example' artifactId 'foo' version = "0.123-SNAPSHOT" artifact("$buildDir/outputs/aar/app-sdk-debug.aar") } } repositories { maven { url "http://nexus-url" credentials { username 'foo' password 'bar' } } }} Update The root cause of the problem is that this project uses flavors. Without flavors the pom is generated properly when using apply plugin: 'maven'
Now provide the response and nothing else.
| This is the solution that worked for me in the end: publishing { publications { sdk(MavenPublication) { artifactId libName artifact "${project.buildDir}/outputs/aar/${libName}-${project.version}.aar" //The publication doesn't know about our dependencies, so we have to manually add them to the pom pom.withXml { // for dependencies and exclusions def dependenciesNode = asNode().appendNode('dependencies') configurations.implementation.allDependencies.withType(ModuleDependency) { ModuleDependency dp -> def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', dp.group) dependencyNode.appendNode('artifactId', dp.name) dependencyNode.appendNode('version', dp.version) // for exclusions if (dp.excludeRules.size() > 0) { def exclusions = dependencyNode.appendNode('exclusions') dp.excludeRules.each { ExcludeRule ex -> def exclusion = exclusions.appendNode('exclusion') exclusion.appendNode('groupId', ex.group) exclusion.appendNode('artifactId', ex.module) } } } } } } repositories { maven { name 'myrepo' url 'https://maven.foo.com' credentials { username mavenUsername password mavenPassword } } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28827593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1009684/']} | jdg_86637 |
stackexchange | llm_judgeable_groundtruth_similarity | 1461888 |
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:
Are the logarithm rules and exponentiation rules (e.g. $a^{x+y}=a^xa^y$) axioms when talking about real numbers? I know many of them can be proved via induction for integers, but no professor has ever mentioned a proof of these 'rules' when having $\Bbb R$ as a domain.
Now provide the response and nothing else.
| They can be, but they don't have to be. One of the simplest setups is to define $\exp$ to be the unique function satisfying $\exp'=\exp$ and $\exp(0)=1$; then define $\ln$ to be the inverse of $\exp$; then define $a^x=\exp(x \ln(a))$ for $a>0$. Then the exponent and logarithm rules are theorems. Most of the proof of the rules is just elementary algebra; the tricky part is proving (from the definition above) the functional equation $\exp(x+y)=\exp(x)\exp(y)$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1461888', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/193752/']} | jdg_86638 |
stackexchange | llm_judgeable_groundtruth_similarity | 12695594 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given an array of strings: x = ["banana","apple","orange"] is there a built in shortcut for performing wildcard searches? ie., maybe x.indexOf("*na*") //returns index of a string containing the substring na
Now provide the response and nothing else.
| Expanding on Pim's answer, the correct way to do it (without jQuery) would be this: Array.prototype.find = function(match) { return this.filter(function(item){ return typeof item == 'string' && item.indexOf(match) > -1; });} But really, unless you're using this functionality in multiple places, you can just use the existing filter method: var result = x.filter(function(item){ return typeof item == 'string' && item.indexOf("na") > -1; }); The RegExp version is similar, but I think it will create a little bit more overhead: Array.prototype.findReg = function(match) { var reg = new RegExp(match); return this.filter(function(item){ return typeof item == 'string' && item.match(reg); });} It does provide the flexibility to allow you to specify a valid RegExp string, though. x.findReg('a'); // returns all threex.findReg("a$"); // returns only "banana" since it's looking for 'a' at the end of the string. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12695594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173773/']} | jdg_86639 |
stackexchange | llm_judgeable_groundtruth_similarity | 1175888 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I have a Type called type . I want to determine if I can do this with my type (without actually doing this to each type): If type is System.Windows.Point then I could do this: Point point1 = new Point(); However if type is System.Environment then this will not fly: Environment environment1 = new Environment(); //wrong So if I am iterating through every visible type in an assembly how do I skip all the types that will fail to create an instance like the second one? I'm kind of new to reflection so I'm not that great with the terminology yet. Hopefully what I'm trying to do here is pretty clear.
Now provide the response and nothing else.
| static classes are declared abstract and sealed at the IL level. So, you can check IsAbstract property to handle both abstract classes and static classes in one go (for your use case). However, abstract classes are not the only types you can't instantiate directly. You should check for things like interfaces ( without the CoClass attribute ) and types that don't have a constructor accessible by the calling code. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1175888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78187/']} | jdg_86640 |
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.