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 | 23324872 |
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 read the following UTF-8 encoded file in R, but whenever I read it, the unicode characters are not encoded correctly: The script I'm using to process the file is as follows: defaultEncoding <- "UTF8"detalheVotacaoMunicipioZonaTypes <- c("character", "character", "factor", "factor", "factor", "factor", "factor", "factor", "factor", "factor", "factor", "factor", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "character", "character")readDetalheVotacaoMunicipioZona <- function( fileName ) { fileConnection = file(fileName,encoding=defaultEncoding) contents <- readChar(fileConnection, file.info(fileName)$size) close(fileConnection) contents <- gsub('"', "", contents) columnNames <- c("data_geracao", "hora_geracao", "ano_eleicao", "num_turno", "descricao_eleicao", "sigla_uf", "sigla_ue", "codigo_municipio", "nome_municipio", "numero_zona", "codigo_cargo", "descricao_cargo", "qtd_aptos", "qtd_secoes", "qtd_secoes_agregadas", "qtd_aptos_tot", "qtd_secoes_tot", "qtd_comparecimento", "qtd_abstencoes", "qtd_votos_nominais", "qtd_votos_brancos", "qtd_votos_nulos", "qtd_votos_legenda", "qtd_votos_anulados", "data_ult_totalizacao", "hora_ult_totalizacao") read.csv(text=contents, colClasses=detalheVotacaoMunicipioZonaTypes, sep=";", col.names=columnNames, fileEncoding=defaultEncoding, header=FALSE)} I read the file sending in the UTF-8 encoding, remove all quotes (even numbers are quoted, so I need to clean them up) and then feed the contents to read.csv . It reads and processes the file correctly but it seems like it's not using the encoding information I'm giving it. What should I do to make it use UTF-8 to read this file? I'm using RStudio on OSX if it makes any difference.
Now provide the response and nothing else.
| This problem is caused by the wrong locale being set, whether inside RStudio or command-line R: If the problem only happens in RStudio not command-line R, go to RStudio->Preferences:General, tell us what 'Default text encoding:'is set to, click 'Change' and try Windows-1252, UTF-8 or ISO8859-1('latin1') (or else 'Ask' if you always want to be prompted). Screenshot attached at bottom. Let us know which one worked! If the problem also happens in command-line R , do the following: Do locale -m on your Mac and tell us whether it supports CP1252 or else ISO8859-1 ('latin1')? Dump the list of supported locales if you need to. (You might as well tell us your version of MacOS while you're at it.) For both of those locales, try to change to that locale: # first try Windows CP1252, although that's almost surely not supported on Mac:Sys.setlocale("LC_ALL", "pt_PT.1252") # Make sure not to omit the `"LC_ALL",` first argument, it will fail.Sys.setlocale("LC_ALL", "pt_PT.CP1252") # the name might need to be 'CP1252'# next try IS08859-1(/'latin1'), this works for me:Sys.setlocale("LC_ALL", "pt_PT.ISO8859-1")# Try "pt_PT.UTF-8" too...# in your program, make sure the Sys.setlocale worked, sprinkle this assertion in your code before attempting to read.csv:stopifnot(Sys.getlocale('LC_CTYPE') == "pt_PT.ISO8859-1") That should work.Strictly the Sys.setlocale() command should go in your ~/.Rprofile for startup, not inside your R session or source-code.However Sys.setlocale() can fail, so just be aware of that. Also, assert Sys.getlocale() inside your setup code early and often, as I do. (really, read.csv should figure out if the encoding it uses is compatible with the locale, and warn or error if not). Let us know which fix worked! I'm trying to document this more generally so we can figure out the correct enhance. Screenshot of RStudio Preferences Change default text encoding menu: | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23324872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/293686/']} | jdg_86641 |
stackexchange | llm_judgeable_groundtruth_similarity | 15394 |
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:
Consider the reaction of $\ce{AgNO3}$ and $\ce{HCl}$. I read that silver chloride would be formed. But $\ce{H} > \ce{Ag}$ in reactivity, then how could $\ce{Ag}$ displace $\ce{H}$ from $\ce{HCl}$ ? If there was a reaction, $\ce{AgCl}$ and $\ce{HNO3}$ were to form. But then these would react again to give us the original compounds back. The actual question was to write down the reaction between $\ce{AgNO3}$ and $\ce{HCl}$. I (wrongly) realized that the compounds wouldn't react because of the reasons stated.
Now provide the response and nothing else.
| One of the most difficult parts of chemistry is learning to recognize a type of reaction based solely on its reactants. This has to be done before you can apply a reaction pattern to the problem, and so it is critical to get this step right in the beginning. In this case, you are looking at the reaction: $$\ce{AgNO3 + HCl -> AgCl + HNO3}$$ You already know the products, but are questioning how these products can be formed since the activity of H is greater than Ag, implying that Ag is easier to oxidize than H. This is true - but take a look at the oxidation numbers of each species in this reaction: $\ce{Ag: +1 -> +1}$ $\ce{NO3: -1 -> -1}$ $\ce{H: +1 -> +1}$ $\ce{Cl: -1 -> -1}$ Since there is no overall transfer of electrons, this can't be a redox reaction, and that means activities won't matter here. That means there must be another driving force for this reaction - another reaction pattern that fits better. I don't want to give you the answer directly, but I will give you some advice that should help: Write the full equation - including the phases. $$\ce{AgNO3(aq) + HCl(aq) -> AgCl(s) + HNO3(aq)}$$ See if you can find another reaction pattern that fits this equation better. Later, I'll update this answer to show how you can identify the correct pattern for aqueous reactions using only the reactants. Update As I mentioned, one of the hardest parts of chemistry is learning to identify reaction patterns based only on the reactants. This is a double-displacement (or metathesis, or precipitation) reaction. It is easy to see now, given that the reactants are aqueous and at least one of the products is solid (the precipitate). Formation of the solid is the driving force for this reaction - the quick explanation is that the forces attracting silver and chloride ions together are stronger than the solvation forces between those ions and water, as well as the forces holding them to sodium and nitrate ions. This is good, but how do we predict that this is a precipitation reaction ahead of time? The key is to have a good understanding of the three common types of salt/acid/base reactions that occur in aqueous solution, and to learn to recognize clues in the reactants. Briefly, the three types that are most commonly seen are: Precipitation Acid/base (Arrhenius definition) Redox (single displacement) You can recognize each of these by the reactants if you know what to look for. Precipitation - Two soluble salts (ionic compounds), or a salt with an acid or base. Acid/base - An Arrhenius acid and base (compound containing hydroxide) Redox - a salt or acid and an elemental metal There are many other types of reactions that occur in aqueous solution, and many variations of the acid/base and redox category, but these three cover the cases most commonly seen in a classroom. Once you have identified the likely pattern that the reaction will follow, the next step is to predict the products using that pattern to see if they make sense. If they do, then you have likely chosen correctly. You can use this algorithm for more advanced chemistry as well - in organic chemistry, for example, one of the major goals is to learn to predict reactions based on functional groups. Once you can identify functional groups and have memorized reaction patterns for them, it becomes possible to predict a huge range of reactions. | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/15394', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/7517/']} | jdg_86642 |
stackexchange | llm_judgeable_groundtruth_similarity | 14686330 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There has been variants of this question asked for generations, but despite writing some quite complicated Windows scripts, I can't seem to find out how to make them actually silent. The following is an excerpt from one of my current scripts: @ECHO OFFSET scriptDirectory=%~dp0COPY %scriptDirectory%test.bat %scriptDirectory%test2.batFOR /F %%f IN ('dir /B "%scriptDirectory%*.noext"') DO (del "%scriptDirectory%%%f")ECHO The result of this is: C:\Temp> test.bat 1 file(s) copied.File Not FoundEcho is off.C:\Temp> Whereas the "1 file(s) copied." is just annoying, the "File Not Found" makes the user think that something has gone wrong (which it hasn't - no files is fine).
Now provide the response and nothing else.
| To suppress output, use redirection to NUL . There are two kinds of output that console commands use: standard output, or stdout , standard error, or stderr . Of the two, stdout is used more often, both by internal commands, like copy , and by console utilities, or external commands, like find and others, as well as by third-party console programs. >NUL suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied. message of the copy command. An alternative syntax is 1>NUL . So, COPY file1 file2 >NUL or COPY file1 file2 1>NUL or >NUL COPY file1 file2 or 1>NUL COPY file1 file2 suppresses all of COPY 's standard output. To suppress error messages, which are typically printed to stderr , use 2>NUL instead. So, to suppress a File Not Found message that DEL prints when, well, the specified file is not found, just add 2>NUL either at the beginning or at the end of the command line: DEL file 2>NUL or 2>NUL DEL file Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot: IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext" | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14686330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1297496/']} | jdg_86643 |
stackexchange | llm_judgeable_groundtruth_similarity | 2366018 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Mysql Server1 is running as MASTER . Mysql Server2 is running as SLAVE . Now DB replication is happening from MASTER to SLAVE . Server2 is removed from network and re-connect it back after 1 day. After this there is mismatch in database in master and slave. How to re-sync the DB again as after restoring DB taken from Master to Slave also doesn't solve the problem ?
Now provide the response and nothing else.
| This is the full step-by-step procedure to resync a master-slave replication from scratch: At the master: RESET MASTER;FLUSH TABLES WITH READ LOCK;SHOW MASTER STATUS; And copy the values of the result of the last command somewhere. Without closing the connection to the client (because it would release the read lock) issue the command to get a dump of the master: mysqldump -u root -p --all-databases > /a/path/mysqldump.sql Now you can release the lock, even if the dump hasn't ended yet. To do it, perform the following command in the MySQL client: UNLOCK TABLES; Now copy the dump file to the slave using scp or your preferred tool. At the slave: Open a connection to mysql and type: STOP SLAVE; Load master's data dump with this console command: mysql -uroot -p < mysqldump.sql Sync slave and master logs: RESET SLAVE;CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=98; Where the values of the above fields are the ones you copied before. Finally, type: START SLAVE; To check that everything is working again, after typing: SHOW SLAVE STATUS; you should see: Slave_IO_Running: YesSlave_SQL_Running: Yes That's it! | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2366018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/284699/']} | jdg_86644 |
stackexchange | llm_judgeable_groundtruth_similarity | 1175056 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
how to get the value of the last element of a List? I've noted that List.hd (or .Head) return an item, while List.tl (or .Tail) returns a List. Is rev the List and get the hd the only way around? Thanks.
Now provide the response and nothing else.
| Try this function. It uses recursion, though it gets optimised to iteration anyway since it's tail recursion. In any case, it is most likely quicker than reversing the entire list (using List.rev ). let rec last = function | hd :: [] -> hd | hd :: tl -> last tl | _ -> failwith "Empty list." The answer of Pavel Minaev is definitely worth taking into account, however. Nonetheless, the algorithm you have requested may be useful in some rare cases, and is the most efficient way to go about the task. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1175056', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42636/']} | jdg_86645 |
stackexchange | llm_judgeable_groundtruth_similarity | 8509399 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have used an approach very similar to the one to implement an Api Key approach to identifying which clients use a web service: http://blogs.msdn.com/b/rjacobs/archive/2010/06/14/how-to-do-api-key-verification-for-rest-services-in-net-4.aspx The question I have is about security... the service was put through some security testing by a third party company. One of their "low-risk" comments (i.e. one that does not require immediate attention), is that parameters are passed as httpget. The service is purely for retrieving information. However, the apikey is in the query string... e.g. a URL might be https://url.com/companies?company_name=searchforthiscompany&address=paris&apikey=a-long-guid "Implication: When parameters are passed as part of HTTP Get requests, they are more likely tobe stored in intermediate or other server log files. A curious user can potentially seesensitive information such as the APIKey. Recommendation:If possible, parameters should be passed as part of the HTTP POST body." Should this be something I need to worry about?! It is nice to be able to just whack a URL into a browser and get back results. Would you change all of your methods to use POST in this case? Any insight appreciated
Now provide the response and nothing else.
| The commit you are seeing is perfectly fine. A pull effectively runs git fetch and then git merge so a merge is usually happening when you run git pull . The alternative to use rebasing instead of merging is possible, but usually you should avoid it. Rebasing allows you to keep a linear history, but also removes any information about the branching that originally happened. It will also cause the history of the current branch being rewritten, recreating all commits that are not contained in the target branch (in your case, the remote). As the recreated commits are different commits, this can cause a lot of confusion when developing together with others, especially when people already checked out parts of those commits before they get rewritten (for example with feature branches). So as a rule of thumb, you should never rewrite any commit that was already pushed. The commits you see are there to combine two (or more) branches. It is perfectly fine to have a commit that does nothing else then merging multiple branches. In fact it makes it very clear when you have a merge commit that combines branches when looking at the history. In comparison to rebasing, merging also allows you to effectively see the original history as it was developed, including the actual branches that coexisted. So, long story short: Yes, having merge commits is perfectly fine and you should not worry about them. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8509399', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/228930/']} | jdg_86646 |
stackexchange | llm_judgeable_groundtruth_similarity | 347555 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two asynchronous tasks that need to get completed - say they're "make a pie" ( make ) and "bake a pie" ( bake ). I also need to cleanup after everything's done - "clean the kitchen" ( cleanup ). bake depends on make , and I want to cleanup when things are done. However, there are a few complications: If some nice person has already made the pie, all I have to do is bake . If a problem happens during make - maybe I get tired of this whole pie business - I need to cleanup . If a problem happens during bake - the oven explodes - I also need to cleanup . My first pass looks like something like this: func pieTime() if !pie.isMade() make() else if !pie.isBaked() bake() else cleanup(null)func make() makeThePie(completion: { if pie.hasError() cleanup(error) else bake() })func bake() bakeThePie(completion: { if pie.hasError() cleanup(error) else cleanup(null) })func cleanup(error) if error != null shout("what the ***: %s", error.string()) destroy(pie) This isn't too bad, but my main problem with this approach is that there is no single exit point from the flow. cleanup gets called from a bunch of places. As the error handling gets more complicated, and you add more asynchronous calls to the chain, there are more and more exit points from the flow to keep track of. If I miss calling cleanup at any of them, the result is an unusable kitchen. Basically, I'm looking for something like a do/catch/finally for asynchronous calls. The only thing I could come up with is a queue - queue up only the tasks you need and queue cleanup at the end - but it seems a bit too heavyweight for just two tasks, such as this instance. Is there a well-established pattern for this problem?
Now provide the response and nothing else.
| You can use a promise chain like the idiomatic q one, roughly: doSomethingThatReturnsAPromise .then(function (result, error) { if (error) { [the previous command failed in some way; handle it or throw.] } }) .then([same again]) […] .finally(function() { [global cleanup] }) The main difference from a tree of calls is that it's very intuitive to follow - there's no question of what the entry point is, there's no question of the sequence of the steps, and the cleanup happens unconditionally once the sequence is done. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/347555', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/150150/']} | jdg_86647 |
stackexchange | llm_judgeable_groundtruth_similarity | 46059615 |
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 shorten tabulated input.tsv rs928302 YES TMPRSS3 rf G V 53 NM_001256317.1 NP_001243246.1 rf G V 53 NM_024022.2 NP_076927.1 rf G V 53 NM_032405.1 NP_115781.1rs1046210 YES BACE2 rf C D 364 NM_012105.4 NP_036237.2 rf C D 364 NM_138992.2 NP_620477.1 rf C D 269 XM_017028314.1 XP_016883803.1rs1064579 YES IFNGR2 rf T V 272 NM_001329128.1 NP_001316057.1 rf T V 253 NM_005534.3 NP_005525.2 rf T V 272 XM_005260969.2 XP_005261026.1 rf T V 278 XM_011529553.1 XP_011527855.1 rf T V 255 XM_011529554.2 XP_011527856.1 And I would like to print in blank fields the same word found on the top and apply to the first, second and third columns until the end of file. When appear a different word the printing below should be this new word and so on. So the output should be: rs928302 YES TMPRSS3 rf G V 53 NM_001256317.1 NP_001243246.1rs928302 YES TMPRSS3 rf G V 53 NM_024022.2 NP_076927.1rs928302 YES TMPRSS3 rf G V 53 NM_032405.1 NP_115781.1rs1046210 YES BACE2 rf C D 364 NM_012105.4 NP_036237.2rs1046210 YES BACE2 rf C D 364 NM_138992.2 NP_620477.1rs1046210 YES BACE2 rf C D 269 XM_017028314.1 XP_016883803.1rs1064579 YES IFNGR2 rf T V 272 NM_001329128.1 NP_001316057.1rs1064579 YES IFNGR2 rf T V 253 NM_005534.3 NP_005525.2rs1064579 YES IFNGR2 rf T V 272 XM_005260969.2 XP_005261026.1rs1064579 YES IFNGR2 rf T V 278 XM_011529553.1 XP_011527855.1rs1064579 YES IFNGR2 rf T V 255 XM_011529554.2 XP_011527856.1 How can do it in Unix environment? Thanks in advance.
Now provide the response and nothing else.
| Method 1: instead of this : //Create a new PHPMailer instance$mail = new PHPMailer(); use this: //Create a new PHPMailer instance$mail = new PHPMailer\PHPMailer\PHPMailer(); Edit on 2022-09-03 Method 2: (correct way) as @Synchro said in comments, you can use the namespace in your script file instead of full namespace/class call: // add namespace in top of your scriptuse PHPMailer\PHPMailer\PHPMailer;// then call specify the class with this : $mail = new PHPMailer(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46059615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8405531/']} | jdg_86648 |
stackexchange | llm_judgeable_groundtruth_similarity | 25922082 |
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 the OrderType for the min(Date) for each Name. So, I want this: Name Date OrderTypeAlex 1/1/2014 DirectAlex 9/15/2014 DistributorCindy 6/4/2014 DistributorJohn 5/8/2014 DirectJohn 2/14/2014 Distributor to return this: Name Date OrderTypeAlex 1/1/2014 DirectCindy 6/4/2014 DistributorJohn 2/14/2014 Distributor
Now provide the response and nothing else.
| We can get row number based on the date for each [Name] and pick the least date record. SELECT [T].* FROM ( SELECT [Name] , [DATE] , [OrderType] , ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [Date]) AS [seq] FROM [TableA]) AS [T]WHERE [T].[seq] = 1 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25922082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4056045/']} | jdg_86649 |
stackexchange | llm_judgeable_groundtruth_similarity | 37683147 |
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 wondering if anyone knew a good way (preferably a built in method, but I'm open to writing my own of course) to get the <script> and <div> tags from the HTML output of the Plotly offline client. I'm already familiar with bokeh and really enjoy using it for 2D visualization, but would really like to integrate Plotly as well for its 3D visualization capabilities. Let me know if you need any extra details about the project.
Now provide the response and nothing else.
| If you call: plotly.offline.plot(data, filename='file.html') It creates a file named file.html and opens it up in your web browser. However, if you do: plotly.offline.plot(data, include_plotlyjs=False, output_type='div') the call will return a string with only the div required to create the chart, which you can store in whatever variable you desire (and not to disk). I just tried it and it returned, for a given chart that I was doing: <div id="82072c0d-ba8d-4e86-b000-0892be065ca8" style="height: 100%; width: 100%;" class="plotly-graph-div"></div><script type="text/javascript">window.PLOTLYENV=window.PLOTLYENV || {};window.PLOTLYENV.BASE_URL="https://plot.ly";Plotly.newPlot("82072c0d-ba8d-4e86-b000-0892be065ca8", [{"y": ..bunch of data..., "x": ..lots of data.., {"showlegend": true, "title": "the title", "xaxis": {"zeroline": true, "showline": true}, "yaxis": {"zeroline": true, "showline": true, "range": [0, 22.63852380952382]}}, {"linkText": "Export to plot.ly", "showLink": true})</script> Notice how its just a tiny portion of an html that you are supposed to embed in a bigger page. For that I use a standard template engine like Jinga2. With this you can create one html page with several charts arranged the way you want, and even return it as a server response to an ajax call , pretty sweet. Update: Remember that you'll need to include the plotly js file for all these charts to work. You could include <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> just before putting the div you got. If you put this js at the bottom of the page, the charts won't work. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37683147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4111864/']} | jdg_86650 |
stackexchange | llm_judgeable_groundtruth_similarity | 3784843 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an application where many "unit" tests use a real connection to an Oracle database during their execution. As you can imagine, these tests take too much time to be executed, as they need to initialize some Spring contexts, and communicate to the Oracle instance. In addition to that, we have to manage complex mechanisms, such as transactions, in order to avoid database modifications after the test execution (even if we use usefull classes from Spring like AbstractAnnotationAwareTransactionalTests ). So my idea is to progressively replace this Oracle test instance by an in-memory database. I will use hsqldb or maybe better h2 . My question is to know what is the best approach to do that. My main concern is related to the construction of the in-memory database structure and insertion of reference data. Of course, I can extract the database structure from Oracle, using some tools like SQL Developer or TOAD , and then modifying these scripts to adapt them to the hsqldb or h2 language. But I don't think that's the better approach. In fact, I already did that on another project using hsqldb , but I have written manually all the scripts to create tables. Fortunately, I had only few tables to create. My main problem during this step was to "translate" the Oracle scripts used to create tables into the hsqldb language. For example, a table created in Oracle using the following sql command: CREATE TABLE FOOBAR ( SOME_ID NUMBER, SOME_DATE DATE, -- Add primary key constraint SOME_STATUS NUMBER, SOME_FLAG NUMBER(1) DEFAULT 0 NOT NULL); needed to be "translated" for hsqldb to: CREATE TABLE FOOBAR ( SOME_ID NUMERIC, SOME_DATE TIMESTAMP PRIMARY KEY, SOME_STATUS NUMERIC, SOME_FLAG INTEGER DEFAULT 0 NOT NULL); In my current project, there are too many tables to do that manually... So my questions: What are the advices you can give me to achieve that? Does h2 or hsqldb provide some tools to generate their scripts from an Oracle connection? Technical information Java 1.6, Spring 2.5, Oracle 10.g, Maven 2 Edit Some information regarding my unit tests: In the application where I used hsqldb , I had the following tests:- Some "basic" unit tests, which have nothing to do with DB.- For DAO testing, I used hsqldb to execute database manipulations, such as CRUD.- Then, on the service layer, I used Mockito to mock my DAO objects, in order to focus on the service test and not the whole applications (i.e. service + dao + DB). In my current application, we have the worst scenario: The DAO layer tests need an Oracle connection to be run. The services layer does not use (yet) any mock objects to simulate the DAO. So services tests also need an Oracle connection. I am aware that mocks and in-memory database are two separates points, and I will address them as soon as possible. However, my first step is to try to remove the Oracle connection by an in-memory database, and then I will use my Mockito knowledges to enhance the tests. Note that I also want to separate unit tests from integration tests. The latter will need an access to the Oracle database, to execute "real" tests, but my main concern (and this is the purpose of this question) is that almost all of my unit tests are not run in isolation today.
Now provide the response and nothing else.
| Use an in-memory / Java database for testing. This will ensure the tests are closer to the real world than if you try to 'abstract away' the database in your test. Probably such tests are also easier to write and maintain. On the other hand, what you probably do want to 'abstract away' in your tests is the UI, because UI testing is usually hard to automate. The Oracle syntax you posted works well with the H2 database (I just tested it), so it seems H2 supports the Oracle syntax better than HSQLDB. Disclaimer: I'm one of the authors of H2. If something doesn't work, please post it on the H2 mailing list. You should anyway have the DDL statements for the database in your version control system. You can use those scripts for testing as well. Possibly you also need to support multiple schema versions - in that case you could write version update scripts (alter table...). With a Java database you can test those as well. By the way, you don't necessarily need to use the in-memory mode when using H2 or HSQLDB. Both databases are fast even if you persist the data. And they are easy to install (just a jar file) and need much less memory than Oracle. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3784843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26457/']} | jdg_86651 |
stackexchange | llm_judgeable_groundtruth_similarity | 2074902 |
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:
$$S= 1\times(1) + 2\times(1+2) + 3\times(1+2+3) +\dots+ n\times(1+2+3+\dots+n)$$
Now provide the response and nothing else.
| We need three formulas. The sum of the $n$ first numbers, the sum of the $n$ first squares and the sum of the $n$ first cubes: $$\sum_{j=1}^n j=\frac{n(n+1)}2$$$$\sum_{j=1}^n j^2=\frac{n(n+1)(2n+1)}6$$$$\sum_{j=1}^n j^3=\frac{n^2(n+1)^2}4$$ Now, $$\sum_{j=1}^nj\sum_{k=1}^jk=\sum_{j=1}^n\frac{j^2(j+1)}2=\frac12\left(\sum_{j=1}^nj^3+\sum_{j=1}^nj^2\right)=\frac{n(n+1)(2n+1)}{12}+\frac{n^2(n+1)^2}8$$ hence $$S=\frac{n(n+1)(n+2)(3n+1)}{24}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2074902', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/317369/']} | jdg_86652 |
stackexchange | llm_judgeable_groundtruth_similarity | 3197319 |
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 redirect all www traffic to non-www traffic I have copied this into my web.config <system.webServer> / <rewrite> / <rules><rule name="Remove WWW prefix" ><match url="(.*)" ignoreCase="true" /><conditions><add input="{HTTP_HOST}" pattern="^www\.example\.com" /></conditions><action type="Redirect" url="http://example.com/{R:1}" redirectType="Permanent" /></rule> per this post How to redirect with "www" URL's to without "www" URL's or vice-versa? but I got a 500 internal server error.
Now provide the response and nothing else.
| You might consider a different approach: protected void Application_BeginRequest (object sender, EventArgs e){ if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback) { UriBuilder builder = new UriBuilder (Request.Url); builder.Host = "www." + Request.Url.Host; Response.Redirect (builder.ToString (), true); }} This will however do a 302 redirect so a little tweak is recommended: protected void Application_BeginRequest (object sender, EventArgs e){ if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback) { UriBuilder builder = new UriBuilder (Request.Url); builder.Host = "www." + Request.Url.Host; Response.StatusCode = 301; Response.AddHeader ("Location", builder.ToString ()); Response.End (); }} This one will return 301 Moved Permanently. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3197319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184773/']} | jdg_86653 |
stackexchange | llm_judgeable_groundtruth_similarity | 14110085 |
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 download selected rows of an asp.net gridview to an excel sheet. What I am doing is trying the check all at once or just a few selected and then after pressing the download button below, all the selected rows get downloaded as excel. Every thing works fine here when I press download button, but rather all the rows get downloaded ignoring the selection. Following is my code public void ExportGridToExcel(GridView grdGridView, string fileName){ Response.Clear(); Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName)); Response.Charset = ""; Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);// I Tried using following (but with no success)//-----Trial Starts----------------//foreach (GridViewRow gvr in gvProgramList.Rows)// {// CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");// if(cbox.Checked)// gvr.Visible = true;// else// gvr.Visible = false;// }//--------Trial ends--------------- grdGridView.DataBind(); ClearControls(grdGridView); // Throws exception: Control 'ComputerGrid' of type 'GridView' // must be placed inside a form tag with runat=server. // ComputerGrid.RenderControl(htmlWrite); // Alternate to ComputerGrid.RenderControl above System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm(); Controls.Add(form); form.Controls.Add(grdGridView); form.RenderControl(htmlWriter); Response.Write(stringWriter.ToString()); Response.End(); foreach (GridViewRow gvr in gvProgramList.Rows) { CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect"); gvr.Visible = true; } grdGridView.DataBind();}private void ClearControls(Control control){ for (int i = control.Controls.Count - 1; i >= 0; i--) { ClearControls(control.Controls[i]); } if (!(control is TableCell)) { if (control.GetType().GetProperty("SelectedItem") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); try { literal.Text = (string)control.GetType().GetProperty("SelectedItem"). GetValue(control, null); } catch { } control.Parent.Controls.Remove(control); } else if (control.GetType().GetProperty("Text") != null) { LiteralControl literal = new LiteralControl(); control.Parent.Controls.Add(literal); literal.Text = (string)control.GetType().GetProperty("Text"). GetValue(control, null); control.Parent.Controls.Remove(control); } } return;}protected void btnDownload_Click(object sender, EventArgs e){ if (gvProgramList.Rows.Count > 0) { ExportGridToExcel(gvProgramList, "ProgramList"); }}
Now provide the response and nothing else.
| Here's a working example - Javascript code: Ext.onReady(function () { Ext.define('ImagePanel', { extend: 'Ext.form.Panel', fileUpload: true, title: 'Upload Panel', width: 300, height: 100, onUpload: function () { this.getForm().submit({ url: 'upload.php', scope: this, success: function (formPanel, action) { var data = Ext.decode(action.response.responseText); alert("Success: " + data.msg); }, failure: function (formPanel, action) { var data = Ext.decode(action.response.responseText); alert("Failure: " + data.msg); } }); }, initComponent: function () { var config = { items: [ { xtype: 'fileuploadfield', buttonText: 'Upload', name: 'uploadedFile', listeners: { 'change': { scope: this, fn: function (field, e) { this.onUpload(); } } } } ] }; Ext.apply(this, Ext.apply(this.initialConfig, config)); this.callParent(arguments); } }); var panel = Ext.create('ImagePanel', { renderTo: Ext.getBody() });}); And PHP code: <?phpif (isset($_FILES)) { $temp_file_name = $_FILES['uploadedFile']['tmp_name']; $original_file_name = $_FILES['uploadedFile']['name']; echo '{"success": true, "msg": "'.$original_file_name.'"}';} else { echo '{"success": false, "msg": "No Files"}';} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14110085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1584140/']} | jdg_86654 |
stackexchange | llm_judgeable_groundtruth_similarity | 9257521 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm developing a web-app, based on the Dribbble API. In this app I have a div which shows all comments with a max-height of 200px, so if there's more than 200px worth on comments, the div gets scrollable. So far so good, works as intended on iOS. However, when I add a Scale transfrm to this div (to mimic iOS's folder opening animation), scrolling the div breaks entirely. You can see the live version here: http://maxsteenbergen.com/longshot/ Is this fixable by setting a a new style using jQ's webkitAnimationEnd or is this without solution? EDIT: In the meantime I found that using two fingers to scroll the div works but obviously, this is not how it's supposed to work.
Now provide the response and nothing else.
| My teammate and I just have implemented ELB in a VPC with 2 private subnets in different availability zones. The reason you get timeouts is that for each subnet you add to the load balancer, it gets one external IP address. (try 'dig elb-dns-name-here' and you will see several IP addresses). If one of these IP address maps a private subnet, it will timeout. The IP that maps into your public subnet will work. Because DNS may give you any one of the IP addresses, sometimes it works, sometimes it times out. After some back and forth with amazon, we discovered that the ELB should only be placed in 'public' subnets, that is subnets that have a route out to the Internet Gateway. We wanted to keep our web servers in our private subnets but allow the ELB to talk to them. To solve this, we had to ensure that we had a corresponding public subnet for each availability zone in which we had private subnets. We then added to the ELB, the public subnets for each availability zone. At first, this didn't seem to work, but after trying everything, we recreated the ELB and everything worked as it should. I think this is a bug, or the ELB was just in an odd state from so many changes. Here is more or less what we did: WebServer-1 is running in PrivateSubnet-1 in availability zone us-east-1b with security group called web-server. WebServer-2 is running in PrivateSubnet-2 in availability zone us-east-1c with security group called web-server. Created a public subnet in zone us-east-1b, we'll call it PublicSubnet-1. We ensured that we associated the routing table that includes the route to the Internet Gateway (ig-xxxxx) with this new subnet. (If you used the wizard to create a public/private VPC, this route already exists.) Created a public subnet in zone us-east-1c, we'll call it PublicSubnet-2. We ensured that we associated the routing table that includes the route to the Internet Gateway (ig-xxxxx) with this new subnet. (If you used the wizard to create a public/private VPC, this route already exists.) Created a new ELB, adding to it PublicSubnet-1 and PublicSubnet-2 (not the PrivateSubnet-X). Also, picked the instances to run in the ELB, in this case WebServer-1 and WebServer-2. Made sure to assign a security group that allows incoming port 80 and 443. Lets call this group elb-group. In the web-server group, allow traffic from port 80 and 443 from the elb-group. I hope that helps! | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9257521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1100565/']} | jdg_86655 |
stackexchange | llm_judgeable_groundtruth_similarity | 9433766 |
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 saw this in the PHP OOP manual http://www.php.net/manual/en/language.oop5.visibility.php and I can't get my head around why the output is not: Foo::testPrivate Foo::testPublic class Bar { public function test() { $this->testPrivate(); $this->testPublic(); } public function testPublic() { echo "Bar::testPublic\n"; } private function testPrivate() { echo "Bar::testPrivate\n"; }}class Foo extends Bar { public function testPublic() { echo "Foo::testPublic\n"; } private function testPrivate() { echo "Foo::testPrivate\n"; }}$myFoo = new foo();$myFoo->test(); // Bar::testPrivate // Foo::testPublic
Now provide the response and nothing else.
| It's all about the visibility of the variables / methods. You'll notice that in the Bar class, the method testPrivate() is private . That means that ONLY itself can access that method. No children. So when Foo extends Bar , and then asks to run the test() method, it does two things: It overrides the testPublic() method because it's public, and Foo has the right to override it with it's own version. It calls test() on Bar (since test() only exists on Bar() ). testPrivate() is not overridden, and is part of the class that holds test() . Therefore, Bar::testPrivate is printed. testPublic() is overridden, and is part of the inheriting class. Therefore, Foo::testPublic is printed. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9433766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/782358/']} | jdg_86656 |
stackexchange | llm_judgeable_groundtruth_similarity | 218890 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a good algorithm for counting the numbers $x$ between $A$ and $B$ with $x$ and $N$ coprime? This is just like this question except for the range. The factorization of $N$ is known. I actually need to solve the problem for fixed $N$ and many ranges, so I think I can mark all multiples of factors of $N$ in a BitSet and simply count what remains. But is there a nicer solution (or one for the case I need the answer for a single range only)?
Now provide the response and nothing else.
| Let $f(C)$ be the number of integers from $1$ to $C$ that are relatively prime to $N$. If we can compute $f(C)$, the rest is easy. Say we are allowing $A \le x\le B$. Then our answer is $f(B)-f(A-1)$. Note that $f(C)$ is $C$ minus the number of integers in the interval $[1,C]$ that are not relatively prime to $N$. Call this number $g(C)$. So $f(C)=C-g(C)$. We attack the problem of finding $g(C)$. If $N$ is a prime power $p^a$, it is easy. The numbers in the interval $[1,C]$ that are not relatively prime to $N$ are the multiples of $p$. Thus $$g(C)=\left\lfloor \frac{C}{p}\right\rfloor,$$ where $\lfloor x\rfloor$ is the usual "floor" function. If $N$ has prime power factorization $p^aq^b$, where $p$ and $q$ are distinct primes, then $g(C)$ is the number of integers in $[1,C]$ that are divisible by $p$ or $q$ or both . By Inclusion/Exclusion, we obtain$$g(C)=\left\lfloor \frac{C}{p}\right\rfloor+\left\lfloor \frac{C}{q}\right\rfloor-\left\lfloor \frac{C}{pq}\right\rfloor.$$The reason is that when we add the first two terms above, we are counting twice all the multiples of $pq$. If $N$ has prime power factorization $p^aq^br^c$, the same basic idea works. We get$$g(C)=\left\lfloor \frac{C}{p}\right\rfloor+\left\lfloor \frac{C}{q}\right\rfloor+\left\lfloor \frac{C}{r}\right\rfloor-\left\lfloor \frac{C}{qr}\right\rfloor -\left\lfloor \frac{C}{pr}\right\rfloor-\left\lfloor \frac{C}{pq}\right\rfloor+\left\lfloor \frac{C}{pqr}\right\rfloor.$$ Similar expressions work for $N$ that has a more complex prime power factorization. Remark: Depending on the relative sizes of $A$, $B$, and $N$, there are shortcuts available, involving the Euler $\varphi$-function. This is because there are $\varphi(N)$ numbers relatively prime to $N$ in the interval $[kN+1,(k+1)N]$. Since you know the prime power factorization of $N$, $\varphi(N)$ is given by a simple formula. Thus our problem is solved if we can find $f(D)$ for $D\lt N$. For dividing $C$ by $N$ gives us the number of full "chunks" of shape $[kN+1,(k+1)N]$ there are up to $C$. These are dealt with using the $\varphi$-function, and the remainder $D$ is dealt with by Inclusion/Exclusion. And in addition to mathematical facts, one will need programming ideas to produce an efficient solution. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/218890', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14435/']} | jdg_86657 |
stackexchange | llm_judgeable_groundtruth_similarity | 114878 |
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 often use the command cat /dev/urandom | strings --bytes 1 | tr -d '\n\t ' | head --bytes 32 to generate pseudo-random passwords. This doesn't work with /dev/random . Specifically cat /dev/urandom | strings --bytes 1 | tr -d '\n\t ' produces output cat /dev/random | strings --bytes 1 produces output cat /dev/random | strings --bytes 1 | tr -d '\n\t ' does not produce output NB: When using /dev/random you may have to wiggle your mouse or press keys (e.g. ctrl, shift, etc.) to generate entropy. Why does the last example not work? Does tr have some kind of large internal buffer that /dev/urandom fills quickly but /dev/random doesn't? P.S. I'm using CentOS 6.5 cat /proc/versionLinux version 2.6.32-431.3.1.el6.x86_64 ([email protected]) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC) ) #1 SMP Fri Jan 3 21:39:27 UTC 2014
Now provide the response and nothing else.
| It will eventually. In: cat /dev/random | strings --bytes 1 | tr -d '\n\t ' cat will never buffer, but it's superfluous anyway as there's nothing to concatenate here. < /dev/random strings --bytes 1 | tr -d '\n\t ' strings though, since its output is not longer a terminal will buffer its output by blocks (of something like 4 or 8kB) as opposed to lines when the output goes to a terminal. So it will only start writing to stdout when it has accumulated 4kB worth of characters to output, which on /dev/random is going to take a while. tr output goes to a terminal (if you're running that at a shell prompt in a terminal), so it will buffer its output line-wise. Because you're removing the \n , it will never have a full line to write, so instead, it will write as soon as a full block has been accumulated (like when the output doesn't go to a terminal). So, tr is likely not to write anything until strings has read enough from /dev/random so as to write 8kB (2 blocks possibly much more) of data (since the first block will probably contain some newline or tab or space characters). On this system I'm trying this on, I can get an average of 3 bytes per second from /dev/random (as opposed to 12MiB on /dev/urandom ), so in the best case scenario (the first 4096 bytes from /dev/random are all printable ones), we're talking 22 minutes before tr starts to output anything. But it's more likely going to be hours (in a quick test, I can see strings writing a block every 1 to 2 blocks read, and the output blocks contain about 30% of newline characters, so I'd expect it'd need to read at least 3 blocks before tr has 4096 characters to output). To avoid that, you could do: < /dev/random stdbuf -o0 strings --bytes 1 | stdbuf -o0 tr -d '\n\t ' stdbuf is a GNU command (also found on some BSDs) that alters the stdio buffering of commands via an LD_PRELOAD trick. Note that instead of strings , you can use tr -cd '[:graph:]' which will also exclude tab, newline and space. You may want to fix the locale to C as well to avoid possible future surprises with UTF-8 characters. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/114878', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/18799/']} | jdg_86658 |
stackexchange | llm_judgeable_groundtruth_similarity | 4900380 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know there's a way to do this but I've been banging my head against a wall trying to figure it out. This works fine: private GenericRecord CreateGeneric(GenericRecord g, Member m){ g.Member = m; return g;}public IList<GenericRecord> ReportFromDatabase(DateTime startDate, DateTime endDate){ List<GenericRecord> returnRecords = new List<GenericRecord>(); returnRecords.AddRange(from r in pjRepository.Records join m in memberRepository.Members on r.SID equals m.MemberId.ToString() where r.TransactionDate >= startDate && r.TransactionDate <= endDate select CreateGeneric((GenericRecord)r, m)); return returnRecords;} But I know there's a way to do it without the CreateGeneric function. How do I select a delegate function inline? returnRecords.AddRange(from r in pjRepository.Records join m in memberRepository.Members on r.SID equals m.MemberId.ToString() where r.TransactionDate >= startDate && r.TransactionDate <= endDate select (delegate { GenericRecord g = (GenericRecord)r; g.Member = m; return g; })); That gives me this exception: The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'. Edit: Another failed attempt returnRecords.AddRange((from r in pjRepository.Records join m in memberRepository.Members on r.SID equals m.MemberId.ToString() where r.TransactionDate >= startDate && r.TransactionDate <= endDate select new { r, m }).Select(x => { GenericRecord g = (GenericRecord)x.r; g.Member = x.m; return g; })); This gives me: A lambda expression with a statement body cannot be converted to an expression tree.
Now provide the response and nothing else.
| Try: returnRecords.AddRange((from r in pjRepository.Records join m in memberRepository.Members on r.SID equals m.MemberId.ToString() where r.TransactionDate >= startDate && r.TransactionDate <= endDate select new { r, m }).AsEnumerable().Select(x => { GenericRecord g = (GenericRecord)x.r; g.Member = x.m; return g; })); The key different is that AsEnumerable() function. That takes an IQueryable and returns an IEnumerable, which behind the scenes forces the evaluation of the expression tree by the Linq provider. This prevents the Linq library from attempting to convert the second Select's lambda to part of the expression tree (which it says it can't); the second Select will instead perform its transformation on the actual im-memory collection produced by evaluating the IQueryable expression tree. Since you require the query to be evaluated before the statement ends anyway (so all the elements can be added to returnRecords), there should be no significant performance difference. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4900380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198856/']} | jdg_86659 |
stackexchange | llm_judgeable_groundtruth_similarity | 281818 |
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 working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a type_info class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. typeid(std::vector<int>).name() returns St6vectorIiSaIiEE . Is there a way to produce something useful from this? Like std::vector<int> for the above example. If it only works for non-template classes, that's fine too. The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.
Now provide the response and nothing else.
| Given the attention this question / answer receives, and the valuable feedback from GManNickG , I have cleaned up the code a little bit. Two versions are given: one with C++11 features and another one with only C++98 features. In file type.hpp #ifndef TYPE_HPP#define TYPE_HPP#include <string>#include <typeinfo>std::string demangle(const char* name);template <class T>std::string type(const T& t) { return demangle(typeid(t).name());}#endif In file type.cpp (requires C++11) #include "type.hpp"#ifdef __GNUG__#include <cstdlib>#include <memory>#include <cxxabi.h>std::string demangle(const char* name) { int status = -4; // some arbitrary value to eliminate the compiler warning // enable c++11 by passing the flag -std=c++11 to g++ std::unique_ptr<char, void(*)(void*)> res { abi::__cxa_demangle(name, NULL, NULL, &status), std::free }; return (status==0) ? res.get() : name ;}#else// does nothing if not g++std::string demangle(const char* name) { return name;}#endif Usage: #include <iostream>#include "type.hpp"struct Base { virtual ~Base() {} };struct Derived : public Base { };int main() { Base* ptr_base = new Derived(); // Please use smart pointers in YOUR code! std::cout << "Type of ptr_base: " << type(ptr_base) << std::endl; std::cout << "Type of pointee: " << type(*ptr_base) << std::endl; delete ptr_base;} It prints: Type of ptr_base: Base* Type of pointee: Derived Tested with g++ 4.7.2, g++ 4.9.0 20140302 (experimental), clang++ 3.4 (trunk 184647), clang 3.5 (trunk 202594) on Linux 64 bit and g++ 4.7.2 (Mingw32, Win32 XP SP2). If you cannot use C++11 features, here is how it can be done in C++98, the file type.cpp is now: #include "type.hpp"#ifdef __GNUG__#include <cstdlib>#include <memory>#include <cxxabi.h>struct handle { char* p; handle(char* ptr) : p(ptr) { } ~handle() { std::free(p); }};std::string demangle(const char* name) { int status = -4; // some arbitrary value to eliminate the compiler warning handle result( abi::__cxa_demangle(name, NULL, NULL, &status) ); return (status==0) ? result.p : name ;}#else// does nothing if not g++std::string demangle(const char* name) { return name;}#endif (Update from Sep 8, 2013) The accepted answer (as of Sep 7, 2013) , when the call to abi::__cxa_demangle() is successful, returns a pointer to a local, stack allocated array ... ouch! Also note that if you provide a buffer, abi::__cxa_demangle() assumes it to be allocated on the heap. Allocating the buffer on the stack is a bug (from the gnu doc): "If output_buffer is not long enough, it is expanded using realloc ." Calling realloc() on a pointer to the stack ... ouch! (See also Igor Skochinsky 's kind comment.) You can easily verify both of these bugs: just reduce the buffer size in the accepted answer (as of Sep 7, 2013) from 1024 to something smaller, for example 16, and give it something with a name not longer than 15 (so realloc() is not called). Still, depending on your system and the compiler optimizations, the output will be: garbage / nothing / program crash. To verify the second bug: set the buffer size to 1 and call it with something whose name is longer than 1 character. When you run it, the program almost assuredly crashes as it attempts to call realloc() with a pointer to the stack. (The old answer from Dec 27, 2010) Important changes made to KeithB's code : the buffer has to be either allocated by malloc or specified as NULL. Do NOT allocate it on the stack. It's wise to check that status as well. I failed to find HAVE_CXA_DEMANGLE . I check __GNUG__ although that does not guarantee that the code will even compile. Anyone has a better idea? #include <cxxabi.h>const string demangle(const char* name) { int status = -4; char* res = abi::__cxa_demangle(name, NULL, NULL, &status); const char* const demangled_name = (status==0)?res:name; string ret_val(demangled_name); free(res); return ret_val;} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/281818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9232/']} | jdg_86660 |
stackexchange | llm_judgeable_groundtruth_similarity | 577045 |
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 searched the Internet and unable to find an answer. Anyone can help?
Now provide the response and nothing else.
| Determining if an address is either unicast or anycast with full confidence is not easy if you do not have access to routing tables on machines running EBGP (for example an ISP's edge router). From an end user standpoint, the decision to use a specific route to the address, or even the possibility of understanding if there are multiple routes cannot be determined with normal networking tools. However, with connections in multiple geographic locations, you could run traceroutes to the IP address(es) in question, and make comparisons between them to determine if they are passing through completely different destinations near the end of the lookups. This could just be down to multihoming, so it is not a method which can provide complete confidence. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/577045', 'https://serverfault.com', 'https://serverfault.com/users/210139/']} | jdg_86661 |
stackexchange | llm_judgeable_groundtruth_similarity | 712916 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How to find cubic $f(x)$ if its remainders are $2x-1$ and $3x-3$ when $f(x)$ is divided by $x^2+x-2$ and $x^2+x-3$, respectively? My effort is as follows but it looks too complicated. Is there any simpler method? Let $ax+b$ and $cx+d$ are its quotients so we have \begin{align}f(x) &= (x^2+x-2)(ax+b)+2x-1\\f(x) &= (x^2+x-3)(cx+d)+3x-3\end{align} By taking $x=-1$, $x=0$, $x=1$ and $x=2$ we will have 4 equations in terms of $a$, $b$, $c$ and $d$. $f(x)$ can then be determined by finding either a pair of $a$ and $b$ or a pair of $c$ and $d$.
Now provide the response and nothing else.
| Yes, there is a much simpler method (it boils down to subtracting two linear polynomials) $$\begin{eqnarray}{\rm mod}\,\ \color{#0a0}{x^2\!+\!x\!-\!3}\!:\ \ f &=& 2x\!-\!1 + (ax\!+\!b)\,(\overbrace{\color{#0a0}{x^2\!+\!x\!-\!3}}^{\large \equiv\ 0\ }\color{#c00}{+1})\\ &\equiv& 2x\!-\!1 + (ax\!+\!b)\,\color{#c00}{(1)}\\ &\equiv& 3x\!-\!3\\\Rightarrow\ \ ax\!+\!b &\,\equiv\,& 3x\!-\!3 - (2x\!-\!1)\,\equiv\, x\!-\!2\\\Rightarrow\ \ f &=& x^3\!-x^2\!-2x+3\quad\ {\bf QED}\end{eqnarray}\qquad\qquad$$ If polynomial modular arithmetic is unfamiliar then you may proceed as follows $$\begin{eqnarray} f &\,=\,& 2x\!-\!1 + (ax\!+\!b)\,(1\color{#c00}{-3\!+\!x\!+\!x^3})\\&=& 2x\!-\!1 + ax\!+\!b + (ax\!+\!b)\,(\color{#c00}{-3\!+\!x\!+\!x^3})\end{eqnarray}$$ When divided by $\,\color{#c00}{-3\!+\!x\!+\!x^3}\,$ the above leaves remainder $\,2x\!-\!1 + ax\!+\!b,\,$ which $\,= 3x\!-\!3\, $ by hypothesis. Therefore, subtracting, we deduce that $\ ax+b\, =\, 3x\!-\!3-(2x\!-\!1)\, =\, x\!-\!2.$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/712916', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26975/']} | jdg_86662 |
stackexchange | llm_judgeable_groundtruth_similarity | 31547827 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it somehow possible to include the mongodb connection settings into a lumen framework. As from what I saw the config/database.php is loaded internally in the lumen package. Is there a way to extend it somehow to include the mongodb connection settings?
Now provide the response and nothing else.
| We're actually using Lumen, Laravel, Mongo, and MySQL in one giant project so I can help you through this one. Assuming you want to use MongoDB with eloquent instead of with the raw MongoClient. You can find the library I'm using from jenssegers here . Install MongoDB Extension Firstly you'll need to install the dependencies for PHP to interact with mongo. The specifics for installing the mongo extension can be found on the PHP documentation . After that you'll have to edit the php.ini files for the platforms (apache/cli/nginx) to load the extension. I added the following before Module Settings extension=mongo.so It goes without saying you need to restart apache/nginx after changing the configuration. Configuring Lumen In your root lumen folder you can add it to your requirements with the following command. composer require jenssegers/mongodb From there you'll need to also load the MongodbServiceProvider before Facades or Eloquent is initialized. $app->register(Jenssegers\Mongodb\MongodbServiceProvider::class);$app->withFacades();$app->withEloquent(); For simplicity of organizing configuration I also created a config folder and a database.php config file. Since Lumen doesn't try to autoload or search this directory we have to tell it to load this config. I put the following line right before the loading the application routes. $app->configure('database'); In database.php the mongodb driver requires a specific structure. I've included mysql in here as I use both, but if you're using mongo exclusively you can change default to mongodb and remove the mysql config. return [ 'default' => 'mysql', 'connections' => [ 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', ''), 'username' => env('DB_USERNAME', ''), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, ], 'mongodb' => array( 'driver' => 'mongodb', 'host' => env('MONGODB_HOST', 'localhost'), 'port' => env('MONGODB_PORT', 27017), 'username' => env('MONGODB_USERNAME', ''), 'password' => env('MONGODB_PASSWORD', ''), 'database' => env('MONGODB_DATABASE', ''), 'options' => array( 'db' => env('MONGODB_AUTHDATABASE', '') //Sets the auth DB ) ), ],]; With the configuration out of the way you can now create a model, as of writing this to create a model for mongo (check the github page) you can use the following as a base. You can ignore the $connection variable if mongo is your default driver. <?phpnamespace App;use Jenssegers\Mongodb\Model as Eloquent;class Example extends Eloquent { protected $connection = 'mongodb'; protected $collection = 'example'; protected $primaryKey = '_id';} There you go, you should be able to interact with mongo normally, for the specifics of the driver check out the github page for documentation on it. If this answer helped you could you mark it as the answer? | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31547827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/743777/']} | jdg_86663 |
stackexchange | llm_judgeable_groundtruth_similarity | 142335 |
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:
Possible Duplicate: Proving $(1 + 1/n)^{n+1} \gt e$ How to prove this: $$\left(\frac{x}{x-1}\right)^x \geq e\qquad\text{for}\qquadx \in \mathbb{N}^*$$ $e$ is the base of the natural logarithm. and I think the equal satisfies if $x$ converges to infinity. Thank you!
Now provide the response and nothing else.
| It is impossible to have a field which is $n$ dimensional over $\mathbb{R}$ for any $n\geq 3$. The reason why this is true boils down to the following two statements. Any field $K\supseteq \mathbb{R}$ which is finite dimensional over $\mathbb{R}$ is algebraic over $\mathbb{R}$. The complex numbers are the algebraic closure of $\mathbb{R}$. Thus is $K\supseteq \mathbb{R}$ is a field which is finite dimensional over $\mathbb{R}$, then it is algebraic over $\mathbb{R}$, and hence is contained in the algebraic closure of $\mathbb{R}$, i.e., $K\subseteq \mathbb{C}$. Since $\mathbb{C}$ has dimension $2$ over $\mathbb{R}$, this implies that $K$ has dimension either $1$ or $2$ over $\mathbb{R}$. In the first case, $K = \mathbb{R}$, and in the second $K = \mathbb{C}$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/142335', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/30831/']} | jdg_86664 |
stackexchange | llm_judgeable_groundtruth_similarity | 54771021 |
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 problem question as in the practice course goes as follows: Write a JavaScript program to create a function which takes 2 integers as inputs. The function divides the first integer with second integer as long as the result (Quotient) is an integer (i.e. remainder is zero) and return the quotient as result. Your output code should be in the format console.log("Result is ", variableName) And below is my code: var num = prompt("Enter number to divide");var d = prompt("Enter divisor");function divide(x, y) { var result; if (d === 1) { result = num; } else { while (num % d === 0) { //while error result = num / d; } } return result;}var output = divide(num, d);console.log("Result is: ", output); If I remove the while loop, program works fine but the problem description says I have to use it. What am I doing wrong?
Now provide the response and nothing else.
| The issue is most likely with your reducer's declaration. The initialState 's type must be the same as the state's type and return value in the reducer function. This will work: function reducer(state: {email: string}) { return state}const initialState = { email: '',}const [state, dispatch] = React.useReducer(reducer, initialState) This will produce an error: // state has a different type than initialState.function reducer(state: {address: string}) { // No return statement.}const initialState = { email: '',}const [state, dispatch] = React.useReducer(reducer, initialState) // Error In the React's typing you can see that the useReducer generic function always expects the initialState type to be of a ReducerState<R> type. The ReducerState<R> is a conditional type that tries to infer the proper state's type and falls back to never if it fails. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54771021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7393799/']} | jdg_86665 |
stackexchange | llm_judgeable_groundtruth_similarity | 18126559 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
On the CI server, I want to fetch a config file that we maintain on Github so it can be shared between many jobs. I'm trying to get this file via curl, but these approaches both fail (I get a 404): # As advised by the oAuth docscurl -H 'Authorization: token the_token' -L -o setup.sh https://raw.github.com/org/repo/file# The url of the raw file after clicking to view itcurl -L https://raw.github.com/org/repo/file?login=username&token=the_token
Now provide the response and nothing else.
| The previous answers don't work (or don't work anymore). You can use the V3 API to get a raw file like this (you'll need an OAuth token): curl -H 'Authorization: token INSERTACCESSTOKENHERE' \ -H 'Accept: application/vnd.github.v3.raw' \ -O \ -L https://api.github.com/repos/owner/repo/contents/path All of this has to go on one line. The -O option saves the file in the current directory. You can use -o filename to specify a different filename. To get the OAuth token follow the instructions here: https://help.github.com/articles/creating-an-access-token-for-command-line-use I've written this up as a gist as well: https://gist.github.com/madrobby/9476733 EDIT: API references for the solution are as follows: https://developer.github.com/v3/#authentication https://developer.github.com/v3/media/#request-specific-version https://developer.github.com/v3/repos/contents/#get-contents | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18126559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/693349/']} | jdg_86666 |
stackexchange | llm_judgeable_groundtruth_similarity | 12838428 |
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 subproject in a Virtual Machine with Ubuntu which I compile with Maven and then run with mvn jetty:run. Maven also packages it as a war. All of this works fine and does what is expected. I am trying to import this WAR from another eclipse in Windows so I have done it by Import -> WAR , thus creating a Web application. I now want to run it from Eclipse so I have created a new Jetty Server and run my application as Run on Server but I am getting Could not find the main class . What is the proper way of doing this? Besides, I have tried deploying the application by putting it in the webapps Tomcat directory . I can see it in the Tomcat GUI and launches the index.html but when I tried to access some of the services it throws No service was found When deploying, in the Tomcat console I can see runtime NoClassDefFoundErrors. Is there anything that mvn jetty:run does that the tomcat regular deployment does not? How is it possible that this didn't happen in my Virtual Machine? Shouldn't those classes be all in the WAR? EDIT: Here is another hint. When I run the project imported from the WAR in the Ubuntu VM, either with Jetty from eclipse or adding it to the webapps folder it works fine. It is only hen running it on Windows Host Environment when it fails. The specific NoClassdefFoundErrors thrown on cmd is the following: Caused by: java.lang.NoClassDefFoundError: org/ow2/frascati/explorer/api/FraSCAtiExplorer That is one of the modules fo the main project.
Now provide the response and nothing else.
| The GetMediaItemUrl extension method seems to give you what you want. public static class ItemExtensions{ public static string GetMediaItemUrl(this Item item) { var mediaUrlOptions = new MediaUrlOptions() { UseItemPath = false, AbsolutePath = true }; return Sitecore.Resources.Media.MediaManager.GetMediaUrl(item, mediaUrlOptions); }}[TestFixture]public class when_using_items_extensions{ [Test] public void a_url_based_on_media_item_id_can_be_generated() { // Arrange Database db = global::Sitecore.Configuration.Factory.GetDatabase("master"); Item item = db.GetItem("/sitecore/media library/Images/MyImage"); // Act var mediaUrl = item.GetMediaItemUrl(); // Assert Assert.That(mediaUrl, Is.EqualTo("/~/media/17A1341ABEEC46788F2159843DCEAB03.ashx")); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12838428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1164879/']} | jdg_86667 |
stackexchange | llm_judgeable_groundtruth_similarity | 32135882 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
INPUT Dictionary 1 "a", "1" "b", "2" Dictionary 2 "a", "3" "b", "4" Dictionary 3 "a", "5" "b", "6" OUTPUT (Concatenation of the dictionaries above) Final dictionary "a", "9" "b", "12" I wrote a pseudo code for this : Create a Final empty dictionary. Loop over the list of dictionaries. Loop over the KeyValue pair. Check if the key exists in final dictionary. If yes then add the value from KeyValue pair to final dictionary. If not then add to dictionary the KeyValue pair Since this requires two foreach loops is there a lync version in c# for this and also which doesn't throw any exception. Some of the questions that i referred on stackoverflow was Combine multiple dictionaries into a single dictionary
Now provide the response and nothing else.
| You can use SelectMany to join all the key-value pairs from each dictionary into a single sequence that you then can group by key and sum the values for each key to determine the final value: var dictionaries = new[] { new Dictionary<String, Int32>() { { "a", 1 }, { "b", 2 } }, new Dictionary<String, Int32>() { { "a", 3 }, { "b", 4 } }, new Dictionary<String, Int32>() { { "a", 5 }, { "b", 6 } }};var result = dictionaries .SelectMany(d => d) .GroupBy( kvp => kvp.Key, (key, kvps) => new { Key = key, Value = kvps.Sum(kvp => kvp.Value) } ) .ToDictionary(x => x.Key, x => x.Value); This solution works with any number of dictionaries - not just fixed set of dictionaries. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32135882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1650470/']} | jdg_86668 |
stackexchange | llm_judgeable_groundtruth_similarity | 4403923 |
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 building my own matrix class to solidify my c++ understanding. It's templated, so I can have an int matrix or a float, or boolean matrix. I wasn't going to implement a copy constructor or assignment operator or a destructor, because I'm not going to have any dynamic member elements but if I have: Matrix<float,3,4> mat1;Matrix<int,45,45> mat2;mat1 = mat2; it returns the following error: /Users/Jake/Dropbox/C++/test.cpp: In function ‘bool test1()’:/Users/Jake/Dropbox/C++/test.cpp:23: error: no match for ‘operator=’ in ‘m2 = m1’/Users/Jake/Dropbox/C++/Matrix.h:22: note: candidates are: Matrix<float, 3u, 4u>& Matrix<float, 3u, 4u>::operator=(const Matrix<float, 3u, 4u>&) which, if the two matrices are both float or both int, it's ok. Dimensions don't have to match. So the default assignment operator works great unless they are of different types. So I implement my own assignment operator: template <class T, unsigned int rows, unsigned int cols>template <class T2, unsigned int rows2, unsigned int cols2>Matrix<T, rows2, cols2> & Matrix<T,rows,cols>::operator= (const Matrix<T2, rows2, cols2> & second_matrix){ unsigned int i,j;for (i=0; i < rows2; i++){ for (j=0; j < cols2; j++){ data[i][j] = second_matrix(i,j); }}this->_rows = rows2;this->_cols = cols2;return *this;} This works if they are different types, but same dimensions- but the values in the second are converted from the second type to the first. My question is, how can I set it up so that they can be different types and different dimensions, and just set this to point at the second, or a copy of the second?
Now provide the response and nothing else.
| Yet another solution is to specify a default type for the parameter as follows: object Finder { def find[T <: Node](name: String)(implicit e: T DefaultsTo Node): T = doFind(name).asInstanceOf[T]} The key is to define the following phantom type to act as a witness for the default: sealed class DefaultsTo[A, B]trait LowPriorityDefaultsTo { implicit def overrideDefault[A,B] = new DefaultsTo[A,B]}object DefaultsTo extends LowPriorityDefaultsTo { implicit def default[B] = new DefaultsTo[B, B]} The advantage of this approach is that it avoids the error altogether (at both run-time and compile-time). If the caller does not specify the type parameter, it defaults to Node . Explanation : The signature of the find method ensures that it can only be called if the caller can supply an object of type DefaultsTo[T, Node] . Of course, the default and overrideDefault methods make it easy to create such an object for any type T . Since these methods are implicit, the compiler automatically handles the business of calling one of them and passing the result into find . But how does the compiler know which method to call? It uses its type inference and implicit resolution rules to determine the appropriate method. There are three cases to consider: find is called with no type parameter. In this case, type T must be inferred. Searching for an implicit method that can provide an object of type DefaultsTo[T, Node] , the compiler finds default and overrideDefault . default is chosen since it has priority (because it's defined in a proper subclass of the trait that defines overrideDefault ). As a result, T must be bound to Node . find is called with a non- Node type parameter (e.g., find[MyObj]("name") ). In this case, an object of type DefaultsTo[MyObj, Node] must be supplied. Only the overrideDefault method can supply it, so the compiler inserts the appropriate call. find is called with Node as the type parameter. Again, either method is applicable, but default wins due to its higher priority. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4403923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364015/']} | jdg_86669 |
stackexchange | llm_judgeable_groundtruth_similarity | 1820572 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $X$ be a transitive $G$-set. ($G$ acts on $X$ transitively.) If $X$ is finite and has at least two elements, show that there is some element $g$ $\in$ G which does not have any fixed points; that is, such that $g$$($$x$$)$ $\ne$ $x$ for all $x$ $\in$ $X$ I am trying to use contradiction, but it is not very clear to me why this is true.
Now provide the response and nothing else.
| The action has only one orbit, and since (this is Burnside's lemma) $$|X/G||G|= \sum_{g\in G} |X^g|$$ where $X^g$ is the set of fixed points of $g$, it is then clear that if every $|X^g|\geqslant 1$ we obtain a contradiction. Namely, that $|G| > |G|$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1820572', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/342670/']} | jdg_86670 |
stackexchange | llm_judgeable_groundtruth_similarity | 4151631 |
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 QuerySet like: items = Item.objects.all() Item has a 'name' field. In the template I want to show: A Axes Alcohol B Bazookas C Coins Cartridges S Swords Sparrows So the items are ordered and group by the first letter. Missing letters are omitted. Does anyone have any ideas?
Now provide the response and nothing else.
| There's a template tag for this, if all you care about is its presentation on the page. First, define an organizational principle in the class. In your case, it's the first letter: class Item(models.Model): ... def first_letter(self): return self.name and self.name[0] or '' And then define a regroup in the template, using the first_letter call: {% regroup items by first_letter as letter_list %}<ul> {% for letter in letter_list %} <li>{{ letter.grouper }} <ul> {% for item in letter.list %} <li>{{ item.name }}</li> {% endfor %} </ul> </li>{% endfor %}</ul> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4151631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111804/']} | jdg_86671 |
stackexchange | llm_judgeable_groundtruth_similarity | 1053232 |
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 lived in the C++ world for years, and I'm just starting out with Ruby. I have a class that I would like to make a thread. In Ruby is it wrong to derive a class from Thread? The examples I see use the concept below. Thread.new { <some block> } Would it be wrong to do this? class MyThread < Thread def initialize end def run <main loop> end
Now provide the response and nothing else.
| I think that this is really a question about domain modeling. There would be nothing wrong with what you are doing if you want to extend / enhance the way that a thread behaves - for example to add debug or performance output but I don't think that's what you want. You probably want to model some concept in your domain with active objects. In that case the standard Ruby approach is better because it allows you to achieve this without bending your domain model. Inheritance really should only be used to model IS_A relationships. The standard ruby code for this neatly wraps up the solution. To make your object active, have it capture the newly created thread in some method Class MyClass... def run while work_to_be_done do some_work end end...endthreads = []# start creating active objects by creating an object and assigning# a thread to eachthreads << Thread.new { MyClass.new.run }threads << Thread.new { MyOtherClass.new.run }... do more stuff# now we're done just wait for all objects to finish ....threads.each { |t| t.join }# ok, everyone is done, see starships on fire off the shoulder of etc# time to die ... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1053232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83404/']} | jdg_86672 |
stackexchange | llm_judgeable_groundtruth_similarity | 33084190 |
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 long run test, which lasts 2 days, which I don't want to include in a usual test run. I also don't want to type command line parameters, that would deselect it and other tests at every usual test run. I would prefer to select a default-deselected test, when I actually need it. I tried renaming the test from test_longrun to longrun and use the command py.test mytests.py::longrun but that does not work.
Now provide the response and nothing else.
| try to decorate your test as @pytest.mark.longrun in your conftest.py def pytest_addoption(parser): parser.addoption('--longrun', action='store_true', dest="longrun", default=False, help="enable longrundecorated tests")def pytest_configure(config): if not config.option.longrun: setattr(config.option, 'markexpr', 'not longrun') | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33084190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1803897/']} | jdg_86673 |
stackexchange | llm_judgeable_groundtruth_similarity | 2113905 |
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 with my hosting provider to get a Django application up and running, but neither of us are very experienced and we've basically hit a complete dead end. I don't have direct access to the conf file but here's how its contents have been described to me: <IfModule mod_wsgi.c>WSGIScriptAlias /fredapp/ /home/fred/public_html/cgi-bin/fredapp/apache/django.wsgiWSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/WSGIProcessGroup fredWSGIApplicationGroup %{GLOBAL}</IfModule>Alias /robots.txt /home/fred/public_html/fred-site/robots.txtAlias /favicon.ico /home/fred/public_html/fred-site/favicon.icoAlias /settings/media/ /home/fred/public_html/fred-site/media/ My "django.wsgi" script is nothing fancy: import os, syssys.path.append('/home/fred/public_html/cgi-bin/')sys.path.append('/home/fred/public_html/cgi-bin/fredapp/')os.environ['DJANGO_SETTINGS_MODULE'] = 'fredapp.settings'import django.core.handlers.wsgiapplication = django.core.handlers.wsgi.WSGIHandler() So my understanding is that all this means that if a request comes in for domain.com/fredapp/ that it should be turned over to the application via django.wsgi. However, the only response I get is: [Fri Jan 22 18:46:08 2010] [error] [client xx.xxx.xx.xx] File does not exist: /home/fred/public_html/domain.com/500.shtml[Fri Jan 22 18:46:08 2010] [error] [client xx.xxx.xx.xx] mod_wsgi (pid=26760): Exception occurred processing WSGI script '/home/fred/public_html/cgi-bin/fredapp/apache/django.wsgi'.[Fri Jan 22 18:46:03 2010] [error] [client xx.xxx.xx.xx] File does not exist: /home/fred/public_html/domain.com/404.shtml[Fri Jan 22 18:46:03 2010] [error] [client xx.xxx.xx.xx] File does not exist: /home/fred/public_html/domain This is running under Apache on Linux. I have tried running each line of the .wsgi script in the Python interpreter on the server, and none of them return any errors. I also tried the sys.stdout = sys.stderr trick and got no further output than what is above. The File does not exist errors have to do with the rest of the site's set-up and occur on any request. I haven't finished setting all that up properly (error pages and index pages and so on) because I'm just trying to get the app itself to run. I've gotten this app up and running under Apache on my own machine, though NOT in Daemon mode, but it's my first Django app, and I don't think my hosting provider has ever configured one before, so we're flying a little blind. If anyone has any suggestions, I'd be very grateful. Thank you!
Now provide the response and nothing else.
| If the quoted configuration about is what you are using, the error is rather obvious actually. You have: WSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/WSGIProcessGroup scratchf It should be: WSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/WSGIProcessGroup fred That is, the name of the process group must match. You should though have seen an error message: No WSGI daemon process called 'scratchf' has been configured This would likely be before the logged error: Exception occurred processing WSGI script This is why it is important that you supply all the error log messages and don't assume that they aren't relevant. Alternatively, you have quoted configuration different to what you are using or not all of the configuration. UPDATE 1 It looks like you may have ErrorDocument directive enabled in Apache to redirect errors to a specific URL. Because however you have mounted Django at root of web server and not excluded those error URLs from being passed through to Django, then when an error is generated Django gets the redirect for the error document but it cannot resolve the URL and subsequently generates a 404. Because Apache saw a 404 for error page redirect, it then returns a 500 default error page. The end result is that true original error and any information is lost. Thus, go into Apache configuration and comment out the ErrorDocument directives. UPDATE 2 Change configuration to: WSGIScriptAlias /fredapp /home/fred/public_html/cgi-bin/fredapp/apache/django.wsgi You should not have trailing slash on the second value on line. Missed that you were actually trying to mount at sub URL and not at root of web server. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2113905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241382/']} | jdg_86674 |
stackexchange | llm_judgeable_groundtruth_similarity | 19006067 |
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 understanding is that in order to get the date from a file passed into a subroutine as an argument, you must re-set that argument as a variable within the subroutine. Is this correct? This doesn't make since to me, so I am wondering if I do not fully understand what is going on. I can use the passed in argument in practically any other subroutine code except for date extraction. set setupEXE=setup.exeCALL :SUB_CheckCorrectDate %setupEXE%GOTO EOF::----------------------------------:SUB_CheckCorrectDateset filename=%1%:: SUCCESSFULfor %%x in (%filename%) do set FileDate=%%~tx@For /F "tokens=1-3 delims=-/ " %%A in ('@echo %FileDate%') do @( Set file_Month=%%ASet file_Day=%%BSet file_Year=%%C):: GET ERROR for %%x in (%1%) do set FileDate=%%~tx@For /F "tokens=1-3 delims=-/ " %%A in ('@echo %FileDate%') do @( Set file_Month=%%ASet file_Day=%%BSet file_Year=%%C) GOTO:EOF:: ------------------:EOF
Now provide the response and nothing else.
| Use %1 to access the parameter, not %i% . The argument variables have the same modifiers as FOR variables, so you can use %~t1 . No need to execute a command in your FOR /F. It is simpler to process a string literal using in ("string") . No need for :EOF label. Every script has an implicit :eof . I like to use exit /b instead. @echo offsetlocalset "setupEXE=setup.exe"call :SUB_CheckCorrectDate "%setupEXE%"exit /b::----------------------------------:SUB_CheckCorrectDateset "filename=%~1"for /F "tokens=1-3 delims=-/ " %%A in ("%~t1") do ( set "file_Month=%%A" set "file_Day=%%B" set "file_Year=%%C")exit /b | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19006067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2759759/']} | jdg_86675 |
stackexchange | llm_judgeable_groundtruth_similarity | 64195 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I have a smattering of knowledge and disconnected facts about this question, so I would like to clarify the following discussion, and I also seek references and citations supporting this knowledge. Please see my specific questions at the end, after "discussion". Discussion and Background In practice, groups that do not have any faithful linear representation seem to be seldom (in the sense that I believe it was not till the late 1930s that anyone found any). By Ado's theorem, every abstract finite dimensional Lie algebra over $\mathbb{R}, \mathbb{C}$ is the Lie algebra of some matrix Lie group. All Lie groups with a given Lie algebra are covers of one another, so even groups that are not subsets of $GL\left(V\right)$ ($V = \mathbb{R}, \mathbb{C}$) are covers of matrix groups. I know that the metaplectic groups (double covers of the symplectic groups $Sp_{2 n}$) are not matrix groups. And I daresay it is known (although I don't know) exactly which covers of semisimple groups have faithful linear representations, thanks to the Cartan classification of all semisimple groups. But is there a know general reason (i.e. theorem showing) why particular groups lack linear representations? I believe a group must be noncompact to lack linear representations, because the connected components of all compact ones are the exponentials of the Lie algebra (actually if someone could point me to a reference to a proof of this fact, if indeed I have gotten my facts straight, I would appreciate that too). But conversely, do noncompact groups always have covers which lack faithful linear representations? Therefore, here are my specific questions: Specific Questions Firm answers with citations to any of the following would be highly helpful: 1) Is there a general theorem telling one exactly when a finite dimensional Lie group lacks a faithful linear representation; 2) Alternatively, which of the (Cartan-calssified) semisimple Lie groups have covers lacking faithful linear representations; 3) Who first exhibited a Lie group without a faithful representation and when; 4) Is compactness a key factor here? Am I correct that a complex group is always the exponetial of its Lie algebra (please give a citation for this). Does a noncompact group always have a cover lacking a faithful linear representation? Many thanks in advance.
Now provide the response and nothing else.
| Most of the answers can be found in Hochschild's book on the structure of Lie group. a) Every complex semisimple group has a faithful rep (Thm 3.2 in Chap. XVII) b) A connected Lie group with Levi decomposition $G=RS$ ($R$ the solvable radical, $S$ a semisimple Levi factor) is linear iff both $R$ and $S$ are linear (Thm 4.2 in Chap. XVIII) c) A solvable Lie group $G$ is linear iff its commutator subgroup $G'$ is closed, and $G'$ has no non-trivial compact subgroup (Thm 3.2 in Chap. XVIII) Now, let $G$ be a semi-simple Lie group. Assume that $G$ is simply connected. Then $G$ admits a greatest linear quotient. Indeed, let $G_{\mathbb{C}}$ be the simply connected complex group corresponding to the complexified Lie algebra of $G$. Let $L$ be the kernel of the canonical homomorphism $G\rightarrow G_{\mathbb{C}}$; so $L$ is a finite index subgroup of the center of $G$. Then $G/L$ is the greatest linear quotient of $G$, in the sense that, if $H$ is locally isomorphic to $G$ and $p:G\rightarrow H$ is a universal covering, the group $H$ s linear iff $p$ factors through $G/L$. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/64195', 'https://mathoverflow.net', 'https://mathoverflow.net/users/14510/']} | jdg_86676 |
stackexchange | llm_judgeable_groundtruth_similarity | 586462 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
We just got a SAN, and I will be assisting in installing it and configuring it, I asked someone to explain to me what we will gain using SAN zoning, but he was unable to answer my question, could some one here explain to me what are some of the advantages we will get from using SAN zoning using Brocade. Thanks
Now provide the response and nothing else.
| Do you mean FC zoning? if so then it's basically something akin to a VLAN in that it allows you to hard-limit connections between devices. With only one big zone essentially all points can talk to all other points, this sounds good, especially when you have a proper switch which will help with bandwidth management (there used to be FC hubs bitd, showing my age there) but it's often nice/required that you have more control. For instance in our environment, entirely Cisco based I have to say, everything is very much firmly tied down by definition. So for example any given HBA port can only talk to the ports it's design to talk to on our arrays - and nothing else at all. Yes it's harder work but in-life it means we can troubleshoot more easily and our security nazi's love it and never throw anything back at us. So it comes down to ease vs. control. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/586462', 'https://serverfault.com', 'https://serverfault.com/users/215052/']} | jdg_86677 |
stackexchange | llm_judgeable_groundtruth_similarity | 8967 |
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:
In the article Fountain of youth? Apr. 14, 2012, Written by: Dr. W. Gifford-Jones, QMI Agency, the author claims: Today more than 8,000 scientific articles have been reported on the importance of telomeres in aging. But one peer reviewed study, published in September 2011, reported on humans who were given the telomerase activator, TA-65, to maintain the normal length of telomeres. This study carried out on men showed that TA-65 resulted in a rejuvenated immune system with fewer senescent white blood cells. This suggests improved immunity protection in the elderly. As we age we invariably experience a gradual decline in vision. A 2005 study showed that TA-65 has a positive effect on the structure and function of the eyes, causing improved vision in elderly men. Also seen was an improvement in the quality of skin. Other studies using TA-65 showed cognitive and verbal memory improvement and increased bone density. Researchers also observed a lowering of cholesterol, blood pressure, fasting blood sugar. And some patients reported improved energy, increased flexibility and being more productive. There seem to be ample studies that indicate that we have a molecule that puts a stopper in what we call symptoms of aging. Not having read the studies referred to, I am skeptical of whether the observed studies demonstrate a phenomenon that is akin to "stopping aging", and in any case how reliable those studies are (i.e. were they in peer reviewed journals and can the results be reproduced).
Now provide the response and nothing else.
| tl;dr : The link between TA-65 and anti-aging is not substantiated by any evidence that meets accepted scientific standards. An answer to this question was posted to this question by (now deleted) user TA-65 , which answer purportedly affirmed the existence of a link between TA-65 and anti-aging. I reproduce the answer, properly down-voted into oblivion, as I believe it contributes to the conclusion about the merits of the claims made (although not for the substance of the answer that user TA-65 provided): YES ! And that proves scientific studies. In fact, the TA-65 is the only product of its kind to have scientific studies on human cells. You can find more about that here: TA-65 Supplement – Review and Scientific Research Also read more about: TA-65 The circumstances of the answer suggest that it was made by a shill promulgating quackery. The user TA-65 seems to have registered solely for the purpose of answering this question. Both of the above links are to ta65doctor.com, a web-site that seems to exist only to sell supplements labelled TA-65. Looking beyond the motivations of user TA-65, the ta65doctor.com website has a list of research , that references: Beyond average: potential for measurement of short telomeres .Aging (Albany NY). 2012 Jun 8. Vera E, Blasco MA. CNIO scientists successfully test the first gene therapy against aging-associated decline 14-May-2012 Centro Nacional de Investigaciones Oncologicas (CNIO) Shorter telomere length is associated with increased ovarian cancer risk in both familial and sporadic cases. J Med Genet. 2012 May;49(5):341-4. Epub 2012 Apr 6. Martinez-Delgado B et al The load of short telomeres is increased and associated with lifetime number of depressive episodes in bipolar II disorder. J Affect Disord. 2011 Dec;135(1-3):43-50. Epub 2011 Aug 30. Elvsåshagen T et al The telomerase activator TA-65 elongates short telomeres and increases health span of adult/old mice without increasing cancer incidence. Aging Cell. 2011 Aug;10(4):604-21. doi: 10.1111/j.1474-9726.2011.00700. Blasco MA et al Biologic function and clinical potential of telomerase and associated proteins in cardiovascular tissue repair and regeneration. Eur Heart J. 2011 May;32(10):1190-6. Madonna R et al A natural product telomerase activator as part of a health maintenance program.Rejuvenation Res. 2011 Feb;14(1):45-56. Harley CB et al María Blasco: Keeping a cap on cancer and aging Interview by Caitlin Sedwick. J Cell Biol. 2011 Feb 7;192(3):370-1 Blasco M. Telomeres in cancer and aging. Philos Trans R Soc Lond B Biol Sci. 2011 Jan 12;366(1561):76-84. Donate LE, Blasco MA. Aging by telomere loss can be reversed. Cell Stem Cell. 2011 Jan 7;8(1):3-4. Bernardes de Jesus B, Blasco MA. The role of telomeres and telomerase in stem cell aging. FEBS Lett. 2010 Sep 10;584(17): 3826-30. Flores I, Blasco MA. Telomere shortening and aging of the immune system. J Physiol Pharmacol. 2008 Dec;59 Suppl 9:169-86. Kaszubowska L. Telomerase deficiency promotes oxidative stress by reducing catalase activity. Free Radic Biol Med. 2008 Nov 1;45(9):1243-51. Epub 2008 Jul 30. Pérez-Rivero G et al Telomeres and aging Physiol Rev. 2008 Apr;88(2):557-79. Aubert G, Lansdorp PM. Telomerase induction in T cells: a cure for aging and disease? Exp Gerontol. 2007 May;42(5):416-20. Epub 2006 Dec 19. Since they sell it, one would reasonably expect ta65doctor.com to put forward the best evidence in support of the association between TA-65 and anti-aging. Below is a synopsis of the conclusions of these papers. It is reasonable based on the analysis below to conclude that the papers cited fail to adequately demonstrate proof of the the claims put forward by the TA-65 website. Combined with the vacuous answer by the shill, it feels correct to conclude that at this time the link between TA-65 and anti-aging is as-yet unsubstantiated by accepted scientific standards. EDIT : The only one evaluating TA-65 specifically is the last one of that whole list above (alternately titled A Natural Product Telomerase Activator As Part of a Health Maintenance Program ). Most of the articles are reviews of Telomerase functions (useless), studies done on mice (useless for humans), and one of the human trials only had 28 participants so its ability to discern information is limited. From the last study, here are a few excerpts to take note of: Calvin Harley is one of the inventors of TA-65. He consults for TA Sciences and is personally taking TA-65 and is one of the subjects studied to generate data for this article. He owns stock and stock options in Geron Corporation, a company that is developing telomerase activators for therapeutic purposes and the company that licensed TA-65 to TA Sciences. He is co-founder, President, and CEO, and holds stock in Telome Health, Inc., a diagnostics company that will provide telomere- and telomerase-related assay services to the healthcare industry. The author of the study for TA-65 has significant financial ties to the company producing TA-65. He's also participating in his own study, which practically ruins any chance the study had at producing clean data. While that tidbit alone isn't enough to write-off TA-65 completely, it should make anyone considering TA-65 extremely skeptical. The number of subjects at 3, 6, 9, and 12 months for most tests was 43, 59, 27, and 37, respectively. The age and gender frequencies of the subset at each time point were similar to those of the total baseline population (n = 114; 63 ± 12 years, 72% male). The total number of participants was 114, but testing was incredibly inconsistent - with a low of 27 and a high of 59 (but never more than about half). That the authors didn't bother to strictly control who reported for tests and only keep those who were consistent about doing so (which is what you normally see for clinical trials - participant attrition over time until you have a single pool of subjects who completed all the exams/treatments), the results drawn from these numbers should be very suspect. I'd venture to call the results useless, but others might provide suggestions as to why they're not. Starting doses of 5–10 mg/day were considered safe on the basis of historical usage of extracts. Some subjects increased their dosage after several months on the product to 25–50 mg/day. Then there's that... Data from this study were collected primarily as a hypothesis-generating exercise because subjects were not participating in a controlled prospective study, and statistical analyses were not formally defined a priori. ... and this, which isn't a huge surprise... The most striking in vivo effects were declines in the percent senescent cytotoxic (CD8+/CD28−) T cells (1.5, 4.4, 8.6, and 7.5% at 3, 6, 9, and 12 months, respectively; p = not significant [N.S.], 0.018, 0.0024, 0.0062) and natural killer cells at 6 and 12 months (p = 0.028 and 0.00013, respectively). Most of these decreases were seen in cytomegalovirus (CMV) seropositive subjects. In a subset of subjects, the distribution of telomere lengths in leukocytes at baseline and 12 months was measured. Although mean telomere length did not increase, there was a significant reduction in the percent short (<4 kbp) telomeres (p = 0.037). And finally the meat of the whole thing. The results of the study show only that T-Cells who had short Telomeres benefited significantly, and that if you've never contracted CMV - your T-Cells might not benefit at all. So, if you want to believe the methods for performing the study are still valid, what you can conclude from the study is that the best affect you'll receive from TA-65 supported by evidence is that your Immune System will work slightly better. | {} | {'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/8967', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/1792/']} | jdg_86678 |
stackexchange | llm_judgeable_groundtruth_similarity | 37540 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to create an interactive grid, whereby one number from a grid is selected by the cursor ("3" in the example below), and all other numbers in the grid are highlighted that are related to the chosen number, and each successive number after that. In the example below, "3" is the selected number, and the highlighted numbers are double the previous one. I am not sure whether a loop, or a direct function (in this case, clearly multiplying by powers of 2) would be the best approach - I assume the function-apply approach would be the quickest for large grids. Below is an example: generated with: m = 10;(*size of the grid*)premade = Transpose@Partition[Range@100, m];col[n_] := Table[{n - 0.5, i - 0.5}, {i, 1, m}]Graphics[{ {Red, Opacity[0.3], Rectangle[{0, 2}, {01, 3}]}, {Red, Opacity[0.3], Rectangle[{0, 5}, {01, 6}]}, {Red, Opacity[0.3], Rectangle[{1, 1}, {02, 2}]}, {Red, Opacity[0.3], Rectangle[{2, 3}, {03, 4}]}, {Red, Opacity[0.3], Rectangle[{4, 7}, {05, 8}]}, {Red, Opacity[0.3], Rectangle[{9, 5}, {10, 6}]}, Table[Text[Style[premade[[#, i]], Large, FontFamily -> "Times"],col[i][[#]]] & /@ Range@m, {i, 1, m}]}, GridLines -> {Range@m, Range@m}, PlotRange -> {{0, m}, {0, m}}, Axes -> False, Frame -> True, GridLinesStyle -> Directive[GrayLevel[0.8], Dashed]] NOTE: All columns will be separate lists.
Now provide the response and nothing else.
| Here is what I would propose related to the use of Graphics : DynamicModule[{color = Red, m = 10, premade, col, posnum, posFriends, unSortedPos, posMouse = {0, 0}, positionColor = {{0, 0}}}, (*Initialization code*) premade = Transpose@Partition[Range@(m*m), m]; col[n_] := Table[{n - 0.5, i - 0.5}, {i, 1, m}]; EventHandler[ Graphics[ { Dynamic@{[email protected], Red, Rectangle /@ positionColor}, Table[Text[Style[premade[[#, i]], Large, FontFamily -> "Times"], col[i][[#]]] & /@ Range@m, {i, 1, m}] }, GridLines -> {Range@m, Range@m}, PlotRange -> {{0, m}, {0, m}}, Axes -> False, Frame -> True, GridLinesStyle -> Directive[GrayLevel[0.8], Dashed], ImageSize -> 350], {"MouseDown" :> (posMouse = Floor[MousePosition["Graphics", Graphics], 1]; posFriends[premade, posnum@premade];)}], Initialization :> ( posFriends[list_, start_] := (unSortedPos = (# - {1, 1} & /@ Flatten[Position[list, #]&/@ Select[Table[start*2^(i-1), {i, 1, 10}], # <= m*m&], 1]); positionColor = Reverse@unSortedPos[[#]] & /@ Range@Length@unSortedPos; ); posnum[list_] := list[[Last@posMouse + 1, First@posMouse + 1]]; )] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/37540', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9923/']} | jdg_86679 |
stackexchange | llm_judgeable_groundtruth_similarity | 148224 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm on RHEL 6.5 and Apache 2.2.15 . When I restart the httpd , I can not start that httpd anymore. Showing following things in the /var/log/httpd/error_log : [Fri Aug 01 18:31:48 2014] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)[Fri Aug 01 18:32:35 2014] [notice] SELinux policy enabled; httpd running as context unconfined_u:system_r:httpd_t:s0[Fri Aug 01 18:32:35 2014] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)[Fri Aug 01 18:42:46 2014] [notice] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0[Fri Aug 01 18:42:46 2014] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)[Fri Aug 01 18:43:15 2014] [notice] SELinux policy enabled; httpd running as context unconfined_u:system_r:httpd_t:s0[Fri Aug 01 18:43:15 2014] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)[Fri Aug 01 18:43:59 2014] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)[Fri Aug 01 18:44:12 2014] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)[Fri Aug 01 18:45:03 2014] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) Actually I have already disabled the SELinux and rebooted. What should I do please?
Now provide the response and nothing else.
| Sorry, I have found the reason. This is totally because of the SSL CERT problem. Not really because of above notices . It was nothing to do with above mentioned Messages. Therefore please just ignore them. How do I do was that I enabled the Apache Detailed Logs and then that's the real move. It shows what really is happening, by showing the Failure at the loading of mod_ssl module, while starting the Apache. Then I realized it is because of ssl.conf (or the respective Vhost file) having the SSL Cert configurations inside. There I made 2 mistakes. First, I didn't give read permissions to the CERT related files (.crt/ .key/ .csr). After that, more badly, one of the file was wrong. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/148224', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/34722/']} | jdg_86680 |
stackexchange | llm_judgeable_groundtruth_similarity | 587114 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am reading Sedra and Smith and just want to be sure that the following characterization of an ideal linear amplifier is correct. A linear amplifier was defined as an amplifier for which the output signal is proportional to the input signal given any input signal. Supposing that we define bandwidth as the range of frequencies over which gain is constant; it then seems to me that one can say that an amplifier is linear if and only if it has infinite bandwidth (otherwise you could construct signals which superpose frequency components with different gains and get distortion through the amplifier). Is this correct? Here is the definition from Sedra and Smith which I quote:
Now provide the response and nothing else.
| TL;DR As engineers, Sedra/Smith make one more assumption than the OP does. Engineers also make one more assumption than do mathematicians. Mathematicians say a system H is linear iff (if and only if) it obeys the superposition principle, that H(x+y) = H(x) + H(y). This is weaker than engineers tend to use, as it allows a time-varying system gain, which can generate output harmonics under certain conditions. So time-independent gain implies superposition, but superposition does not imply time-independent gain. Engineers tend to be lazy and say linear when they mean LTI - Linear Time-Invariant. An LTI system can still have a frequency response. Engineers tend to say that an amplifier is linear when it has a gain Vout/Vin = k(f), where k can vary with frequency. When excited by any single sinuosoid, the output will look like a perfect scaled copy of the input. If k varies with frequency, then when excited by multiple sinusoids, the output will not look like the input, but there will be no intermodulation distortion, the only output frequencies will be those present in the input. Now for the important difference in assumptions. If the input range of frequencies is limited to the flat frequency response part of the spectrum (a condition that is often assumed but not stated), and the amplifier also has linear phase - that is constant signal delay, then the output will look like a scaled version of the input, and finally we can write Vout/Vin = constant. Plenty of amplifiers and filters exist where phase is not linear even though the gain may be, and the output of those does not look like the input. The output is usually referred to as suffering from phase distortion. An ideal amplifier will have infinite bandwidth and zero noise, and not suffer clipping up to any arbitrary signal level. The response of inductors or capacitors is linear, they obey superposition. Networks involving those do not obey Vout/Vin = k, there is a differential or integral operator involved. Engineers do also use time-varying systems, although they call them mixers. A diode ring pumped with a strong local oscillator (LO) drive changes its gain with the LO period. When a low level signal is passed through, it does obey superposition, and engineers do talk about 'linear' mixers. A good mixer obeys superposition up to higher signal levels than a bad mixer. In a good mixer, the signal passing through does not suffer any intermodulation distortion between its frequency components. There is intermodulation between the LO and the signal components, that's how you get the sum and difference frequencies! | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/587114', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/237839/']} | jdg_86681 |
stackexchange | llm_judgeable_groundtruth_similarity | 31683811 |
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 RecyclerView with its Adapter and LayoutManager. Adapter has approximate 15 different ViewHolders. One of them contain WebView which loads external contents (99% of them are videos outside of YouTube).The problem comes when any View of Adapter gets out of the screen - video in WebView keeps playing and sound is playing. Still, that's acceptable for me. The key problem starts when I move to another Activity. The sound of the video is still present. Is there any way RecyclerView could notify me when any of its children views change visibility state (meaning disappears from display)?
Now provide the response and nothing else.
| Gonna respond to myself. Best approach is add RecyclerView.OnChildAttachStateChangeListener to my RecyclerView and then handle events with my WebView when onChildViewDetachedFromWindow(View view) is called. Example: mRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() { @Override public void onChildViewAttachedToWindow(View view) { WebView webView = (WebView) view.findViewById(R.id.webview); if (webView != null) { webView.onResume(); } } @Override public void onChildViewDetachedFromWindow(View view) { WebView webView = (WebView) view.findViewById(R.id.webview); if (webView != null) { webView.onPause(); } } }); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31683811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3289311/']} | jdg_86682 |
stackexchange | llm_judgeable_groundtruth_similarity | 243548 |
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:
Can somone help me find a closed form expression for this sum given any rational value of x, and any integer p, where {x} denotates the fractional part of x.$$\sum_ {k=1}^{\infty}\frac{ \left\{p^kx \right\} }{p^k} $$ It also seems to converge to rational values. For example if i let $p=5,x=\frac13$, the series converges to $\frac{11}{72}$ I don't think it should be very hard, but im not sure, I would appreciate any help.
Now provide the response and nothing else.
| Suppose $x\in\mathbb{Q}$, $0\lt x\lt1$, and $x$ has the base-$p$ expansion$$x=\sum_{k=1}^\infty\frac{d_k}{p^k}\tag{1}$$Then$$\frac{\{p^nx\}}{p^n}=\sum_{k=n+1}^\infty\frac{d_k}{p^k}\tag{2}$$So that$$\begin{align}f_p(x)&=\sum_{n=0}^\infty\frac{\{p^nx\}}{p^n}\\&=\sum_{n=0}^\infty\sum_{k=n+1}^\infty\frac{d_k}{p^k}\\&=\sum_{k=1}^\infty\sum_{n=0}^{k-1}\frac{d_k}{p^k}\\&=\sum_{k=1}^\infty\frac{k\,d_k}{p^k}\tag{3}\end{align}$$Since the sum in $(3)$ starts at $k=0$, $f_p(x)-x$ is the function in the question. However, if $f_p(x):\mathbb{Q}\mapsto\mathbb{Q}$, then $f_p(x)-x:\mathbb{Q}\mapsto\mathbb{Q}$. Finite base-$p$ expansion Obviously, if the base-$p$ expansion of $x$ is finite, then the sum in $(3)$ is finite$$f_p(x)=\sum_{k=1}^m\frac{k\,d_k}{p^k}\tag{4}$$which is a finite sum of rational numbers, hence $f_p(x)\in\mathbb{Q}$. Repeating base-$p$ expansion If the base-$p$ expansion of $x$ repeats with period $m$, then$$\begin{align}f_p(x)&=\sum_{k=1}^m\sum_{n=0}^\infty\frac{(k+nm)d_k}{p^{k+nm}}\\[6pt]&=\sum_{k=1}^m\frac{d_k}{p^k}\sum_{n=0}^\infty\frac{k+nm}{p^{nm}}\\[6pt]&=\sum_{k=1}^m\frac{d_k}{p^k}\left(\frac{kp^m}{p^m-1}+\frac{mp^m}{(p^m-1)^2}\right)\\[6pt]&=\frac1{p^m-1}\left(mx+p^m\sum_{k=1}^m\frac{k\,d_k}{p^k}\right)\tag{5}\end{align}$$which is again a finite sum of rational numbers, hence $f_p(x)\in\mathbb{Q}$. Mixed base-$p$ expansions Note that if there are no base-$p$ carries when adding $x$ and $y$, then each digit of the sum is the sum of the digits, and therefore, by $(1)$ and $(3)$,$$f_p(x+y)=f_p(x)+f_p(y)\tag{6}$$Furthermore,$$\begin{align}f_p\left(\frac{x}{p^n}\right)&=\sum_{k=1}^\infty\frac{(k+n)d_k}{p^{k+n}}\\&=\frac1{p^n}\left(nx+f_p(x)\right)\tag{7}\end{align}$$Combining $(4)$, $(5)$, $(6)$, and $(7)$, we get Conclusion If $x\in\mathbb{Q}$, then$$\sum_{k=1}^\infty\frac{\{p^kx\}}{p^k}=f_p(x)-x\in\mathbb{Q}$$ Example 1 In base $5$, $\frac{14}{25}=.\color{#C00000}{24}$. By $(4)$$$\begin{align}f_5\left(\frac{14}{25}\right)&=\frac{\color{#00A000}{1}\cdot\color{#C00000}{2}}{5^{\color{#00A000}{1}}}+\frac{\color{#00A000}{2}\cdot\color{#C00000}{4}}{5^{\color{#00A000}{2}}}\\[6pt]&=\frac{18}{25}\end{align}$$ Example 2 In base $5$, $\color{#0000FF}{\frac13}=.\overline{\color{#C00000}{13}}$, therefore, $p=5,m=2,d_1=1,d_2=3$. By $(5)$$$\begin{align}f_5\left(\color{#0000FF}{\frac13}\right)&=\frac1{5^2-1}\left(2\cdot\color{#0000FF}{\frac13}+5^2\left(\frac{\color{#00A000}{1}\cdot\color{#C00000}{1}}{5^\color{#00A000}{1}}+\frac{\color{#00A000}{2}\cdot\color{#C00000}{3}}{5^\color{#00A000}{2}}\right)\right)\\[6pt]&=\frac{35}{72}\end{align}$$ Example 3 In base $5$, $\frac{67}{75}=.24\overline{13}$. Using $(6)$ and $(7)$ and the previous examples, we get$$\begin{align}f_5\left(\frac{67}{75}\right)&=f_5\left(\frac{14}{25}\right)+f_5\left(\frac13\cdot\frac1{25}\right)\\[6pt]&=\frac{18}{25}+\frac1{5^2}\left(2\cdot\frac13+\frac{35}{72}\right)\\[6pt]&=\frac{1379}{1800}\end{align}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/243548', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50290/']} | jdg_86683 |
stackexchange | llm_judgeable_groundtruth_similarity | 3745494 |
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 Delphi 2010.I have to set UseLatestCommonDialogs to Falseand additionally set ofOldStyleDialog property of Open and Save dialogs to trueif I want that Open and Save Dialogs works in Windows 7(otherwise they do not open at all).It is also true that I reserve quite a lot of space for a stack: {$M 16384, 60048576} since I use recursive algorithms on large datasets.Now I wonder what is the problem: New dialogs seem very space consuming, sometimes they work at the beginning and after a set of open and save dialogs executions it does not open dialogs any more(maybe also dialogs do not free memory after they are executed?) Is there a bug in Windows 7? Anybody else experienced a similar problem? It looks a little strange to work on Windows 7 with ancient dialogs(they are even older that XP style, I think they look like in Windows NT). Any suggestion will be very appreciated. Thanks in advance.
Now provide the response and nothing else.
| The default stack space allocation specified by $M is global to all threads in the process that don't specify their own specific requirements. 60M is a lot for this, far more than almost any stack will ever grow to. The File dialogs are essentially a hosted version of Windows Explorer. They load up shell extensions into your process for things like thumbnails, column handlers, context menus, etc. As Windows grows more featured, both MS and third parties feel free to use more and more resources - including threads - to add more info asynchronously, without blocking the UI. A simple test with notepad.exe on my Windows 7 64-bit machine shows that it has 1 thread before the dialog, but 19 threads while the dialog is open. In a 32-bit process with a default stack reservation close to 60M, that would want to reserve over 1G, or over half the total address space accessible to 32-bit applications by default. If there's much data being worked with in the application at all, it's very easy to see one running out of address space through memory fragmentation - all the code from the EXE, system DLLs, etc. needs to fit in there somewhere too. 60M is simply too high a default stack reservation to expect to work without problems. Have you considered moving your deeply recursive computations in a thread you create? You'd need to use BeginThread() from System directly though, in order to explicitly specify the stack reservation. Alternatively, is it possible to try reducing the stack usage of your algorithms? If you're allocating records or arrays on the stack, consider allocating them dynamically. If you have a function which recurs a lot (nested deeply) and has a lot of local variables, consider creating a record containing the locals and allocating it dynamically. If you're depending on the recursion to sequence work (e.g. depth-first traversals of trees / graphs), consider using the recursion simply to sequence work (e.g. add nodes to a list), and do the real processing iteratively. And if necessary, look at redoing the algorithm to work with an explicit stack. Another advantage of having an explicit stack is that you can trivially switch to breadth-first when desired, by using a queue instead of a stack, a one-liner if the stack and queue implementations use a polymorphic interface. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3745494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/451881/']} | jdg_86684 |
stackexchange | llm_judgeable_groundtruth_similarity | 14687821 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to update child managed object context so it has the same data with parent? As far as I know, when saving, child only goes one step, namely to parents. Yet when fetching fetch always go really deep all the way to the parent and persistent store. So I expect things will be the same. Yet it's not. I have a managed object context that is parent of all other managed object context. One child change data and save. The parent is also changed. I do executeFetchRequest on parent and I see that the data change. However, some child of the parents still use old data. Same object id same data. Somehow the value of the property remain the same. How to tell the child to reload fresh data from the parent? To be more exact Say P is the parent Say it has C1 C2 C3 as child Then C1 changes data and commit. The change is propagated to P. However, executing executeFetchRequest at C2 and C3 still shows old data. What gives? For example, when I check for the imageBlob property, this is what I get: Child: 2013-02-05 13:57:42.865 BadgerNew[78801:c07] imageBlob: <UIImage: 0x89c3c50>2013-02-05 13:57:42.866 BadgerNew[78801:c07] imageBlob: <null>2013-02-05 13:57:42.866 BadgerNew[78801:c07] imageBlob: <null>2013-02-05 13:57:42.866 BadgerNew[78801:c07] imageBlob: <null> Parent: 2013-02-05 13:57:42.868 BadgerNew[78801:c07] imageBlob: <UIImage: 0x114af650>2013-02-05 13:57:42.868 BadgerNew[78801:c07] imageBlob: <UIImage: 0x8e492e0>2013-02-05 13:57:42.868 BadgerNew[78801:c07] imageBlob: <UIImage: 0x114c79b0>2013-02-05 13:57:42.869 BadgerNew[78801:c07] imageBlob: <UIImage: 0xa8c76e0> Here is a more comprehensive version why I jot down the moc, the parent moc, the blob, the URL and the object ID.Child: In particular I want the mainqueue managedobject context to be another child of the parent rather than the parent of all other managedObjectContext. On the other hand, I also want the mainQueue Managed object context to have uptodate information. I wonder what the standard solution be.
Now provide the response and nothing else.
| The child has invalid existing references. If you want the siblings to be in sync after parent save, you must invalidate the children with reset . After calling reset , all the receiver's managed objects are “forgotten.” If you use this method, you should ensure that you also discard references to any managed objects fetched using the receiver, since they will be invalid afterwards. You can also use refreshObject:mergeChanges: on the individual objects changed on all the child contexts when saving the parent context if you want finer control on changed objects in the child contexts. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14687821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/700663/']} | jdg_86685 |
stackexchange | llm_judgeable_groundtruth_similarity | 141227 |
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 decided to check out what name my ethernet device will end up with, but contrary to other distros , Debian doesn't seem to have activated this change (or is holding it back?), Keep the old persistent network interface naming scheme for now and make the new one opt-in via net.ifnames=1 on the kernel command line. The problem is that I have to edit the grub kernel lines, and that seems like overkill for something that can be disabled by modifying a file . Is there another way?
Now provide the response and nothing else.
| Version 220-7 on Debian dropped the patch that made this opt-in: * Switch to net.ifnames persistent network interfaces (on new installations/for new hardware), and deprecate the old 75-persistent-net-generator.rules. This came about from a proposal in debian-devel list. Systems which were using the old naming won't be renamed until the user migrates. Read README.Debian for the migration guide. The new name can be predicted by using: sudo udevadm test /sys/class/net/eth0 2>/dev/null |grep ID_NET_NAME_ where eth0 is the current name of the device. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/141227', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/41104/']} | jdg_86686 |
stackexchange | llm_judgeable_groundtruth_similarity | 2103322 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it better if I use ID nr:s instead of VARCHARS as foreign keys?And is it better to use ID nr:s isntead of VARCHARS as Primary Keys?By ID nr I mean INT! This is what I have now: category table:cat_id ( INT ) (PK)cat_name (VARCHAR)category options table:option_id ( INT ) (PK)car_id ( INT ) (FK)option_name ( VARCHAR ) I COULD HAVE THIS I THINK: category table:cat_name (VARCHAR) (PK)category options table:cat_name ( VARCHAR ) (FK)option_name ( VARCHAR ) ( PK ) Or am I thinking completely wrong here?
Now provide the response and nothing else.
| The problem with VARCHAR being used for any KEY is that they can hold WHITE SPACE. White space consists of ANY non-screen-readable character, like spaces tabs, carriage returns etc. Using a VARCHAR as a key can make your life difficult when you start to hunt down why tables aren't returning records with extra spaces at the end of their keys. Sure, you CAN use VARCHAR, but you do have to be very careful with the input and output. They also take up more space and are likely slower when doing a Queries. Integer types have a small list of 10 characters that are valid, 0,1,2,3,4,5,6,7,8,9 . They are a much better solution to use as keys. You could always use an integer-based key and use VARCHAR as a UNIQUE value if you wanted to have the advantages of faster lookups. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2103322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_86687 |
stackexchange | llm_judgeable_groundtruth_similarity | 108104 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?" So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type? So I have typeof(int)typeof(DateTime)System.Type t = something; and I want int? DateTime? or Nullable<int> (which is the same)if (t is primitive) then Nullable<T> else just T Is there a built-in method?
Now provide the response and nothing else.
| Here is the code I use: Type GetNullableType(Type type) { // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable. type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null if (type.IsValueType) return typeof(Nullable<>).MakeGenericType(type); else return type;} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/108104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5790/']} | jdg_86688 |
stackexchange | llm_judgeable_groundtruth_similarity | 4905393 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With Scala, what is the best way to read from an InputStream to a bytearray? I can see that you can convert an InputStream to char array Source.fromInputStream(is).toArray()
Now provide the response and nothing else.
| How about: Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray Update: use LazyList instead of Stream (since Stream is deprecated in Scala 3) LazyList.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4905393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/586134/']} | jdg_86689 |
stackexchange | llm_judgeable_groundtruth_similarity | 1869305 |
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 not want to learn an IDE or similar software which is only made for one platform only. I want to spend my time+energy in learning something which is a timeless-truth. I want to switch to an editor-religion, which has no religion but of development and progress, it sees & treats all with equality. Yes, please provide me some guide about how to switch to Emacs on windows.like, doing compiler settings, source setting, TFS binding ...and all things I do not know about. PS most of (all) my code is in C++ (unmanaged)
Now provide the response and nothing else.
| You'll need to consider whether you want to use Emacs as your editor only, but continue to maintain your project settings, source files and build/debug environment in Visual Studio, or switch completely to Emacs as you editor and use some other tools (e.g., make) to build your project using VS compilers or other compilers completely. The former case is relatively easy - you can have your file open in Emacs, and the project open in Visual studio, and just Alt-tab over to VS to build and debug. There are a couple good ports of graphical Emacs for Windows, or you can just use Cygwin combined with the terminal version of the application. The second option - switching to a fully UNIX-like build environment is more involved and extends far beyond what editor you will be using. Update, given comment below on "baby steps": If your goal is to get to a complete non-VS (with the possible exception of the actual compiler and linker executable) environment in baby steps, then I would recommend first simply using Emacs to edit your source, and becoming used to the various shortcut keys and so on. Speaking only about raw editing, I find myself considerably more productive in Emacs than VS given the power of the editing functionality - and less use of the mouse is another upside if you suffer from mouse-related RSI. That's the first baby step you can take. Unfortunately, the next step - to move from the VS build environment to something cross platform isn't so simple, and I can't see a particularly gradual way to do it. You'll need to decide what your alternative would be - it could be as simple the classic GNU tool chain - make, makedepends, gcc, gdb and related components. Here, I'd recommend Cygwin on Windows - get used to this and you'll be immediately familiar with the tools when you make the jump to a UNIX environment. The details of how to set up a nice environment with this toolchain could probably fill a book or two, but if your needs are simple it is not difficult. There are certainly other more modern alternatives, although many of them are oriented towards Java - but you can still use things like ANT and Maven with other languages with the appropriate plugin or extension. Once you've got your non-VS build set up (nothing to do with Emacs), only then can you go about the task of learning how to trigger your builds, fix compile errors and debug your programs using emacs in an integrated way. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1869305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/171180/']} | jdg_86690 |
stackexchange | llm_judgeable_groundtruth_similarity | 462047 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the case of finite-dimensional vector spaces, an endomorphism is injective if and only if it is surjective. In the case of finitely generated modules over a commutative ring, if an endomorphism is surjective, then it is injective. I am wondering about the converse, which i suspect is not true. I am interested in counterexamples that give insight into why an injective endomorphism of a finite module is not necessarily surjective. Edit: at several occasions in abstract algebra injectivity and surjectivity appear to be dual notions. At other cases this duality breaks down. The case i am referring to seems to be one of these and i am interested in understanding what it is that makes one notion (surjectivity) "more difficult" to achieve than the other (injectivity).
Now provide the response and nothing else.
| Hint: Let us write it as follows: $$\sum_{n=1}^{1999} \sqrt{1+ \frac{1}{n^{2}} + \frac{1}{(n+1)^{2}}}$$ We can rewrite the radical as: $$\sqrt{\frac{n^{2}(n+1)^{2} + n^{2} + (n+1)^{2}}{n^{2}(n+1)^{2}}}$$ Which simplifies to: $$\sqrt{\frac{(n^{2}+n+1)^{2}}{n^{2}(n+1)^{2}}} = \frac{n^{2}+n+1}{n^{2}+n} = 1 + \frac{1}{n^{2}+n}$$ So now our sum is: $$\sum_{n=1}^{1999} 1 + \frac{1}{n^{2}+n}$$ Extracting the constant term gives $$\sum_{n=1}^{1999} 1 + \frac{1}{n^{2}+n} = 1999 + \sum_{n=1}^{1999}\frac{1}{n(n+1)}$$ By partial fractions decomposition, we see: $$\frac{1}{n(n+1)} = \frac{1}{n} -\frac{1}{n+1}$$ The series therefore telescopes, making the sum easy to compute. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/462047', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11921/']} | jdg_86691 |
stackexchange | llm_judgeable_groundtruth_similarity | 84052 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an old laptop with far too little RAM to run Linux (including specialty distributions). It can however run Windows 98 just fine, and I'm looking into turning it into a tiny retro webserver. Is it possible to keep an old operating system webserver from being hacked? All I'm looking for is a simple port 80 static website with no over-the-web administration abilities. I have no significant experience with security, or exploiting security holes. So I'm not sure where to look. Can a DOS/WIN95/WIN98 box be exploited if all it does is respond to simple HTTP requests?
Now provide the response and nothing else.
| Probably not. In order to respond to HTTP requests, the operating system must be able to run a TCP/IP stack, process packets, and complete a TCP handshake, all requiring the system to utilize or spawn threads in memory, call libraries, etc. Therefore, the system would still be susceptible to protocol attacks it may not be patched for (TCP sequence prediction is one that comes to mind for a web server that might run on Win98). You could compile and run a modern server like nginx or Apache (probably would have to heavily modify it, as it won't run on Win98 out of the box), but older operating systems being on a network are inherently prone to network probing and network attacks. Even if TCP 80 were port forwarded through a firewall, the web server process would still be running inside of a system lacking modern protections like DEP, ASLR, etc. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/84052', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/70635/']} | jdg_86692 |
stackexchange | llm_judgeable_groundtruth_similarity | 183046 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What does $\dot\sim$ notation (dot over tilde) mean, in the context like $x \mathrel{\dot\sim} \mathcal N(0,1)$? Turns out it is easier to find how to typeset it correctly: tex.SE explains that one should type \mathrel{\dot\sim} instead of simply \dot\sim to fix the spacing issue -- than to find what it actually means. It has only been used 4 times on CV until now; is it standard?
Now provide the response and nothing else.
| Unless there was some other clue as to the intended meaning, I'd interpret that as "is approximately distributed as". It's fairly standard. Note that some of the other usual ways of indicating "approximation" by modifying a symbol don't really work with $\sim$. Note that $\sim$ can be read as "is distributed as" and that adding the dot over a symbol at least sometimes indicates approximation -- compare $=$ with $\mathrel{\dot =}$. So "$x \mathrel{\dot\sim} \mathcal N(0,1)$" could be read something like "$x$ is approximately distributed as standard normal". Personally, I don't mind the closer spacing in \dot\sim ($\dot\sim$) for that use. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/183046', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/28666/']} | jdg_86693 |
stackexchange | llm_judgeable_groundtruth_similarity | 28342660 |
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 small program where i initialize a string and write to a file stream: #include<iostream>#include<fstream>using namespace std;int main(){ std::ofstream ofs(file.c_str()); string s="Hello how are you"; if(ofs) ofs<<s; if(!ofs) { cout<<"Writing to file failed"<<endl; } return 0; } My diskspace is very less, and the statement " ofs< " fails. So I know that this is an error logically. The statement "if(!ofs)" does not encounter the above issue, hence I am unable to know why it failed. Please tell me, by which other options I would be able to know that "ofs< has failed. Thanks in advance.
Now provide the response and nothing else.
| In principle, if there is a write error, badbit should be set. Theerror will only be set when the stream actually tries to write, however,so because of buffering, it may be set on a later write than when the error occurs, or even afterclose. And the bit is “sticky”, so once set, it will stayset. Given the above, the usual procedure is to just verify the status of theoutput after close; when outputting to std::cout or std::cerr , afterthe final flush. Something like: std::ofstream f(...);// all sorts of output (usually to the `std::ostream&` in a// function).f.close();if ( ! f ) { // Error handling. Most important, do _not_ return 0 from // main, but EXIT_FAILUREl.} When outputting to std::cout , replace the f.close() with std::cout.flush() (and of course, if ( ! std::cout ) ). AND: this is standard procedure. A program which has a return code of 0(or EXIT_SUCCESS ) when there is a write error is incorrect. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28342660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2168706/']} | jdg_86694 |
stackexchange | llm_judgeable_groundtruth_similarity | 337773 |
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 ordered an STM32F4xx board to use it in an embedded systems class a couple months ago. It has arrived yesterday and I figured out it does not have the ST Link module included. How can I program it? I understand I can get an STLink module, but i would like to know if there is another way.
Now provide the response and nothing else.
| While you can use the serial or (on the `407 USB or several other interfaces) bootloader, realistically, you should get a cheap SWD adapter. You can even use a Discovery board for any SMT32 variant for this purpose, if you remove the jumpers that connect the stlink to the on-board target. While the bootloader gets you only code loading, the SWD interface (with any of ST's Windows software, or on Linux/Mac either of Texane's open source tool, or OpenOCD) gets you code loading and the ability to have a breakpoint debugger. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/337773', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/162247/']} | jdg_86695 |
stackexchange | llm_judgeable_groundtruth_similarity | 36603042 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I came across some code with a line similar to x[x<2]=0 Playing around with variations, I am still stuck on what this syntax does. Examples: >>> x = [1,2,3,4,5]>>> x[x<2]1>>> x[x<3]1>>> x[x>2]2>>> x[x<2]=0>>> x[0, 2, 3, 4, 5]
Now provide the response and nothing else.
| This only makes sense with NumPy arrays . The behavior with lists is useless, and specific to Python 2 (not Python 3). You may want to double-check if the original object was indeed a NumPy array (see further below) and not a list. But in your code here, x is a simple list. Since x < 2 is Falsei.e 0, therefore x[x<2] is x[0] x[0] gets changed. Conversely, x[x>2] is x[True] or x[1] So, x[1] gets changed. Why does this happen? The rules for comparison are: When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers). When you order a numeric and a non-numeric type, the numeric type comes first. When you order two incompatible types where neither is numeric, they are ordered by the alphabetical order of their typenames: So, we have the following order numeric < list < string < tuple See the accepted answer for How does Python compare string and int? . If x is a NumPy array , then the syntax makes more sense because of boolean array indexing . In that case, x < 2 isn't a boolean at all; it's an array of booleans representing whether each element of x was less than 2. x[x < 2] = 0 then selects the elements of x that were less than 2 and sets those cells to 0. See Indexing . >>> x = np.array([1., -1., -2., 3])>>> x < 0array([False, True, True, False], dtype=bool)>>> x[x < 0] += 20 # All elements < 0 get increased by 20>>> xarray([ 1., 19., 18., 3.]) # Only elements < 0 are affected | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36603042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6107054/']} | jdg_86696 |
stackexchange | llm_judgeable_groundtruth_similarity | 2406780 |
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 inspired by/taken from this thread: http://www.allegro.cc/forums/thread/603383 The Problem Assume the user gives you a numeric input ranging from 1 to 7. Input should be taken from the console, arguments are less desirable. When the input is 1, print the following: *********** ********* ******* ***** *** * Values greater than one should generate multiples of the pattern, ending with the one above, but stacked symmetrically. For example, 3 should print the following: *********** *********** *********** ********* ********* ********* ******* ******* ******* ***** ***** ***** *** *** *** * * * *********** *********** ********* ********* ******* ******* ***** ***** *** *** * * *********** ********* ******* ***** *** * Bonus points if you print the reverse as well. *********** *********** ********* ********* ******* ******* ***** ***** *** *** * * *********** ********* ******* ***** *** * * *** ***** ******* ********* *********** * * *** *** ***** ***** ******* ******* ********* ********* *********** *********** Can we try and keep it to one answer per language, that we all improve on?
Now provide the response and nothing else.
| Assembler, 165 bytes assembled Build Instructions Download A86 from here Add a reference to the A86 executable into your DOS search path Paste the code below into a text file (example: triforce.asm ) Invoke the assembler: a86 triforce.asm This will create a .COM file called triforce.com Type triforce to run This was developed using the standard WinXP DOS box (Start->Programs->Accessories->Command Prompt). It should work with other DOS emulators. Assemble using A86 and requires WinXP DOS box to run the .COM file it produces. Press 'q' to exit, keys 1-7 to draw the output. l20:mov ah,7 int 21h cmp al,'q' je ret sub al,'0' cmp al,1 jb l20 cmp al,7 ja l20 mov [l0-1],al mov byte ptr [l7+2],6 jmp $+2 mov ah,2 mov ch,0 mov bh,3 l0:mov bl,1 l1:mov dh,0 l3:cmp dh,ch je l2 mov dl,32 int 21h inc dh jmp l3 ret l2:mov dh,bh l6:mov cl,12 l5:mov dl,42 cmp cl,bl ja l4 mov dl,32 cmp dh,1 je l21 l4:int 21h dec cl jnz l5 l21:dec dh jnz l6 mov dl,10 int 21h mov dl,13 int 21h l10:inc ch l9:add bl,2 l7:cmp ch,6 jne l1 l13:add byte ptr [l7+2],6 l11:dec bh l12:cmp bh,0 jne l0 xor byte ptr [l0+1],10 xor byte ptr [l9+1],40 xor byte ptr [l10+1],8 xor byte ptr [l13+1],40 sub byte ptr [l7+2],12 mov dh,[l0-1] inc dh xor [l12+2],dh xor byte ptr [l11+1],8 xor byte ptr [l1+1],1 inc bh cmp byte ptr [l0+1],11 je l0 jmp l20 It uses lots of self-modifying code to do the triforce and its mirror, it even modifies the self-modifying code. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2406780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188512/']} | jdg_86697 |
stackexchange | llm_judgeable_groundtruth_similarity | 180254 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $k$ be a number field and $S$ be a finite set of places of $k$.Let $G$ be a connected semisimple algebraic group over $k$.Let $k_S=\prod_{v\in S}k_v$where $k_v$ is the completion of $k$ at $v$. Question: Is maximal compact subgroup of $G(k_S)$ unique up to conjugation?If it is not unique, are there finitely many of them up to conjugation?
Now provide the response and nothing else.
| Since the maximal compact subgroup question has a complicated history, and is treated at very different levels of generality in the literature (Bruhat-Tits papers in particular), it may be helpful to fill in Paul's answer a bit. There was early work in special cases by Bruhat over half a century ago, in the aftermath of Chevalley's uniform 1955 construction of split groups over an arbitrary field coming from simple Lie algebras over $\mathbb{C}$. But the clearest picture began to emerge from the important 1965 paper by Iwahori and Matsumoto (see in particular their Prop. 2.32): here . In this approach and the further work of Bruhat-Tits one considers in particular a simple, simply connected algebraic group $G$ such as $\mathrm{SL}_n$ defined over a complete non-archimedian field $K$, obtaining a $(B,N)$-pair structure and Bruhat decomposition which leads eventually to a determination of the conjugacy classes of maximal compact subgroups of $G(K)$ (which are maximal "parahoric" subgroups): the number of these is $\ell +1$, where $\ell$ is the $K$-rank of $G$. The minimal "parahoric" subgroups are themselves all conjugate. Here the usual Weyl group is expanded to an affine (or extended affine) Weyl group. The later papers by Bruhat and Tits develop such ideas in vast generality, but as early as 1966 their announcements of results show clearly the direction in which they were going. To state the technical results for $G(k_S)$ in the question here takes some care, but the basic example cited by Paul shows how the $\ell+1$ arises (the rank in his split example being $n-1$). As Paul indicates, a direct computation can be done in the smallest case $\mathrm{SL}_2$. See for example the end of $\S15$ in my old Springer Lecture Notes 789 on arithmetic groups, where the Bruhat-Tits building appears as simply a tree and Serre's ideas about groups acting on trees can be used. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/180254', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11056/']} | jdg_86698 |
stackexchange | llm_judgeable_groundtruth_similarity | 33612935 |
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 accessing a very large Pandas dataframe as a global variable. This variable is accessed in parallel via joblib . Eg. df = db.query("select id, a_lot_of_data from table")def process(id): temp_df = df.loc[id] temp_df.apply(another_function)Parallel(n_jobs=8)(delayed(process)(id) for id in df['id'].to_list()) Accessing the original df in this manner seems to copy the data across processes. This is unexpected since the original df isnt being altered in any of the subprocesses? (or is it?)
Now provide the response and nothing else.
| The entire DataFrame needs to be pickled and unpickled for each process created by joblib. In practice, this is very slow and also requires many times the memory of each. One solution is to store your data in HDF ( df.to_hdf ) using the table format. You can then use select to select subsets of data for further processing. In practice this will be too slow for interactive use. It is also very complex, and your workers will need to store their work so that it can be consolidated in the final step. An alternative would be to explore numba.vectorize with target='parallel' . This would require the use of NumPy arrays not Pandas objects, so it also has some complexity costs. In the long run, dask is hoped to bring parallel execution to Pandas, but this is not something to expect soon. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33612935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3066956/']} | jdg_86699 |
stackexchange | llm_judgeable_groundtruth_similarity | 1841365 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
currently we are developing an app in which we use database table to store platform settings, like maximum file size, maximum users number, support email, etc. it means that each time we add a platform setting we have to add a column to this table. in my previous projects i am used to store such information in file. what is better/faster approach? ps, i am almost sure someone already had such question, but i can't seem to find it
Now provide the response and nothing else.
| We store config settings in a key/value type table, something like: CREATE TABLE Configuration.GlobalSettings( SectionName VARCHAR(50), SettingName VARCHAR(50), SettingValue VARCHAR(1000), SettingType TINYINT); The SectionName & SettingName are the primary key, we just split them up to make it easier to query what is in a section, and to allow the loading of individual sections into handlers rather than loading the whole lot at once. The SettingValue is a string, and then the SettingType is a discriminator that tells us how the setting value should be interpreted (e.g. 1 = string, 2 = bool, 3 = decimal, etc.). This means you don't have to change the table structure for new settings, just add a new one in the deployment script or wherever it is you set these things up. We find it a better way do do config than a file because it means you can easily programmatically change config values through an admin interface when needed, which can enforce logic around what can go into each setting. You can't do that so easily with a file (though, of course, it is possible). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1841365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131618/']} | jdg_86700 |
stackexchange | llm_judgeable_groundtruth_similarity | 42014195 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to make a game and I am trying to render a lot of text. When the text renders, the rest of the text goes off the screen. Is there any easy way to make the text go to the next line of the pygame window? helpT = sys_font.render \ ("This game is a combination of all of the trends\n of 2016. When you press 'Start Game,' a menu will pop up. In order to beat the game, you must get a perfect score on every single one of these games.",0,(hecolor)) screen.blit(helpT,(0, 0))
Now provide the response and nothing else.
| As I said in the comments; you have to render each word separately and calculate if the width of the text extends the width of the surface (or screen). Here's an example: import pygamepygame.init()SIZE = WIDTH, HEIGHT = (1024, 720)FPS = 30screen = pygame.display.set_mode(SIZE, pygame.RESIZABLE)clock = pygame.time.Clock()def blit_text(surface, text, pos, font, color=pygame.Color('black')): words = [word.split(' ') for word in text.splitlines()] # 2D array where each row is a list of words. space = font.size(' ')[0] # The width of a space. max_width, max_height = surface.get_size() x, y = pos for line in words: for word in line: word_surface = font.render(word, 0, color) word_width, word_height = word_surface.get_size() if x + word_width >= max_width: x = pos[0] # Reset the x. y += word_height # Start on new row. surface.blit(word_surface, (x, y)) x += word_width + space x = pos[0] # Reset the x. y += word_height # Start on new row.text = "This is a really long sentence with a couple of breaks.\nSometimes it will break even if there isn't a break " \ "in the sentence, but that's because the text is too long to fit the screen.\nIt can look strange sometimes.\n" \ "This function doesn't check if the text is too high to fit on the height of the surface though, so sometimes " \ "text will disappear underneath the surface"font = pygame.font.SysFont('Arial', 64)while True: dt = clock.tick(FPS) / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: quit() screen.fill(pygame.Color('white')) blit_text(screen, text, (20, 20), font) pygame.display.update() Result | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42014195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7508602/']} | jdg_86701 |
stackexchange | llm_judgeable_groundtruth_similarity | 52477389 |
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 move multiple markers on google map and each in separate thread. Currently I am using java thread class inside loop to create separate thread for each vehicle. Here is the sample code: private void proceedToMoveVehicle(ArrayList<RealTimeDetailsResponce> sourceList, ArrayList<RealTimeDetailsResponce> destinationList) { for (int i = 0; i < destinationList.size(); i++) { for (int j = 0; j < sourceList.size(); j++) { if (destinationList.get(i).getVehicleNo().equalsIgnoreCase(sourceList.get(j).getVehicleNo())) { final com.google.maps.model.LatLng vehicleStartPositions = new com.google.maps.model.LatLng(sourceList.get(j).getLatitude(), sourceList.get(j).getLongitude()); final double destainationLatitude = destinationList.get(i).getLatitude(); final double destainationLongitude = destinationList.get(i).getLongitude(); final String vehicleTitle = sourceList.get(j).getVehicleNo(); final com.google.maps.model.LatLng vehicleEndPositions = new com.google.maps.model.LatLng(destainationLatitude, destainationLongitude); final double speedValue = 0.0000; if (vehicleStartPositions.lat != vehicleEndPositions.lat || vehicleStartPositions.lng != vehicleEndPositions.lng) { Thread thread = new Thread(new Runnable() { @Override public void run() { getPathyFromDirectionAPiRequestNew(vehicleStartPositions, vehicleEndPositions, vehicleTitle); runOnUiThread(new Runnable() { @Override public void run() { moveVehicle(vehicleTitle, speedValue); } }); } }); thread.start(); } } } }} I am getting vehicle's updated location from server after every 5 seconds. Here, the draw back is I'm not able to reuse these threads again once i get the updated location and again I have to create a new thread. I have heard about android handler thread, in that we can reuse a thread using Looper. Can someone help me to do this with handler thread.
Now provide the response and nothing else.
| It appears you are using the ngrx-store-freeze npm package. This package ensures that any updates you make to the store are not mutated directly. Part of this process is to apply an Object.freeze() to the payload object of the action you are attempting to dispatch. i.e. this.store.dispatch(new UploadFiles(file)) . Default behavior for the <input type="file"> control is to save it's value as a FileList object. Because this object is a primitive data type, Javascript will treat it as read-only, thus preventing you from writing to it's properties. This also explains why Object.freeze() fails, as it cannot apply a freeze to a read only data type. I experienced the same issue recently using NGRX and the <input type="file"> form control. The fix was to clone the FileList into a new object before dispatching to the store. onChange(control: FormControl) { const primitiveFileList: FileList = control.value; const clonedFiles = { ...primitiveFileList }; this.store.dispatch(new UploadFiles(clonedFiles));} If anyone else knows any potential downfalls to this approach, I'd appreciate your input. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52477389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7562784/']} | jdg_86702 |
stackexchange | llm_judgeable_groundtruth_similarity | 43195987 |
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 mixins configured in my objectmapperbuilder config, using the regular spring web controller, the data outputted according to the mixins.However using webflux, a controller with a method returning a Flow or Mono have the data serialized like if the objectmapper a default one. How to get webflux to enforce an objectmapper configuration to be used ? sample config: @BeanJavaTimeModule javatimeModule(){ return new JavaTimeModule();}@BeanJackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(){return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .mixIn(MyClass.class, MyClassMixin.class);}
Now provide the response and nothing else.
| I actually found my solution by stepping through the init code: @Configurationpublic class Config { @Bean JavaTimeModule javatimeModule(){ return new JavaTimeModule(); } @Bean Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(){ return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .mixIn(MyClass.class, MyClassMixin.class); } @Bean Jackson2JsonEncoder jackson2JsonEncoder(ObjectMapper mapper){ return new Jackson2JsonEncoder(mapper); } @Bean Jackson2JsonDecoder jackson2JsonDecoder(ObjectMapper mapper){ return new Jackson2JsonDecoder(mapper); } @Bean WebFluxConfigurer webFluxConfigurer(Jackson2JsonEncoder encoder, Jackson2JsonDecoder decoder){ return new WebFluxConfigurer() { @Override public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { configurer.defaultCodecs().jackson2JsonEncoder(encoder); configurer.defaultCodecs().jackson2JsonDecoder(decoder); } }; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43195987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1568967/']} | jdg_86703 |
stackexchange | llm_judgeable_groundtruth_similarity | 62330 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I realize this should be a fairly basic question, but I'm still not quite satisfied with what I've been told from numerous sources. The general explanation seems to state that as we go down a group, there are more electron shells present to contribute to a "shielding" phenomenon, where inner electrons cancel out part of the inward force from the nucleus with a repulsive force. Thus with more energy levels present and more shielding, valence electrons begin to reside further and further away from the nucleus. But at the same time, textbooks make a big deal about the concept of effective nuclear charge, which states that the "effective" force a given valence electron feels is a function of the net charge of the nucleus and non-valence electrons combined—the effective nuclear charge. I find this contradictory, since as we go down a group, the effective nuclear charge remains constant (equal numbers of protons and non-valence electrons are added). So what am I missing here? Why does shielding matter? Is the force on a single valence electron a function of the net nuclear charge or do we have to look at it from a more piecewise level, considering how other electrons are in between it and the nucleus and how it interacts with those individual electrons?
Now provide the response and nothing else.
| The description of $Z_\mathrm{eff}$ you gave is a bit too simplistic. As you correctly said, that would predict the same value of $Z_\mathrm{eff}$ for all elements in a group, which is not true. In general we have $Z_\mathrm{eff} = Z - \sigma$ where $Z$ is the nuclear charge (that solely depends on the number of protons) and $\sigma$ is the shielding constant, which reflects the electron-electron repulsions but is not a simple function of the number of core electrons. One of the earliest models to determine $\sigma$ was described by Slater in 1930. 1 These are easily found online as "Slater's rules" . These are quite simplistic, and so people tried to find better ways to calculate $\sigma$. Nowadays, one very popular source for values of $Z_\mathrm{eff}$ are the Clementi values. 2 That's still quite long ago, so you can imagine that since then, we have come up with even more complicated ways to calculate it. A peculiarity is that the values of $Z_\mathrm{eff}$ actually increase down the group. At the very least, that should dispel the myth that $Z_\mathrm{eff}$ only depends on the number of core electrons. (Source: Keeler & Wothers, Chemical Structure & Reactivity: An Integrated Approach , p 264 ) "Surely that should mean that the atomic radii decrease down the group!" you say. I don't fault you for thinking that at all. However, that's not what we see: the atomic radii clearly increase going down the group. The second factor is the principal quantum number, $n$. In the hydrogen atom, an electron in the 1s orbital has a much smaller radius 3 than an electron in the 2s orbital. That's something that comes right out of the quantum mechanical description of the hydrogen atom. 4 The same can be said for other atoms: a 2s orbital in lithium is smaller than a 3s orbital in lithium. Note that I didn't compare a 2s orbital in lithium with a 3s orbital in sodium. Why? That's because sodium has a larger effective nuclear charge, and this serves to contract all the orbitals in sodium relative to those in lithium. Essentially, the orbitals are pulled inwards by the larger $Z_\mathrm{eff}$. So, as you can see, going from lithium to sodium, there are two competing factors: Larger $n$ suggests that the outermost electron should be further away from the nucleus. Larger $Z_\mathrm{eff}$ suggests that the outermost electron should be nearer to the nucleus. Unsurprisingly, it turns out that the variation of atomic radius is dependent on a combination of the two. We know that the atomic radius increases going down the group, so that must mean that the increase in $n$ (going from 2 to 3) outweighs the increase in $Z_\mathrm{eff}$ (going from 1.28 to 2.51), although it's sadly difficult to find an exact mathematical formulation in any textbook. It's likely that the exact dependency is very complicated and nowadays, such atomic properties are mostly calculated computationally anyway, which removes the need for such a mathematical formula. Notes and references 1 Phys. Rev. 1930, 36 (1), 57 2 J. Chem. Phys. 1963, 38, 2686 3 I'm talking about $\langle r \rangle$, not the radius of a Bohr orbit, although that does also increase going from 1s to 2s. 4 I'm avoiding the circular logic that "higher energy means further away". It is further away because that is just the form of the radial wavefunction obtained by solving the Schrodinger equation - period. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/62330', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/17271/']} | jdg_86704 |
stackexchange | llm_judgeable_groundtruth_similarity | 27710585 |
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 in ajax/JS/jQuery. I have an ajax call that checks if a file is available on server. To accomplish this I use setInterval() and clearInterval(). I am having trouble in setting the display property to an html element upon successful ajax call. Any guidance is highly appreciated. <html><head></head><body ><div id="export-div" hidden>Click Me</div><script type="text/javascript"> function foo_func() { $('#export-div').show(); //*****tried, but does not work******* var foo = document.getElementById("export-div"); foo.style.display = "block"; // **********Does not work*************** alert(foo.innerHTML); //Alert box correctly pops up with text 'Click Me' clearInterval(timerForLoadingResult); //I initially had this inside the ajax success/done function }</script><script type="text/javascript"> var timerForLoadingResult = setInterval(checkServerForFile,5000); //call the function in every 5 seconds and write ajax in that function. function checkServerForFile() { var chck = $.ajax("<?php echo "/Results/".$filename; ?>") //searches for a file on server chck.success(function(){ alert( "Ajax call successful" ); //This alert box also pops up foo_func(); }); };</script></body></html>
Now provide the response and nothing else.
| As @SLaks mentioned I didn't need a MemoryStream, the problem with my code was the path and the filename for further help this is the working code: if (newItem.FieldType == FormFieldType.Signature){ if (newItem.ItemValue != null) { //string completeImageName = Auth.host + "/" + li[i]; string path; string filename; string stringName = newItem.ItemValue; var base64Data = Regex.Match(stringName, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value; var binData = Convert.FromBase64String(base64Data); path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //filename = Path.Combine(path, base64Data.Replace(@"/", string.Empty)); long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; string fileName = "Sn" + milliseconds.ToString() + ".PNG"; filename = Path.Combine(path, fileName); if (!File.Exists(filename)) { //using (var stream = new MemoryStream(binData)) //{ File.WriteAllBytes(filename, binData); //} } newItem.ItemValue = filename; }}App.Database.SaveReportItem(newItem); And the image showed: | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27710585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3779193/']} | jdg_86705 |
stackexchange | llm_judgeable_groundtruth_similarity | 37460592 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why some developers create one method that returns new static ? What is the reason to have a method that returns new static ? I am not asking what is the difference between static and self, or what static & self mean. For example, here is one simple class: <?phpclass Expression{ public static function make() { return new static; } public function find($value) { return '/' . $value .'/'; } public function then($value) { return $this->find($value); } public function hi($value) { return "hi"; }} As you can see, there is a static method make() which returns new static . Then, some developers call other methods like this: $regex = Expression::make()->find('www'); What is the purpose of this? I see that here we don't use new Expression syntax, and if that's the point - then why not make all methods static? What is the difference, what is the reason to have that one method that returns new static (while other methods are not static)?
Now provide the response and nothing else.
| new static instantiates a new object from the current class, and works with late static bindings (instantiates the subclass if the class was subclassed, I expect you understand that). Having a static method on a class which returns a new instance of same is an alternative constructor . Meaning, typically your constructor is public function __construct , and typically it requires a certain bunch of parameters: class Foo { public function __construct(BarInterface $bar, array $baz = []) { ... }} Having an alternative constructor allows you to provide different defaults, or convenience shortcuts to instantiate this class without having to supply those specific arguments and/or for being able to provide different arguments which the alternative constructor will convert to the canonical ones: class Foo { public function __construct(BarInterface $bar, array $baz = []) { ... } public static function fromBarString($bar) { return new static(new Bar($bar)); } public static function getDefault() { return new static(new Bar('baz'), [42]); }} Now, even though your canonical constructor requires a bunch of complex arguments, you can create a default instance of your class, which will probably be fine for most uses, simply with Foo::getDefault() . The canonical example in PHP for this is DateTime and DateTime::createFromFormat . In your concrete example the alternative constructor doesn't actually do anything, so it's rather superfluous, but I expect that's because it's an incomplete example. If there's indeed an alternative constructor which does nothing other than new static , it's probably just meant as convenience syntax over (new Foo)-> , which I find questionable. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37460592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4437206/']} | jdg_86706 |
stackexchange | llm_judgeable_groundtruth_similarity | 1045 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As my textbook An Introduction to Genetic Analysis points out, yeast mitochondrial DNA has approximately 78 kb of genetic data, while the human mitochondrial DNA contains 17 kb. Is there any evolution reason for this drastic change in size? Also, are there any particularities about mitochondrial function that have been compromised with this reduction in size? References Griffiths, Anthony J. F. An Introduction to Genetic Analysis. New York: W.H. Freeman, 2000.
Now provide the response and nothing else.
| One of the contributing factors the size of the yeast mitochondrial genome are 'selfish' mobile genetic elements termed homing endonucleases genes (HEGs). These genes are typically found in introns that encode site-specific DNA endonucleases. These endnoclueases cleave the HEG - alleles during yeast mating leading to DNA recombination using the HEG + allele as template. I suspect over time as organisms became more complex and HEGs become unable to mobilize they would become fixed in the organisms genome. Upon being fixed there is no selection pressure to maintain the open reading frame of the HEG or the intron its encoded within ( ref ). This causes the eventual loss of the HEG and intron since they provide no real benefit to the organisms genome. I don't know how much of the yeast mitochondrial genome is taken up by these introns. I believe that there are 4 of them in yeast some of the introns also require reverse transcriptase for splicing and mobility. Other fungal species can have many more introns and sometimes weird things like introns embedded within introns. | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/1045', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/307/']} | jdg_86707 |
stackexchange | llm_judgeable_groundtruth_similarity | 1237736 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to understand the proof behind showing a set is a subset of another set, but I'm struggle to do so. Can some one help using this example to show: $A \subseteq B$? Here $A = \{x | x = 4n + 3, n \in \mathbb{N}\}$, $B = \{x | x = 2n+1, n \in \mathbb{N}\}$.
Now provide the response and nothing else.
| It doesn't hold that $B \subseteq A$, but $A \subseteq B$. In order to show this, we pick a $x \in A$. Then $x$ is of the form $x=4n+3$ for some $n \in \mathbb{N}$. $x=4n+3=2(2n+1)+1$. $n \in \mathbb{N}$, so $2n+1$ also belongs to $\mathbb{N}$. So $x$ is of the form $2m+1, m \in \mathbb{N}$ and thus $x \in B$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1237736', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/191620/']} | jdg_86708 |
stackexchange | llm_judgeable_groundtruth_similarity | 1602479 |
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:
Two particles of mass $m$ can move smoothly along the $x$-axis and are connected by a spring of natural length $l$ and spring constant $k$. Here are the questions and my proposed answers. I'm stuck on the last question. I really hope you can help me. 1) If the coordinates of the particles are $x_1$ and $x_2$, show that the potential energy stored in the spring is $\frac{1}{2}k(\space x_2-x_1-l)^2$. Answer: $PE_{spring}=\frac{1}{2}kx^2$ where $x$ is the extension of the spring relative to equilibrium. $$x=(x_2-x_1-l)$$$$\implies \space V=\frac{1}{2}k(\space x_2-x_1-l)^2 .$$ 2) Hence deduce the Lagrangian of the system. Answer: $L=T-V$ where $T$= kinetic energy.$$T=\frac{1}{2}m(\dot {x}_1^2 +\dot {x}_2^2)$$ Substituting into $L=T-V$ we have $$L=\frac{1}{2}m(\dot {x}_1^2 +\dot {x}_2^2)-\frac{1}{2}k(x_2-x_1-l)^2.$$ 3) Write down the Lagrange equations of motion and show that the general solution satisfies the condition $x_1+x_2=Ct +D, x_1-x_2=-l+A\cos(\omega t)+B\sin(\omega t)$ where $\omega =\sqrt{\frac{2k}{m}}$. And hence describe the motion of the system. I'm really stuck on this question. Any help would be much appreciated.
Now provide the response and nothing else.
| Don’t worry, it is a bit complicated.We’re getting rid of cos4x so we could substitute t=cos2x. \begin{equation} \int \frac{dx}{cos4x\cdot sin2x}=\int \frac{sin2xdx}{\left ( 2cos^{2}2x-1\right )sin^{2}2x}=\begin{vmatrix}t=cos2x & \\ dt=-2sin2xdx & \end{vmatrix}=\int \frac{-\frac{1}{2}dt}{\left ( 2t^{2}-1 \right )\left ( 1-t^{2} \right )}=\frac{1}{4}\int\frac{dt}{\left ( t^{2}-\frac{1}{2} \right )\left ( t^{2}-1 \right )}\end{equation}Now we have integral with rational function so we separate it into two fractions:\begin{equation}\frac{1}{4}\int\frac{dt}{\left ( t^{2}-\frac{1}{2} \right )\left ( t^{2}-1 \right )}=\frac{1}{2}\left ( \int \frac{dt}{t^{2}-1} -\int \frac{dt}{t^{2}-\frac{1}{2}}\right )=\frac{1}{2}\left [ \frac{1}{2}\left ( \int \frac{dt}{t-1} -\int \frac{dt}{t+1}\right )-\frac{\sqrt{2}}{2}\left ( \int \frac{dt}{t-\frac{1}{\sqrt{2}}} -\int \frac{dt}{t+\frac{1}{\sqrt{2}}}\right ) \right ]=\frac{1}{4}\left ( ln\left | t-1 \right |- ln\left | t+1 \right |\right )-\frac{\sqrt{2}}{4}\left (ln\left | t-\frac{1}{\sqrt{2}} \right |- ln\left | t+\frac{1}{\sqrt{2}} \right | \right )+C=\frac{1}{4}ln\left | \frac{t-1}{t+1} \right |-\frac{\sqrt{2}}{4}ln\left | \frac{t-\frac{1}{\sqrt{2}}}{t+\frac{1}{\sqrt{2}}} \right |+C\end{equation}So in the end, we have:\begin{equation}\int \frac{dx}{cos4x\cdot sin2x}=\frac{1}{4}ln\left | \frac{cos2x-1}{cos2x+1} \right |-\frac{\sqrt{2}}{4}ln\left | \frac{cos2x-\frac{1}{\sqrt{2}}}{cos2x+\frac{1}{\sqrt{2}}} \right |+C\end{equation} | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1602479', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/295970/']} | jdg_86709 |
stackexchange | llm_judgeable_groundtruth_similarity | 19336150 |
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 multiply the contents of a list <double> ? List<double> mult=new List<double>{3, 5, 10}; So far I have: double r=0.0;for(int i=0;i<mult.Count;i++){ r=mult[i]*mult[(i+1)];}
Now provide the response and nothing else.
| To fix your loop, start with 1.0 and multiply each item in the list, like this: double r = 1.0;for(int i = 0; i < mult.Count; i++){ r = r * mult[i]; // or equivalently r *= mult[i];} But for simplicity, you could use a little Linq with the Aggregate extension method: double r = mult.Aggregate((a, x) => a * x); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19336150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2469027/']} | jdg_86710 |
stackexchange | llm_judgeable_groundtruth_similarity | 4562012 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to make hyper link <a>Link</a> a double click link: i:e link should open on double click and single click should do nothing.
Now provide the response and nothing else.
| Okay, so, you can do this: HTML: <a id='golink' href='gosomewhere.html'>Go Somewhere</a> JavaScript using jQuery: jQuery(function($) { $('#golink').click(function() { return false; }).dblclick(function() { window.location = this.href; return false; });}); Live copy: jQuery(function($) { $('#golink').click(function() { return false; }).dblclick(function() { window.location = this.href; return false; });}); <a id='golink' href='http://stackoverflow.com' target="_blank">Go Somewhere</a><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> (It doesn't have to be an ID; you can do this with a class or anything else that lets you form a selector that jQuery can process to hook things up.) If the user has JavaScript disabled, the link will work normally. Crawlers will find the link normally, etc. If a user has JavaScript enabled, the event handlers will get hooked up and it will require a double click. The above blows away keyboard navigation, though, so then you have to handle that: jQuery(function($) { $('#golink').click(function() { return false; }).dblclick(function() { window.location = this.href; return false; }).keydown(function(event) { switch (event.which) { case 13: // Enter case 32: // Space window.location = this.href; return false; } });}); Live copy: jQuery(function($) { $('#golink').click(function() { return false; }).dblclick(function() { window.location = this.href; return false; }).keydown(function(event) { switch (event.which) { case 13: // Enter case 32: // Space window.location = this.href; return false; } });}); <a id='golink' href='http://stackoverflow.com' target="_blank">Go Somewhere</a><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> I can't imagine this is good for accessibility, and I bet there are other things not catered for above. Which all feeds into: But I'd strongly recommend against doing it without a really good use case. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4562012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253169/']} | jdg_86711 |
stackexchange | llm_judgeable_groundtruth_similarity | 17810 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I apply M-; to comments out blocks in matlab-mode? Currently it only adds comments at the end of line. Thanks!
Now provide the response and nothing else.
| Q : " However, what I'd like to do is customize the ellipsis so that it takes the same face as the outline header it is on. How would one do that? " A : This cannot be done using the buffer-display-table . It's an all or nothing type of deal -- i.e., a change to the buffer-display-table affects everything in the buffer, not merely a particular heading. It is possible to create a different custom overlay for each heading, but it may not be very efficient -- in that case, the display slot 4 would not be used. Here is an example of what is going on behind the scenes when setting the face for the ellipsis in either outline-mode or org-mode . The display engine of Emacs has built-in support for text with invisible property at the end of the line, which can be visualized via the buffer-display-table . For more information about this special slot, type: M-x describe-variable RET buffer-display-table RET (let ((display-table (if buffer-display-table buffer-display-table (make-display-table)))) (unless buffer-display-table (setq buffer-display-table display-table)) (set-display-table-slot display-table 4 (vconcat (mapcar (lambda (c) (make-glyph-code c 'font-lock-keyword-face)) "...")))) | {} | {'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/17810', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/10018/']} | jdg_86712 |
stackexchange | llm_judgeable_groundtruth_similarity | 25583038 |
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 build a Docker image without docker itself. I have looked at [Packer]( http://www.packer.io/docs/builders/docker.html , but it requires that Docker be installed on the builder host. I have looked at the Docker Registry API documentation but this information doesn't appear to be there. I guess that the image is simply a tarball, but I would like to see a complete specification of the format, i.e. what exact format is required and whether there are any metadata files required. I could attempt downloading an image from the registry and look what's inside, but there is no information on how to fetch the image itself. The idea of my project is to implement a script that creates an image from artifacts I have compiled, and uploads it to the registry. I would like to use OpenEmbedded for this purpose, essentially this would be an extension to Bitbake.
Now provide the response and nothing else.
| After reading James Coyle's blog , I figured that docker save and docker load commands are what I need. > docker imagesREPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZEprogrium/consul latest e9fe5db22401 11 days ago 25.81 MB> docker save e9fe5db22401 | tar x> ls e9fe5db22401*VERSION json layer.tar The VERSION file contains only 1.0 , and json contains quite a lot of information: { "id": "e9fe5db224015ddfa5ee9dbe43b414ecee1f3108fb6ed91add11d2f506beabff", "parent": "68f9e4929a4152df9b79d0a44eeda042b5555fbd30a36f98ab425780c8d692eb", "created": "2014-08-20T17:54:30.98176344Z", "container": "3878e7e9b9935b7a1988cb3ebe9cd45150ea4b09768fc1af54e79b224bf35f26", "container_config": { "Hostname": "7f17ad58b5b8", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 0, "Cpuset": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "ExposedPorts": { "53/udp": {}, "8300/tcp": {}, "8301/tcp": {}, "8301/udp": {}, "8302/tcp": {}, "8302/udp": {}, "8400/tcp": {}, "8500/tcp": {} }, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "HOME=/", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "SHELL=/bin/bash" ], "Cmd": [ "/bin/sh", "-c", "#(nop) CMD []" ], "Image": "68f9e4929a4152df9b79d0a44eeda042b5555fbd30a36f98ab425780c8d692eb", "Volumes": { "/data": {} }, "WorkingDir": "", "Entrypoint": [ "/bin/start" ], "NetworkDisabled": false, "OnBuild": [ "ADD ./config /config/" ] }, "docker_version": "1.1.2", "author": "Jeff Lindsay <[email protected]>", "config": { "Hostname": "7f17ad58b5b8", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 0, "Cpuset": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "ExposedPorts": { "53/udp": {}, "8300/tcp": {}, "8301/tcp": {}, "8301/udp": {}, "8302/tcp": {}, "8302/udp": {}, "8400/tcp": {}, "8500/tcp": {} }, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "HOME=/", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "SHELL=/bin/bash" ], "Cmd": [], "Image": "68f9e4929a4152df9b79d0a44eeda042b5555fbd30a36f98ab425780c8d692eb", "Volumes": { "/data": {} }, "WorkingDir": "", "Entrypoint": [ "/bin/start" ], "NetworkDisabled": false, "OnBuild": [ "ADD ./config /config/" ] }, "architecture": "amd64", "os": "linux", "Size": 0} The layer.tar file appears to be empty. So inspected the parent, and the grandparent, both contained no file in their layer.tar files. So assuming that 4.0K is the standard size for an empty tarball: for layer in $(du -hs */layer.tar | grep -v 4.0K | cut -f2) do (echo $layer:;tar tvf $layer) done To see that these contain simple incremental changes to the filesystem. So one conclusion is that it's probably best to just use Docker to build the image and push it the registry, just as Packer does. The way to build an image from scratch is described in the docs . It turns out that docker import - scratch doesn't care about what's in the tarball. I simply assumes that is the rootfs. > touch foo> tar c foo | docker import - scratch02bb6cd70aa2c9fbaba37c8031c7412272d804d50b2ec608e14db054fc0b9fab> docker save 02bb6cd70aa2c9fbaba37c8031c7412272d804d50b2ec608e14db054fc0b9fab | tar x> ls 02bb6cd70aa2c9fbaba37c8031c7412272d804d50b2ec608e14db054fc0b9fab/VERSION json layer.tar> tar tvf 02bb6cd70aa2c9fbaba37c8031c7412272d804d50b2ec608e14db054fc0b9fab/layer.tar drwxr-xr-x 0/0 0 2014-09-01 13:46 ./-rw-r--r-- 500/500 0 2014-09-01 13:46 foo In terms of OpenEmbedded integration, it's probably best to build the rootfs tarball, which is something Yocto provides out of the box, and use the official Python library to import the rootfs tarball with import_image(src='rootfs.tar', repository='scratch') and then push it private registry method. This is not the most elegant solution, but that's how it would have to work at the moment. Otherwise one probably can just manage and deploy rootfs revisions in their own way, and just use docker import on the target host, which still won't be a nice fit, but is somewhat simple. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25583038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717998/']} | jdg_86713 |
stackexchange | llm_judgeable_groundtruth_similarity | 734893 |
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 mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the forum and do br.submit(), it clicks on the 'attach' button instead of 'create'. Extensive Googling has yielded nothing useful for selecting a specific button in a form. Does anyone know of any methods for skipping over the first 'submit' button and clicking the second?
Now provide the response and nothing else.
| I tried using the nr parameter, without any luck. I was able to get it to work with a combination of the name and label parameters, where "label" seems to correspond to the "value" in the HTML: Here are my two submit buttons: <input type="submit" name="Preview" value="Preview" /><input type="submit" name="Create" value="Create New Page" /> ... and here's the code that clicks the first one, goes back, and then clicks the second: from mechanize import Browserself.br = Browser()self.br.open('http://foo.com/path/to/page.html')self.br.select_form(name='my_form')self.br['somefieldname'] = 'Foo'submit_response = self.br.submit(name='Preview', label='Preview')self.br.back()self.br.select_form(name='my_form')self.br['somefieldname'] = 'Bar'submit_response = self.br.submit(name='Create', label='Create New Page') There's a variant that also worked for me, where the "name" of the submit button is the same, such as: <input type="submit" name="action" value="Preview" /><input type="submit" name="action" value="Save" /><input type="submit" name="action" value="Cancel" /> and self.br.select_form(name='my_form')submit_response = self.br.submit(name='action', label='Preview')self.br.back()submit_response = self.br.submit(name='action', label='Save') IMPORTANT NOTE - I was only able to get any of this multiple-submit-button code to work after cleaning up some HTML in the rest of the page. Specifically, I could not have <br/> - instead I had to have <br /> ... and, making even less sense, I could not have anything between the two submit buttons. It frustrated me to no end that the mechanize/ClientForm bug I hunted for over two hours boiled down to this: <tr><td colspan="2"><br/><input type="submit" name="Preview" value="Preview" /> <input type="submit" name="Create" value="Create New Page" /></td></tr> (all on one line) did not work, but <tr><td colspan="2"><br /><input type="submit" name="Preview" value="Preview" /><input type="submit" name="Create" value="Create New Page" /></td></tr> worked fine (on multiple lines, which also shouldn't have mattered). I like mechanize because it was easy to install (just copy the files into my include directory) and because it's pretty simple to use, but unless I'm missing something major, I think that bugs like this are kind of awful - I can't think of a good reason at all why the first example there should fail and the second should work. And, incidentally, I also found another mechanize bug where a <textarea> which is contained within a <p> is not recognized as a valid control, but once you take it out of the <p> container it's recognized just fine. And I checked, textarea is allowed to be included in other block-level elements like <p> . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/734893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/76322/']} | jdg_86714 |
stackexchange | llm_judgeable_groundtruth_similarity | 25827 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a group $G$ of permutations on $[n]=\{1, \cdots, n\}$, and two vectors $u,v\in \Gamma^n$ where $\Gamma$ is a finite alphabet which is not quite relevant here, the question is whether there exists some $\pi\in G$ such that $\pi(u)=v$ where $\pi(u)$ means applying the permutation $\pi$ on $u$ in an expected way. Suppose further that $G$ is given, as the input, by a finite set $S$ of generators. What's the complexity of the problem? In particular, is it in NP?
Now provide the response and nothing else.
| Let $g_1, \ldots, g_k, g \in S_n$ where $S_n$ is the permutation group on $n$ elements. Testing whether $g \in \langle g_1, \ldots, g_k \rangle$ can be done in $\text{NC} \subseteq \text{P}$ by [1]. Let $u, v \in \Gamma^n$, then simply guess $g \in S_n$, test in polynomial time whether $g \in G$ and whether $g(u) = v$. This yields an $\text{NP}$ upper bound. To complement this answer: Group membership was shown to belong to $\text{P}$ (Furst et al. 1980), then to $\text{NC}^3$ for abelian groups (McKenzie & Cook 1987; Mulmuley 1987), to $\text{NC}$ for nilpotent groups (Luks & McKenzie 1988), solvable groups (Luks & McKenzie 1988), groups with bounded non-abelian composition factors (Luks 1986), and finally all groups (Babai et al. 1987). A similar complexity classification of aperiodic monoids membership owes to (Beaudry 1988; Beaudry et al. 1992; Kozen 1977), who show that membership for any fixed aperiodic monoid variety is either in $\text{AC}^0$ , in $\text{P}$, in $\text{NP}$, or in $\text{PSPACE}$ (and complete for that class with very few exceptions). [1] L. Babai, E. M. Luks & A. Seress. Permutation groups in NC. Proc. $19^\text{th}$ annual ACM symposium on Theory of computing, pp. 409-420, 1987. | {} | {'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/25827', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/27313/']} | jdg_86715 |
stackexchange | llm_judgeable_groundtruth_similarity | 57846500 |
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 this stackblitz I'm getting the following error (Even though the MatBottomSheetModule is imported): ERROR Error: StaticInjectorError(AppModule)[CountryCodeSelectComponent -> MatBottomSheetRef]: StaticInjectorError(Platform: core)[CountryCodeSelectComponent -> MatBottomSheetRef]: NullInjectorError: No provider for MatBottomSheetRef! Thoughts? Angular / Components Feature Request If you agrre you can vote for this. I requested making the use case symmetrical WRT how we make use of other similar Angular components / services. https://github.com/angular/components/issues/17011
Now provide the response and nothing else.
| You need providers for Bottom Sheet which you were missing. Make these changes to material.module.ts import {MatBottomSheetRef, MAT_BOTTOM_SHEET_DATA} from '@angular/material/bottom-sheet';@NgModule({ exports: [...] providers: [ { provide: MatBottomSheetRef, useValue: {} }, { provide: MAT_BOTTOM_SHEET_DATA, useValue: {} } ],}) This is the recommended approach for Treeshaking for webpack for more performant and minimized bundles: In file: country-code-select.component.ts // Removed -1// import { MatBottomSheetRef } from '@angular/material'; //Added +1import { MatBottomSheetRef} from '@angular/material/bottom-sheet'; The Stackblitz for your reference https://stackblitz.com/edit/angular-material-baseline2-country-code-select-6hisdk And you are set. Cheers! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57846500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684269/']} | jdg_86716 |
stackexchange | llm_judgeable_groundtruth_similarity | 561760 |
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 studying QFT, and Peskin is his book takes a couple of paragraphs to talk about causality in QFT, using the Klein-Gordon field as an example.The book says on p. 28: To really discuss causality, however, we should ask whether [...] a measurement performed at one point can affect a measurement at another point whose separation from the first is spacelike. [...] we should compute the commutator; if this commutator vanishes, one measurement cannot affect the other. and then proceeds to calculate the said commutator for both spacelike and timelike intervals, the first one is zero, the second one is nonzero, so no measurement in the Klein-Gordon theory can affect another measurement outside the light-cone. All the calculations in Peskin's book are correct, but I'm not understanding his claim: if a commutator is zero, shouldn't this mean that the measurements can be done simultaneously? If the said measurements are spins of entangled particles, doesn't this mean that my measurement is affecting the other one on a spacelike interval, therefore violating causality?
Now provide the response and nothing else.
| All the calculations in Peskin's book are correct, but I'm not understanding his claim: if a commutator is zero, shouldn't this mean that the measurements can be done simultaneously? I think that you are confusing the notion of " simultaneous measurement " (or "simultaneous diagonalizability ") in quantum mechanics with the notion of " simultaneity" in relativity. A " simultaneous measurement " in QM is a measurement that can in principle be performed simultaneously because measuring one quantity does not affect the outcome of the other (and vice-versa ) so there is no need to speak of which measurement came first. This, however, tells you nothing about the chronological order of the measurements. The point that Peskin & Schröder are trying to make is that even though propagators don't vanish outside the light-cone, that should not alarm us. What is important is that information is not transmitted outside of the light cone. Taking two points A and B to be space-like separated and measuring the fields at those two points, it shouldn't matter whether we measure $\phi(A)$ first and $\phi(B)$ after, because if it did, then one would be able to tell the difference, hence information would be transmitted outside of the light-cone. Since the two commute, no such thing happens. meaning that other field theories, like the Dirac one, can and will violate causality. In the next Chapter of Peskin & Schröder (Chapter 3), he shows that causality is preserved for the case of anti-commuting Dirac fermions, negating your statement. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/561760', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/220004/']} | jdg_86717 |
stackexchange | llm_judgeable_groundtruth_similarity | 16993433 |
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 my first project in MVVM and I've chosen to use the MVVM Light Toolkit. I have a GameViewModel that handles business on the main screen of my game. I need to find out how to open a new window ( AdventurerView ) with an instance of Adventurer as a parameter when a command is executed, have it bound to AdventurerViewModel , and display and return data. Instances of this window will be opened and closed frequently. I have been stuck on this for a couple of days now and it's driving me crazy. I would like to learn how to do this in an MVVM-friendly way, preferably with the tools provided by MVVM Light or pure XAML. I've tried using MVVM Light's ViewModelLocator but since AdventurerView is a window it won't work; it says "Can't put a Window in a Style", though the program still compiles and runs. Could there be something I could change to make that work? Or is there another way to bind them in XAML? Or another approach entirely? I would really love to be able to move on from this. I have also tried using MVVM Light's messenger to no avail (which still doesn't tackle the View/ViewModel issue). I just need to be able to create a window that is bound to AdventurerViewModel and display/return the appropriate data. AdventurerView.xaml is in its default state at the moment, but I feel that if I could bind the appropriate data that might help (DataContext). AdventurerViewModel is pretty bare-bones as well class AdventurerViewModel : ViewModelBase{ #region Members private Adventurer _adv; #endregion #region Properties public Adventurer Adv { get { return _adv; } set { _adv = value; } } #endregion #region Construction public AdventurerViewModel(Adventurer adv) { this._adv = adv; } #endregion} App.xaml with the non-working DataTemplate at the bottom: <Application StartupUri="MainWindow.xaml" xmlns:views="clr-namespace:AoW.Views" xmlns:vm="clr-namespace:AoW.ViewModels" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="AoW.App" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"><Application.Resources> <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" /> <DataTemplate DataType="{x:Type vm:GameViewModel}"> <views:GameView /> </DataTemplate> <DataTemplate DataType="{x:Type vm:TitleViewModel}"> <views:TitleView /> </DataTemplate> <DataTemplate DataType="{x:Type vm:AdventurerViewModel}"> <views:AdventurerView /> </DataTemplate></Application.Resources></Application> The command in GameViewModel that will hopefully make this all happen (the messagebox just confirms that the command is firing): private void ExecuteShowAdvCommand(Adventurer adv) { System.Windows.MessageBox.Show(adv.Name); } I don't really know what else to include.
Now provide the response and nothing else.
| Ok I put together a demo that should make this hopefully easier for you Download Link Functionality: 3 Windows in Total ( MainWindow , ModalWindow , NonModalWindow ) MainWindow has a TextBox you can type whatever you want into. 2 buttons on the top will open the Modal / NonModal Window accordingly Each window when opened will display the message that was in MainWindow's TextBox in a TextBlock inside them. In each window you can tick a CheckBox to update the value in result's textblock in MainWindow (For the Modal Window this will kick in when modal window is closed. For NonModal changes can be seen asap) That's it for functionality, Concepts: Registering Multiple VM's with the SimpleIoC and using GetInstance(...) to request them out. Messenger class usage with a custom message type OpenWindowMessage Opening Modal / Non Modal Windows from a parent VM staying true to the MVVM principles Passing data between windows(just shown in NonModal) Important Note: - The method used in this example to set the non DP DialogResult from the modal window is not MVVM friendly cos it uses code-behind to set the DialogResult property on a Window.Closing event which should be avoided(If needing to be "testable"). My preferred approach is a bit long and is very well documented HERE (Mixture of question and answer). Hence why I ignored it for the sake of this sample. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16993433', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1667020/']} | jdg_86718 |
stackexchange | llm_judgeable_groundtruth_similarity | 7535 |
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:
What precautions should I take when mixing analog audio and digital (uC control) on the same board? I don't want to hear the I2C bus in my speakers. I'm thinking about Separate power supplies Separate ground planes, with each part within its own ground plane A single connection over a ferrite bead between ground planes Lots of decoupling, preferably by RC instead of simply a C Slew rate control, esp. on serial buses (lots of edges!) Physical distance between both world The RC decoupling may or may not be overkill, but it costs only a resistor. Other suggestions?
Now provide the response and nothing else.
| I've never had an issue with I2C being audible in a circuit including using I2C adjustable resistors in a 60dB gain microphone pre-amp so i doubt you'll have much issue but here are some thoughts. Avoid using multiple ground planes unless you really need it. You can easily cause more noise problems than you solve if your not very careful to avoid routing any signal over the split in the plane. Unless your goal is very high fidelity, use a single solid ground plane. In general you will find almost every mixed signal IC will call for separate analog and digital grounds/supplies. While this is great in an ideal world, if you don't have the space to do this properly, you will cause more noise problems than you will solve. For instance your better off using a single power supply with an LC filter in front of the analog input than you are running a separate supply across the board on a 15mil trace. Other thoughts: Use an I2C clock above the audio range, 40khz or higher. Use the largest pull up resistors you can given your bus speed. This limits the current and hence noise generation. Also make sure the I2C bus isn't ringing, if it is use series termination at all devices (40-50ohm resistor should be fine). Match the I2C traces to 50ohm if you can and make 1 long run through all devices rather than T-ing off the bus. A single, solid ground plane. Remember that high frequency signals will follow the path of least inductance to ground, not the path of least resistance. With this in mind lay out the PCB such that ground currents from the digital portions are not traveling under the analog portions. Proper decoupling, do not use resistors. You have to calculate this for your particular design but a 0.1uF and a 10nF ceramic cap per power pin and larger, 10uF caps per major IC or section is generally a safe bet. Always place caps as close as possible to the power pin and get to ground ASAP. Don't be stingy with the vias, even using multiple vias to ground for each decoupling cap is not a bad idea if you have the space. Use either a separate regulated power supply or use an LC filter to segment off an analog supply from the digital supply. If you use a split plane, you again can't cross this split on an adjacent layer with ANY traces. Use protection around any sensitive analog components or pins. Ground rings around op amp inputs, etc. In fact a ground pour on the surface of the analog section is not a bad idea as long as its properly coupled to the ground plane (lots of vias) and doesn't have orphaned copper. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/7535', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/2064/']} | jdg_86719 |
stackexchange | llm_judgeable_groundtruth_similarity | 47820 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I recently came across the method of characteristics (before that I had only used separation of variables) and decided to read up on it. I tried reading the wikipedia article on it , but I'm still not clear how to get the solution! They all only seem to give the characteristics... I thought I'd start with a very simple form of their Eq.( 1 ) as: $$\frac{\partial u}{\partial x}+a(x,y,u) \frac{\partial u}{\partial y}=0$$ I'm not clear as to how to solve this, as it starts with "suppose a solution $u$ is known" (which I don't know!), and with $z=u(x,y)$, I end up with $$\begin{align}dx/dt&=1\\dy/dt&=a(x,y,z)\\dz/dt&=0\end{align}$$ How do I proceed from here? How do I get $u(x,y)$? I know I need a boundary condition for a D.E., but I don't know what to choose... is $u(0,y)=u_0$ a sufficient BC?
Now provide the response and nothing else.
| I don't like the Wikipedia article either. Try looking at Walter Strauss' PDE book (that's where I learned this method from--and I think he explains it much better[but my professor explained it better than both!]). Firstly, in that example from wikipedia, I don't see the initial condition anywhere: $u(x_0,0) = f(x_0)$. Also I'm going to make $a$ a constant; you'll be able to see how to work from there. To solve this pde, you want a function $u$ such that when we take a derivative of $u$ with respect to some variable $s$, we get both sides of the equation we want (both 0 and $u_x + au_y$) Remember from Calculus 3 the chain rule: $\dfrac{du}{ds} = \dfrac{\partial{u}}{\partial{x}}\dfrac{dx}{ds} + \dfrac{\partial{u}}{\partial{y}}\dfrac{dy}{ds} = 0$, with zero being what we want the RHS of our equation to look like (it could be something else). Now we see something! If we set $\dfrac{dx}{ds} = a, \dfrac{dy}{ds} = 1, \dfrac{du}{ds} = 0$, we recover what we were looking for! Now we have three ODEs in a single variable. We integrate, and we need some initial conditions (which [kinda] have). Now we have the characteristics name: Along this made up parameterization if we let $x(0) = x, y(0) = 0$, we recover our original initial condition: $u(x(0),y(0)) = u(x_0,0) = f(x_0)$! So let's integrate our 3 ODEs: $x(s) = as + c_1$ $y(s) = s + c_2$ $u(s) = c_3$ use our initial conditions: $x(0) = x_0 \Rightarrow c_1 = x_0, x(s) = as + x_0$ $y(0) = 0 \Rightarrow c_2 = 0, y(s) = s$ $u(0) = f(x_0) \Rightarrow c_3 = f(x_0), u(s) = f(x_0)$ Now we must solve for $x_0$, since we have $u(s) = u(x(s),y(s))$ but that does us no good. Look at our solved ODE in x! $x_0 = as-x$ and now our second ODE! $s = y$! Therefore $u(x(s),y(s)) = f(x_0) = f(ay-x)$. This means the solution to the PDE $au_x + u_y = 0$ with initial condition $u(x_0, 0) = f(x_0)$ is solved by changing $f(x_0)$ to $f(ay-x)$ (ex: $f(x) = 3x$ becomes $f(ay-x) = 3(ay-x)$) Hope this helped. Please let me know if I can help more. I left out some of the geometry of why this exactly works, but now you should be able to solve them. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/47820', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_86720 |
stackexchange | llm_judgeable_groundtruth_similarity | 43314328 |
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 package version # devtools::install_github("hadley/dplyr")> packageVersion("dplyr")[1] ‘0.5.0.9001’ With the following tibble: library(dplyr)df <- structure(list(gene_symbol = structure(1:6, .Label = c("0610005C13Rik", "0610007P14Rik", "0610009B22Rik", "0610009L18Rik", "0610009O20Rik", "0610010B08Rik"), class = "factor"), fold_change = c(1.54037, 1.10976, 0.785, 0.79852, 0.91615, 0.87931), pvalue = c(0.5312, 0.00033, 0, 0.00011, 0.00387, 0.01455), ctr.mean_exp = c(0.00583, 59.67286, 83.2847, 6.88321, 14.67696, 1.10363), tre.mean_exp = c(0.00899, 66.22232, 65.37819, 5.49638, 13.4463, 0.97043), ctr.cv = c(5.49291, 0.20263, 0.17445, 0.46288, 0.2543, 0.39564), tre.cv = c(6.06505, 0.28827, 0.33958, 0.53295, 0.26679, 0.52364)), .Names = c("gene_symbol", "fold_change", "pvalue", "ctr.mean_exp", "tre.mean_exp", "ctr.cv", "tre.cv"), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame")) That looks like this: > df# A tibble: 6 × 7 gene_symbol fold_change pvalue ctr.mean_exp tre.mean_exp ctr.cv tre.cv <fctr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>1 0610005C13Rik 1.54037 0.53120 0.00583 0.00899 5.49291 6.065052 0610007P14Rik 1.10976 0.00033 59.67286 66.22232 0.20263 0.288273 0610009B22Rik 0.78500 0.00000 83.28470 65.37819 0.17445 0.339584 0610009L18Rik 0.79852 0.00011 6.88321 5.49638 0.46288 0.532955 0610009O20Rik 0.91615 0.00387 14.67696 13.44630 0.25430 0.266796 0610010B08Rik 0.87931 0.01455 1.10363 0.97043 0.39564 0.52364 I'd like to round the floats (2nd columns onward) to 3 digits. What's the way to do it with dplyr::mutate_all() I tried this: cols <- names(df)[2:7]# df <- df %>% mutate_each_(funs(round(.,3)), cols)# Warning message:#'mutate_each_' is deprecated.# Use 'mutate_all' instead.# See help("Deprecated") df <- df %>% mutate_all(funs(round(.,3)), cols) But get the following error: Error in mutate_impl(.data, dots) : 3 arguments passed to 'round'which requires 1 or 2 arguments
Now provide the response and nothing else.
| While the new across() function is slightly more verbose than the previous mutate_if variant, the dplyr 1.0.0 updates make the tidyverse language and code more consistent and versatile. This is how to round specified columns: df %>% mutate(across(2:7, round, 3)) # columns 2-7 by position df %>% mutate(across(cols, round, 3)) # columns specified by variable cols This is how to round all numeric columns to 3 decimal places: df %>% mutate(across(where(is.numeric), round, 3)) This is how to round all columns, but it won't work in this case because gene_symbol is not numeric: df %>% mutate(across(everything(), round, 3)) Where we put where(is.numeric) in across 's arguments, you could put in other column specifications such as -1 or -gene_symbol to exclude column 1. See help(tidyselect) for even more options. Update for dplyr 1.0.0 The across() function replaces the _if/_all/_at/_each variants of dplyr verbs. https://dplyr.tidyverse.org/dev/articles/colwise.html#how-do-you-convert-existing-code Since some columns are not numeric, you could use mutate_if with the added benefit of rounding columns iff (if and only if) it is numeric: df %>% mutate_if(is.numeric, round, 3) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/43314328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67405/']} | jdg_86721 |
stackexchange | llm_judgeable_groundtruth_similarity | 24577 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Imagine we have an application which is trying to establish a secure connection to a server by using SSL. Now we want the user to authenticate himself with a client certificate which he stores in an secure keystore. So if I read this specification right the server is sending its certificate during the handshake protocol and is able to demand a certificate from the client with a certificate request, if that's neccessary. Now the user sends his certificate to the server just like the server did before which means in plaintext since no keys were exchanged yet. What I'm not getting now is, if the client certificate is send in plaintext and the certificate is not bound to a specific device and the public key of the client inside its certificate is not used to generate the symmetric key which is used for encryption later,why is it not possible for an attacker to sniff the handshake protocol between the client and the server, assuming he is sitting in the same wireless lan as his victim?Like that he could see the client certificate, copy it and use it on his own. So how is this scenario prevented? Of cause the attacker would not be able to change some data of the certificate since he doesn't have the private key the certificate was signed with, but wouldn't it be enough to copy the certificate to steal his victims identity?What am I missing here? Is the certificate bound to the device after all? But I thought it wouldn't since it's just containing some information about the client himself and his public key. I thought it would be a better idea to send the client certificate after the handshake protocol when a symmetric key was exchanged and the application data is encrypted. I know you could also user additional user credentials like a username and a password but I am just talking about the security of the client certificate now. So what do you think?
Now provide the response and nothing else.
| The certificate contains only the public key -- that's public data. The important part is not the Certificate message that the client sends, but the CertificateVerify message which the client also sends. That message contains a digital signature which the client computes using his private key, and over the previous handshake messages. The attacker can sniff all he wants, he will not get the private key, which is not sent, and he will not be able to compute another signature, applicable over another SSL exchange. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/24577', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/16465/']} | jdg_86722 |
stackexchange | llm_judgeable_groundtruth_similarity | 51587003 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my layout I have two Widgets in a row, one text and the an icon. As shown below, assume that * refers to the icon, and using "-" to represent the row: ---------------------------- Text * ---------------------------- How do I make my text centered in the entire row, and the icon to the right end ?
Now provide the response and nothing else.
| The main thing you need to notice is that if you don't want to use Stack you should provide same width-consuming widgets both on left and right. I would do this with either Expanded and Padding Row( children: <Widget>[ Expanded( child: Padding( padding: const EdgeInsets.only(left: 32.0), child: Text( "Text", textAlign: TextAlign.center, ), ), ), Icon(Icons.add, size: 32.0,) ],) or with Row 's mainAxisAlignment and a SizedBox Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ const SizedBox(width: 32.0), Text("Text"), Icon(Icons.add, size: 32.0) ],) or with Expanded and a SizedBox on the left instead of the padding :). The padding or extra container on the left is so that the textAlign will truly center the text in the row taking into account the space taken up by the Icon. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51587003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/883430/']} | jdg_86723 |
stackexchange | llm_judgeable_groundtruth_similarity | 53587659 |
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 proxy config file which has API(web service) link to target to make calls to our database. This proxy config is working fine locally using npm start . Now I Need to deploy this app to our production windows server on IIS. I used ng build and ng build --prod looks like this is not generating build with proxy setting. I need help that How I can generate a build with proxy setting so that I can deploy it to prod server. Api is deployed on some other domain and this angular app will be deployed on some other domain. Thanks
Now provide the response and nothing else.
| The proxy config file is for the local development web server. The main reason you use it is so you can avoid cross domain requests when developing the Angular app and the api on your local machine without having to allow cross domain requests in the api. When you release to production there is no support for the proxy config file. You will be releasing to your production web server. If your api is hosted under the same domain then there is no need for proxying requests as they are not cross domain and if the api is on another domain you will need to allow cross domain request in the api. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53587659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10557682/']} | jdg_86724 |
stackexchange | llm_judgeable_groundtruth_similarity | 73430 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How does an atomic transition between ground and excited states depend upon the direction of polarisation of incident light?
Now provide the response and nothing else.
| 1) "In what situations is it okay to separate the complete wavefunction like that?" As a simple product, only for distinguishable non-interacting particles. If you add antisymmetry, as Ruslan notes, you get a Slater determinant wavefunction which is exact for indistinguishable non-interacting fermions. Since electrons interact through the Coulomb operator, this is indeed never exact for many-electron wavefunctions, as Dan mentions. The simple product wavefunction was first used by Douglas Hartree; Vladimir Fock added antisymmetry resulting in the Hartree-Fock method (and I guess the Professor in your class is taking you in that direction). Now you say that you heard this in a graduate chemical engineering course, and Hartree-Fock is still very useful in chemistry. But, as you note, this wavefunction completely ignores entanglement. I'll try to explain why is the product wavefunction still useful despite this shortcoming with an example of chemistry. Consider a hydrogen molecule at equilibrium bond length. This is a two-electron wavefunction and we can write a wavefunction which considers entanglement as \begin{equation} | \Psi \rangle = c_1 | \sigma_\alpha\sigma_\beta \rangle + c_2 | \sigma_\alpha^*\sigma_\beta^* \rangle \end{equation}where $| \sigma_\alpha\sigma_\beta \rangle$ is the Slater determinant formed from the bonding orbitals $ \sigma_\alpha$ and $\sigma_\beta$, whereas $| \sigma_\alpha^*\sigma_\beta^* \rangle $ is a Slater determinant made with the antibonding orbitals $\sigma_\alpha^*$ and $\sigma_\beta^*$ ($\alpha$ and $\beta$ represent the spin of the orbital of course, and I'm assuming that you are familiar with molecular orbitals). By the variational principle, $c_1$ and $c_2$ must minimize the energy of $| \Psi \rangle $. However, at equilibrium bond length the energy of $| \sigma_\alpha\sigma_\beta \rangle$ is much lower than that of $| \sigma_\alpha^*\sigma_\beta^* \rangle $ resulting in $c_1 >> c_2$ and hence $| \Psi \rangle \sim | \sigma_\alpha\sigma_\beta \rangle$. Thus, this is a case in which Hartree-Fock (i.e. a single Slater determinant) can yield a qualitatively correct result. If you add perturbation theory to $| \sigma_\alpha\sigma_\beta \rangle$, you get very accurate (quantitative) results. However, Hartree-Fock may fail terribly in some cases. Suppose now that we separate the atoms that compose the Hydrogen molecule at such a large distance that their atomic orbitals do not interact anymore. At this point, $| \sigma_\alpha\sigma_\beta \rangle$ and $| \sigma_\alpha^*\sigma_\beta^* \rangle $ become degenerate and $c_1 = c_2$. Thus, in this case we have a multideterminant wavefunction which can't be described by Hartree-Fock. Indeed, in this case the Hartree-Fock energy is unphysical and much larger than that of two Hydrogen atoms. The lesson of this example is that (antisymmetrized) product wavefunctions are useful in cases where the entanglement is small, but fail terribly if the entanglement is strong. In general in chemistry, this failure occurs when one has degenerate or near degenerate orbitals, which occurs mostly in molecules at dissociation, transition metals, and singlet diradicals. However, simple closed shell species from the first two rows of the periodic table can often be well described by antisymmetrized product wavefunctions (single Slater determinants). 2) "How do you know that an isolated electron in an experiment isn't influenced by the rest of the particles in the universe?" The electron interacts with the rest of the particles in the universe, but the interaction is negligible. Recall that this interaction must be through the Coulomb operator $1/|r_1 - r_2|$ (in atomic units) and usually $|r_1 - r_2|$ will be large enough so that we can ignore interactions of (say) a molecule in gas phase with the rest of the universe (we can't ignore interactions of molecule with a solvent when dealing with solutions though, but there are approximate methods for dealing with those). | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/73430', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/26724/']} | jdg_86725 |
stackexchange | llm_judgeable_groundtruth_similarity | 1154384 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
my textbook said to determine the greatest coefficient in a binomial expansion $ (a+b)^n $ we can use the inequality: \begin{align}\frac{n-k+1}{k} \cdot \frac{b}{a} \geq 1\end{align} Then solve for $k$ which will result in something like $ k \leq constant$ which we can then substitute back to solve for the greatest coefficient. my question is what about $(a-b)^n $? (where $a > 0$, $ b > 0$) Solving for k would result in: \begin{align}k \leq -\frac{b \cdot(n+1)}{a+1}\end{align} Since $b$, $n$ and $a$ are all positive. Then $k$ appear to be a negative number (which is wrong) Can someone tell me where did I got wrong? Thank you.
Now provide the response and nothing else.
| Here why $\Gamma\left(\frac{1}{2}\right)=\sqrt{\pi}$ :$$\Gamma\left(\frac{1}{2}\right)=\intop_{t=0}^{+\infty}t^{\frac{1}{2}-1}e^{-t}dt=\intop_{t=0}^{+\infty}\frac{e^{-t}}{\sqrt{t}}dt,$$ and with $y=\sqrt{t}$, $dy=\frac{dt}{2\sqrt{t}}$, we get$$\Gamma\left(\frac{1}{2}\right)=2\intop_{y=0}^{+\infty}e^{-y^{2}}dy=\intop_{y=-\infty}^{+\infty}e^{-y^{2}}dy=\sqrt{\pi}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1154384', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/200871/']} | jdg_86726 |
stackexchange | llm_judgeable_groundtruth_similarity | 31949118 |
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 Alamofire, very first time. I am using the latest version Alamofire 1.3.1. I want to send one image , one video and some POST parameters in one API call. I am using multipart form data. The mutipart module is working. I am facing a problem to send extra POST parameters params . Below is my code. "params" is the dictionary which contains extra parameters? How can I append these POST parameters in the request. Please help var fullUrl :String = Constants.BASE_URL + "/api/CompleteChallenge" var params = [ "authKey": Constants.AuthKey, "idUserChallenge": "16", "comment": "", "photo": imagePath, "video": videoPath, "latitude": "1", "longitude": "1", "location": "india" ] let imagePathUrl = NSURL(fileURLWithPath: imagePath!) let videoPathUrl = NSURL(fileURLWithPath: videoPath!) Alamofire.upload( .POST, URLString: fullUrl, // http://httpbin.org/post multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(fileURL: imagePathUrl!, name: "photo") multipartFormData.appendBodyPart(fileURL: videoPathUrl!, name: "video") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { request, response, JSON, error in } } case .Failure(let encodingError): } } )
Now provide the response and nothing else.
| I found the solution :) finally. We can append data in the request as multipartformdata. Below is my code. Alamofire.upload( .POST, URLString: fullUrl, // http://httpbin.org/post multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(fileURL: imagePathUrl!, name: "photo") multipartFormData.appendBodyPart(fileURL: videoPathUrl!, name: "video") multipartFormData.appendBodyPart(data: Constants.AuthKey.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"authKey") multipartFormData.appendBodyPart(data: "\(16)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"idUserChallenge") multipartFormData.appendBodyPart(data: "comment".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"comment") multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"latitude") multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"longitude") multipartFormData.appendBodyPart(data:"India".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"location") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { request, response, JSON, error in } case .Failure(let encodingError): } } ) EDIT 1: For those who are trying to send an array instead of float, int or string, They can convert their array or any kind of data-structure in Json String, pass this JSON string as a normal string. And parse this json string at backend to get original array | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31949118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2811053/']} | jdg_86727 |
stackexchange | llm_judgeable_groundtruth_similarity | 18400694 |
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 shortest way to express the folowing decission rule df<-data.frame(a=LETTERS[1:5],b=1:5)index<-df[,"a"]=="F"if(any(index)){ df$new<-"A"}else{ df$new<-"B"}
Now provide the response and nothing else.
| Shortest is df$new=c("B","A")[1+any(df$a=="F")] More elegant is: df$new <- if (any(df$a == "F")) "A" else "B" or df <- transform(df, new = if (any(a == "F")) "A" else "B") The ifelse operator was suggested twice, but I would reserve it for a different type of operation: df$new <- ifelse(df$a == "F", "A", "B") would put a A or a B on every row depending on the value of a in that row only (which is not what your code is currently doing.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18400694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1461646/']} | jdg_86728 |
stackexchange | llm_judgeable_groundtruth_similarity | 1820980 |
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:
Evaluate the following integral: $$\iint_D \frac {\ln(2 - \sin \xi \cos \eta)\sin \xi} {2 - 2\sin \xi \cos \eta + \sin^2 \xi \cos^2 \eta} \mathrm d\xi \; \mathrm d\eta$$ where $D = [ 0, \pi/2] \times [ 0, \pi / 2]$. My observations: The integral can be rewritten as $$\iint_D \sin \xi f(\sin \xi \cos \eta) \mathrm d \xi \mathrm d \eta$$ where $f(x) = \frac {\ln (2-x)} {(x-1)^2 + 1}$ Substituting $\mu = \pi / 2 - \xi$, $\nu = \pi / 2 - \eta$ Substituting $x = \sin \eta \cos \xi, y = \sin \eta \sin \xi$ Expanding in terms of seriesSource: The problem appeared in The American Mathematical Monthly
Now provide the response and nothing else.
| Note that the integral $I$ as given by $$I=\int_0^{\pi/2}\int_0^{\pi/2} \frac{\log(2-\sin(\theta)\cos(\phi))}{2-2\sin(\theta)\cos(\phi)+\sin^2(\theta)\cos^2(\phi)}\,\sin(\theta)\,d\theta\,d\phi$$ is the surface integral of $f(x)=\frac{\log(2-x)}{2-2x+x^2}$ over a sphere in the first octant. Therefore, we can write $$\begin{align}I&=\int_0^1 \int_0^{\sqrt{1-x^2}}\frac{\log(2-x)}{2-2x+x^2}\frac{1}{\sqrt{1-x^2-y^2}}\,dy\,dx\\\\&=\int_0^1 \frac{\log(2-x)}{2-2x+x^2}\left(\int_0^{\sqrt{1-x^2}}\frac{1}{\sqrt{1-x^2-y^2}}\,dy\right)\,dx\\\\&=\frac{\pi}{2}\int_0^1 \frac{\log(2-x)}{2-2x+x^2}\,dx\\\\&=\frac{\pi^2\log(2)}{16}\end{align}$$ where the last equality comes from the analysis in the ensuing note. NOTE: EVALUATING $\int_0^1 \frac{\log(2-x)}{2-2x+x^2}\,dx$ $$\begin{align}\int_0^1 \frac{\log(2-x)}{2-2x+x^2}&=\int_0^1 \frac{\log(1+x)}{1+x^2}\,dx \tag 1\\\\&=\int_0^{\pi/4} \left(\log(\sin(x)+\cos(x))-\log(\cos(x))\right)\,dx \tag 2\\\\&=\int_0^{\pi/4} \left(\log(\sqrt{2}\cos(x-\pi/4))-\log(\cos(x))\right )\,dx \tag 3\\\\&=\frac{\pi \log(2)}{8}+\int_0^{\pi/4} \log(\cos(x-\pi/4))\,dx-\int_0^{\pi/4}\log(\cos(x))\,dx \tag 4\\\\&=\frac{\pi \log(2)}{8}+\int_0^{\pi/4}\log(\cos(x))\,dx-\int_0^{\pi/4}\log(\cos(x))\,dx \tag 5\\\\&=\frac{\pi \log(2)}{8}\end{align}$$ In arriving at $(1)$, we enforced the substitution $x\to 1-x$. In going from $(1)$ to $(2)$, we enforced the substitution $x\to \tan(x)$. In going from $(2)$ to $(3)$, we used the identity $A\sin (x)+B\cos(x)=\sqrt{A^2+B^2}\cos\left(x-\arctan2(B,A)\right)$. In going from $(3)$ to $(4)$, we wrote $\log(\sqrt{2}\cos(x-\pi/4))=\frac{\log(2)}{2}+\log(\cos(x-\pi/4))$ and integrated the constant term over $[0,\pi/4]$. In going from $(4)$ to $(5)$, we enforced the substitution $x\to \pi/4-x$ and exploited the evenness of the cosine function. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1820980', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/112612/']} | jdg_86729 |
stackexchange | llm_judgeable_groundtruth_similarity | 29357103 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array of structs: struct CalendarDate { var date: NSDate? var selected = false}private var collectionData = [CalendarDate]() Which I simply populate with a date like this: for _ in 1...7 { collectionData.append(CalendarDate(date: NSDate(), selected: false)) } So when you tap on a collectionView, I simply want to loop through the data and mark them all as False. for c in collectionData { c.selected = false ///ERROR: Cannot assign to 'selected' in 'c' } Why do I get this error? If I do this, it works fine but I want to know what I did wrong above: for i in 0..<collectionData.count { collectionData[i].selected = false }
Now provide the response and nothing else.
| As I understand it, the iterator for c in collectionData returns copies of the items in collectionData - ( structs are value types, not reference types, see http://www.objc.io/issue-16/swift-classes-vs-structs.html ), whereas the iteration for i in 0..<collectionData.count accesses the actual values. If I am right in that, it is pointless to assign to the c returned from the iterator... it does not "point" at the original value, whereas the collectionData[i].selected = false in the iteration is the original value. Some of the other commentators suggested for (var c) in collectionData but although this allows you to assign to c , it is still a copy, not a pointer to the original, and though you can modify c , collectionData remains untouched. The answer is either A) use the iteration as you originally noted or B) change the data type to a class, rather than a struct. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29357103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1446573/']} | jdg_86730 |
stackexchange | llm_judgeable_groundtruth_similarity | 13677125 |
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 force git to run a post-receive hook on a server even if I don't have a new commit to push? Background I use git to automatically deploy a website to a server. I have a bare repo in a protected area of the server and a post-receive hook that checks out the contents and systematically copies over certain files into a public_html folder. (Inspired by this tutorial ) I got tired of modifying the post-receive hook manually on the server, so my post-receive hook now actually copies over a new version of itself from the repo: #!/bin/shrm -rf ~/../protected/*GIT_WORK_TREE=~/../protected git checkout -f# Rewrite over this file with any updates from the post-receive filecp ~/../protected/post-receive hooks/post-receive# Delete public_html# Copy stuff public_html The problem, of course, is that the new post-receive hook never gets run. A seemingly simple solution would be merely to push again, but now everything is already up to date. This is annoying, because it requires me to fake a new commit every time I update the post-receive hook. Is there a way to invoke the post-receive hook without faking a commit or ssh ing in? What I tried git pushgit push -f
Now provide the response and nothing else.
| Use '--allow-empty' After the initial push replacing the script, you can do this : git commit --allow-empty -m 'push to execute post-receive' The --allow-empty flag overrides git's default behavior of preventing you from making a commit when there are no changes. Use an alias and make your life even easier Add the following to ~/.gitconfig [alias] pushpr = "!f() { git push origin master;git commit --allow-empty -m 'push to execute post-receive';git push origin master; }; f" Now Just do git pushpr git pushpr This will push any changes to master, which in your case will trigger your post receive replacement script, then it will push again (using the --allow-empty flag) which will then execute your updated post-receive script. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13677125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/200688/']} | jdg_86731 |
stackexchange | llm_judgeable_groundtruth_similarity | 500132 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Problem :Find the number of distinct real roots of $(x-a)^3+(x-b)^3+(x-c)^3=0$ where $a,b,c$ are distinct real numbers Solution : $(x-a)^3+(x-b)^3+(x-c)^3=0$ $3x^3-3x^2(a+b+c)+3x(a^2+b^2+c^2)-a^3-b^3-c^3=0$ By Descartes rule of sign,number of positive real roots $=3$ But are they distinct $?$ Answer :- number of distinct real roots $ =1$
Now provide the response and nothing else.
| If $$f(x)=(x-a)^3+(x-b)^3+(x-c)^3$$ then $$f'(x)=3(x-a)^2+3(x-b)^2+3(x-c)^2$$ Since $a,b,c$ are distinct real numbers $f'(x) > 0$ for all $x\in\mathbb{R}$ and therefore $f$ is strictly increasing and therefore it has only one real root. EDIT: The last statement is true since $f$ is a polynomial function of degree $3$ ($a_0>0$) so $\lim_{x\to-\infty} f(x) = -\infty$, $\lim_{x\to\infty} f(x) = \infty$ and $f$ is continuous. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/500132', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/73496/']} | jdg_86732 |
stackexchange | llm_judgeable_groundtruth_similarity | 164676 |
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 looking at this circuit: Which has come from here The claim is made that "it detects a voltage drop across a large bridge rectifier that acts as a high power shunt", which is referring to the transformer wired across D1. However, that transformer appears to be wired in parallel with the rectifier, so wouldn't the coil on the transformer see a full 120V? I don't get how wiring the circuit this way causes the drop over the rectifier to become the supply for the transformer coil. What's going on? Edit: From the description given, I am under the impression that the coil on the transformer is supplied with a very low (comparatively) voltage. I don't understand why this is the case. The transformer appears to be directly connected to the mains voltage in this circuit - so it should be supplied with 120v.
Now provide the response and nothing else.
| For those not familiar with woodworking, this device is intended to be installed in the power feed to a table saw, and will start a vacuum to collect sawdust when the saw is operating. If you remove the bridge rectifier, you will see that the 6 volt winding of the transformer is connected in series with one leg of the AC. As the bridge rectifier is wired it is effectively two pairs of series-connected diodes, with the pairs connected with opposite polarities, like so: simulate this circuit – Schematic created using CircuitLab When the saw is operating, the diodes will produce a voltage drop of about 2 volts which will be stepped up by the transformer to produce sufficinet voltage to operate the relay to start the vacuum. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/164676', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/32554/']} | jdg_86733 |
stackexchange | llm_judgeable_groundtruth_similarity | 1886891 |
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:
We divided two number $83$ and $107$ by a natural number $b$. Remainder of first division is $5$ ($83$ by $b$) and remainder of second division is $3$ ($107$ by $b$). How we can find number $b$ ?
Now provide the response and nothing else.
| Hint: $b\mid 83-5=78$ and $b\mid107-3=104$ so that: $$b\mid\gcd(78,104)$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1886891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/359704/']} | jdg_86734 |
stackexchange | llm_judgeable_groundtruth_similarity | 46482998 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Today I started looking at the Chrome extensions the first time ever, I have a very silly questions, I am sure the answer is NO to this as per google search but I just wanted to make sure from the community here. Is it possible to use C# to write code instead of javascript? Is it possible to use Partial Views (ASP.NET MVC) in chrome extension as it renders HTML? I found this in VS Marketplace https://marketplace.visualstudio.com/items?itemName=MadsKristensen.GoogleChromeExtensionProjectTemplate Is there any other templates which have bootstrap etc Cheers
Now provide the response and nothing else.
| You can create browser extension with C#.Specifically, Using Client-side Blazor. To publish, the following operations are required. First, you publish like normal standalone app. https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/blazor/webassembly?view=aspnetcore-3.1#standalone-deployment Then, Remove the underscore from directory name. Since it cannot be used in the extension. # remove underbar from directory namemv _framework/_bin _framework/binmv _framework framework# rewritesed 's/_bin/bin/g' framework/blazor.webassembly.jssed 's/_framework/framework/g' framework/blazor.webassembly.js index.html Then, Add manifest.json and setting CSP like this, "content_security_policy": "script-src 'self' 'unsafe-eval' 'sha256-v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA='; object-src 'self'", Blazor boot script add script tag to html, so you should add scripts hash to allow execute bootup script. This is sample app I created. https://github.com/key-moon/WeatherForecastExtensionWithBlazor And, This is commentary (wrote in Japanese). https://qiita.com/keymoon/items/03357e58eddf75871527 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46482998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1139966/']} | jdg_86735 |
stackexchange | llm_judgeable_groundtruth_similarity | 9734758 |
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 strings like these: "my value1" => my value1"my Value2" => my Value2myvalue3 => myvalue3 I need to get rid of " (double-quotes) in end and start, if these exist, but if there is this kind of character inside String then it should be left there. Example: "my " value1" => my " value1 How can I do this in PHP - is there function for this or do I have to code it myself?
Now provide the response and nothing else.
| The literal answer would be trim($string,'"'); // double quotestrim($string,'\'"'); // any combination of ' and " It will remove all leading and trailing quotes from a string. If you need to remove strictly the first and the last quote in case they exist, then it could be a regular expression like this preg_replace('~^"?(.*?)"?$~', '$1', $string); // double quotespreg_replace('~^[\'"]?(.*?)[\'"]?$~', '$1', $string); // either ' or " whichever is found If you need to remove only in case the leading and trailing quote are strictly paired, then use the function from Steve Chambers' answer However, if your goal is to read a value from a CSV file , fgetcsv is the only correct option. It will take care of all the edge cases, stripping the value enclosures as well. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9734758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/159793/']} | jdg_86736 |
stackexchange | llm_judgeable_groundtruth_similarity | 5318718 |
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 get new line but if I use \n it does not work. Any way to have new line by adding something to string like \r\n (which also does not work) gfx.DrawString("Project No \n" + textBoxProjNumber.Text, fontUnder, XBrushes.Black, 230, 95); (the example snippet shows what I've tried but does not work).
Now provide the response and nothing else.
| Have you tried the XTextFormatter class? See here: http://www.pdfsharp.net/wiki/TextLayout-sample.ashx Code snippet: PdfDocument document = new PdfDocument();PdfPage page = document.AddPage();XGraphics gfx = XGraphics.FromPdfPage(page);XFont font = new XFont("Times New Roman", 10, XFontStyle.Bold);XTextFormatter tf = new XTextFormatter(gfx);XRect rect = new XRect(40, 100, 250, 220);gfx.DrawRectangle(XBrushes.SeaShell, rect);tf.DrawString(text, font, XBrushes.Black, rect, XStringFormats.TopLeft); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5318718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430167/']} | jdg_86737 |
stackexchange | llm_judgeable_groundtruth_similarity | 1124753 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Which code snippet will give better performance? The below code segments were written in C#. 1. for(int tempCount=0;tempCount<list.count;tempcount++){ if(list[tempCount].value==value) { // Some code. }} foreach(object row in list){ if(row.value==value) { //Some coding }}
Now provide the response and nothing else.
| Well, it partly depends on the exact type of list . It will also depend on the exact CLR you're using. Whether it's in any way significant or not will depend on whether you're doing any real work in the loop. In almost all cases, the difference to performance won't be significant, but the difference to readability favours the foreach loop. I'd personally use LINQ to avoid the "if" too: foreach (var item in list.Where(condition)){} EDIT: For those of you who are claiming that iterating over a List<T> with foreach produces the same code as the for loop, here's evidence that it doesn't: static void IterateOverList(List<object> list){ foreach (object o in list) { Console.WriteLine(o); }} Produces IL of: .method private hidebysig static void IterateOverList(class [mscorlib]System.Collections.Generic.List`1<object> list) cil managed{ // Code size 49 (0x31) .maxstack 1 .locals init (object V_0, valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<object> V_1) IL_0000: ldarg.0 IL_0001: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<object>::GetEnumerator() IL_0006: stloc.1 .try { IL_0007: br.s IL_0017 IL_0009: ldloca.s V_1 IL_000b: call instance !0 valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<object>::get_Current() IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: call void [mscorlib]System.Console::WriteLine(object) IL_0017: ldloca.s V_1 IL_0019: call instance bool valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<object>::MoveNext() IL_001e: brtrue.s IL_0009 IL_0020: leave.s IL_0030 } // end .try finally { IL_0022: ldloca.s V_1 IL_0024: constrained. valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<object> IL_002a: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_002f: endfinally } // end handler IL_0030: ret} // end of method Test::IterateOverList The compiler treats arrays differently, converting a foreach loop basically to a for loop, but not List<T> . Here's the equivalent code for an array: static void IterateOverArray(object[] array){ foreach (object o in array) { Console.WriteLine(o); }}// Compiles into....method private hidebysig static void IterateOverArray(object[] 'array') cil managed{ // Code size 27 (0x1b) .maxstack 2 .locals init (object V_0, object[] V_1, int32 V_2) IL_0000: ldarg.0 IL_0001: stloc.1 IL_0002: ldc.i4.0 IL_0003: stloc.2 IL_0004: br.s IL_0014 IL_0006: ldloc.1 IL_0007: ldloc.2 IL_0008: ldelem.ref IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: ldloc.2 IL_0011: ldc.i4.1 IL_0012: add IL_0013: stloc.2 IL_0014: ldloc.2 IL_0015: ldloc.1 IL_0016: ldlen IL_0017: conv.i4 IL_0018: blt.s IL_0006 IL_001a: ret} // end of method Test::IterateOverArray Interestingly, I can't find this documented in the C# 3 spec anywhere... | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1124753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52923/']} | jdg_86738 |
stackexchange | llm_judgeable_groundtruth_similarity | 3836130 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does the following code give a 80004005 error when run? I'm trying to get the status of several sites every 10 seconds...(the ones given are examples). 'http://www.sebsworld.net/information/?page=VBScript-URL'http://www.paulsadowski.com/wsh/xmlhttp.htm'the array of sitessites = Array("http://www.google.com/","http://en.wikipedia.org/wiki/Main_Page")While(True) For Each site In sites 'Get site status Set Http = WScript.CreateObject("Microsoft.XMLHTTP") Http.Open "GET", site, True Http.Send If(Http.Status <> 200) Then 'site isn't 200 MsgBox "The site at " & vbNewLine & site & vbNewLine & "has status: " & Http.Status End If Next WScript.Sleep(10)'Sleep 10 secondsWend
Now provide the response and nothing else.
| First, you have to change Http.Open "GET", site, True to Http.Open "GET", site, False because you cannot use Http.Status immediately after Http.Send if the call is asynchronous. Furthermore, you shoud use Set Http = WScript.CreateObject("MSXML2.ServerXMLHTTP") instead of Set Http = WScript.CreateObject("Microsoft.XMLHTTP") because the normal XMLHTTP object has problems with redirected web sites (www.google.com normally redirects you to another site). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3836130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/389823/']} | jdg_86739 |
stackexchange | llm_judgeable_groundtruth_similarity | 1926063 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to perform some operations on variables in a makefile?For instance, defining JPI=4JPJ=2 is it possible to define in the same makefile a variable JPIJ equal to the expanded value of $(JPI)*$(JPJ) ?
Now provide the response and nothing else.
| Using Bash arithmetic expansion : SHELL=/bin/bashJPI=4JPJ=2all: echo $$(( $(JPI) * $(JPJ) )) The first line is to choose the Bash shell instead of the default (sh) . Typically, sh doesn't support arithmetic expansion. However in Ubuntu, /bin/sh is provided by Dash, which supports this feature . So that line could be skipped. The double dollar sign is because we want the expansion to be done by the shell . Note: the JPI and JPJ variables are expanded by make first, then the expression is passed to bash like this: $(( 4 * 2 )) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1926063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234291/']} | jdg_86740 |
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.