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 | 10515391 |
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 postgres, you can query for the first value of in a group with DISTINCT ON . How can this be achieved in Oracle? From the postgres manual: SELECT DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions are interpreted using the same rules as for ORDER BY (see above). Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. For example, for a given table: col1 | col2 ------+------ A | AB A | AD A | BC B | AN B | BA C | AC C | CC Ascending sort: > select distinct on(col1) col1, col2 from tmp order by col1, col2 asc; col1 | col2 ------+------ A | AB B | AN C | AC Descending sort: > select distinct on(col1) col1, col2 from tmp order by col1, col2 desc; col1 | col2 ------+------ A | BC B | BA C | CC
Now provide the response and nothing else.
| The same effect can be replicated in Oracle either by using the first_value() function or by using one of the rank() or row_number() functions. Both variants also work in Postgres. first_value() select distinct col1, first_value(col2) over (partition by col1 order by col2 asc)from tmp first_value gives the first value for the partition, but repeats it for each row, so it is necessary to use it in combination with distinct to get a single row for each partition. row_number() / rank() select col1, col2 from ( select col1, col2, row_number() over (partition by col1 order by col2 asc) as rownumber from tmp) foowhere rownumber = 1 Replacing row_number() with rank() in this example yields the same result. A feature of this variant is that it can be used to fetch the first N rows for a given partition (e.g. "last 3 updated") simply by changing rownumber = 1 to rownumber <= N . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10515391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/320220/']} | jdg_380941 |
stackexchange | llm_judgeable_groundtruth_similarity | 1561586 |
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:
Does cross product have an identity? I.e. Does there exist some $\vec{id}\in \mathbb{R}^3$ such that $$\vec{id} \times \vec{v} = \vec{v}\times \vec{id} = \vec{v}$$ for all $\vec{v}\in \mathbb{R}^3$?
Now provide the response and nothing else.
| The answer must be no because $\vec{id}\times \vec{v}$ is perpendicular to both $\vec{id}$ and $\vec{v}$ and the only vector that is perpendicular to itself is the $0$ vector. Thus $\vec{id}\times \vec{v}=\vec{v}$ iff $\vec{v}=\vec{0}$ no matter what $\vec{id}$ is, so this cannot be true in general. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1561586', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296190/']} | jdg_380942 |
stackexchange | llm_judgeable_groundtruth_similarity | 10870154 |
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 kind of framework / design pattern should I use for application which possibly has 1000 over biz rule validations? The type of systems I am working on consist of lots of input forms which allow users to enter. Each input form has different sections. i.e. Form A has Section A/B/C/D. Form B has section B/C/D Some of these biz rule validation are common to both forms, I am looking at a approach to reuse the rules as well. How do I build a robust business rule validation framework?
Now provide the response and nothing else.
| drools framework is specifically designed to evaluate business rules spring framework allows writing beans using dynamic languages like groovy and jruby . You can easily plug JavaScript strategy design pattern seems like a good fit: implement each rule as a separate strategy and run them one after another. similar chain of responsibility pattern can be used: each rule either fails or succeeds and passes control to next rule | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10870154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247814/']} | jdg_380943 |
stackexchange | llm_judgeable_groundtruth_similarity | 32643076 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Assuming the Date is a nullable DateTime : Mapper.CreateMap<SomeViewModels, SomeDTO>() .ForMember(dest => dest.Date, opt => opt.MapFrom(src => { DateTime? finalDate = null; if (src.HasDate == "N") { // so it should be null } else { endResult = DateTime.Parse(src.Date.ToString()); } return finalDate; })); The error I got was: Error 30 A lambda expression with a statement body cannot be convertedto an expression tree. Of course I'm fully aware that I can simplify the query such as: Mapper.CreateMap<SomeViewModels, SomeDTO>() .ForMember(dest => dest.Date, opt => opt.MapFrom(src => src.HasDate == "N" ? null : DateTime.Parse(src.Date.ToString()))); But what if I insist to retain the structure of the first example, because I have more complicated if else statements, that the second example will not able to cater for, or at least will not be very readable?
Now provide the response and nothing else.
| Use ResolveUsing method: Mapper.CreateMap<SomeViewModels, SomeDTO>() .ForMember(dest => dest.Date, o => o.ResolveUsing(Converter));private static object Converter(SomeViewModels value){ DateTime? finalDate = null; if (value.Date.HasDate == "N") { // so it should be null } else { finalDate = DateTime.Parse(value.Date.ToString()); } return finalDate;} Here is more information: AutoMapper: MapFrom vs. ResolveUsing | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32643076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3876419/']} | jdg_380944 |
stackexchange | llm_judgeable_groundtruth_similarity | 22608376 |
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 is a lot of posts that i have seen and i didn't find the error in the code bellow :config.xml : <events> <core_block_abstract_to_html_after> <observers> <type>singleton</type> <class>WebDirect_CustomPrice_Model_Observer</class> <method>convertPricespanToInput</method> </observers> </core_block_abstract_to_html_after> </events> Observer class : class WebDirect_CustomPrice_Model_Observer{ const MODULE_NAME = 'WebDirect_CustomPrice'; public function convertPricespanToInput($observer = NULL) { if (!$observer) { return; } if ('product.info.simple' == $observer->getEvent()->getBlock()->getNameInLayout()) { if (!Mage::getStoreConfig('advanced/modules_disable_output/'.self::MODULE_NAME)) { $transport = $observer->getEvent()->getTransport(); $block = new WebDirect_CustomPrice_Block_priceSpanToInput(); $block->setPassingTransport($transport['html']); $block->toHtml(); } } return $this; }} and a class that add a custom javascript in product view page : class WebDirect_CustomPrice_Block_priceSpanToInput extends Mage_Core_Block_Text { //protected $_nameInLayout = 'selectify.qty_input_to_select'; //protected $_alias = 'qty_input_to_select'; public function setPassingTransport($transport) { $this->setData('text', $transport.$this->_generateQtyInputToSelectHtml()); } private function _generatepriceSpanToInputHtml() { $price = Mage::registry('current_product')->getPrice(); $product_Id = Mage::registry('current_product')->getId(); return ' <script type="text/javascript"> //<![CDATA[ document.observe("dom:loaded", function() { $("product-price-'.$product_Id.'").replace(\'<span class="price" id="product-price-'.$product_Id.'"> <input type="text" id="CP_ID" class="input-text price" name="custom_price" style="width:auto;" value="'.$price.'" onchange="onChangeCP(this);"/></span><input type="hidden" id="custom_price_total" name="custom_price_total" value="'.$price.'">\'); }); //]]> </script> '; }} is there any error in that code ? I can't see anything!
Now provide the response and nothing else.
| The issue is in defining observer function in your config.xml. <events> <core_block_abstract_to_html_after> <observers> <type>singleton</type> <class>WebDirect_CustomPrice_Model_Observer</class> <method>convertPricespanToInput</method> </observers> </core_block_abstract_to_html_after> </events> should be replaced by: <events> <core_block_abstract_to_html_after> <observers> <some_unique_identifier> <type>singleton</type> <class>WebDirect_CustomPrice_Model_Observer</class> <method>convertPricespanToInput</method> </some_unique_identifier> </observers> </core_block_abstract_to_html_after> </events> where "some_unique_identifier" can be any unique string. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22608376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3307292/']} | jdg_380945 |
stackexchange | llm_judgeable_groundtruth_similarity | 10080536 |
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 seems to be just a little documentation on the grouped_select feature in simple_form 2.0 at http://simple-form.plataformatec.com.br/#usage/collections . The documentation offers the line: f.input :country_id, :collection => @continents, :as => :grouped_select, :group_method => :countries But that doesn't seem to be giving me enough context to make it work. Here's what I have. I have three models: Inquiry, Ad, and Insertions Ads has_many Insertions, and Insertions belongs_to AdsInquiry belongs_to Insertion, and Insertions has_many Inquiries This dropdown is for the Inquiry view. Using simple_form I can get = f.input :insertion, :collection => @ads to at least output a list of the ad titles in the dropdown. I'd like the ad.title to serve as the optgroup. Then I'd like to have the Ads insertions to serve as the selectable content... so something like: <select> <optgroup label="Ad.Title"> <option value="Ad.Insertion.id">Ad.Insertion.Title</option> <option value="Ad.Insertion.id">Ad.Insertion.Title</option> <option value="Ad.Insertion.id">Ad.Insertion.Title</option> <option value="Ad.Insertion.id">Ad.Insertion.Title</option> </optgroup> <optgroup label="Ad.Title"> <option value="Ad.Insertion.id">Ad.Insertion.Title</option> <option value="Ad.Insertion.id">Ad.Insertion.Title</option> <option value="Ad.Insertion.id">Ad.Insertion.Title</option> <option value="Ad.Insertion.id">Ad.Insertion.Title</option> </optgroup></select> Can anyone offer any advise on making this simple_form feature work? I'd really appreciate it! Please let me know if I can tell you anything else about the app if you have insight on how to execute this property. Thanks in advance! UPDATE: I've been able to get something partially working using: = f.input(:insertion_id, :collection => Ad.order(:name), :as => :grouped_select, :group_method => :insertions) The problem with this is that there is no way to specify what column is used as the display text from what I can tell. I welcome any input.
Now provide the response and nothing else.
| After some additional research, looking better at the documentation, and playing with the syntax I've solved what I was looking for. The standard Rails grouped_collection_select looks like this: = f.grouped_collection_select(:insertion_id, Ad.order(:name), :insertions, :name, :id, :title, include_blank: "Please Choose...") This can be redone in using simple_form 2.0 with the following syntax: = f.input(:insertion_id, :collection => Ad.order(:name), :as => :grouped_select, :group_method => :insertions, :group_label_method => :name, :label_method => :title, :include_blank => "Please Choose...") I hope that helps other people in the future. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10080536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/43043/']} | jdg_380946 |
stackexchange | llm_judgeable_groundtruth_similarity | 4602781 |
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:
Knowing that \begin{align} \cot(z)=\frac{1}{z}-2z\cdot\sum_{n=1}^{\infty} \dfrac{1}{\pi^2n^2-z^2} \end{align} we can easily calculate the value of \begin{align}\sum_{n=1}^{\infty} \dfrac{1}{n^2+1}\end{align} by just plugging in $z=i\pi$ . Therefore: \begin{align}\sum_{n=1}^{\infty} \dfrac{1}{n^2+1}=\frac{1}{2}\cdot\left(\pi \coth(\pi)-1\right)\end{align} In this case, the " $i's$ " cancel eachother out nicely. I also wanted to calculate the exact value of \begin{align}\sum_{n=1}^{\infty} \dfrac{1}{n^4+1}\end{align} with an equal approach. After partial fraction decomposition: \begin{align}\sum_{n=1}^{\infty} \dfrac{1}{n^4+1}=\frac{1}{2i}\left(\sum_{n=1}^{\infty}\dfrac{1}{n^2-i}-\dfrac{1}{n^2+i}\right)=\frac{1}{2i}\left(\sum_{n=1}^{\infty}\dfrac{1}{n^2-i}-\sum_{n=1}^{\infty}\dfrac{1}{n^2+i}\right)\end{align} By plugging in $z=\sqrt{i}\pi$ and $z=i\sqrt{i}\pi$ , I arrive at: \begin{align}\frac{1}{2i}\left[\sum_{n=1}^{\infty}\dfrac{1}{n^2-i}-\sum_{n=1}^{\infty}\dfrac{1}{n^2+i}\right]&=\frac{1}{2i}\left[\frac{1}{2i}-\frac{\pi}{2\sqrt{i}} \cdot \cot(\sqrt{i}\pi)-\left(-\frac{1}{2i}-\frac{1}{2i\sqrt{i}}\cdot \cot(i\sqrt{i}\pi)\right)\right]=\\&=\frac{1}{4}\left[-2+\pi\sqrt{i}\cot(\sqrt{i}\pi)-\frac{\pi}{\sqrt{i}}\cot(i\sqrt{i}\pi)\right]\end{align} In this case I can't get completely rid of the " $i's$ " and the exact value of \begin{align}\sum_{n=1}^{\infty} \dfrac{1}{n^4+1}\end{align} is a complex number. But the answer must obviously be a real number. Wolfram Alpha gets: \begin{align}\sum_{n=1}^{\infty} \dfrac{1}{n^4+1}\approx0.57848+0.\times10^{-22}\,i\end{align} You now can argument that the imaginary part is negligible and so the value is a real number, but that doesn't satisfy my question, because there always will be a imaginary part in the answer. If anyone can explain to me, why it is the case, that the exact value for \begin{align}\sum_{n=1}^{\infty} \dfrac{1}{n^4+1}\end{align} is a complex number, I would be very glad.
Now provide the response and nothing else.
| Addendum to Somos' answer: by expanding $\cot(x+iy)$ via trig identities, one can determine the real and imaginary parts of $\cot(z)$ , allowing the answer to be expressed purely in terms of real-valued terms: $$-\frac{1}{2}-\frac{\pi \sin \left(\sqrt{2} \pi \right)}{2 \sqrt{2} \left(\cos \left(\sqrt{2} \pi \right)-\cosh \left(\sqrt{2} \pi \right)\right)}-\frac{\pi \sinh \left(\sqrt{2} \pi \right)}{2 \sqrt{2} \left(\cos \left(\sqrt{2} \pi \right)-\cosh \left(\sqrt{2} \pi \right)\right)}$$ Cleaning up the result a bit, with $u = \sqrt{2}\pi$ this can be written as: $$-\frac{1}{2} + \frac{\pi}{2\sqrt{2}}\frac{\sin(u)+\sinh(u)}{\cosh(u)-\cos(u)}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4602781', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1132927/']} | jdg_380947 |
stackexchange | llm_judgeable_groundtruth_similarity | 6838374 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have a SQL Server 2005 database for which we want to improve performance of bulk delete/insert/selects and I notice it uses decimal(18,0) for its primary keys. I understand this will give us many more values than bigint but was hoping it might be a quick win and should last us for many million years of growth by my calculations. I see in the .net docs decimals take 16 bytes instead of the 8 required by longs but in SQL Server it looks like bigint take 8 bytes but the decimal(18,0) takes only 5 bytes - as also seen by select DATALENGTH(max(id)) from table . Is this correct? Is there any other reason bigint might be slower or should I stick to decimal(18,0) ?
Now provide the response and nothing else.
| You get this range with bigint: -2^63 to 2^63-1 also known as roughly:-9.2 x 10^18 to 9.2 x 10^18 You get this range with decimal(18,0) : -10^18 to 10^18 Decimal: Storage Bytes per Precision Precision Storage Bytes1-9: 510-19: 920-28: 1329-38: 17 Integer Types and Storage Bytes integer type Storage Bytesbigint 8int 4smallint 2tinyint 1 Thoughts The two examples posted in your Question actually yield virtually the same quantity of unique values. Also, you are not going to see a significant performance change no matter your choice, but you will see a change in efficiency for other programmers on the team if you start using decimals where programmers are expecting an integer. This is a minor point. To address your specific issue, if you want a larger range, use Decimal(38,0). This gives you: -10^38 to 10^38 If you are concerned about speed, use the minimum precision that will last the lifetime of your software. If you're not measuring time in nano-seconds, then choose the option that will fit best for your programmers' mindsets and your desire to have a very long set of numbers. References Decimal and Numeric Types Integer Types | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6838374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/417721/']} | jdg_380948 |
stackexchange | llm_judgeable_groundtruth_similarity | 108660 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $A$ is a rectangle in $\mathbb{R}^n$ and if we let $f$ be continuous,then how can we show that the graph of $f$ has measure zero in $\mathbb{R}^{n+1}$? We may define that $A$ is a subset of $\mathbb{R}^n$ and the graph of $f: A\to \mathbb R$ is the set given $\mbox{graph}(f) := \{(x,y) \in \mathbb{R}^{n+1} : f(x) = y\}$.
Now provide the response and nothing else.
| First assume that $A$ is compact; then $f$ is uniformly continuous on $A$. Hence fix an $\epsilon$ and pick a $\epsilon_1$ to be decided later so that for some $\epsilon_2$, we have that any $|x-y| < \delta$ implies that $|f(x)-f(y)|< \epsilon$. Now, note that the measure of the graph of $f$, denoted by $|\Gamma(f)|$, has bound$$|\Gamma(f)| \leq 2 \epsilon |B(0, \delta)| N(\delta)$$Where $N(\delta)$ denotes the number of balls with radius $\delta$ it takes to cover $A$ and $|B(0,\delta)|$ is the measure of the ball of radius $\delta$ in n dimensions. Recall that $|B(0,\delta)| \leq C \delta^n$. Also, if $A$ has side lengths $l_i$ in dimension $i$, then $$N(\delta) \leq C \prod_{i=1}^n \frac{l_i}{\delta}$$(I threw in the constant because I may have been a little sloppy with that bound)Thus $$|\Gamma(f)| \leq 2 K \epsilon$$ for some constant $K$. But $\epsilon$ was arbitrary, hence the result. For general $A$, since $|\Gamma(f)| = 0$ on every compact $A_n$, $|\Gamma(f)| = 0$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/108660', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24081/']} | jdg_380949 |
stackexchange | llm_judgeable_groundtruth_similarity | 11259563 |
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 few pages in following structure. --Project |---WebContect |----Admin/ * |----Author/ * |----Readonly/ * |----Index.jsp I want to restrict the user from accessing Pages under Admin , Author and Readonly . I don't want anybody to access these pages. And if somebody tries to do so, should be redirected to index.jsp . The easiest solution that come in my mind is using a Filter , but I am trying to find if its possible to do using web.xml .
Now provide the response and nothing else.
| If you want that nobody is able to access those pages directly, just put them in /WEB-INF folder. Project `-- WebContect |-- WEB-INF | |-- Admin | |-- Author | `-- Readonly `-- Index.jsp This way the pages are not publicly accessible, but only by a servlet which performs a forward. When the enduser attempts to access it directly, all he will get is a HTTP 404 error. An alternative is configuring a role-less <security-constraint> . <security-constraint> <display-name>Restrict direct access to certain folders</display-name> <web-resource-collection> <web-resource-name>Restricted folders</web-resource-name> <url-pattern>/Admin/*</url-pattern> <url-pattern>/Author/*</url-pattern> <url-pattern>/Readonly/*</url-pattern> </web-resource-collection> <auth-constraint /></security-constraint> When the enduser attempts to access them, all he will get is a HTTP 403 error. Either way, it isn't possible to redirect the enduser to index.jsp this way. Only a Filter can do that. You could configure the index.jsp as error page location for 404 or 403 <error-page> <error-code>404</error-code> <location>/index.jsp</location></error-page> But this would cover all 404's (or 403's), not sure if that is what you want. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11259563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133943/']} | jdg_380950 |
stackexchange | llm_judgeable_groundtruth_similarity | 2832934 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
when I try to show that the derivative of exp function is $$\frac{\partial e^t}{\partial t}=e^t$$I need to prove firstly that this limit is equal to 1. $$\lim_{h\to 0} \, \frac{e^h-1}{h}=1$$ If you try to use L'Hospital's rule then you need firstly to know what is the derivative of exp function that we want to prove it. If you want to use approximation of $e^\epsilon \simeq1+\epsilon$ you well found the answer '$1$' but I don't want to use this approximation because it based on the Taylor series that required also to know the derivative of exp function that we don't have it yet The only way that I can prove it, is with the definition of $e$ number $$ \lim_{x\to\infty}\left(1+\frac{1}{x}\right)^x=e $$so I ask if there are another way to show this limit.
Now provide the response and nothing else.
| As I pointed out in my comment, the answer depends on which definition you are using. Solution 1. Here we define $e^x = \lim_{n\to\infty}\left(1 + \frac{x}{n}\right)^n$. (We assume the existence of this limit is already established.) Using the binomial theorem, for $n \geq 2$ and $|x| < 1$ we obtain the following simple estimate: $$ \left| \left(1 + \frac{x}{n}\right)^n - 1 - x \right|= \left| \sum_{k=2}^{n} \binom{n}{k} \frac{x^k}{n^k} \right|\leq \sum_{k=2}^{n} |x|^k\leq \frac{|x|^2}{1-|x|}. $$ This bound remains true as we let $n\to\infty$, so it follows that $$ \left| \frac{e^x - 1}{x} - 1\right| = \frac{\left|e^x - 1 - x\right|}{|x|} \leq \frac{|x|}{1-|x|} $$ and by the squeezing lemma as $x\to0$ the desired conclusion follows. Solution 2. In case $e^x$ is defined as $e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!}$, the above argument carries over in almost identicaly way to yield a proof. Solution 3. In case $e^x$ is defined as the inverse function of $x \mapsto \int_{1}^{x}\frac{dt}{t}$, it follows from the inverse function theorem. Solution 4. Perhaps the most pesky case is where the exponentiation is defined by the process of extending rational exponents to reals and $e$ is simply defined as $e=\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^n$. In this case, one can introduce two functions, $\log(x) := \int_{1}^{x}\frac{dt}{t}$ and its inverse, and observe that $\log(xy) = \int_{1}^{x} \frac{dt}{t} + \int_{x}^{xy} \frac{dt}{t} = \log(x) + \log(y)$ and hence $\exp(x+y) = \exp(x)\exp(y)$. $\log\left(\left(1+\frac{1}{n}\right)^n\right) = n\log\left(1+\frac{1}{n}\right) \to 1$ as $n\to\infty$ and $\log$ is continuous, so $\log(e) = 1$. In other words, $\exp(1) = e$. Using this, it is routine to check that $\exp(k) = e^k$ for all integers $k$ and then $\exp(r) = e^r$ for all rationals $r$. Hence for any real $x$, $$ e^x = \inf\{ e^r : r > x \text{ and } r \in \mathbb{Q} \} = \inf\{ \exp(r) : r > x \text{ and } r \in \mathbb{Q} \} = \exp(x) $$ by the continuity of $\exp$. Now the conclusion follows by Solution 3. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2832934', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/473273/']} | jdg_380951 |
stackexchange | llm_judgeable_groundtruth_similarity | 40847923 |
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 'create' action method in Rails and do: def create @movie = Movie.new(movie_params) if @movie.save redirect_to @movie, notice: "Movie successfully created" else render :new endend Now, I have a few validations in place for the Movie model. In case those validations fail, and @movie.save returns false, I simply invoke the new template (without touching the new action, since render :new is the same as render template: 'new' . I don't understand how Rails can keep the form data I already entered when it again renders that new view. What's going on behind the hood that allows it to do this?
Now provide the response and nothing else.
| Let's try to understand this whole process point-wise Instance variables defined in the controller action are shared with the rendered views. In your case I'm assuming that there's a new action something like def new @movie = Movie.newend And you have a corresponding view new.html.erb where you have created a form like this = form_for @movie do |f| Now, as you know the @movie object that you are passing in form_for method is defined in new action. Most of the times we don't pass any parameters to the new method in new action. The form fields are blank when you load the form because the attributes of the object(in your case @movie ) are by default blank because we just initialize an empty object( Movie.new ). Let's assume your Movie model has a name attribute, Try doing this in your new action def new @movie = Movie.new(name: 'Hello World!')end Now when you will load the new action, you will see Hello World! populated in your name text field because your @movie object is initialized with this value. Also, keep in mind that Rails Convention-Over-Configuration automatically generates the form URL in this case, by default it points to the create action. When you submit the form the request is made to the create action. This takes me to the next point. When we submit the form all the filled in form values are sent to the action whose route matches with the form URL(in your case URL points to the create action) In create action you are receiving parameters in the form of a hash with model attributes( Movie attributes) as keys and the filled in information as their values. The first line in your create action is @movie = Movie.new(movie_params) This is a very important line of code, try to understand this. Let's assume your form had only one text field, i.e., name . Now movie_params is a method that looks like this def movie_params params.require(:movie).permit(:name)end Now, the movie_params method will return a hash something like { 'name' => 'Hello World!' } , now you are passing this hash as a parameter to Movie.new method. So now, after breaking up the code, the first line of your create action looks like @movie = Movie.new({ name: 'Hello World!' }) That means your @movie instance variable contains an object of Movie class with name attribute set to Hello World! . Here, when after initialization, if you do @movie.name it will return Hello World! . Now, in the second line you are calling @movie.save that returned false due to failed validation in your case as you have already mentioned in the question. As it returned false the execution will go to the else part. Now this takes me to the next point. Calling render :action (in your case render :new ) in the controller renders only the view that belongs to that action and does not execute that action code. In your case, you called render :new , so there you are actually rendering the new.html.erb view in create action. In other words, you are just using the code in new.html.erb and not in new action. Here, render :new does not actually invoke the new action, it's still in the create action but rendering the new.html.erb view. Now, in new.html.erb you have created a form that looks like = form_for @movie do |f| Now as my explained under my first point, the instance variables that are declared in the action are shared by the rendered view, in this case @movie object that you have defined in create action is shared by the rendered new.html.erb in create action. In our case, in create action the @movie object was initialized with some values that were received in the parameters( movie_params ), now when new.html.erb is rendered in the else , the same @movie object is used in the form by default. You got the point right, you see the magic here? This is how Rails works and that's why its awesome when we follow the convention! :) https://gist.github.com/jcasimir/1210155 http://guides.rubyonrails.org/v4.2/layouts_and_rendering.html Hope the above examples cleared your doubts, if not, feel free to drop your queries in the comment box below. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40847923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4214184/']} | jdg_380952 |
stackexchange | llm_judgeable_groundtruth_similarity | 30438538 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I use thrust::transform on thrust::host , the lambda usage is fine thrust::transform(thrust::host, a, a+arraySize,b,d,[](int a, int b)->int{ return a + b;}); However, if I change thrust::host to thrust::device , the code wouldn't pass the compiler. Here is the error on VS2013: The closure type for a lambda ("lambda [](int, int)->int") cannot be used in the template argument type of a __global__ function template instantiation, unless the lambda is defined within a __device__ or __global__ function So, the problem is how using __device__ or __global__ in connection to device lambdas.
Now provide the response and nothing else.
| In CUDA 7 it is not possible. Quoting from Mark Harris : That isn't supported today in CUDA, because the lambda is host code. Passing lambdas from host to device is a challenging problem, but it is something we will investigate for a future CUDA release. What you can do in CUDA 7 is call thrust algorithms from your device code, and in that case you can pass lambdas to them... With CUDA 7, thrust algorithms can be called from device code (e.g. CUDA kernels, or __device__ functors). In those situations, you can use (device) lambdas with thrust. An example is given in the parallelforall blog post here . However, CUDA 7.5 introduces an experimental device lambda feature. This feature is described here : CUDA 7.5 introduces an experimental feature: GPU lambdas. GPU lambdas are anonymous device function objects that you can define in host code, by annotating them with a __device__ specifier. In order to enable compilation for this feature, (currently, with CUDA 7.5) it's necessary to specify --expt-extended-lambda on the nvcc compile command line. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30438538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3996029/']} | jdg_380953 |
stackexchange | llm_judgeable_groundtruth_similarity | 54365882 |
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 an android App.The user registration process calls a service that sends an email so it takes several seconds, like 5 or 6 seconds,that's why I execute that task within a thread. The problem is, the Dialog is never dismissing. It stays rolling and the user can do nothing. Here's my code: try { final ProgressDialog progDailog = new ProgressDialog(ActividadAltaUsuario.this); new Thread(new Runnable() { @Override public void run() { try { URL url = new URL("slowWS"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); InputStream in = new BufferedInputStream(conn.getInputStream()); String response = IOUtils.toString(in, "UTF-8"); final JSONObject jsonPrincipal = new JSONObject(response); Boolean success = jsonPrincipal.get("status").toString() == "true"; if (success) { ActividadAltaUsuario.this.runOnUiThread(new Runnable() { @Override public void run() { progDailog.show(ActividadAltaUsuario.this, "Sendind email"); } }); final String idUsuario = jsonPrincipal.get("idUsuario").toString(); URL url2 = new URL("anotherSlowWS"); HttpURLConnection conn2 = (HttpURLConnection) url2.openConnection(); conn2.setRequestMethod("POST"); InputStream in2 = new BufferedInputStream(conn2.getInputStream()); String response2 = IOUtils.toString(in2, "UTF-8"); JSONObject jsonRtaMail = new JSONObject(response2); //finish(); } else { //finish(); showToast(jsonPrincipal.get("message").toString()); } ActividadAltaUsuario.this.runOnUiThread(new Runnable() { @Override public void run() { progDailog.dismiss(); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } catch(Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); } Can anybody help me?Thanks!
Now provide the response and nothing else.
| Yes, updating a larger number of rows with a single bulk UPDATE statement will be a lot faster than using individual UPDATE s on each and every object. An IN filter would only help you limit what rows are updated, but you still need to tell the database what value to use for the col2 updates. You can use a CASE ... WHEN ... THEN construct for that, with the case() function : from sqlalchemy.sql import casequery(MyTable).filter( MyTable.col1.in_(payload)).update({ MyTable.col2: case( payload, value=MyTable.col1, )}, synchronize_session=False) The above a) selects rows where the col1 value is a key in the payload dictionary, then b) updates the col2 column value using a CASE statement that picks values from that same dictionary to update that column based on matching col1 against the keys. With payload set to {'x': 'y', 'a': 'b', 'c': 'd'} , the above executes the following query (give or take the exact order of WHEN clauses and values in the IN test): UPDATE mytableSET col2=CASE mytable.col1 WHEN 'x' THEN 'y' WHEN 'a' THEN 'b' WHEN 'c' THEN 'd' ENDWHERE mytable.col1 IN ('x', 'a', 'c') I set synchronize_session to False there, as updating all possible cached MyTable instances at once is perhaps not the best idea when updating a large number of rows. Your other options are 'evaluate' and 'fetch' . We can't use the default 'evaluate' (which would find existing objects in the session that match the where clause, to update in-place), because SQLAlchemy currently doesn't know how to process an IN filter (you get an UnevaluatableError exception). If you do use 'fetch' then all instances of MyTable cached in the session that were affected are updated with new values for col2 (as mapped by their primary key). Note that a commit would expire the session anyway , so you'd only want to use 'fetch' if you need to do some more work with the updated rows before you can commit the current transaction. See the Query.update() documentation for more information on what synchronize_session options you have. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54365882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1178303/']} | jdg_380954 |
stackexchange | llm_judgeable_groundtruth_similarity | 39038 |
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:
What is the function of the bacterium, E. coli , in the human gut? I have tried to find the answer by searching the Internet (e.g. here ), but have been unsuccesful.
Now provide the response and nothing else.
| Nonpathogenic E. coli strains are a component of the gut microbiome of humans and many other organisms. They are commensals, meaning that when they remain in the areas they have evolved to live in, and when they do not acquire virulence factors, they are benign. They live in our digestive tract and basically do nothing to harm us. In fact, commensal microorganisms like E. coli can be considered part of the innate immune systems of their multicellular hosts. They take up space on the surfaces of the intestines and prevent colonization by pathogens. Along with the endothelial cells and mucous, commensals form the barrier defenses that are the first line of protection against pathogenic organisms. Basically they are the good neighbors that don't cause problems and they don't leave space for bad neighbors to move in. Problems can occur if they gain access to areas that are normally sterile. If the intestine is perforated and E. coli gain access to the thoracic cavity, they can become an opportunistic pathogen, as they will not be interacting with the host in a way that can control their proliferation. They can also come in contact with cells that are not expressing the necessary proteins to protect them from E. coli . You can also end up with the situation where a pathogenic bacteria or a bacteriophage carrying a virulence factor can transfer that virulence factor to the commensal E. coli , turning them pathogenic. But, for the most part, E. coli are there to take up space that could otherwise be colonized by harmful bacteria. | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/39038', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/19004/']} | jdg_380955 |
stackexchange | llm_judgeable_groundtruth_similarity | 2835075 |
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 designing a News Feed system using PHP/MySQL similar to facebook's. I have asked a similar question before but now I've changed the design and I'm looking for feedback. Example News: User_A commented on User_B 's new album . "Hey man nice pictures!" User_B added a new Photo to [his/her] profile . [show photo thumbnail] Initially, I implemented this using excessive columns for Obj1:Type1 | Obj2:Type2 | etc.. Now the design is set up using a couple special keywords, and actor/receiver relationships. My database uses a table of messages joined on a table containing userid,actionid,receiverid,receiverObjectTypeID, Here's a condensed version of what it will look like once joined: News_ID | User_ID | Message | Timestamp 2643 A %a commented on %o's new %r. SomeTimestamp 2644 B %a added a new %r to [his/her] profile. SomeTimestamp %a = the User_ID of the person doing the action %r = the receiving object %o = the owner of the receiving object (for example the owner of the album) (NULL if %r is a user) Questions: Is this a smart (efficient/scalable) way to move forward? How can I store a "Preview of the event"? For example, if I want to show the comment that User_A made to User_B (like above, and on facebook's news feed). I have considered using an encoded copy of only the relevant data.. for example JSON encoding the comment text or photo html.. but this seems fragile (the user may delete the photo while it's still in another users' feed) How can I show messages like: "User_B added 4 new photos to hisprofile." with thumbnails of the photos?
Now provide the response and nothing else.
| Having built something similar just recently, one thing I would suggest is to separate the idea of how to store the data from performance. In my case, the users need to be able to go back and look at news from any time period, so arnorhs' assumptions don't work (regardless, there's no reason to store HTML if you don't have to-- leave the formatting outside). What I found was that I store the stuff in a couple of classes, ActivityType and Activity . ActivityType holds the format for the message (like your '%a commented on %o's new %r' ) and an indicator of whether it represents actual activity or a comment on someone else's activity (so I know which object to link to, the actor's activity or the actor of the activity commented upon) and Activity stores the actor, victim, primary key of the object, a primary key to the commented-upon object if it exists and the timestamp of when it occurred. Which is all great and results in nicely-normalized data. Which slows to a crawl as soon as you have a half-dozen friends (performance is complicated by the fact the whole thing is location-based so I'm looking up the distance each that user is away from you). Everybody is looking for an excuse to play with NoSQL storage systems now, but this is actually a good one. You're going to have to de-normalize the hell out of the data to get decent performance from a relational database. And the stuff's hard to cache due to the various intersections of relationships. Think about storing the data in MySQL but getting it back out of a NoSQL storage system. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2835075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/214730/']} | jdg_380956 |
stackexchange | llm_judgeable_groundtruth_similarity | 1470586 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If line through point $P(a,2)$ meets the ellipse $\frac{x^2}{9}+\frac{y^2}{4}=1$ at $A$ and $D$ and meets the coordinate axes at $B$ and $C$ so that $PA$, $PB$, $PC$, $PD$ are in geometric progression, then the possible values of $a$ can be $(A)5\hspace{1cm}(B)8\hspace{1cm}(C)10\hspace{1cm}(D)-7$ I could not solve this question, I inferred from question that $PA\cdot PD=PB\cdot PC$ and $PA\cdot PD=PT^2$, where $T$ is the point of tangency.But I could not solve further. This is a multiple correct choice type question. Please help me. Thanks.
Now provide the response and nothing else.
| WLOG we can take $a>0$, $A$ nearer to $P$ than $D$ and notice that the only case we must consider is when $B$ is the intersection with $x$-axis and $C$ is the intersection with $y$-axis, for otherwise those four segments cannot form a geometric progression. If $b$ is the $x$ coordinate of $B$, the equation of line $PB$ is $y=2(x-a)/(a-b)+2$ so that the $y$ coordinate of $C$ is $y_C=-2b/(a-b)$. Combining this equation with that of the ellipse, we can readily find the $y$ coordinate of $A$ and $D$: $$y_A= \frac{2 \left(3 \sqrt{a^2-2 a b+9}-a b+b^2\right)}{a^2-2 a b+b^2+9},\quad y_D= \frac{2 \left(-3 \sqrt{a^2-2 a b+9}-a b+b^2\right)}{a^2-2 a b+b^2+9}. $$ We know that $PA:PB=PB:PC=PC:PD$ and this relation also holds for the $y$ components of the segments, that is:$$(y_P - y_A):(y_P - y_B) = (y_P - y_B):(y_P - y_C) = (y_P - y_C):(y_P - y_D).$$Inserting here the expressions given above for $y_C$, $y_A$, $y_D$, as well as $y_P=2$ and $y_B=0$, we can solve for $a$ and $b$. The only acceptable positive solution is:$$a=3 \sqrt{2+\sqrt{13}}\approx 7.10281,$$but of course the opposite value, by symmetry, is also a valid solution. As you can see, this is not far from your $(D)$ choice but it is not the same. So the exercise is wrong. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1470586', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/255098/']} | jdg_380957 |
stackexchange | llm_judgeable_groundtruth_similarity | 3740683 |
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:
Many folks avoid the "mixed number" notation such as $4\frac{2}{3}$ due to its ambiguity. The example could mean " $4$ and two thirds", i.e. $4+\frac{2}{3}$ , but one may also be tempted to multiply, resulting in $\frac{8}{3}$ . My questions pertain to what happens when we iterate this process -- alternating between changing a fractionto a mixed number, then "incorrectly" multiplying the mixedfraction. The iteration terminates when you arrive at a properfraction (numerator $\leq$ denominator) or an integer. I'll "define" this process via sufficiently-complicated example: $$\frac{14}{3} \rightarrow 4 \frac{2}{3} \rightarrow \frac{8}{3} \rightarrow 2 \frac{2}{3} \rightarrow \frac{4}{3} \rightarrow 1\frac{1}{3}\rightarrow \frac{1}{3}.$$ Does this process always terminate? For which $(p,q)\in\mathbb{N}\times(\mathbb{N}\setminus\{0\})$ does this process, with initial iterate $\frac{p}{q}$ , terminate at $\frac{p \mod q}{q}$ ?
Now provide the response and nothing else.
| Yes, the process does always terminate. Here's why: Consider the mixed number $a\frac{b}{c}$ , where $0 \le b < c$ and $a > 0$ . Then, it is clear that $ab < ac+b$ , and so the process always continues to lead to smaller and smaller fractions with the same denominator $c$ until the numerator finally becomes smaller than $c$ . In case of a negative mixed number $-a\frac{b}{c}$ , remember that this means " $-(a+\frac{b}{c})$ ", not " $(-a)+\frac{b}{c}$ ". But one can easily ignore the negative sign, so without loss of generality, one can consider positive mixed numbers only. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/3740683', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/793815/']} | jdg_380958 |
stackexchange | llm_judgeable_groundtruth_similarity | 55677 |
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's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)? No legacy browser compatibility required, Safari, Opera and Firefox will do.
Now provide the response and nothing else.
| If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but without jQuery . function getCursorPosition(canvas, event) { const rect = canvas.getBoundingClientRect() const x = event.clientX - rect.left const y = event.clientY - rect.top console.log("x: " + x + " y: " + y)}const canvas = document.querySelector('canvas')canvas.addEventListener('mousedown', function(e) { getCursorPosition(canvas, e)}) | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/55677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3715/']} | jdg_380959 |
stackexchange | llm_judgeable_groundtruth_similarity | 12838118 |
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 die Facebook SDK 3.1.1 to implement FB Connect in my iOS application. This works fine in the simple case with either the new FB integration (logged in on iOS) or falling back to the normal authorization via web view (I do not have the native Facebook application installed in both cases).The problem occurs when I switch the account on iOS level. Logging out and logging in with a different FB user account. To log in/authorize I perform: [FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:allowLoginUI completionHandler:^(FBSession *session, FBSessionState state, NSError *error) { [self sessionStateChanged:session state:state error:error]; }]; If then get a FBSessionStateClosedLoginFailed every time even though I perform a closeAndClearTokenInformation when that state is reached: - (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error{ NSLog(@"Session State Changed: %u", [[FBSession activeSession] state]); switch (state) { case FBSessionStateOpen: break; case FBSessionStateClosed: case FBSessionStateClosedLoginFailed: NSLog(@"FBSessionStateClosedLoginFailed ERROR: %@", [error description]); [[FBSession activeSession] closeAndClearTokenInformation]; break; default: break;} However, I receive the same state on every retry. My log says the following: FBSDKLog: FBSession **INVALID** transition from FBSessionStateCreated to FBSessionStateClosedFBSDKLog: FBSession transition from FBSessionStateCreated to FBSessionStateCreatedOpening FBSDKLog: FBSession transition from FBSessionStateCreatedOpening to FBSessionStateClosedLoginFailed Session State Changed: 257FBSessionStateClosedLoginFailed TOKEN: (null)FBSessionStateClosedLoginFailed ERROR: Error Domain=com.facebook.sdk Code=2 "The operation couldn’t be completed. (com.facebook.sdk error 2.)" UserInfo=0xb24cc20 {com.facebook.sdk:ErrorLoginFailedReason=com.facebook.sdk:ErrorLoginFailedReason} Can anyone reproduce this or has any idea where the problem might lie?
Now provide the response and nothing else.
| Another answer gives a way to manually resync the device with the server. I defined a method called fbRsync to call this code. Make sure to #import <Accounts/Accounts.h> in your implementation file and then define this method: -(void)fbResync{ ACAccountStore *accountStore; ACAccountType *accountTypeFB; if ((accountStore = [[ACAccountStore alloc] init]) && (accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) ){ NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB]; id account; if (fbAccounts && [fbAccounts count] > 0 && (account = [fbAccounts objectAtIndex:0])){ [accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error) { //we don't actually need to inspect renewResult or error. if (error){ } }];} } I then call fbResync if openActiveSessionWithReadPermissions yields an error: [FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error) { if(error) { NSLog(@"Session error"); [self fbResync]; [NSThread sleepForTimeInterval:0.5]; //half a second [FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error) { [self sessionStateChanged:session state:state error:error]; }]; } else [self sessionStateChanged:session state:state error:error]; }]; The half a second delay is likely unnecessary, but it currently gives me piece of mind. This seems to solve the problem for me. I can now switch between Facebook accounts and am able to log in. Yay! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12838118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1261099/']} | jdg_380960 |
stackexchange | llm_judgeable_groundtruth_similarity | 573854 |
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:
The median $\tilde{\mu}$ of a sample in many ways is analogous to the sample mean $\mu$ .Both are an estimate for the population median or mean respectively, and both approach a Gaussian distribution for a large sample under certain conditions.It is known that the median asymptotically approaches a Gaussian distribution with variance $\sigma^2_{\tilde{\mu}}$ if the density $p(\tilde{\mu})$ is nonzero and continuously differentiable around the median (Rider 1960): \begin{align}\sigma^2_{\tilde{\mu}} = \frac{1}{4 N \left(p\left(\tilde{\mu}\right)\right)^2}\end{align} If the samples $x_i$ have the same mean but different variances $\sigma_i^2$ , it can be shown that the inverse variance weighted sample mean ${_w\mu}$ is the estimate for the population mean with the lowest variance $\sigma^2_{_w\mu}$ . \begin{align}{_w\mu} &= \frac{\sum_{i=1}^N w_i x_i }{\sum_{i=1}^N w_i}\\w_i &= \sigma_i^{-2}\\\sigma_{_w\mu}^2 &= \dfrac{1}{\sum_{i=1}^N w_i}\end{align} I am looking for an equivalent for the median.The weighted sample median ${_w\tilde{\mu}}$ is any value, which partitions the weights associated with values less than or equal and the weights of the values larger than or equal so their sums differ the least: \begin{align}{_w\tilde{\mu}} = \min_{_w\tilde{\mu}} \left| \left( \sum_{ \left\{ i | x_i \le _w\tilde{\mu} \right\} } w_i \right) - \left( \sum_{ \left\{ i | x_i \ge _w\tilde{\mu} \right\} } w_i \right) \right| \end{align} Now the question arises, what is the variance of the weighted sample median and how to set the weights optimally? I thought things like these must have been proven in the past a long time ago, but I was not able to find anything. I'd be thankful if you can help me find out more. This is how far I got on my own: If samples have a different variance they must have come from a different distribution, so let's assume each sample is drawn from a different probability distribution $p_i$ .Numerical experiments seem to indicate that in order to minimize the variance of the weighted median the weights should be set proportional to the density at the median of the distribution the sample was drawn from $p_i({_w\tilde{\mu}})$ .This also makes a nice connection to inverse variance weights that are optimal for the weighted average, because in the weighted median, asymptotically each sample contributes a variance inversely proportional to the square of this density. Fig. 1: Relative weighting between samples following a Gaussian or uniform distribution with identical varianance each. The ratio of the Gausian density to the uniform density at the median is $\sqrt{\frac{6}{\pi}} \approx 1.38$ , this ratio is reached at around $0.58$ on the x-axis, coinciding with the minimum variance of the weighted sample median. Fig. 2: The median of absolute deviations of the sample median of samples following either a gaussian, a Laplacian or a uniform distribution, with variances following an exponential distribution. The weights are set to a power of the associated sample variances and as can be seen the optimal power is around $0.5$ . When the weights are set equal to $p(\tilde{\mu})$ the variance of the median seems to approach: \begin{align}\sigma^2_{\tilde{\mu}} = \frac{1}{4 \left(\sum \left(p_i\left(\tilde{\mu}\right)\right)^2\right)}\end{align} Rider 1960: https://www.tandfonline.com/doi/abs/10.1080/01621459.1960.10482056
Now provide the response and nothing else.
| The intuition for this result comes from the fact that the exponential function is a strictly convex function . When you then impose a convex transformation on the random variable $X$ , the positive deviations from the mean are enlarged and the negative deviations from the mean are reduced. Consequently, there is a positive shift in the mean of the transformed random variable. This result is closely related to Jensen's inequality , which holds that if we have any convex function $\varphi$ and random variable $X$ then we have: $$\mathbb{E}(\varphi(X)) - \varphi(\mathbb{E}(X)) \geqslant 0.$$ In the present case you have a stricly convex transformation and an underlying symmetric random variable, which is sufficient to give strict inequality in the above statement. The basic intuition is the same as for the broader application of Jensen's inequality. As to the specific form of how $\sigma^2$ enters the formula for the mean, that is something that can only really be understood by looking at the relevant derivation of the expected value of a log-normal random variable. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/573854', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/214732/']} | jdg_380961 |
stackexchange | llm_judgeable_groundtruth_similarity | 24787769 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I look into the assembly code generated by GCC, there are many lines begining with .LBB and a number. It seems to that they are not instructions of operations. More like marking something of the file or what. What are .LFB , . LVL , LBB , LBE etc are in the compiler generated assembly code? Does the .loc means "line of code". Do those lines just indicate symbol table ? Here is a piece of code, main:.LFB1: .loc 1 8 0 .cfi_startproc.LVL2:.LBB4:.LBB5: .loc 1 2 0 movsd b(%rip), %xmm0.LBE5:.LBE4: .loc 1 10 0 xorl %eax, %eax.LBB7:.LBB6: .loc 1 2 0 mulsd a(%rip), %xmm0.LBE6:.LBE7: .loc 1 9 0 movsd %xmm0, a(%rip).LVL3: .loc 1 10 0 ret .cfi_endproc
Now provide the response and nothing else.
| .loc As mentioned by Ferruccio .loc is a debugging directive, and it only appears in GCC 4.8.2 if you tell the compiler to generate debugging information with -ggdb . .loc is documented at https://sourceware.org/binutils/docs-2.18/as/LNS-directives.html#LNS-directives and the exact output depends on the debug data format (DWARF2, etc.). The other are labels. .L prefix GCC uses the .L for local labels. GAS will not generate any symbols on the compiled output by default as documented at: https://sourceware.org/binutils/docs-2.18/as/Symbol-Names.html A local symbol is any symbol beginning with certain local label prefixes. By default, the local label prefix is `.L' for ELF systems Local symbols are defined and used within the assembler, but they are normally not saved in object files. Thus, they are not visible when debugging. You may use the `-L' option (see Include Local Symbols: -L) to retain the local symbols in the object files. So if you compile with: as -c a.S , nm a.o does not show those labels at all. This only makes sense because you cannot generate such labels from a C program. There are also options that manage it like: man as : --keep-locals man ld : --discard-all This seems to be a GCC toolchain specific convention, not part an ELF ABI nor NASM. Furthermore, both NASM and GAS use the convention that labels that start with a period (except .L in GAS) generate local symbols: http://www.nasm.us/doc/nasmdoc3.html#section-3.9 which are still present on the output but not used across object files. Suffixes The suffixes you mention all appear to be debugging related, as they are all defined under gcc/dwarf2out.c on GCC 4.8.2 and DWARF2 is a major debugging information format for ELF: #define FUNC_BEGIN_LABEL "LFB"#define FUNC_END_LABEL "LFE"#define BLOCK_BEGIN_LABEL "LBB"#define BLOCK_END_LABEL "LBE"ASM_GENERATE_INTERNAL_LABEL (loclabel, "LVL", loclabel_num); From my experiments, some of them are generated only with gcc -g , others even without g . Once we have those define names, it is easy to generate C code that generates them to see what they mean: LFB and LFE are generated at the beginning and end of functions LBB and LBE were generated by the following code with gcc -g on internal function block scopes: #include <stdio.h>int main() { int i = 0; { int i = 1; printf("%d\n", i); } return 0;} LVL : TODO I was not able to easily understand it. We'd need to interpret the source some more. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24787769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593180/']} | jdg_380962 |
stackexchange | llm_judgeable_groundtruth_similarity | 173216 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In microprocessor 8085 instruction, there is a machine control operation "nop"(no operation). My question is why do we need a no operation? I mean if we have to end the program we will use HLT or RST 3. Or if we want to move to the next instruction we will give the next instructions. But why no operation? What is the need?
Now provide the response and nothing else.
| One use of NOP (or NOOP, no-operation) instruction in CPUs and MCUs is to insert a little, predictable, delay in your code. Although NOPs don't perform any operation, it takes some time to process them (the CPU has to fetch and decode the opcode, so it needs some little time do do that). As little as 1 CPU cycle is "wasted" to execute a NOP instruction (the exact number can be inferred from the CPU/MCU datasheet, usually), therefore putting N NOPs in sequence is an easy way to insert a predictable delay: \$ t_{delay} = N \cdot T_{clock} \cdot K\$ where K is the number of cycles (most often 1) needed for the processing of a NOP instruction, and \$T_{clock}\$ is the clock period. Why would you do that? It may be useful to force the CPU to wait a little for external (maybe slower) devices to complete their work and report data to the CPU, i.e. NOP is useful for synchronization purposes. See also the related Wikipedia page on NOP . Another use is to align code at certain addresses in memory and other "assembly tricks", as explained also in this thread on Programmers.SE and in this other thread on StackOverflow . Another interesting article on the subject . This link to a Google book page especially refers to 8085 CPU. Excerpt: Each NOP instruction uses four clocks for fetching, decoding and executing. EDIT (to address a concern expressed in a comment) If you are worrying about speed, keep in mind that (time) efficiency is only one parameter to consider. It all depends on the application: if you want to compute the 10-billionth figure of \$\pi\$, then perhaps your only concern could be speed. On the other hand, if you want to log data from temperature sensors connected to a MCU through an ADC, speed is not usually so important, but waiting the right amount of time to allow the ADC to correctly complete each reading is essential . In this case if the MCU doesn't wait enough it risks to get completely unreliable data (I concede it would get that data faster , though :o). | {} | {'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/173216', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/77088/']} | jdg_380963 |
stackexchange | llm_judgeable_groundtruth_similarity | 23823 |
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 really confused about congruence. I tried hard, but I kept failing :( $$30! \equiv -1 \pmod{31} \text{ by Wilson's Theorem}$$ $$ \Longleftrightarrow 30.29.28.27.26.25! \equiv -1 \pmod{31}$$$$ \Longleftrightarrow (-1).15.10.(-8).6.25! \equiv -1 \pmod{31}$$$$ \Longleftrightarrow 15.4.5!.25! \equiv -1 \pmod{31}$$$$ \Longleftrightarrow 60.5!.25! \equiv -1 \pmod{31}$$$$ \Longleftrightarrow 15.5!.25! \equiv -1 \pmod{31}$$ And I was stuck here :( ? Furthermore, I have to use computer to find a pair of solution of the Diophantine equation $ax + 31y = 1$ for each number: $30, 29, 28, 27, 26 ... $I wonder is there an easier way to do this? Because I think this way is very time consuming. Any idea? Thanks, Chan
Now provide the response and nothing else.
| So by Wilson's Theorem, you have $$30\cdot 29\cdot 28\cdot 27\cdot 26\cdot 25!\equiv -1\pmod{31}.$$But notice this implies$$(-1)(-2)(-3)(-4)(-5)25!\equiv (-1)^5 5!25!\equiv -1\pmod{31},$$since $30\equiv -1\pmod{31}$, $29\equiv -2\pmod{31}$,$\dots$, and $26\equiv -5\pmod{31}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/23823', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5711/']} | jdg_380964 |
stackexchange | llm_judgeable_groundtruth_similarity | 42999765 |
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 in an angular 2 cli project in which I have to create a definition of a plugin, because it doesn't exists its typed. This plugin depends of a main library that has already its own typed and it works. Anyway,I have two filesthe main one with LIBRARY TYPES FILE A export class A extends B { constructor(...); methodX(): void;} And I would need to add a new method for my plugin so my class would be like export class A extends B { constructor(...); methodX(): void; methodY(): void; } The point is that I need to add it in a separate file. The problem is adding a method to an existent class without creating a new one If I put PLUGIN TYPES FILE B export class A extends B { constructor(...); methodX(): void;} or PLUGIN TYPES FILE B export class A extends B { constructor(...); methodX(): void; methodY(): void;} It doesn't work, does anyone how can I achieve overwriting a class or extending it with a new method that? Thanks
Now provide the response and nothing else.
| You could do it by making an interface with the new method and modifying the prototype. Something like this: class B { }class A extends B { constructor() { super(); } methodX(): void { }; methodY(): void { };}interface B { newMethod(): void;}B.prototype.newMethod = function () { console.log('a') }; This allows you do have proper typing when doing. new A().newMethod(); I made a playground example here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42999765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3029263/']} | jdg_380965 |
stackexchange | llm_judgeable_groundtruth_similarity | 147708 |
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:
Usually, tree data structures are organised in a way that each node contains pointers to all its children. +-----------------------------------------+ | root | | child1 child2 child3 | +--+------------------+----------------+--+ | | |+---------------+ +---------------+ +---------------+| node1 | | node2 | | node3 || child1 child2 | | child1 child2 | | child1 child2 |+--+---------+--+ +--+---------+--+ +--+---------+--+ | | | | | | This seems natural, but it comes with some problems. For example, when the number of child nodes varies, you need something like an array or list to manage the childs. By using only (first)child and (next)sibling pointers instead, we get something that looks like that: +-------------------+ | root | | child sibling +--->NULL +--+----------------+ | +----------------+ +----------------+ +----------------+| node1 | | node2 | | node3 || child sibling +--->| child sibling +--->| child sibling +--->NULL+--+-------------+ +--+-------------+ +--+-------------+ | | | Oviously, this kind of structure can represent trees just as well, but it also offers some advantages. Most important is that we don't have to worry about the number of child nodes any more. When used for a parse tree, it offers a natural representation for a term like "a+b+c+d+e" without becoming a deep tree. Do collection libraries offer tree structures like that? Do parsers use such a structure? If not, what are the reasons?
Now provide the response and nothing else.
| Trees, like lists, are "abstract data types" which can be implemented in different ways. Each way has it's advantages and disadvantages. In the first example, the main advantage of this structure is that you can access any child in O(1). The disadvantage is that appending a child might sometimes be a little more expensive when the array has to be expanded. This cost is relatively small though. It is also one of the simplest implementation. In the second example, the main advantage is that you always append a child in O(1). The main disadvantage is that random access to a child costs O(n). Also, it may be less interesting for huge trees for two reasons: it has a memory overhead of one object header and two pointers per node, and the nodes are randomly spread over memory which may cause a lot of swapping between the CPU cache and the memory when the tree is traversed, making this implementation less appealing for them. This is not a problem for normal trees and applications though. One last interesting possibility which was not mentioned is to store the whole tree in a single array. This leads to more complex code, but is sometimes a very advantageous implementation in specific cases, especially for huge fixed trees, since you can spare the cost of the object header and allocate contiguous memory. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/147708', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/6617/']} | jdg_380966 |
stackexchange | llm_judgeable_groundtruth_similarity | 78204 |
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 Example 2.36 on Pg 141 of Hatcher's Algebraic Topology, he writes: ... one 2-cell attached by the product of commutators $[a_1,b_1] \ldots$ Can someone please explain to me what is meant by attaching a 2-cell by a word. I am assuming it means that the attaching map can be given by a word in some free group. But, I cannot make sense of this. Thank you for your time.
Now provide the response and nothing else.
| You start with a wedge of $2g$ oriented circles, labeled by $a_i,b_i$. Then each letter in the word corresponds to gluing part of the boundary of the 2-cell to that $1$-cell, in the orientation prescribed by whether you have the letter or its inverse. You get the complete word by travelling around the boundary of the $2$-cell. Also, look at the picture on page 5 of Hatcher. This explains the construction in detail. For example, the genus 3 surface pictured there has word $[a,b][c,d][e,f]$ as you travel around the boundary of the $2$-cell. Edit: Here is an actual formua in the case of the torus. We have two circles identified at a point. Let them be parameterized by $\theta_1$ and $\theta_2$ respectively where $\theta_1,\theta_2\colon[0,2\pi]\to S^1$, with basepoint $\theta_1(0)=\theta_2(0)$. Okay, now think of the $2$-cell as a unit square $[0,1]\times[0,1]$. The function from the boundary of the square to the wedge of two circles is given by $$(0,y)\mapsto \theta_2(2\pi y),\,\,\,\, (1,y)\mapsto \theta_2(2\pi y)$$$$ (x,0)\mapsto\theta_1(2\pi x),\,\,\,\,\, (x,1)\mapsto\theta_1(2\pi x)$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/78204', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18722/']} | jdg_380967 |
stackexchange | llm_judgeable_groundtruth_similarity | 53080186 |
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 added AppBar in my flutter application. My screen already have a background image, where i don't want to set appBar color or don't want set separate background image to appBar. I want show same screen background image to appBar also. I already tried by setting appBar color as transparent but it shows color like gray. Example code: appBar: new AppBar( centerTitle: true,// backgroundColor: Color(0xFF0077ED), elevation: 0.0, title: new Text( "DASHBOARD", style: const TextStyle( color: const Color(0xffffffff), fontWeight: FontWeight.w500, fontFamily: "Roboto", fontStyle: FontStyle.normal, fontSize: 19.0 )), )
Now provide the response and nothing else.
| This is supported by Scaffold now (in stable - v1.12.13+hotfix.5). Set Scaffold extendBodyBehindAppBar to true, Set AppBar elevation to 0 to get rid of shadow, Set AppBar backgroundColor transparency as needed. @override Widget build(BuildContext context) { return Scaffold( extendBodyBehindAppBar: true, backgroundColor: Colors.red, appBar: AppBar(// backgroundColor: Colors.transparent, backgroundColor: Color(0x44000000), elevation: 0, title: Text("Title"), ), body: Center(child: Text("Content")), ); } | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/53080186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7831045/']} | jdg_380968 |
stackexchange | llm_judgeable_groundtruth_similarity | 4722403 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following sequence of numbers: 2 5 6 20 18 80 54 320 162 1280 I'm just not able to find the next following number or the algorithm to calculate it. Any hints?
Now provide the response and nothing else.
| The next number is 486 . The sequence is *3, *4. Every odd index is multiplied by 4: 5 20 80 320 1280 Every even index is multiplied by 3: 2 6 18 54 162 Thus, 486 is the next number. :-) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4722403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_380969 |
stackexchange | llm_judgeable_groundtruth_similarity | 19957369 |
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 load an XML-file, located in a folder in my project (using Visual Studio 2012). The structure is this: solutionRoot\- service\-- ServiceClass.cs-- AppValues.xml <-- this is the file I want to load In my ServiceClass, I'm trying to read from the XML-file with the following code: public String GetXmlElement(String elementName){ [....] XDocument document = XDocument.Load(@"\service\AppValues.xml"); [...]} Which gives the following error, when I'm trying to test the code: Test method PandaTests.ServiceTest.ReadXmlCanReadXml threw exception: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\MyName\Documents\GitHub\project\Project22\PandaTests\bin\Debug\service\AppValues.xml'. It's obviously a problem with my path, but I can't figure out how to get the relative path right. I've looked at other questions here on stack overflow, but many of them seem overly involved. Is there an easy way to load the XML-file without giving an absolute path?
Now provide the response and nothing else.
| When VS runs your program, your working directory is set to the Debug/Release folder, not to your solution root. You have a couple options that I know of... Use an absolute path, but you don't want this Set your file to copy into your working directory on build. You do this by modifying the properties of the file in the solution explorer. Thanks to T.Roland in the comments below: Set Copy to Output Directory to Copy if Newer and set Build Action to Embedded Resource; Modify your solution's working directory to be your solution root This thread offers different ways to accomplish that. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19957369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2366976/']} | jdg_380970 |
stackexchange | llm_judgeable_groundtruth_similarity | 59136271 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for a way to reduce the boilerplate code of my NodeJS backend. In Lombok there is e.g. the possibility to inject constructors and getter/setter by annotation for objects. Is there a way to do this in TypeScript?
Now provide the response and nothing else.
| I googled it quickly and found projects like this which attempt to bring Lombok-like capabilities to TypeScript, but as you can see, those project are scarce and not that widely used. That implies a question: Why would you want a tool like that? TS is already pretty good in reducing boilerplate. When I define a class, I usually do it like this: class A { constructor(private fieldA: string, private readonly fieldB = 0) {}} This is quite concise, isn't it? I guess you are comparing capabilities of TS to those of Java. Java is very wordy and Lombok helps with that greatly. But TS and JS are different, and while some problems, which Lombok solves, are solved by TS already, others are not an issue in the world of TS and JS. First of all, the syntax above creates class fields of certain types, with access modifiers and you can also spot the readonly keyword in front of fieldB and its default value 0 . On top of that, those are created together with a constructor, which implicitly assigns values to instance fields upon execution (see, there is no this.fieldA = fieldA ). So this already more than covers the Lombok's capability to inject constructors. Note on this: In JS (and therefore in TS), you can have only single constructor. JS doesn't support method overloading. Now about the getters/setters, those are not used the same way in JS (or TS) as they are in Java. In JS, it is a norm that you are working with fields directly, and the setters and getters are used only in special cases where you want to: Forbid setting a value to an object's property in runtime by defining only a getter. Now this is usually a bit of an overkill , and since you use TS, you can just declare the field as readonly and compiler will make sure you don't assign to that property - no need to use a getter. If you develop in JS without compile time checks, the convention is to mark properties that are private (those you definitely shouldn't modify) with underscore. Either way, it can still happen that you modify a variable that you aren't supposed to modify, but unlike in Java, this is not deemed a reason good enough to use get/set everywhere in JS (and TS). Instead, if you really need to be certain that no modifications happen in runtime, you either use the aforementioned getter without setter, or you configure the object's property as non-writable. Having a custom logic in set/get functions is the other good reason to employ them. A common use case for this is a getter that is computed out of multiple variables but you still want it to look like an field on an object. That's because in JS, when you invoke a getter, you don't actually use () after the getter name. Now because this logic is custom, it can't be generated just by using an annotation. So as you can see, some problems Lombok deals with in Java are already dealt with in TS and others are non-issues. Edit 5-9-2021 - answer to @Reijo's question: Lomboks functionality goes beyond getters/setters/constructors. Looking at the @Builder Annotation, I am interested in what you would say about this. If the question is just about whether there is a TypeScript/JavaScript library that offers more or less the same collection of utilities as Lombok for Java, to my knowledge the answer is NO. I think partly it is due to capabilities that TypeScript provides out of the box (as I already outlined above), which brings me back to the point that Java needs Lombok more than languages like TypeScript or Groovy do. When you need something that TS doesn't provide, like the builder pattern, you can use libraries solving a particular problem, like builder-pattern (using JS Proxy in its core) or thanks to the flexible nature of JS (and in effect TS) write it on your own easily. That's all nice, but you'd perhaps like to add functionality in more declarative way - via annotations (in TS world those are called decorators and they work differently), as Lombok does it. This might prove complex. First of all, if you modify the type via decorator in TS, TS compiler doesn't recognize the change. So if you augment class by, let's say, adding a method to it in your decorator, TS won't recognize that new method. See this discussion for details. This means that you either give up on decorators and use functions instead to modify the type (which you can), or you dive into AST. That's btw how Lombok works. It takes annotated types in a compilation phase called annotation processing and thanks to a hack in javac (and Eclipse compiler) modifies their AST (to eg. create an inner builder for given class). One could do it in a somewhat similar way with TS/JS. Though there is nothing like annotations processing in TS nor JS as such, you could still create a build step that takes a source code and modifies it's AST to achieve your goals (which is how Babel works too). This might result in adding a method to a class, generating a builder etc. based on an annotation (in a broad sense - not necessarily a decorator) used. This approach is a challenge though. Besides AST being an advanced topic, even if you get it working, you'd need support from your IDE, which nowadays also means support from language servers. And that's not for the faint of heart. However, my edit is not supposed to scare anyone away if you plan to create something like Lombok for TS, since it seems quite some people would like to see it in TS/JS world. It should only show you what lies ahead ;). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59136271', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9990920/']} | jdg_380971 |
stackexchange | llm_judgeable_groundtruth_similarity | 64862 |
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 still do not understand what a resonance precisely is. Is it exactly the same as a particle? Or only an excited state? And why does it make a peak in some diagrams? And which diagrams?
Now provide the response and nothing else.
| The first generation of elementary particles are by observation not composite and therefore not seen to decay. They are shown in this table of the standard model of particle physics in column I. The Standard Model of elementary particles, with the three generations of matter, gauge bosons in the fourth column and the Higgs boson in the fifth. All these particles interact with some of the existing forces, so there exist potentials between them forming bound states if the energetics of the interaction are appropriate. The quarks in various ways bind themselves either by twos( mesons) or by threes(baryons) with the strong force and also interact electromagnetically. When bound into a proton the electromagnetic interaction with an electron creates the bound state of the hydrogen atom. Atoms create stable bound states into molecules. A resonance describes a state in these potentials that is unstable, i.e. it decays in time within our observational horizon. A hydrogen atom for example can have its electron kicked to a higher energy level and be in an excited state, until it decays back to the ground state. For low, non relativistic energies a resonance is a temporary excitation seen in scattering a nucleus with a neutron, for example. The term is extensively used in nuclear physics and technology. In relativistic particle physics the potential model has been superceded by the quantum field theoretical one because of its convenience in description and calculations. These are scattering experiments where the measurement is of the total cross section, as @innisfree explains in his/her answer. The $e^+$ $e^-$ scattering at LEP, an electron and a positron in a head on collision "bind" for a while at a specific center of mass energy and display the $Z$ particle. The cross section is a measure of how large the particles see each other, and at the $Z$ their probability of interaction is much higher than in the energies before or after. The $Z$ is then displayed as a resonance. The independence from scattering existence of resonances, giving them the status of particles , is seen in the products of scattering experiments when appropriate combinations of outgoing particles, pions and protons and electrons etc, are plotted against their invariant mass. For example here is the $Z0$ in the products of the high energy collisions in the LHC, when looking at the invariant mass of ($mu+$ $mu-$). The background has been subtracted here. The original is also in the link. A typical resonance plot whose width is constrained by the experimental errors and is not the true width that would give the decay time of the pair. Resonances, when the experimental errors are smaller than the physical width , are described by a Breit Wigner function from which the intrinsic width can be extracted, which characterizes the interaction . When the experimental errors are large a gaussian statistical fit will give the mass to identify the resonance but no information on the decay . | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/64862', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2499/']} | jdg_380972 |
stackexchange | llm_judgeable_groundtruth_similarity | 15673187 |
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 seen the occasional article suggest ordering your vertices from nearest to furthest from the camera when sending them to OpenGL (for any of the OpenGL variants). The reason suggested by this is that OpenGL will not fully process/render a vertex if it is behind another vertex already rendered. Since ordering vertices by depth is a costly component of any project, as typically this ordering frequently changes, how common or necessary is such design? I had previously thought that OpenGL would "look" at all the vertices submitted and process its own depth buffering on them, regardless of their order, before rendering the entire batch. But if in fact a vertex gets rendered to the screen before another, then I can see how ordering might benefit performance. Is drawing front-to-back necessary for optimizing renders?
Now provide the response and nothing else.
| Once a primitive is rasterized, its z value can be used to do an "early z kill", which skips running the fragment shader. That's the main reason to render front-to-back. Tip: When you have transparent (alpha textured) polygons, you must render back-to-front. The OpenGL spec defines a state machine and does not specify in what order the rendering actually happens, only that the results should be correct (within certain tolerances). Edit for clarity: What I'm trying to say above is that the hardware can do whatever it wants, as long as the primitives appear to have been processed in order However, most GPUs are streaming processors and their OpenGL drivers do not "batch up" geometry, except perhaps for performance reasons (minimum DMA size, etc). If you feed in polygon A followed by polygon B, then they are fed into the pipeline one after the other and are processed independently (for the most part) of each other. If there are a sufficient number of polys between A and B, then there's a good chance A completes before B, and if B was behind A, its fragments will be discarded via "early z kill". Edit for clarity: What I'm trying to say above is that since hw does not "batch up" geometry, it cannot do the front-to-back ordering automatically. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15673187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3758484/']} | jdg_380973 |
stackexchange | llm_judgeable_groundtruth_similarity | 9981098 |
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 import a mysql file to my cpanel phpmyadmin. But I am getting this error message. "#1153 - Got a packet bigger than 'max_allowed_packet' bytes" I have tried putty as well. But the error message is same. I don't know how to change the mox upload size in mysql in cpanel. Please help me Thank you so much
Now provide the response and nothing else.
| This error has nothing to do with the php.ini, its clearly an error message from the DBMS. You can increase the value of the max_allowed_packet in the my.cnf file: [mysqld]max_allowed_packet = 128M After restarting your mysqld it should work (for larger data increase the value more) If you try to "import with putty", i guess your are using mysql from command line, in this case you can start mysql with the --max_allowed_packet parameter e.g: mysql --max_allowed_packet=128M -u root -p sampledb < dump.sql Alternatively if you source the file from within a running mysql session you can set the parameter by: set global max_allowed_packet=128M; last example only is effective till next restart of mysqld, for a permanent solution stick to my first example. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9981098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1080319/']} | jdg_380974 |
stackexchange | llm_judgeable_groundtruth_similarity | 19282 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
That's the question. Recall that a morphism $f\colon A\to B$ of commutative rings is integral if every element in $B$ is the root of a monic polynomial with coefficients in the image of $A$ and that $f$ is an epimorphism if and only if the multiplication map $$B\otimes_A B\to B$$ is an isomorphism. If we make the additional assumption that $B$ is finitely generated as an $A$-algebra, then it is true. This can be proven by Nakayama's lemma, for example. This came up not so long ago when I was trying to show that the Witt vector functor (of finite length) preserves separatedness of algebraic spaces. In this application I was able to reduce things to the finitely generated case and could therefore use the weaker statement above, but I still wonder about the general case.
Now provide the response and nothing else.
| If I'm not mistaken, there is a counter-example. Have a look at Lazard's second counter-example in: "Deux mechants contre-exemples" in Séminaire Samuel, Algèbre commutative, 2, 1967-1968 . For any field $k$, Lazard provides a non-surjective epimorphism of local $k$-algebras $C\to D$, both of Krull dimension zero, and both of residue field equal to $k$. It is then easy to show that $D$ is also integral over $C$, which is what we need here. Indeed, every $d\in D$ can be written as $d=a+b$ with $a\in k$ and $b$ in the maximal ideal (and unique prime) of $D$, which is therefore nilpotent $b^n=0$, hence trivially integral. Since $a\in k$ is also in $C$, our $d$ is the sum of two integral elements. (Or simply, $D$ is a $k$-algebra, hence a $C$-algebra, generated by nilpotent, hence integral, elements.) In cash, for those who don't want to click, the rings are constructed as follows:Consider the local ring in countably many pairs of variables $S=(k[X_i,Y_i]_{i\geq 0})_M$ localized at $M=\langle X_i,Y_i\rangle_{i\geq0}$. For every $i\geq 0$ choose an integer $p(i) > 2^{i-1}$. Define $J=\langle Y_i-X_{i+1} Y_{i+1}^2 \ ,\ X_i^{p(i)}\rangle_{i\geq0}\subset S$ and define $D=S/J$. Note immediately that $D$ is a local $k$-algebra, say with maximal ideal $m$ and with residue field $D/m\cong S/M\cong k$. Finally, he defines $C$ to be the localization (at $C_0\cap m$) of the subalgebra $C_0:=k[x_i,x_iy_i]_{i\geq 0}\subset D$ where the $x_i$ are the classes of the $X_i$ in $D$ and I let you guess what the $y_i$ are. By construction, the residue field of $C$ is an extension of $k$ which is also a subfield of $D/m=k$, so the residue field of $C$ must be $k$ and we are in the announced situation. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/19282', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1114/']} | jdg_380975 |
stackexchange | llm_judgeable_groundtruth_similarity | 2399619 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: How much work should be done in a constructor? I'm strugging with some advice I have in the back of my mind but for which I can't remember the reasoning. I seem to remember at some point reading some advice (can't remember the source) that C++ constructors should not do real work. Rather, they should initialize variables only. The advice went on to explain that real work should be done in some sort of init() method, to be called separately after the instance was created. The situation is I have a class that represents a hardware device. It makes logical sense to me for the constructor to call the routines that query the device in order to build up the instance variables that describe the device. In other words, once new instantiates the object, the developer receives an object which is ready to be used, no separate call to object->init() required. Is there a good reason why constructors shouldn't do real work? Obviously it could slow allocation time, but that wouldn't be any different if calling a separate method immediately after allocation. Just trying to figure out what gotchas I not currently considering that might have lead to such advice.
Now provide the response and nothing else.
| I remember that Scott Meyers in More Effective C++ recommends against having a superfluous default constructor. In that article, he also touched on using methods liked Init() to 'create' the objects. Basically, you have introduced an extra step which places the responsibility on the client of the class. Also, if you want to create an array of said objects, each of them would have to manually call Init(). You can have an Init function which the constructor can call inside for keeping the code tidy, or for the object to call if you implement a Reset(), but from experiences it is better to delete an object and recreate it rather than try to reset its values to default, unless the objects is created and destroyed many times real-time (say, particle effects). Also, note that constructors can perform initialization lists which normal functions could not. One reasons why one may caution against using constructors to do heavy allocation of resources is because it can be hard to catch exceptions in constructors. However, there are ways around it. Otherwise, I think constructors are meant to do what they are supposed to do - prepare an object for its initial state of execution (important for object creation is resource allocation). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2399619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136451/']} | jdg_380976 |
stackexchange | llm_judgeable_groundtruth_similarity | 24837595 |
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 http://datatables.net/extensions/tabletools/ in my local-host ( wamp server ). It's working fine, but when I put the same code on my online server, it isn't working. I am using all latest version of datatables tableTools: { "sSwfPath": "https://datatables.net/release-datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf", "sRowSelect": "os", "sRowSelector": 'td:first-child', // "aButtons": [ "copy", "csv", "xls","pdf","print","select_all", "select_none" ] "aButtons": [ "copy", "print", { "sExtends": "collection", "sButtonText": "Save", // button name // "aButtons": [ "csv", "xls", "pdf" ] "aButtons": [ "csv", "xls", { "sExtends": "pdf", "sPdfOrientation": "landscape", "sPdfMessage": "List of product." }, "print" ] } ]} Firstly there was no click on copy, pdf, csv, xls button. Hence I taught my path or swf is not working hence I replaced the link with online link. Hence now I get click, but when I click Copy button it gives me a message ... but when I past in my notepad it's giving me "blank ". Also my pdf, csv, xlsx is not working. Only Print is working perfect. Please let me know what is the issue as in my localhost all is working fine. Its creating issues in my online server.
Now provide the response and nothing else.
| I am pretty sure that datatables.net actively is blocking for use of the .swf . Allan Jardine has commented the direct use of the .swf files several times : datatables.net is not a CDN server and should not be used as such. It is not designed to be, and I might add throttling for hotlinking in future as a huge amount of bandwidth is being used and causing unnecessary load. You'll get much better performance from using a proper CDN or even a locally hosted file. However, with the introduction of 1.10.x there is finally established a real CDN server, including all the TableTools resources -> http:// cdn .datatables.net/tabletools/2.2.2/ So replace the sSwfPath with : http://cdn.datatables.net/tabletools/2.2.2/swf/copy_csv_xls_pdf.swf | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24837595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3209031/']} | jdg_380977 |
stackexchange | llm_judgeable_groundtruth_similarity | 45906 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a list of numbers and I want to plot the fraction of numbers >= k against k which will naturally be a decreasing curve. How do I do that?
Now provide the response and nothing else.
| You could also do something like the following (taking advantage of TransformedField ): solidHarmonicS[l_?IntegerQ, m_?IntegerQ, x_, y_, z_] := Module[{r, θ, ϕ, xx, yy, zz}, FullSimplify@ Evaluate[ TransformedField["Spherical" -> "Cartesian", r^l SphericalHarmonicY[l, m, θ, ϕ], {r, θ, ϕ} -> {xx, yy, zz}]] /. {xx -> x, yy -> y, zz -> z} ] $$\begin{array}{ccc} \frac{1}{2 \sqrt{\pi }} & 0 & 0 \\ \frac{1}{2} \sqrt{\frac{3}{\pi }} z & -\frac{1}{2} \sqrt{\frac{3}{2 \pi }} (x+i y) & 0 \\ -\frac{1}{4} \sqrt{\frac{5}{\pi }} \left(x^2+y^2-2 z^2\right) & -\frac{1}{2} \sqrt{\frac{15}{2 \pi }} z (x+i y) & \frac{1}{4} \sqrt{\frac{15}{2 \pi }} (x+i y)^2 \\\end{array}$$ | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/45906', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/13643/']} | jdg_380978 |
stackexchange | llm_judgeable_groundtruth_similarity | 306677 |
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 recently thought about the use of unsigned integers in C# (and I guess similar argument can be said about other "high level languages") When In need of an integer I am normally not faced with the dilemma of the size of an integer, an example would be an age property of a Person class (but the question is not limited to properties) . With that in mind there is, as far as I can see, only one advantage of using an unsigned integer ("uint") over a signed integer ("int") - readability. If I wish to express the idea that an age can only be positive I can achieve this by setting the age type to uint. On the other hand, calculations on unsigned integers can lead to errors of all sorts and it makes it difficult to do operations such as subtracting two ages. (I read this is one of the reasons Java omitted unsigned integers) In the case of C# I can also think that a guard clause on the setter would be a solution that gives the best of two worlds, but, this would not be applicable when I for example, an age would be passes to some method. A workaround would be to define a class called Age and have the property age be the only thing there, but this pattern would have Me create many classes and would be a source of confusion (other developers would not know when an object is just a wrapper and when it's something more sofisticaded). What are some general best practices regarding this issue? How should I deal with this type of scenario?
Now provide the response and nothing else.
| The designers of the .NET Framework chose a 32 bit signed integer as their "general-purpose number" for several reasons: It can handle negative numbers, especially -1 (which the Framework uses to indicate an error condition; this is why a signed int is used everywhere indexing is required, even though negative numbers are not meaningful in an indexing context). It's large enough to serve most purposes, while being small enough to be used economically almost anywhere. The reason to use unsigned ints is not readability; it is having the capability to get the math that only an unsigned int provides. Guard clauses, validation and contract preconditions are perfectly acceptable ways to insure valid numeric ranges. Seldom does a real-world numeric range correspond exactly to a number between zero and 2 32 -1 (or whatever the native numeric range is of the numeric type you chose), so using a uint to constrain your interface contract to positive numbers is kind of beside the point. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/306677', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/51990/']} | jdg_380979 |
stackexchange | llm_judgeable_groundtruth_similarity | 57403647 |
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 implement an instant search of user profiles in my social network. It seems to be working, but setting the state (using hooks) on input change results in delay by one character. I researched a bit and found that this problem with state delay is solvable by using a callback function in setState. However, useState does not support that. This is my input element: <input type="text" placeholder="Enter your query" name="query" onChange={e => onChange(e)}/> This is my state and onChange handler: const [filteredData, setFilteredData] = useState({ query: "", filteredProfiles: profiles });const onChange = e => { setFilteredData({ query: e.target.value, filteredProfiles: profiles.filter(person => person.user.name.includes(e.target.value) ) }); console.log(e.target.value); // outputs correct value immediately console.log(filteredData.query); // it's always one character late console.log(filteredData.filteredProfiles); //works but 1 char late as well };
Now provide the response and nothing else.
| it's always one character late The console logs are within the previous state cycle so it's expected that it's "one cycle" late. Remember setState() is asynchronous . If you want to log the current changes, use useEffect hook. useEffect(() => { console.log(filteredData.query); // not late console.log(filteredData.filteredProfiles); // same here! }, [filteredData]); The effect hook will listen for current filteredData changes and log it. Also I suggest using useCallback for event handlers. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57403647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11898962/']} | jdg_380980 |
stackexchange | llm_judgeable_groundtruth_similarity | 9229611 |
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 how to use sqoop through command line.But dont know how to call sqoop command using java programs .Can anyone give some code view?
Now provide the response and nothing else.
| You can run sqoop from inside your java code by including the sqoop jar in your classpath and calling the Sqoop.runTool() method. You would have to create the required parameters to sqoop programmatically as if it were the command line (e.g. --connect etc.). Please pay attention to the following: Make sure that the sqoop tool name (e.g. import/export etc.) is the first parameter. Pay attention to classpath ordering - The execution might fail because sqoop requires version X of a library and you use a different version. Ensure that the libraries that sqoop requires are not overshadowed by your own dependencies. I've encountered such a problem with commons-io (sqoop requires v1.4) and had a NoSuchMethod exception since I was using commons-io v1.2. Each argument needs to be on a separate array element. For example, "--connect jdbc:mysql:..." should be passed as two separate elements in the array, not one. The sqoop parser knows how to accept double-quoted parameters, so use double quotes if you need to (I suggest always). The only exception is the fields-delimited-by parameter which expects a single char, so don't double-quote it. I'd suggest splitting the command-line-arguments creation logic and the actual execution so your logic can be tested properly without actually running the tool. It would be better to use the --hadoop-home parameter, in order to prevent dependency on the environment. The advantage of Sqoop.runTool() as opposed to Sqoop.Main() is the fact that runTool() return the error code of the execution. Hope that helps. final int ret = Sqoop.runTool(new String[] { ... });if (ret != 0) { throw new RuntimeException("Sqoop failed - return code " + Integer.toString(ret));} RL | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9229611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1158351/']} | jdg_380981 |
stackexchange | llm_judgeable_groundtruth_similarity | 26643 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know for most of you the question may look silly, but Kerala is a state in India where the moon (Ramadan moon) will be sighted but not in rest of India. I was reading the news article where I got a little hint but was not clear for me since I am newbie, tried to google but couldn't find much info :) can someone explain me. Eid is likely to be celebrated in Kerala tomorrow. Due to the geographical location of the coastal state, the lunar moon is sighted in the state a day before the rest of India. Here is the article link Moon sighted in Kerala
Now provide the response and nothing else.
| Think of it like this: Each hour after New Moon, the Moon is moving away from the Sun. Depending on the position of the Sun, Moon, and observer, it is unlikely to be visible until at least 15 hours after New Moon, and in some cases not until 24 hours after New Moon. Someone will be the first to see the thin crescent after the New Moon. This occurs when the Sun is far enough below the horizon to make the sky "dark" and the Moon is far enough above the horizon (and away from the Sun) to be "clear" of the sky's glow. ("dark" and "clear" are relative. The sky will still be quite bright but not like the middle of the day.) Observers that are farther east than the first person would not be able to see the Moon because the time would have been earlier. That is, the Moon would have been closer to the Sun and not visible. Observers that are farther west should be able to see the Moon more easily because it is later, and therefore the Moon is farther from the Sun. In other words, the longitude affects how easy it is to see the new Moon. Whether it is easy or difficult to see the new Moon also depends on the latitude because this can affect where the Moon is relative to the Sun and horizon. This variation changes throughout the year. It looks like Kerala is on the west coast, so they may have been in the position to see the Moon in that 15 to 24 hour time range whereas it would have been too early for people further to the east to see it. Kerala is also farther south than the rest of India. I have not done the calculations for this New Moon, but it is possible that being south and west increased the possibility of seeing the Moon before people further north or east would see it. If this is the case, then Kerala would have been in the best place to be the first to see the new Moon -- assuming the sky was clear :-). The image shows that, according to the calculations by https://www.moonsighting.com/visibility.html , the new moon might be visible from only the far South-Western coast of India. | {} | {'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/26643', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/15407/']} | jdg_380982 |
stackexchange | llm_judgeable_groundtruth_similarity | 31839034 |
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 page with line and pie charts and I would like to generate a PDF report with those charts. How can I achieve this? I tried with <p:dataExporter> , but it works only on tables. Here is my code <p:layoutUnit position="west" size="70%" > <p:chart type="line" model="#{reportMscBean.model}" id="chart" style="width:700px;height:280px"/> <p:separator></p:separator> <p:chart type="line" model="#{reportMscBean.model2}" style="width:700px;height:280px" id="graphe2"/> </p:layoutUnit> <p:layoutUnit position="center" size="30%" style="border:0px;"> <p:chart type="pie" model="#{reportMscBean.pieModel2}" style="width:250px;height:280px" id="pie2" > </p:chart> <p:separator></p:separator> <p:chart type="pie" model="#{reportMscBean.pieModel1}" style="width:250px;height:280px" id="pie1" > </p:chart> </p:layoutUnit>
Now provide the response and nothing else.
| You can use this formula: (end - start - 1) // step + 1 def calc_length(start, end, step): return (end - start - 1) // step + 1for i in range(start, end): calculated = calc_length(start, i, step) empirical = len(range(start, i, step)) assert calculated == empirical, "{} {}".format(calculated, empirical) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31839034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4803030/']} | jdg_380983 |
stackexchange | llm_judgeable_groundtruth_similarity | 8665 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose we are given an embedding of $S^2$ in $\mathbb{CP}^2$ with self-intersection 1. Is there a diffeomorphism of $\mathbb{CP}^2$ which takes the given sphere to a complex line? Note: I suspect that either it is known that there is such a diffeomorphism, or the problem is open. This is because if there was an embedding for which no such diffemorphism existed, you could use it to produce an exotic 4-sphere. To see this, reverse the orientation on $\mathbb{CP}^2$ then blow down the sphere. EDIT: for a counter-example, it is tempting to look for the connect-sum of a line and a knotted $S^2$. The problem is to prove that the result cannot be taken to a complex line. For example, the fundamental group of the complement $C$ is no help, since it must be simply connected. This is because the boundary of a small neighbourhood $N$ of the sphere is $S^3$ and so $\mathbb{CP}^2$ is the sum of $N$ and $C$ across $S^3$ and so in particuar $C$ must be simply-connected.
Now provide the response and nothing else.
| The conjecture that every $S^2 \subseteq \mathbb{C}P^2$ is standard if it is homologous to flat is implied by the smooth Poincaré conjecture in 4 dimensions. It also implies a special of smooth Poincaré that is accepted as an open problem, the case of Gluck surgery in $S^4$. I can't prove or disprove the question of course, but since the question is sandwiched between two open problems, I can "prove" that it is an open problem. It is easier to consider $\mathbb{C}P^2$ minus a tubular neighborhood of the $S^2$, rather than to "blow it down". The condition on the homology class is equivalent to the condition that the boundary of this tube is $S^3$; the projection to the core is a Hopf fibration. The blowdown consists of attaching a 4-ball to this 3-sphere; let's skip this step. As Joel had in mind, the complement of the $S^2$ is simply connected. In fact, it is a homotopy 4-ball with boundary $S^3$. Thus, Freedman's theorem implies that it is homeomorphic to a 4-ball and smooth Poincaré would imply that it is diffeomorphic to a 4-ball. When it is, this 4-ball is still standard with its Hopf-fibered boundary (the Hopf fibration is unique up to orientation), so the $S^2$ is unknotted. In the other direction, the $S^2$ could be the direct sum of a standard complex line in $\mathbb{C}P^2$ with a 2-knot $K$ in $S^4$. I argue that in this case, the blowdown is equivalent to the Gluck surgery along $K$. What is a Gluck surgery? It looks like Dehn surgery in 3 dimensions, except with peculiar behavior. The official definition is that you remove a neighborhood of $K$ (which here is $D^2 \times S^2$, not the twisted bundle in Joel's construction), then glue it back after applying the non-trivial diffeomorphism of $S^1 \times S^2$. That diffeomorphism comes from the non-trivial element in $\pi_1(\text{SO}(3)) = \mathbb{Z}/2$. One thing that is peculiar is that the Gluck surgery does not change the homotopy type of its 4-manifold, which is why it produces many candidate counterexamples to smooth Poincaré. Again, it is easier to think about the closed complement to Joel's $S^2$ than the blowdown. The corresponding version of Gluck surgery is to remove all of $D^2 \times K$, but only glue back a thickened $D^2$ (a 2-handle) along an attaching circle, and not glue back in the remaining 4-ball along the rest of $K$. What is peculiar here is that the attaching circle does not change; it is still a vertical circle in $S^1 \times S^2$. What changes instead is that the framing of the attachment is twisted by 1. (Or it can be twisted by some other odd number, since $\pi_1(\text{SO}(3)) = \mathbb{Z}/2$ and not $\mathbb{Z}$. More prosaically, the "belt trick" lets you change the twisting by an even number.) Anyway, if Joel's sphere is $K$ connect summed with a complex line $L$, then you can represent this crucial 2-handle with another complex line $J$ in $\mathbb{C}P^2$. The question is whether the framing of its attachment to $L$ is odd or even. The fact that a perturbation $J'$ of $J$ intersects $J$ once tells me that the framing is odd. So the result is Gluck surgery. The old version of this answer was less developed (and at first I made the $\pi_1$ mistake that is corrected in the comments and the edit to the question). But it is still worth noting that there are many open special cases of smooth Poincaré that consist of just one homotopy 4-sphere. Some topologists interpret this as strong evidence that smooth Poincaré is false. Others suppose that we just might not be very good at finding diffeomorphisms with $S^4$. A few examples, including some Gluck surgeries, were shown to be standard only after many years, for instance in this paper by Selman Akbulut. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/8665', 'https://mathoverflow.net', 'https://mathoverflow.net/users/380/']} | jdg_380984 |
stackexchange | llm_judgeable_groundtruth_similarity | 3112157 |
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=1+\frac{1}{2+\frac{1}{1+\frac{1}{2+\frac{1}{...}}}};$$ then the value of $(2x-1)^2$ equals... I don't how to start this question. Please help.
Now provide the response and nothing else.
| If you only want to know the value that the continued fraction converges to, you use a simple technique: $$x=1+\frac{1}{2+\frac{1}{1+\frac{1}{2+\frac{1}{...}}}}=1+\frac{1}{2+\frac{1}{x}}$$ With some manipulation you could come up with the value of $x$ , but you want $(2x-1)^2:$ $$x\left(2+\frac{1}{x} \right)=\left(2+\frac{1}{x} \right)+1$$ $$2x+1=3+\frac{1}{x}$$ Multiply everything by $x$ , since we know it's not zero: $$2x^2-2x-1=0$$ Complete the square that we want by multiplying by $2$ : $$4x^2-4x-2=4x^2-4x+1-3=(2x-1)^2-3=0$$ Hence the answer is 3. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3112157', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_380985 |
stackexchange | llm_judgeable_groundtruth_similarity | 41777643 |
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 docker-compose.yml configuration. In one of the containers there is a Tomcat server and it has some default .war file deployed in webapps directory. I want to have an ability to pass (override) the war archive to be deployed by some which resides on the host machine. I think the best would be to have ability somehow switch / override starting docker-compose : as a default, I want to run the webapp ( war file) which is inside the container, but I want to have a possibility to mount a directory from my host (for example during development / debugging) if need be. Currently, I have the following line in my docker-compose.yml , which is commented out if I need the default. volumes:# By default, there is the latest version of the application already present in the container# If you want to provider the container with your own .war file, uncomment the following line# - ./application/webapps:/usr/local/tomcat/webapps Is there a better way how to achieve that?
Now provide the response and nothing else.
| Instead of (not) mounting a volume commenting out that line, I would use https://docs.docker.com/compose/extends/#example-use-case to run a service extension that specifies a volume. I do this to tackle two different problems: I don't specify a volume when the docker image is meant to run in production and has all the necessary files bundled in it. I specify a volume during development, to check live changes. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41777643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7302365/']} | jdg_380986 |
stackexchange | llm_judgeable_groundtruth_similarity | 8536368 |
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 no idea how do this. I know only how do detect one key: private void Form1_KeyDown(object sender, KeyEventArgs e){ if (e.KeyCode == Keys.C) { MessageBox.Show("C key"); }}
Now provide the response and nothing else.
| You have to keep track of keydown/keyup events, and keep a list of all the keys that are currently "down". The keyboard handler can only trigger on individual keys, and it's up to your code to detect/keep track of which ones are down, and if those individual keydown events are close enough to each other to be counted as "together". | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8536368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/447979/']} | jdg_380987 |
stackexchange | llm_judgeable_groundtruth_similarity | 27254700 |
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 an extension page action that works only in a specific domain, can I add more than one link to the page action? My background.js is this. it is possible to add more links in background.html for the extension page action? //background.js chrome.runtime.onInstalled.addListener(function() { chrome.declarativeContent.onPageChanged.removeRules(undefined, function() { chrome.declarativeContent.onPageChanged.addRules([ { conditions: [ new chrome.declarativeContent.PageStateMatcher({ pageUrl: { urlContains: 'www.exemple.com' }, })],actions: [ new chrome.declarativeContent.ShowPageAction() ]}]);
Now provide the response and nothing else.
| Yes, you can register a page action for multiple sites by adding multiple PageStateMatcher s to the list of conditions . chrome.runtime.onInstalled.addListener(function() { chrome.declarativeContent.onPageChanged.removeRules(undefined, function() { chrome.declarativeContent.onPageChanged.addRules([{ conditions: [ new chrome.declarativeContent.PageStateMatcher({ pageUrl: { hostSuffix: 'example.com' } }), new chrome.declarativeContent.PageStateMatcher({ pageUrl: { hostSuffix: 'example.net' } }), ], actions: [ new chrome.declarativeContent.ShowPageAction() ] }]); });}); Note: I replaced urlContains with hostSuffix because you wanted to show the page action on certain domains, not on all pages whose URL contain the website's host (e.g. you probably don't want to match http://localhost/path/containing/www.example.com ). See the documentation of the UrlFilter type for more ways to match pages. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27254700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4313866/']} | jdg_380988 |
stackexchange | llm_judgeable_groundtruth_similarity | 63893443 |
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 looked everywhere but nothing is working. I am trying to increment/decrement position based on which one they select on screen. I am using useSelector to try and get a slice of the code. const leagueSettings = useSelector((state) => state.drafts.rosterSettings); But I cannot get the mapping to work. The state never updates. I can see that I am sending in an updated count for the position and the correct position. My action.js export const ADD_ROSTER_SPOT = "ADD_ROSTER_SPOT";export const REMOVE_ROSTER_SPOT = "REMOVE_ROSTER_SPOT";export const addRosterSpot = (position, count) => { return { type: ADD_ROSTER_SPOT, position: position, amount: count };};export const removeRosterSpot = (position, count) => { return { type: REMOVE_ROSTER_SPOT, position: position, amount: count };}; my reducer.js import { ADD_ROSTER_SPOT, REMOVE_ROSTER_SPOT } from "../actions/draft";let initialState = { leagueSettings: [], // list of league settings, rosterSettings: [ { Position: "QB", amount: 1 }, { Position: "WR", amount: 1 }, { Position: "RB", amount: 1 }, { Position: "TE", amount: 1 }, ], drafted: [], // list of players drafted by others};export default (state = initialState, action) => { switch (action.type) { case ADD_ROSTER_SPOT: return state.rosterSettings.map(pos => { if (pos.Position === action.position) { return {...pos, amount: pos.amount + 1} } console.log(state) return pos; }); case REMOVE_ROSTER_SPOT: return state.rosterSettings.map((pos) => { if (pos.Position === action.position) { return { ...pos, amount: pos.amount - 1 }; } return pos; }); default: return state; }};
Now provide the response and nothing else.
| Try using the gitlab-ci.yml "rules" feature to check for the merge request event. Your current gitlab-ci.yml will run your "dotnet" job every commit, merge request, schedule, and manually triggered pipeline. https://docs.gitlab.com/ee/ci/yaml/#workflowrules dotnet: script: "echo This builds!" stage: build rules: - if: '$CI_COMMIT_REF_NAME != "master" && $CI_PIPELINE_SOURCE == "push" || $CI_PIPELINE_SOURCE == "merge_request_event"'production: script: "echo This deploys!" stage: deploy rules: - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_REF_NAME == "master"' | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/63893443', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11821388/']} | jdg_380989 |
stackexchange | llm_judgeable_groundtruth_similarity | 14700417 |
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 pretty new to this flot API. I want to have dashed gridlines/ticklines instead of solid line both X-axis' and Y-axis'. Can anyone help me with this?? Thanks in advance!
Now provide the response and nothing else.
| I was able to produce dashed lines for the grid's markings by modifying the library. I'm currently using Flot ver 0.8.0 First I added a new attribute under grid (around line 400), just below the markingsLineWidth: markingsStyle: 'dashed' Since Flot is using canvas to render the charts, I added a dashedLineTo() extension for the canvas using this code from David Owens. I added it just right after the color parser plugin on top of the Flot's code, with credits given to David. The dashedLineTo() has the following parameters: dashedLineTo(fromX, fromY, toX, toY, pattern) For the pattern, I used [5,5] which means there will alternating 5px of dash, and 5px of space. Finally I modified the drawGrid function in the plugin, when the markings are being drawn. if(options.grid.markingsStyle == 'dashed') { ctx.dashedLineTo(xrange.from, yrange.from, xrange.to, yrange.to, [5,5])} else { ctx.moveTo(xrange.from, yrange.from); ctx.lineTo(xrange.to, yrange.to);} Just thought you can use this as a reference when modifying the library. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14700417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2017536/']} | jdg_380990 |
stackexchange | llm_judgeable_groundtruth_similarity | 34172888 |
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 can't I use @Autowired in this case? @SpringBootApplicationpublic class Application { @Autowired BookingService bookingService; public static void main(String[] args) { bookingService.book("Alice", "Bob", "Carol"); }} but can use @Bean @SpringBootApplicationpublic class Application { @Bean BookingService bookingService() { return new BookingService(); } public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(Application.class, args); BookingService bookingService = ctx.getBean(BookingService.class); bookingService.book("Alice", "Bob", "Carol"); }} Aren't the two ways to generate BookingService the same thing?
Now provide the response and nothing else.
| @Bean and @Autowired do two very different things. The other answers here explain in a little more detail, but at a simpler level: @Bean tells Spring 'here is an instance of this class, please keep hold of it and give it back to me when I ask'. @Autowired says 'please give me an instance of this class, for example, one that I created with an @Bean annotation earlier'. Does that make sense? In your first example, you're asking Spring to give you an instance of BookingService , but you're never creating one, so Spring has nothing to give you. In your second example, you're creating a new instance of BookingService , telling Spring about it, and then, in the main() method, asking for it back. If you wanted, you could remove the two additional lines from the second main() method, and combine your two examples as below: @SpringBootApplicationpublic class Application { @Autowired BookingService bookingService; @Bean BookingService bookingService() { return new BookingService(); } public static void main(String[] args) { bookingService.book("Alice", "Bob", "Carol"); }} In this case, the @Bean annotation gives Spring the BookingService , and the @Autowired makes use of it. This would be a slightly pointless example, as you're using it all in the same class, but it becomes useful if you have the @Bean defined in one class, and the @Autowired in a different one. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/34172888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4736415/']} | jdg_380991 |
stackexchange | llm_judgeable_groundtruth_similarity | 234101 |
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:
The Residual Sum of squares (RSS) in Weighted regression is written as $$(\mathbf{y-X\hat{\boldsymbol\beta}})^{'}\mathbf{C}^{-1}(\mathbf{y-X\hat{\boldsymbol\beta}})$$Where $$\hat{\boldsymbol\beta}=(\mathbf{X^{'}C^{-1}X})^{-1}\mathbf{X^{'}C^{-1}y}$$ I am trying to write the RSS in an efficient manner which reduces computational complexity, for example I am able to write the RSS as follows$$(\mathbf{y-X\hat{\boldsymbol\beta}})^{'}\mathbf{C}^{-1}(\mathbf{y-X\hat{\boldsymbol\beta}})=tr(\mathbf{e^{'}C^{-1}e})=tr(\mathbf{e^{'}eC^{-1}})=tr(\mathbf{EC^{-1}})$$ where $tr=trace, \mathbf{e}=(\mathbf{y-X\hat{\boldsymbol\beta}})$ and $E=\mathbf{e^{'}e}$Although this expression seems mathematically simple however the computational complexity is the same I hope anyone can help me find an efficient way to write and code the RSS in weighted regression. Also, I would appreciate a reference to an $R$ function that can find this RSS so that I can take a look how the expression is written. PS : $C$ need not to be a diagonal matrix, however it is symmetric positive semi-definite e.g. a covariance matrix
Now provide the response and nothing else.
| There are several good ways to do this using R. One classical method is to compute the Choleski factor of the covariance matrix: R <- chol(C)yc <- backsolve(R, y, transpose=TRUE)Xc <- backsolve(R, X, transpose=TRUE)fit <- lm.fit(Xc, yc)RSS <- sum(fit$effects[-(1:fit$rank)]^2) This code requires C to be a strictly positive definite matrix. C has to be positive definite anyway in order to guarantee that the RSS is finite. If you want to make the computation even more explicit, you could replace the last two lines with this: QR <- qr(Xc)e <- qr.qty(QR, yc)e <- e[-(1:QR$rank)]RSS <- sum(e^2) The above code is performing the following mathematical steps. First, we factorize$$C = R^TR$$where $R$ is an upper triangular matrix. Then we solve the linear systems$$R^Ty_c=y$$and$$R^TX_c=X$$for $y_c$ and $X_c$ using an efficient forward substitution algorithm. Note that the above two steps are far more efficient than inverting $C$. From this point we can view this as an unweighted regression problem with $y_c$ and $X_c$.Amongst other things, the lm.fit function uses the QR decomposition of $X_c$ to find an $n\times(n-p)$ matrix $Q$ such that $Q^TQ=I$ and $Q^TX=0$.Here, $p$ is the column rank of $X$.The orthogonal residuals (or effects) can then be computed as$$e=Q^Ty$$and finally the RSS is $e^Te$.Actually the function computed $Q^Ty$, where $Q$ was $n\times n$, and stored this vector in fit$effects . We then threw away the first $p$ values to get $e$. You might have been hoping for a simpler mathematical formula, but efficient computation requires that one avoids evaluating mathematical entities such as inverse matrices or ordinary residuals. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/234101', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/78448/']} | jdg_380992 |
stackexchange | llm_judgeable_groundtruth_similarity | 8571 |
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 the following process for encrypting and decrypting data in a python script using the PyCrypto module: Encryption - Server A AES 256 shared key is generated Associated IV is generated Data is encrypted using AES 256 shared key and associated IV using CBC mode and stored into the db RSA 4096 public key is used to encrypt the AES 256 key and associated IV which are also stored in the db Decryption - Server B Encrypted AES 256 shared key and associated IV from db are decrypted using RSA 4096 private key Data from db is now decrypted using the decrypted AES 256 shared key and associated IV Does the above process ensure the security of data against an attack model where the attacker has managed to gain access to the database?
Now provide the response and nothing else.
| My main feedback: You don't provide enough technical detail to provide a complete critique of your proposal, but you have provided enough information that I can see that you are making several common mistakes. Here are the main mistakes I can see so far: Mistake #1: inventing your own encryption format. Usually, designing your own format for storing encrypted data is not a good idea ; you are likely to get something wrong. It is better to use a standard format, like GPG or the OpenPGP Message Format. Mistake #2: failure to include message integrity protection. Encrypting data without also authenticating opens you up to subtle but serious attacks . This is highly counter-intuitive, and a very common mistake. It is tempting to think, gee, I want to keep this secret, so if I encrypt it with a good encryption algorithm, I'll be fine. But nope, you won't be fine. You also need message authentication, to defend against chosen-ciphertext attacks. And you need to apply with a proper mode (e.g., authenticated encryption, or Encrypt-then-MAC) and with proper key management (independent keys for authentication and encryption, or appropriate use of key separation). To avoid these problems, follow the advice at the links I gave above. Other miscellaneous feedback: There may well be other problems; you haven't provided us enough information to identify them all. Here are some examples of potential problems: For instance, you don't describe how the IV is generated. In past systems, poor IV generation has occasionally led to security problems. (The IV needs to be generated using a crypto-strength pseudorandom number generator.) You don't describe how the AES key is encrypted. (You need to use a proper padding scheme, e.g., OAEP or PKCS#2.) The key lengths you have selected are overkill. Keep in mind that, when modern cryptography is properly implemented and used, it is almost never the weakest link in the system. Instead, attackers usually defeat crypto not by breaking the crypto algorithms, but by bypassing the crypto and attacking some other aspect of the system -- maybe applying social engineering to the humans, maybe finding a security hole in the code and compromising an endpoint, maybe exploiting errors in the key management, or any of a number of other ways of attacking a system. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/8571', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/5412/']} | jdg_380993 |
stackexchange | llm_judgeable_groundtruth_similarity | 18086476 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
so im working on a project for work. the long black container on the bottom does not span the entire width of the page. It stops a few pixels short on either side. Here is my code: http://74.117.156.152/~pr0digy/ <header class="mainHeader"> <img src="images/uslegalbox.png" alt="usls box" > </header> <div class="textBox"> <article class="capexText"> <h2>Capital</h2><br /> <h2>Expenditures</h2> </article> <div class="buttonsBox"> <nav><ul> <li><a href="#" >New CapEx</li> <li><a href="#" >Check Status</li> </ul></nav> </div> </div> And the CSS to go along with it: body { background: url('images/bg.jpg'); background-size: 100%; background-repeat:no-repeat; color: #000305; font-size: 87.5%; /* Base font size is 14px */ font-family: Arial; 'Lucida Sans Unicode'; line-height: 1.2; text-align: left; width: 100%; }.mainHeader { width: 30% height: auto; margin: 2% 0 0 -1%;}.mainHeader img { width: 35%; height: auto;}.textBox { margin-top: 10%; height: 275px; background-image: url('images/buttonsbox.png'); background-repeat: repeat-x;} I'm sure im just missing something simple, so any help would be appreciated. Thanks!
Now provide the response and nothing else.
| Try /^(.*\.(?!(htm|html|class|js)$))?[^.]*$/i Try it here: http://regexr.com?35rp0 It will also work with extensionless files. As all the regexes, it's complex to explain... Let's start from the end [^.]*$ 0 or more non . characters( ... )? if there is something before (the last ?).*\.(?!(htm|html|class|js)$) Then it must be any character in any number .* followed by a dot \. not followed by htm, html, class, js (?! ... ) plus the end of the string $ (this so that htmX doesn't trigger the condition)^ the beginning of the string This one (?!(htm|html|class|js) is called zero width negative lookahead. It's explained at least 10 times every day on SO, so you can look anywhere :-) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18086476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2657772/']} | jdg_380994 |
stackexchange | llm_judgeable_groundtruth_similarity | 2599925 |
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'd like to print PDF file(s) on windows' network printer via GhostScript. (I dont want to use Adobe Reader) I've read gswin32c.exe which can do the job. I experimented with many commands and coudn't find the way how to force gs to print PDF on my (windows default) network drive. I don't need point exact network printer- default can be used. But if there is no such option I'm happy to pass printer name as well. (I've tried with param -SDevice="\server_IP\printer_name" but this didnt work as well...) Command working under Windows cmd: gswin32c -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=1 -sDEVICE=ljet4 -sOutputFile="\\spool\\\Server_Name\Printer_name" "C:\test.pdf" Method created base on above - doesnt work and thorws exception. (Error code = 1) /// <summary> /// Prints the PDF. /// </summary> /// <param name="ghostScriptPath">The ghost script path. Eg "C:\Program Files\gs\gs8.71\bin\gswin32c.exe"</param> /// <param name="numberOfCopies">The number of copies.</param> /// <param name="printerName">Name of the printer. Eg \\server_name\printer_name</param> /// <param name="pdfFileName">Name of the PDF file.</param> /// <returns></returns> public bool PrintPDF (string ghostScriptPath, int numberOfCopies, string printerName, string pdfFileName) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.Arguments = " -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=" + Convert.ToString(numberOfCopies) + " -sDEVICE=ljet4 -sOutputFile=\"\\\\spool\\" + printerName + "\" \"" + pdfFileName + "\""; startInfo.FileName = ghostScriptPath; startInfo.UseShellExecute = false; Process process = Process.Start(startInfo); return process.ExitCode == 0; } Any idea how to make it working under C#?
Now provide the response and nothing else.
| I've finally made it working and easy for debugging. My final method code for those interested: /// <summary> /// Prints the PDF. /// </summary> /// <param name="ghostScriptPath">The ghost script path. Eg "C:\Program Files\gs\gs8.71\bin\gswin32c.exe"</param> /// <param name="numberOfCopies">The number of copies.</param> /// <param name="printerName">Name of the printer. Eg \\server_name\printer_name</param> /// <param name="pdfFileName">Name of the PDF file.</param> /// <returns></returns> public bool PrintPDF (string ghostScriptPath, int numberOfCopies, string printerName, string pdfFileName) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.Arguments = " -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=" + Convert.ToString(numberOfCopies) + " -sDEVICE=ljet4 -sOutputFile=\"\\\\spool\\" + printerName + "\" \"" + pdfFileName + "\" "; startInfo.FileName = ghostScriptPath; startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; Process process = Process.Start(startInfo); Console.WriteLine( process.StandardError.ReadToEnd() + process.StandardOutput.ReadToEnd() ); process.WaitForExit(30000); if (process.HasExited == false) process.Kill(); return process.ExitCode == 0; } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2599925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/77273/']} | jdg_380995 |
stackexchange | llm_judgeable_groundtruth_similarity | 21447 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have tens of PIC16 chips. I would like to retrieve some kind of unique serial number from the chip for identification purposes. I know it can be done manually. But it's tedious. Questions: Does PIC has a built-in serial number? If the answer is No, is there a easy way to upload a code with unique serial number to each chip when I order the chip from Microchip?
Now provide the response and nothing else.
| No Is possible, but I don't know what quantities are required, i.e. if they'll do it for tens of devices. We always had batches of at least 1000 parts. It's just like preprogramming with your software, but you indicate at which location(s) the unique ID should be programmed. You'll need to supply the starting ID, and the format (BCD, binary, LSD/MSD first, ...). Note that this number resides in normal program memory, and it will be erased if you erase the part for reprogramming. edit The reason controllers most often don't have this at chip level is that it's expensive: the programming is done by lasering, which is an extra production step. Mass-programmed microcontrollers can easily have the unique ID programmed with the software, and this doesn't require an extra step. An alternative would be an SSN (Silicon Serial Number) like the Maxim DS2411 . These are also laser-programmed, so not cheap either, but you avoid the extra logistic steps, where there can always go something wrong. I've known it happen. (another edit) Mike suggests a MAC address chip as an alternative. These are EEPROMs which have a unique ID (MAC addresses are globally unique) programmed in a part of the device which is write protected. The rest of the part can be used as normal EEPROM, like for storing device parameters. The EEPROMs appear to be a lot cheaper than the SSN, while serving the same function. see also Method for assigning unique per-board addresses | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/21447', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4185/']} | jdg_380996 |
stackexchange | llm_judgeable_groundtruth_similarity | 8209936 |
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 developed a small web-app in Symfony 2 and Doctrine 2. Can i deploy it to a web-host that doesn't give SSH access? I ask this because i see there are a lot of task that must be done from the terminal, like updating the database schema, creating symlinks for the assets, clearing cache, etc...
Now provide the response and nothing else.
| Should not be a problem: Create a copy of the system somewhere, ideally with identical DB connection params like the production system. Run all the necessary tasks with the --env=prod parameter, if your DB settings allow it. Clone the created production database to the production system (with phpMyAdmin). You can clone the schema from the production database, run app/console doctrine:schema:update --dump-sql locally and then run the generated SQL on the production server. Copy all the files, excluding the dirs in app/cache and app/log | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8209936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1008770/']} | jdg_380997 |
stackexchange | llm_judgeable_groundtruth_similarity | 4064934 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to find a proof of the following fact: Let $M$ be a real symmetric matrix, then the largest singular value satisfies: $$\sigma_1(M) = \lim_{k \to \infty} \left[\text{Trace}(M^{2k})\right]^{\frac{1}{2k}}$$
Now provide the response and nothing else.
| $\newcommand{\diag}{\mathrm{diag}}$ $\newcommand{\tr}{\mathrm{Trace}}$ Since $M$ is symmetric, $M^2 = M'M$ , which can then be decomposed as \begin{align*}M'M = O\diag(\sigma_1^2(M), \ldots, \sigma_n^2(M))O',\end{align*} where $O$ is order $n$ orthogonal matrix. It then follows that $M^{2k} = (M'M)^k =O\diag(\sigma_1^{2k}, \ldots, \sigma_n^{2k})O'$ , whence $\tr(M^{2k}) = \sigma_1^{2k} + \cdots + \sigma_n^{2k}$ . Hence by squeeze principle, it is easy to verify that \begin{align*}\lim_{k \to \infty}(\sigma_1^{2k} + \cdots + \sigma_n^{2k})^{1/2k} = \sigma_1.\end{align*} | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4064934', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/151735/']} | jdg_380998 |
stackexchange | llm_judgeable_groundtruth_similarity | 7582156 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Trying to serialize just the elements from a specific table but it only returns a result if i do the whole Form in the below code, i want to ajax just the elements in tbl2 <form> <input type="text" id="tb1" name="tbl1"/> <table name="tbl1"> <tr><td><input type="text" name="tb2"/></td></tr> </table> <table name="tbl2"> <tr><td><input type="text" name="tb3"/></td></tr> <tr><td><input type="text" name="tb4"/></td></tr> </table></form> the code var params = $("#tbl2").serialize();var resp = $.ajax({ async: false, type: "POST", url: AppRoot + "webhandlers/postback.ashx", data: params});
Now provide the response and nothing else.
| First and foremost, a <table> cannot have a name attribute, and even if it could, the jQuery ID selector ( # ) would not match it. If you use id instead ( <table id="tbl2"> ), it will work like this: var params = $("#tbl2 :input").serialize(); The :input selector selects all the form elements (here, inside #tbl2 ), it is needed because serialize() will only work on those. Please also check out my jsFiddle Demo . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7582156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/935122/']} | jdg_380999 |
stackexchange | llm_judgeable_groundtruth_similarity | 294292 |
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 can I change the master volume level? Using this code [DllImport ("winmm.dll")]public static extern int waveOutSetVolume (IntPtr hwo, uint dwVolume);waveOutSetVolume (IntPtr.Zero, (((uint)uint.MaxValue & 0x0000ffff) | ((uint)uint.MaxValue << 16))); I can set the wave volume but if the master volume is too low this won't have any effect. Thanks for any help.
Now provide the response and nothing else.
| Okay, here goes: const int MAXPNAMELEN = 32;const int MIXER_SHORT_NAME_CHARS = 16;const int MIXER_LONG_NAME_CHARS = 64;[Flags] enum MIXERLINE_LINEF : uint{ ACTIVE = 0x00000001, DISCONNECTED = 0x00008000, SOURCE = 0x80000000}[Flags] enum MIXER : uint{ GETLINEINFOF_DESTINATION = 0x00000000, GETLINEINFOF_SOURCE = 0x00000001, GETLINEINFOF_LINEID = 0x00000002, GETLINEINFOF_COMPONENTTYPE = 0x00000003, GETLINEINFOF_TARGETTYPE = 0x00000004, GETLINEINFOF_QUERYMASK = 0x0000000F, GETLINECONTROLSF_ALL = 0x00000000, GETLINECONTROLSF_ONEBYID = 0x00000001, GETLINECONTROLSF_ONEBYTYPE = 0x00000002, GETLINECONTROLSF_QUERYMASK = 0x0000000F, GETCONTROLDETAILSF_VALUE = 0x00000000, GETCONTROLDETAILSF_LISTTEXT = 0x00000001, GETCONTROLDETAILSF_QUERYMASK = 0x0000000F, OBJECTF_MIXER = 0x00000000, OBJECTF_WAVEOUT = 0x10000000, OBJECTF_WAVEIN = 0x20000000, OBJECTF_MIDIOUT = 0x30000000, OBJECTF_MIDIIN = 0x40000000, OBJECTF_AUX = 0x50000000, OBJECTF_HANDLE = 0x80000000, OBJECTF_HMIXER = OBJECTF_HANDLE | OBJECTF_MIXER, OBJECTF_HWAVEOUT = OBJECTF_HANDLE | OBJECTF_WAVEOUT, OBJECTF_HWAVEIN = OBJECTF_HANDLE | OBJECTF_WAVEIN, OBJECTF_HMIDIOUT = OBJECTF_HANDLE | OBJECTF_MIDIOUT, OBJECTF_HMIDIIN = OBJECTF_HANDLE | OBJECTF_MIDIIN}[Flags] enum MIXERCONTROL_CT : uint{ CLASS_MASK = 0xF0000000, CLASS_CUSTOM = 0x00000000, CLASS_METER = 0x10000000, CLASS_SWITCH = 0x20000000, CLASS_NUMBER = 0x30000000, CLASS_SLIDER = 0x40000000, CLASS_FADER = 0x50000000, CLASS_TIME = 0x60000000, CLASS_LIST = 0x70000000, SUBCLASS_MASK = 0x0F000000, SC_SWITCH_BOOLEAN = 0x00000000, SC_SWITCH_BUTTON = 0x01000000, SC_METER_POLLED = 0x00000000, SC_TIME_MICROSECS = 0x00000000, SC_TIME_MILLISECS = 0x01000000, SC_LIST_SINGLE = 0x00000000, SC_LIST_MULTIPLE = 0x01000000, UNITS_MASK = 0x00FF0000, UNITS_CUSTOM = 0x00000000, UNITS_BOOLEAN = 0x00010000, UNITS_SIGNED = 0x00020000, UNITS_UNSIGNED = 0x00030000, UNITS_DECIBELS = 0x00040000, /* in 10ths */ UNITS_PERCENT = 0x00050000, /* in 10ths */}[Flags] enum MIXERCONTROL_CONTROLTYPE : uint{ CUSTOM = MIXERCONTROL_CT.CLASS_CUSTOM | MIXERCONTROL_CT.UNITS_CUSTOM, BOOLEANMETER = MIXERCONTROL_CT.CLASS_METER | MIXERCONTROL_CT.SC_METER_POLLED | MIXERCONTROL_CT.UNITS_BOOLEAN, SIGNEDMETER = MIXERCONTROL_CT.CLASS_METER | MIXERCONTROL_CT.SC_METER_POLLED | MIXERCONTROL_CT.UNITS_SIGNED, PEAKMETER = SIGNEDMETER + 1, UNSIGNEDMETER = MIXERCONTROL_CT.CLASS_METER | MIXERCONTROL_CT.SC_METER_POLLED | MIXERCONTROL_CT.UNITS_UNSIGNED, BOOLEAN = MIXERCONTROL_CT.CLASS_SWITCH | MIXERCONTROL_CT.SC_SWITCH_BOOLEAN | MIXERCONTROL_CT.UNITS_BOOLEAN, ONOFF = BOOLEAN + 1, MUTE = BOOLEAN + 2, MONO = BOOLEAN + 3, LOUDNESS = BOOLEAN + 4, STEREOENH = BOOLEAN + 5, BASS_BOOST = BOOLEAN + 0x00002277, BUTTON = MIXERCONTROL_CT.CLASS_SWITCH | MIXERCONTROL_CT.SC_SWITCH_BUTTON | MIXERCONTROL_CT.UNITS_BOOLEAN, DECIBELS = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_DECIBELS, SIGNED = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_SIGNED, UNSIGNED = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_UNSIGNED, PERCENT = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_PERCENT, SLIDER = MIXERCONTROL_CT.CLASS_SLIDER | MIXERCONTROL_CT.UNITS_SIGNED, PAN = SLIDER + 1, QSOUNDPAN = SLIDER + 2, FADER = MIXERCONTROL_CT.CLASS_FADER | MIXERCONTROL_CT.UNITS_UNSIGNED, VOLUME = FADER + 1, BASS = FADER + 2, TREBLE = FADER + 3, EQUALIZER = FADER + 4, SINGLESELECT = MIXERCONTROL_CT.CLASS_LIST | MIXERCONTROL_CT.SC_LIST_SINGLE | MIXERCONTROL_CT.UNITS_BOOLEAN, MUX = SINGLESELECT + 1, MULTIPLESELECT = MIXERCONTROL_CT.CLASS_LIST | MIXERCONTROL_CT.SC_LIST_MULTIPLE | MIXERCONTROL_CT.UNITS_BOOLEAN, MIXER = MULTIPLESELECT + 1, MICROTIME = MIXERCONTROL_CT.CLASS_TIME | MIXERCONTROL_CT.SC_TIME_MICROSECS | MIXERCONTROL_CT.UNITS_UNSIGNED, MILLITIME = MIXERCONTROL_CT.CLASS_TIME | MIXERCONTROL_CT.SC_TIME_MILLISECS | MIXERCONTROL_CT.UNITS_UNSIGNED}[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]struct MIXERLINE{ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] public struct TargetInfo{ public uint dwType; public uint dwDeviceID; public ushort wMid; public ushort wPid; public uint vDriverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAXPNAMELEN)] public string szPname; } public uint cbStruct; public uint dwDestination; public uint dwSource; public uint dwLineID; public MIXERLINE_LINEF fdwLine; public uint dwUser; public uint dwComponentType; public uint cChannels; public uint cConnection; public uint cControls; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_SHORT_NAME_CHARS)] public string szShortName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_LONG_NAME_CHARS)] public string szName; public TargetInfo Target;}[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]struct MIXERCONTROL{ [StructLayout(LayoutKind.Explicit)] public struct BoundsInfo{ [FieldOffset(0)] public int lMinimum; [FieldOffset(4)] public int lMaximum; [FieldOffset(0)] public uint dwMinimum; [FieldOffset(4)] public uint dwMaximum; [FieldOffset(8), MarshalAs(UnmanagedType.ByValArray, SizeConst=4)] public uint[] dwReserved; } [StructLayout(LayoutKind.Explicit)] public struct MetricsInfo{ [FieldOffset(0)] public uint cSteps; [FieldOffset(0)] public uint cbCustomData; [FieldOffset(4), MarshalAs(UnmanagedType.ByValArray, SizeConst=5)] public uint[] dwReserved; } public uint cbStruct; public uint dwControlID; public MIXERCONTROL_CONTROLTYPE dwControlType; public uint fdwControl; public uint cMultipleItems; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_SHORT_NAME_CHARS)] public string szShortName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_LONG_NAME_CHARS)] public string szName; public BoundsInfo Bounds; public MetricsInfo Metrics;}[StructLayout(LayoutKind.Explicit)]struct MIXERLINECONTROLS{ [FieldOffset(0)] public uint cbStruct; [FieldOffset(4)] public uint dwLineID; [FieldOffset(8)] public uint dwControlID; [FieldOffset(8)] // not a typo! overlaps previous field public uint dwControlType; [FieldOffset(12)] public uint cControls; [FieldOffset(16)] public uint cbmxctrl; [FieldOffset(20)] public IntPtr pamxctrl;}[StructLayout(LayoutKind.Explicit)]struct MIXERCONTROLDETAILS{ [FieldOffset(0)] public uint cbStruct; [FieldOffset(4)] public uint dwControlID; [FieldOffset(8)] public uint cChannels; [FieldOffset(12)] public IntPtr hwndOwner; [FieldOffset(12)] // not a typo! public uint cMultipleItems; [FieldOffset(16)] public uint cbDetails; [FieldOffset(20)] public IntPtr paDetails;}[StructLayout(LayoutKind.Sequential)]struct VOLUME{ public int left; public int right;}struct MixerInfo{ public uint volumeCtl; public uint muteCtl; public int minVolume; public int maxVolume;}[DllImport("WinMM.dll", CharSet=CharSet.Auto)]static extern uint mixerGetLineInfo (IntPtr hmxobj, ref MIXERLINE pmxl, MIXER flags);[DllImport("WinMM.dll", CharSet=CharSet.Auto)]static extern uint mixerGetLineControls (IntPtr hmxobj, ref MIXERLINECONTROLS pmxlc, MIXER flags);[DllImport("WinMM.dll", CharSet=CharSet.Auto)]static extern uint mixerGetControlDetails(IntPtr hmxobj, ref MIXERCONTROLDETAILS pmxcd, MIXER flags);[DllImport("WinMM.dll", CharSet=CharSet.Auto)]static extern uint mixerSetControlDetails(IntPtr hmxobj, ref MIXERCONTROLDETAILS pmxcd, MIXER flags);static MixerInfo GetMixerControls(){ MIXERLINE mxl = new MIXERLINE(); MIXERLINECONTROLS mlc = new MIXERLINECONTROLS(); mxl.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERLINE)); mlc.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERLINECONTROLS)); mixerGetLineInfo(IntPtr.Zero, ref mxl, MIXER.OBJECTF_MIXER | MIXER.GETLINEINFOF_DESTINATION); mlc.dwLineID = mxl.dwLineID; mlc.cControls = mxl.cControls; mlc.cbmxctrl = (uint)Marshal.SizeOf(typeof(MIXERCONTROL)); mlc.pamxctrl = Marshal.AllocHGlobal((int)(mlc.cbmxctrl * mlc.cControls)); mixerGetLineControls(IntPtr.Zero, ref mlc, MIXER.OBJECTF_MIXER | MIXER.GETLINECONTROLSF_ALL); MixerInfo rtn = new MixerInfo(); for(int i = 0; i < mlc.cControls; i++){ MIXERCONTROL mxc = (MIXERCONTROL)Marshal.PtrToStructure((IntPtr)((int)mlc.pamxctrl + (int)mlc.cbmxctrl * i), typeof(MIXERCONTROL)); switch(mxc.dwControlType){ case MIXERCONTROL_CONTROLTYPE.VOLUME: rtn.volumeCtl = mxc.dwControlID; rtn.minVolume = mxc.Bounds.lMinimum; rtn.maxVolume = mxc.Bounds.lMaximum; break; case MIXERCONTROL_CONTROLTYPE.MUTE: rtn.muteCtl = mxc.dwControlID; break; } } Marshal.FreeHGlobal(mlc.pamxctrl); return rtn;}static VOLUME GetVolume(MixerInfo mi){ MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS(); mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS)); mcd.dwControlID = mi.volumeCtl; mcd.cMultipleItems = 0; mcd.cChannels = 2; mcd.cbDetails = (uint)Marshal.SizeOf(typeof(int)); mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails); mixerGetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER); VOLUME rtn = (VOLUME)Marshal.PtrToStructure(mcd.paDetails, typeof(VOLUME)); Marshal.FreeHGlobal(mcd.paDetails); return rtn;}static bool IsMuted(MixerInfo mi){ MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS(); mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS)); mcd.dwControlID = mi.muteCtl; mcd.cMultipleItems = 0; mcd.cChannels = 1; mcd.cbDetails = 4; mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails); mixerGetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER); int rtn = Marshal.ReadInt32(mcd.paDetails); Marshal.FreeHGlobal(mcd.paDetails); return rtn != 0;}static void AdjustVolume(MixerInfo mi, int delta){ VOLUME volume = GetVolume(mi); if(delta > 0){ volume.left = Math.Min(mi.maxVolume, volume.left + delta); volume.right = Math.Min(mi.maxVolume, volume.right + delta); }else{ volume.left = Math.Max(mi.minVolume, volume.left + delta); volume.right = Math.Max(mi.minVolume, volume.right + delta); } SetVolume(mi, volume);}static void SetVolume(MixerInfo mi, VOLUME volume){ MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS(); mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS)); mcd.dwControlID = mi.volumeCtl; mcd.cMultipleItems = 0; mcd.cChannels = 2; mcd.cbDetails = (uint)Marshal.SizeOf(typeof(int)); mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails); Marshal.StructureToPtr(volume, mcd.paDetails, false); mixerSetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER); Marshal.FreeHGlobal(mcd.paDetails);}static void SetMute(MixerInfo mi, bool mute){ MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS(); mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS)); mcd.dwControlID = mi.muteCtl; mcd.cMultipleItems = 0; mcd.cChannels = 1; mcd.cbDetails = 4; mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails); Marshal.WriteInt32(mcd.paDetails, mute ? 1 : 0); mixerSetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER); Marshal.FreeHGlobal(mcd.paDetails);} This code is huge and ugly. It's a translation of some C++ code, and with having to define all the P/Invoke stuff, it's a lot more code. But I've tested it, and it works. To use it, you simply need something like: MixerInfo mi = GetMixerControls();AdjustVolume(mi, 100); // add 100 to the current volume or MixerInfo mi = GetMixerControls();AdjustVolume(mi, (mi.maxVolume - mi.minVolume) / 10); // increase the volume by 10% of total range or MixerInfo mi = GetMixerControls();SetVolume(mi, mi.maxVolume); // let's get this party crunk'd! or MixerInfo mi = GetMixerControls();SetMute(mi, true); // shhhh!!!!!! WARNING Due to the use of fixed-sized ints and field offsets, this may fail fantastically on 64-bit Windows. I don't know, I haven't tested it and haven't paid enough attention to know if these field sizes expand to 64 bits. caveat codor EDIT For the sake of simplicity (relatively speaking), I've left out any error handling. You should really check the return codes of all the mixerXXX functions, but I'll leave that as an exercise for the reader (read as: I was too lazy to do this). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/294292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/894/']} | jdg_381000 |
stackexchange | llm_judgeable_groundtruth_similarity | 17080112 |
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 generate random numbers with range for byte , ushort , sbyte , short , int , and uint . I am able to generate for all those types using the Random method in C# (e.g. values.Add((int)(random.Next(int.MinValue + 3, int.MaxValue - 2))); ) except for uint since Random.Next accepts up to int values only. Is there an easy way to generate random uint ?
Now provide the response and nothing else.
| The simplest approach would probably be to use two calls: one for 30 bits and one for the final two. An earlier version of this answer assumed that Random.Next() had an inclusive upper bound of int.MaxValue , but it turns out it's exclusive - so we can only get 30 uniform bits. uint thirtyBits = (uint) random.Next(1 << 30);uint twoBits = (uint) random.Next(1 << 2);uint fullRange = (thirtyBits << 2) | twoBits; (You could take it in two 16-bit values of course, as an alternative... or various options in-between.) Alternatively, you could use NextBytes to fill a 4-byte array, then use BitConverter.ToUInt32 . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17080112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2309949/']} | jdg_381001 |
stackexchange | llm_judgeable_groundtruth_similarity | 839644 |
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 fstream. Is there any way to get the failure message/exception? For example if I'm unable to open the file?
Now provide the response and nothing else.
| Streams by default do not throw exceptions on error, they set flags. You can make them throw exceptions by using the stream's exception() member function: ifstream ifs;ifs.exceptions( std::ios::failbit ); // throw if failbit get set Theoretically, you could then do something like this: try { int x; ifs >> x;}catch( const std::exception & ex ) { std::cerr << "Could not convert to int - reason is " << ex.what();} Unfortunately, the C++ Standard does not specify that thrown exceptions contain any error message, so you are in implementation specific territory here. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/839644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103521/']} | jdg_381002 |
stackexchange | llm_judgeable_groundtruth_similarity | 33563230 |
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 been trying to understand Dynamic Programming, and what I understood is that there are two parts of DP. Optimal substructures Overlapping subproblems I understand the second one, but I am not able to understand the first one.
Now provide the response and nothing else.
| Optimal substructure means, that any optimal solution to a problem of size n , is based on an optimal solution to the same problem when considering n' < n elements. That means, when building your solution for a problem of size n , you split the problem to smaller problems, one of them of size n' . Now, you need only to consider the optimal solution to n' , and not all possible solutions to it, based on the optimal substructure property. An example is the knapsack problem : D(i,k) = min { D(i-1,k), D(i-1,k-weight(i)) + cost(i) } The optimal substructure assumption here, is D(i,k) can check only optimal solutions to D(i-1,k) , and none optimal solutions are not considered. An example where this does not hold is the Vertex Cover problem . If you have a graph G=(V,E), assume you have an optimal solution to a subgraph G'=(V',E[intersection]V'xV') such that V' <= V - the optimal solution for G does not have to be consisted of of the optimal solution for G' / | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33563230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1669747/']} | jdg_381003 |
stackexchange | llm_judgeable_groundtruth_similarity | 27438817 |
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 Laravel 5 app with two environments and two configurations: testing (for PHPUnit configuration, in-memory db) and local (my development configuration). Even when the environment is configured to be local , the application only loads the configuration in the resources/config/testing folder. I can see the environment in the same app from the APP_ENV environment variable, and it is local . Should I just not be using a testing configuration directory for configuring my tests? What's a better way to configure my testing environment in Laravel 5?
Now provide the response and nothing else.
| Laravel 5 doesn't cascade config files correctly anymore so your testing config file is overriding anything you have in your local config file. Now you aren't supposed to have any subfolders for each environment, but rather set configuration settings inside the .env file in the root folder. This file isn't checked in to the repo to ensure that nothing sensitive is checked into the repo. You should have a separate .env file for each environment your application is living. TESTING For php unit (functional) you can set env variables in the phpunit.xml file e.g.. <php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="array"/> <env name="SESSION_DRIVER" value="array"/></php> For behat (acceptance) testing the Laracasts Laravel Behat extension allows you to create a .env.behat file to change the environment variables. For phpspec (unit) testing well the environment shouldn't matter as your testing individual methods in isolation and mock everything else. For selenium (integration / system / e2e) testing the environment variables should come from the .env file on the server wherever you are doing this testing. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27438817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1210797/']} | jdg_381004 |
stackexchange | llm_judgeable_groundtruth_similarity | 149966 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for a way to segment a grayscale image (or a 2D array) by its pixel values. We look at two neighboring pixels, if their values are close within a certain threshold, then we say they are connected. How to find all the connected segments in the image? Here are some three examples, example 1: threshold = 1;data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; give {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}} This is because 1 is connected to 2, 2 is connected to 3, etc. And all the pixels are connected. So there is only 1 component in the image. example 2: threshold = 0;data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; give {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} This is because all pixels are isolated and thus we have 9 components. example 3: threshold = 2;data = {{5, 0, 2, 3, 10}, {9, 10, 10, 2, 2}, {10, 10, 3, 3, 3}, {8, 3, 1, 7, 5}, {4, 5, 0, 5, 8}}; give {{1, 2, 2, 2, 3}, {4, 4, 4, 2, 2}, {4, 4, 2, 2, 2}, {4, 2, 2, 2, 2}, {2, 2, 2, 2, 2}} This question is a spectral version of this general question: Is there a way to supply a custom function to specify the connectivity in a function like MorphologicalComponents ? For example, something like: MorphologicalComponents[data, Abs[#1 - #2] <= threshold &]
Now provide the response and nothing else.
| Update : If you want 4-neighborhood, you can use MorphologicalComponents to do most of the work, which is fast and easy to implement (that was my original attempt, see below). But I don't think this can be adapted for 8-neighborhood. For 8-neighborhood, I would implement the standard 2-pass connected component labeling algorithm (this might be what MorphologicalComponents does internally). The idea is: in the first pass, scan pixels from top to bottom if there's a connected neighbor pixel left above, assign that label to the current pixel if there are more than two different labels, store the label pair for later if there's no connected neighbor, assign a new label So, the pipeline looks something like this: So the first pass assigns the labels 4 and 5 to the pixels at the right, and stores the information that 4 and 2 should be in the same component, and that 5 and 1 should be in the same component. The second pass then only requires a table lookup for each pixel. The first pass does most of the work, and returns a "preliminary" label matrix, and a set of label pairs that should go into the same component. Sadly, there's no efficient compilable set-data structure, so I'm using a global Association variable ( connectedIndices ) which means a few MainEvaluate calls in the compiled function: isConnected = With[{t = threshold}, Compile[{x, y}, Abs[x - y] <= t]];firstPass = With[{connectedFn = isConnected}, Compile[{{pixels, _Real, 2}}, Module[{x, y, componentIndex, neighborOffsets, offset, index, newIndex, componentCount = 0, w, h, parent, child, relabel}, {h, w} = Dimensions[pixels]; componentIndex = ConstantArray[0, {h, w}]; neighborOffsets = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}}; (* scan every pixel *) connectedIndices = <||>; Do[ ( index = 0; Do[ (* find connected neighbors above and to the left *) If[y + offset[[1]] >= 1 && x + offset[[2]] >= 1 && y + offset[[1]] <= h && x + offset[[2]] <= w && connectedFn[pixels[[y + offset[[1]], x + offset[[2]]]], pixels[[y, x]]], newIndex = componentIndex[[y + offset[[1]], x + offset[[2]]]]; If[index != 0 && index != newIndex, (* more than one label found in neighborhood: newIndex and index really are the same component - save information for second pass *) AssociateTo[connectedIndices, MinMax[{index, newIndex}] -> 1]; ]; index = newIndex; ], {offset, neighborOffsets}]; If[index == 0, (* no label found in neighborhood: new component *) index = ++componentCount]; componentIndex[[y, x]] = index; ), {y, 1, Length[pixels]}, {x, 1, Length[pixels[[1]]]} ]; Return[componentIndex] ], {{relabelConnectedComponents[__], _Integer, 1}}, CompilationOptions -> {"InlineCompiledFunctions" -> True}, CompilationTarget -> "C"]] The second pass is straightforward: We can use graph functions to get a relabeling-lookup table from the connected label pairs: Clear[relabelConnectedComponents]relabelConnectedComponents[connectedIndices_, componentCount_] := Module[{comp, relabel, count}, comp = SortBy[ ConnectedComponents[ Graph[Range[componentCount], UndirectedEdge @@@ connectedIndices]], Min]; relabel = ConstantArray[0, componentCount]; Do[ Do[relabel[[oldIndex]] = index, {oldIndex, comp[[index]]}], {index, Length[comp]}]; relabel] (note that this graph only contains one node per component not per pixel , so this is much much faster than using ConnectedComponents on the pixels directly) And apply that lookup table: Clear[secondPass]secondPass[componentIndex_] := Module[{relabel}, (* second pass - relabel connected components *) If[Length[Keys@connectedIndices] == 0, componentIndex, relabel = relabelConnectedComponents[Keys[connectedIndices], Max[componentIndex]]; relabel[[#]] & /@ componentIndex ]]; Usage: secondPass@firstPass[data] This seems to be about 5-6 times slower than the built-in MorphologicalComponents , which means it's about 50% slower than the method below, which works on upsample data. But it should work for any neighborhood. (Original answer, using MorphologicalComponents ) First, two small utility functions: upsample duplicates every value in a list, showGrid displays a matrix of numbers: upsample = Riffle[#, #] &; showGrid[d_, opt___] := Grid[d /. n_?NumberQ :> Item[n, Background -> ColorData[95][n]], opt, ItemSize -> {1.5, 2}, Dividers -> {{{{True, False}}, -1 -> True}, {{{True, False}}, -1 -> True}}] You could upsample the data (duplicate every row and column): dataUpsampled = upsample /@ upsample[data];showGrid[dataUpsampled] Then you take the differences between rows, columns and across corners, and compare the differences to the threshold: padAndThreshold = PadRight[UnitStep[Abs[#] - threshold - 1], Dimensions[dataUpsampled]] &;dx = padAndThreshold[Differences /@ dataUpsampled];dy = padAndThreshold[Differences@dataUpsampled];dxy = padAndThreshold[ dataUpsampled[[2 ;;, 2 ;;]] - dataUpsampled[[;; -2, ;; -2]]];dyx = padAndThreshold[ dataUpsampled[[2 ;;, ;; -2]] - dataUpsampled[[;; -2, 2 ;;]]]; and combine them: boundaries = UnitStep[-(dx + dy + dxy + dyx)];showGrid[boundaries] now you can use MorphologicalComponents on this array: showGrid[MorphologicalComponents[boundaries]] To get the original sized result, simply remove the even rows and columns: comp = MorphologicalComponents[boundaries][[;; ;; 2, ;; ;; 2]];showGrid[comp, Dividers -> All] | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/149966', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1364/']} | jdg_381005 |
stackexchange | llm_judgeable_groundtruth_similarity | 6433921 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the pros and cons of standardizing on using Option Compare Text vs Option Compare Binary for VB.NET development? --- EDIT --- Just some background since it seems like it would help - my development team has found it much easier to standardize on Option Strict On , Option Infer On , and Option Explicit due to their obvious advantages over the alternatives. What we haven't found as easy to standardize on is Option Compare Text/Binary as there seem to be advantages and disadvantages to both and different developers have differing opinions. Some of the arguments for each side have been as follows: Some of the advantages/arguments for Option Compare Text: It reduces verbosity in the code by removing the need for StringComparer s and .ToLower() calls and StringComparison.OrdinalIgnoreCase all over the place Data needs are rarely concerned with casing, as evidenced by most databases being case-insensitive. Rarely would you ever really want to distinguish between THIS and This and this when doing a data comparison. Certain specific use cases are simpler when you don't have to worry about casing. For example, handling ASP.NET control events where commands are sent to the codebehind as strings and casing-issues are difficult to track down as the compiler cannot help you. Think Select Case statements for <asp:repeater> events as an example. Many of the concerns raised about text comparison concern internationalization, which is often not that relevant to a lot of applications. VB specifically is case insensitive as a language, though Visual Studio helps you by at least enforcing consistency in your casing. SQL is case insensitive as well. Strings are the only place where you have to remember to worry about it, which highlights the awkwardness in ways you wouldn't normally notice it if you were worried about it everywhere. Some of the advantages/arguments for Option Compare Binary: C# works this way, as do most other languages. It's somewhat unexpected to have alternate behavior and the unexpected is not good in programming. There is a slight performance penalty with Option Compare Text as evidenced by the IL generated on compile. Option Compare Binary doesn't have that penalty. Option Compare Text only makes certain parts of string handling case insensitive. But, it doesn't make it so that things like dictionary indexing are case insensitive by default. So, it's not like Option Compare Text actually makes it so that you don't have to worry about casing at all. If it only works half way, why bother? Programming is hard. It's best not to attempt to smooth over that fact. Worrying about string casing is part of the deal. Humans recognize THIS is different from This and tHiS . Of course your code should too - after all, they aren't really the exact same string. So I'm really just wondering if there are any other considerations. -- EDIT 2 -- Perhaps it would help if I defined what I'd consider an answer to this. If you can point to any authoritative external resource that talks through these issues more thoroughly, or point to a standards and best practices discussion or book that gives guidance on this topic, that would certainly count.
Now provide the response and nothing else.
| With Option Compare Text you don't need to worry about case when comparing strings. That can be a big benefit, and avoid converting everything to lower ( or upper) case to comapre for string equality. The other place where this plays a part is sorting of strings. Option Compare Text will sort like the file list in Windows, but Option Compare Binary will sort like a Unix file list (all the upper case file names appear before the lower-case file names). Update After reading the comments and the other answer, and thinking a bit more, I'd say Option Compare Binary is the way to go from point of view of consistency with the rest of the .Net Framework. If dictionary keys etc. are case-sensitive regardless of the Option Compare setting then using binary comparisons by default throughout your code is just being consistent. All you then need to worry about is if, for a particular comparison, you need it to be case-insensitive and code for that. If you go with Option Compare Text then not only do you need to worry about whether or not you need a particular comparison to be case-(in)sensitive you also need to be aware of the default behaviour in the current context. It then becomes an argument not of consitency with other languages, but of consistency with the framework you're developing to. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6433921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83144/']} | jdg_381006 |
stackexchange | llm_judgeable_groundtruth_similarity | 316772 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There is the formula $$\sum_i (-1)^i\binom{a}{k+i}\binom{l+i}{b} = (-1)^{a+k} \binom{l-k}{b-a}.$$Only finitely many summands are non-zero (those for $i\in\{b-l,\ldots,a-k\}$), so the sum is finite. The formula can be shown by induction. However, this does not give any further insight. So I'm looking for another proof giving a better idea why this formula is true, like deducing it from better known identities, giving a bijection between two finite sets etc.
Now provide the response and nothing else.
| Let's do a variable switch, with $n = l -k$, $m = b-a$, $j = k+i$. Then the formula to be proved is$$\sum_j (-1)^{j-k} \binom{a}{j} \binom{n+j}{m+a} = (-1)^{a+k} \binom{n}{m},$$or$$\sum_j (-1)^j \binom{a}{j} \binom{n+j}{m+a} = (-1)^a \binom{n}{m}.$$ Now, suppose we have $a$ labeled, uncolored balls, and $n$ labeled, blue balls. Color some number of those $a$ balls red. Then let's dot $m+a$ of the colored (red and blue) balls. Define the parity of the resulting state of balls as $+1$ if there are an even number of red balls and $-1$ if there are an odd number of red balls. The left-hand side then counts the resulting signed sum over all configurations of colored and uncolored, dotted and undotted balls, where the sum conditions on the number $j$ of red balls. Define a sign-reversing involution in the following manner: Take the highest-labeled, undotted ball that is uncolored or red and swap it to red or uncolored, respectively. This changes the parity of the configuration, and so the sum over all of the configurations for which the involution can be applied is $0$. The value of the sum, then, must be the number (including the parity) of configurations for which the involution cannot be applied. The only configurations for which the involution cannot be applied are those for which all the uncolored or red balls are dotted. So all $a$ of the uncolored balls must have been colored red, and all $a$ of those red balls must have been dotted. Thus exactly $m$ of the $n$ blue balls must have been dotted. The number of these configurations is therefore $\binom{n}{m}$, and the parity is $(-1)^a$, as there are $a$ red balls in this configuration. Therefore,$$\sum_j (-1)^j \binom{a}{j} \binom{n+j}{m+a} = (-1)^a \binom{n}{m}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/316772', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/61691/']} | jdg_381007 |
stackexchange | llm_judgeable_groundtruth_similarity | 19512249 |
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 developed an app, following is the code This is the code of this app <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".HomeScreen" > <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="*" android:weightSum="4" > <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" > <Button android:id="@+id/fBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/fStr" /> <Button android:id="@+id/rBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/rStr" /> <Button android:id="@+id/sBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/sStr" /> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" > <Button android:id="@+id/cBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/cStr" /> <Button android:id="@+id/aBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/aStr" /> <Button android:id="@+id/lBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/lStr" /> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" > <Button android:id="@+id/oBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/oStr" /> <Button android:id="@+id/tBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/tStr" /> <Button android:id="@+id/eBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/eStr" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" > <Button android:id="@+id/dBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/dStr" /> <Button android:id="@+id/hBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/hStr" /> <Button android:id="@+id/aaBtn" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableTop="@drawable/ic_launcher" android:layout_weight=".3" android:textAppearance="?android:attr/textAppearanceSmall" android:text="@string/aStr" /> </TableRow> </TableLayout></RelativeLayout> strings.xml <?xml version="1.0" encoding="utf-8"?><resources> <string name="fStr">Fffffffff</string><string name="rStr">Rrrrrr</string><string name="sStr">Ssssss </string><string name="lStr">Lllll</string><string name="oStr">Oooooooooooo</string><string name="tStr">Ttttt</string><string name="eStr">Eeeeee</string><string name="dStr">Dddddddddd</string><string name="cStr">Cccccccc</string><string name="hStr">Hhhh</string><string name="aStr">Aaaaaaaaaa aaaa</string></resources> This app has an issue. The gap between button image and text is too much, specially in 5.1 WVGA screen. It does the same look in my mobile, which has the screen size of 4.5 inches Following is the image How can I solve this issue?
Now provide the response and nothing else.
| The DrawerLayout should be the root element. Put the ViewPager inside it. <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <ListView android:id="@+id/left_drawer" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:background="#111" android:choiceMode="singleChoice" android:divider="@android:color/transparent" android:dividerHeight="0dp" /></android.support.v4.widget.DrawerLayout> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19512249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1379286/']} | jdg_381008 |
stackexchange | llm_judgeable_groundtruth_similarity | 39898434 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It's actually a very simple question, but after an hour I can not solve my problem. I need to create a 2d array of Int. var arr = [[Int]]()orvar arr : [[Int]] = [] tried to change value : arr[x][y] = 1 fatal error: Index out of range Should I use APPEND or I need specify the size of the array? I'm confused..
Now provide the response and nothing else.
| It's not simple really. The line: var arr : [[Int]] = [] Creates a variable of type Array of Array of Int and initially the array is empty. You need to populate this like any other other array in Swift. Let's step back to a single array: var row : [Int] = [] You now have an empty array. You can't just do: row[6] = 10 You first have to add 7 values to the array before you can access the value at index 6 (the 7th value). With your array of arrays, you need to fill in the outer array with a whole set of inner arrays. And each of those inner arrays need to be filled out with the proper number of values. Here is one simple way to initialize your array of arrays assuming you want a pre-filled matrix with every value set to 0. var matrix : [[Int]] = Array(repeating: Array(repeating: 0, count: 10), count: 10) The outer count represents the number of rows and the inner count represents the number of columns. Adjust each as needed. Now you can access any cell in the matrix: matrix[x][y] = 1 // where x and y are from 0 to rows-1/columns-1 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39898434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6583801/']} | jdg_381009 |
stackexchange | llm_judgeable_groundtruth_similarity | 4553405 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way in Haskell to bind the second argument but not the first of a function without using lambda functions or defining another "local" function? Example. I have a binary function like: sub :: Int -> Int -> Intsub x y = x - y Now if I want to bind the first argument, I can do so easily using (sub someExpression): mapSubFrom5 x = map (sub 5) x*Main> mapSubFrom5 [1,2,3,4,5][4,3,2,1,0] That works fine if I want to bind the first n arguments without "gap". If I want to bind the second argument but not the first, the two options I am aware of are more verbose: Either via another, local, function: mapSub5 x = map sub5 x where sub5 x = sub x 5*Main> mapSub5 [1,2,3,4,5][-4,-3,-2,-1,0] Or using lambda: mapSub5 x = map (\x -> sub x 5) x While both are working fine, I like the elegance of "sub 5" and wonder if there is a similarly elegant way to bind the n-th (n > 1) argument of a function?
Now provide the response and nothing else.
| flip , which produces a new function with the first two arguments inversed, has already been mentioned as a straigtforward solution. However, it's worth noting that Haskell defines a nice infix syntax for binary operators. First of all, it's simply sub = (-) With parentheses around, all operators are - syntactially too - ordinary functions. Now we can curry operators with some special syntax. Binding to the first operand: addOne = (1 +) ... and to the second half = (/ 2) Thus your code becomes map (-5) [1..5] Unfortunately, -5 is a number literal, but you get the point. :) Now since we can turn any function into a binary operator by putting backticks around it like in f x y == x `f` y we can use this special operator syntax to write map (`sub` 5) [1..5] Note: Currying the first argument is common, the second one - as in your case - nicely possible. But: I wouldn't do that for futher arguments. Haskell functions are written in a style that the common ones to curry are in the front for exactly that reason. Using some special syntax for further arguments feels much too implicit for me. Just use the lambda and give the variables descriptive names. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4553405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/299399/']} | jdg_381010 |
stackexchange | llm_judgeable_groundtruth_similarity | 622264 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What does where T : somevalue mean? I just saw some code that said where T : Attribute . I think this has something to do with generics but I am not sure what this means or what it is doing. Does anyone know?
Now provide the response and nothing else.
| It is a constraint on a type parameter , meaning that the type T given to a generic class or method must inherit from the class Attribute For example: public class Foo<T> : where T : Attribute{ public string GetTypeId(T attr) { return attr.TypeId.ToString(); } // ..}Foo<DescriptionAttribute> bar; // OK, DescriptionAttribute inherits AttributeFoo<int> baz; // Compiler error, int does not inherit Attribute This is useful, because it allows the generic class to do things with objects of type T with the knowledge that anything that is a T must also be an Attribute . In the example above, it's okay for GetTypeId to query the TypeId of attr because TypeId is a property of an Attribute , and because attr is a T it must be a type that inherits from Attribute . Constraints can also be used on generic methods, with the same effect: public static void GetTypeId<T>(T attr) where T : Attribute{ return attr.TypeId.ToString();} There are other constraints you can place on a type; from MSDN : where T: struct The type argument must be a value type. Any value type except Nullable can be specified. where T : class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type. where T : new() The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last. where T : <base class name> The type argument must be or derive from the specified base class. where T : <interface name> The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic. where T : U The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/622264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75086/']} | jdg_381011 |
stackexchange | llm_judgeable_groundtruth_similarity | 734653 |
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:
This question pertains to the section § 2. On the Relativity of Lengths and Times of Einstein's original 1905 paper "ON THE ELECTRODYNAMICSOF MOVING BODIES". I'm trying to figure out exactly what Einstein is saying in his demonstration that simultaneity is relative. The conclusion is very familiar to me, so I'm not asking for an alternative demonstration. I want to understand the passage quoted below; and, in particular, the footnote. Apparently he is saying that when the system at rest measures the length of the rod by "simultaneously" recording the positions of the ends, each moving observer is to set his clock to match the rest-frame time of the measurement event at his location. Then it gets weird. He seems to be saying that the clocks moving with $\rm A$ and $\rm B$ are to continue to match the coinciding rest-frame clocks as they pass them, into the future. But for that to happen, the moving clocks will need a different unit of time than clocks at rest. Furthermore, for my interpretation to be correct, the statement "[T]hese observers apply to both clocks the criterion established in § 1 for the synchronization of two clocks." will have to mean that the moving observers are not setting their clocks by this method, but are merely checking to see if they are synchronized; and those moving clocks are "slaved" to local rest-frame time. I say this because the footnote indicates that both the rest-frame and moving clock at, say the reflection event, are to read time $t_{\rm B}.$ Am I reading this correctly? We imagine further that at the two ends $\rm A$ and $\rm B$ of the rod, clocks are placed which synchronize with the clocks of the stationary system, that is to say that their indications correspond at any instant to the “time of the stationary system” at the places where they happen to be. These clocks are therefore “synchronous in the stationary system.” We imagine further that with each clock there is a moving observer, and that these observers apply to both clocks the criterion established in § 1 for the synchronization of two clocks. Let a ray of light depart from $\rm A$ at the time [footnote] $t_{\rm A}$ , let it be reflected at $\rm B$ at the time $t_{\rm B}$ , and reach $\rm A$ again at the time $t^\prime_{\rm A}$ . Taking into consideration the principle of the constancy of the velocity of light we find that $$t_{\rm B}-t_{\rm A}=\frac{r_{\rm AB}}{c-v} \text{ and } t^\prime_{\rm A}-t_{\rm B}=\frac{r_{\rm AB}}{c+v}$$ where $r_{\rm AB}$ denotes the length of the moving rod—measured in the stationary system. Observers moving with the moving rod would thus find that the two clocks were not synchronous, while observers in the stationary system would declare the clocks to be synchronous. Footnote: “Time” here denotes “time of the stationary system” and also “position of hands of the moving clock situated at the place under discussion.”
Now provide the response and nothing else.
| Then it gets weird. Yes, that is an apt description. Remember, this was brand new. There weren’t any of the standard pedagogical techniques then and he couldn’t ask for any help in making a better explanation. So this specific section was a little weird and no subsequent author (including himself) ever used this argument again. Then it gets weird. He seems to be saying that the clocks moving with A and B are to continue to match the coinciding rest-frame clocks as they pass them, into the future. But for that to happen, the moving clocks will need a different unit of time than clocks at rest Yes, that is correct. A similar thing is actually done with GPS satellites. They are moving in the earth centered inertial frame (ECIF), and so their clocks are adjusted so that they do not keep correct proper time but rather they match the ECIF time. the moving observers are not setting their clocks by this method, but are merely checking to see if they are synchronized Yes, you are reading it correctly. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/734653', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/117014/']} | jdg_381012 |
stackexchange | llm_judgeable_groundtruth_similarity | 10236004 |
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 set up a link_to in a partial (update_dashboard) and it looks like this link_to "Link", hash, {:url => {:controller => "results", :action => "update_report"}}, :remote => true 'hash' is a set of inputs that I am passing to the controller. As it can be seen. i want the "Link" to map to the 'update_report' action in the 'results' controller. but, i find that after the page is rendered, when I click on the link, it just displays the partial in a new page. I went into Firebug and this is how the link is rendered <a url="{:controller=>"results", :action=>"update_report"}" href="/test/update_dashboard?branch=xxxx&brand=xx&end_time=2012-02-29+22%3A59&repo=xxxx%2Fxx&start_time=2012-02-17+18%3A20">Link</a> Why is the href pointing to /test/update_dashboard ? Why is is not taking the parameter that i supplied for the controller attribute Any help is greatly appreciated.
Now provide the response and nothing else.
| As pointed out by Ryan above, the command you need is GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password'; However, note that the documentation indicates that in order for this to work, another user account from localhost must be created for the same user; otherwise, the anonymous account created automatically by mysql_install_db takes precedence because it has a more specific host column. In other words; in order for user user to be able to connect from any server; 2 accounts need to be created as follows: GRANT ALL ON *.* to user@localhost IDENTIFIED BY 'password'; GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password'; Read the full documentation here. And here's the relevant piece for reference: After connecting to the server as root, you can add new accounts. The following statements use GRANT to set up four new accounts: mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' -> WITH GRANT OPTION;mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' -> WITH GRANT OPTION;mysql> CREATE USER 'admin'@'localhost';mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';mysql> CREATE USER 'dummy'@'localhost'; The accounts created by these statements have the following properties: Two of the accounts have a user name of monty and a password of some_pass. Both accounts are superuser accounts with full privileges to do anything. The 'monty'@'localhost' account can be used only when connecting from the local host. The 'monty'@'%' account uses the '%' wildcard for the host part, so it can be used to connect from any host. It is necessary to have both accounts for monty to be able to connect from anywhere as monty . Without the localhost account, the anonymous-user account for localhost that is created by mysql_install_db would take precedence when monty connects from the local host. As a result, monty would be treated as an anonymous user. The reason for this is that the anonymous-user account has a more specific Host column value than the 'monty'@'%' account and thus comes earlier in the user table sort order. (user table sorting is discussed in Section 6.2.4, “Access Control, Stage 1: Connection Verification”.) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10236004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/631380/']} | jdg_381013 |
stackexchange | llm_judgeable_groundtruth_similarity | 18901467 |
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 been working through some codeproject articles on driver dev, but have some confusion about IOCTLs and IRPs. From what I have seen, it seems that IOCTLs are sent from usermode, and translated into IRPs. And IRPs are messages between the OS and the device, but this doesnt seem to line up with the descriptions I am reading... leading me to think that I might be missing something. TLDR What is the difference between an IOCTL and IRP?
Now provide the response and nothing else.
| IRPs are Windows kernel structures. They are used to represent an I/O request as it moves around the kernel system. A filesystem, for example, that needs to read from a block device generates an IRP that represents its read request and hands it to the block device. The block device processes the IRP, puts the results in the IRP, marks it complete, and tells the filesystem to look at the IRP to get the data. Devices can maintain queues of IRPs they are working on. An IOCTL is a request to a device, typically received from a user-space application. They're generally used for requests that don't fit into a standard API. For example, you wouldn't normally use an IOCTL to open a file on a filesystem. When a program issues an IOCTL to a device, an IRP (typically IRP_MJ_DEVICE_CONTROL ) is created in kernel space to reflect that request. In summary, an IOCTL is a particular type of "miscellaneous" request to a device driver. An IRP is a data structure for managing all kinds of requests inside the Windows driver kernel architecture. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18901467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1544702/']} | jdg_381014 |
stackexchange | llm_judgeable_groundtruth_similarity | 95410 |
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 see in this post that the main difference is that KDF outputs have "certain randomness properties", and I don't understand what does it mean. Suposing that that "certain randomness properties" are for protect from rainbow tables and that precomputed stuff. But using hash with proper salting we can also protect from those attacks. So in that sense I believe that there's no difference between this two tools, differing only in the implementation. I also know that other aim of the KDF is to be enough slow in order to slow down hypothetical attacks, without spoiling user experience in terms of speed. Well, in the strict sense, this could be also achieved in hashing adding some useless operations (e.g. for(i = 0; i < 1000000; i++); ), even if it wouldn't be very clean. So, what's the difference? Is one better than other? When would we have to use one, and when the other?
Now provide the response and nothing else.
| There are actually two kinds of KDFs. One kind is designed to derive a key from high-entropy input (like another key); this can be done with a fast keyed hash like HMAC. The other kind takes a password as input. Passwords are low-entropy; they're not inherently very hard to brute-force. A good password hash thus has to be slow. In your question, you said that adding for (i=0; i<bignum; i++); would slow the hash. This is actually completely useless. The attacker does not have to play by your rules. Hashes need to protect passwords when the attackers have a copy of the hashes. If the attacker can compute hashes quickly, it doesn't matter how slowly you compute them. Hashes need to be inherently slow; there should be no shortcuts to evaluate them faster than the legitimate server. The "randomness properties" are because a KDF needs to produce a key. They have nothing to do with precomputation, including rainbow tables. Cryptographic algorithms typically make certain assumptions about the key; among other things, they normally assume it was selected totally at random from the set of possible keys. Keys are also expected to be a certain length; their derivation functions need arbitrary-length output. In contrast, it's OK if a password hash has lots of structure to the output. Maybe there's a 70% chance that adjacent bits have the same value. Maybe it spreads 128 bits of entropy into 4096 bits of output. As long as it's hard to reverse, that's a fine hash, but it's unsuitable as a key. A secure password-based key derivation function is a secure password hash (PBKDF2 is in fact one of the big 3 hashes). The reverse is not necessarily true. Which one to use is simple: use a password-based key derivation function to derive a key from a password, and a hash to store passwords. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/95410', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/82143/']} | jdg_381015 |
stackexchange | llm_judgeable_groundtruth_similarity | 6712117 |
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 may not be the correct place for this question, if not feel free to move it. I tagged as Delphi/Pascal because it's what I am working in atm, but this could apply to all programming I guess. Anyway I am doing some code cleanup and thinking of moving all the strings in my program to a separate single .pas file. Are there any pros and cons to doing this? Is it even worth doing? To clarify: I mean that I will be creating a separate file, Strings.pas in it I will make all my text string variables. Ex Current Code Messages.Add('The voucher was NOT sent to ' + sName+ ' because the application is in TEST MODE.'); Messages.Add('Voucher Saved to ' + sFullPath); Messages.Add('----------------------------------------------------------'); New Code would be something like: Messages.Add(sMsgText1 + '' + sName + '' + sMsgText2 + '' + sFullPath) The Strings.pas file would hold all the string data. Hope that makes better sense
Now provide the response and nothing else.
| Moving your strings to a separate file is a good idea! It keeps them together and will let you easily change them if required. Your question doesn't say you want to be able to translate them, but centralizing will help that to. But, code like: Messages.Add(sMsgText1 + '' + sName + '' + sMsgText2 + '' + sFullPath) is not better than code like: Messages.Add('The voucher was NOT sent to ' + sName+ ' because the application is in TEST MODE.'); You've turned a messy but readable function call into a messy and un -readable function call . With the old code (the second snippet just above), you can read the code and see roughly what the message is going to say, because a lot of it is there in text. With the new code, you can't. Second, the reason for moving the strings to to keep related items together and make it easier to change them. What if you want to change the above message so that instead of saying "The file 'foo' in path 'bar'..." it is phrased "The file bar\foo is..."? You can't: the way the messages are built is still fixed and scattered throughout your code. If you want to change several messages to be formatted the same way, you will need to change lots of individual places. This will be even more of a problem if your goal is to translate your messages, since often translation requires rephrasing a message not just translating the components. (You need to change the order of subitems included in your messages, for example - you can't just assume each language is a phrase-for-phrase in order substitution.) Refactor one step further I'd suggest instead a more aggressive refactoring of your message code. You're definitely on the right track when you suggest moving your messages to a separate file. But don't just move the strings: move the functions as well. Instead of a large number of Messages.Add('...') scattered through your code, find the common subset of messages you create. Many will be very similar. Create a family of functions you can call, so that all similar messages are implemented with a single function, and if you need to change the phrasing for them, you can do it in a single spot. For example, instead of: Messages.Add('The file ' + sFile + ' in ' + sPath + ' was not found.');... and elsewhere:Messages.Add('The file ' + sFileName + ' in ' + sURL + ' was not found.'); have a single function: Messages.ItemNotFound(sFile, sPath);...Messages.ItemNotFound(sFileName, sURL); You get: Centralized message strings Centralized message functions Less code duplication Cleaner code (no assembling of strings in a function call, just parameters) Easier to translate - provide an alternate implementation of the functions (don't forget that just translating the substrings may not be enough, you often need to be able to alter the phrasing substantially.) Clear descriptions of what the message is in the function name, such as ItemNotFount(item, path) , which leads to Clearer code when you're reading it Sounds good to me :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6712117', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/393142/']} | jdg_381016 |
stackexchange | llm_judgeable_groundtruth_similarity | 2363207 |
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:
For a positive integer $n$, and a non empty subset $A$ of $\{1,2,...,2n\}$, call $A$ good if the set $\{u\pm v|u,v\in A\}$ does not contain the set $\{1,2,...,n\}$. Find the smallest real number $c$, such that for any positive integer $n$, and any good subset $A$ of $\{1,2,...,2n\}$, $|A|\leq cn$. This is a problem I do not know how to attack. There is a solution on AOPS, but I don't like its approach. It seems like probabilistic methods would do, but I'm not sure.
Now provide the response and nothing else.
| The vectors are $(0,1,1,1)$, $(0,0,0,1)$ and $(1,1,2,0)$. Since your vector has first component $1$, this forces $(1,1,2,0)$ to appear with a coefficient $1$. This reduces your problem to $(1,m-2,5)$ with $(0,0,1)$ and $(1,1,1)$ (forget the first coordinate). The same argument now forces $(1,1,1)$ to appear with coefficient $1$, so $(0,m-3,4)$ is a multiple of $(0,0,1)$, only possible if $m=3$, in which case $(0,0,1)$ appears with coefficient $4$. This gives $$(1,2,3,5) = (0,1,1,1)+4(0,0,0,1)+(1,1,2,0)$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2363207', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/463553/']} | jdg_381017 |
stackexchange | llm_judgeable_groundtruth_similarity | 3482389 |
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 this site they say there are 10 LISP primitives. The primitives are: atom, quote, eq, car, cdr, cons, cond, lambda, label, apply . http://hyperpolyglot.wikidot.com/lisp#ten-primitives Stevey reckons there are seven (or five): Its part of the purity of the idea of LISP: you only need the seven (or is it five?) primitives to build the full machine. http://steve-yegge.blogspot.com/2006/04/lisp-is-not-acceptable-lisp.html What is the minimum number of primitives to build a LISP machine (ie something that can run an eval/value function on LISP code)? (And which ones are they?) (I can understand you could live without atom, label and apply )
Now provide the response and nothing else.
| Basic Predicates/F-functions McCarthy 's Elementary S-functions and Predicates were: atom Which was necessary because car and cdr are defined for lists only, which means you cannot count on any sort of answer to indicate what was happening if you gave car an atom. eq For testing equality between atoms. car For returning the first half (address) of the cons cell. (Contents of address register). cdr For returning the second half (decrement) of the cons cell. (Contents of decrement register). cons For making a new cons cell, with the address half containing the first argument to cons, and the decrement half containing the second argument. Tying it together: S-Functions He then went on to add to his basic notation, to enable writing what he called S-functions: quote To represent an expression without evaluating it. cond The basic conditional to be used with the previously described predicates. lambda To denote a function. label Though he didn't need this for recursion, he might not have known about the Y-Combinator ( according to Paul Graham ), he added this for convenience and to enable easy recursion. So you can see he actually defined 9 basic "operators" for his Lisp machine. In a previous answer to another one of your questions, I explained how you could represent and operate on numbers with this system. But the answer to this question really depends on what you want out of your Lisp machine. You could implement one without the label function, as you could simply functionally compose everything, and obtain recursion through applying the Y-Combinator. atom could be discarded if you defined the car operation on atoms to return NIL . You could essentially have McCarthy's LISP machine with 7 of these 9 defined primitives, but you could ostensibly define a more concise version depending on how much inconvenience you'd want to inflict on yourself. I like his machine quite fine, or the many primitives in the newer languages like Clojure. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3482389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15441/']} | jdg_381018 |
stackexchange | llm_judgeable_groundtruth_similarity | 36255440 |
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 try to move symfony to shared host. I moved symfony structure to / and my web folder is /public_html. Warning: require(/home/user/app/cache/prod/doctrine/orm/Proxies/__CG__UserBundleEntityUser.php): failed to open stream: No such file or directory in /home/user/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php on line 209 Warning: require(/home/user/app/cache/prod/doctrine/orm/Proxies/__CG__UserBundleEntityUser.php): failed to open stream: No such file or directory in /home/user/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php on line 209 Fatal error: require(): Failed opening required '/home/user/app/cache/prod/doctrine/orm/Proxies/__CG__UserBundleEntityUser.php' (include_path='.:/opt/php55/lib/php') in /home/user/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php on line 209 This error occurs only in the prod environment. The exception is not thrown in the dev environment. I tried the following: rm -rf /app/cache + chmod 777app/console cache:warmup I use Symfony 2.8.3. The following directories are present locally and on the server: LOCAL CACHE:- /annotations, /twig, /vich_uploader + /doctrine, /translations SERVER CACHE:- /annotations, /twig, /vich_uploader If I upload my local cache to the server, the exception disappears.
Now provide the response and nothing else.
| You did not create the proxy classes before you tried to access your application. This is usually done by: app/console cache:warmup --env=prod The auto-generation of proxy-classes is disabled by default in the prod environment. You can enable automatic generation of proxy-classes similar to the dev environment by adding this to your config: app/config/config_prod.yml doctrine: orm: auto_generate_proxy_classes: true # <- change to true proxy_dir: '%kernel.cache_dir%/doctrine/orm/Proxies' proxy_namespace: Proxies | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36255440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083774/']} | jdg_381019 |
stackexchange | llm_judgeable_groundtruth_similarity | 1846791 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that for $n \to \infty, \space \sin(n)$ does not have limit. Is this also true for the sequence $\sin(n^2)$?
Now provide the response and nothing else.
| Let we give the tough approach. We want to show that the sequence given by $\sin(n^2)$ is dense in the interval $[-1,1]$. For such a purpose, it is enough to show that the sequence given by $e^{in^2}$ is dense in the unit circle, since the projection on the $y$-axis preserves density. But density (truth to be told, equidistribution , that is way stronger) is a consequence of Weyl's inequality / Van Der Corput's trick with $f(x)=x^2$. Now a variation on the easy, tricky proof. Assuming that $\sin(n^2)\to L$, we must have$$ \lim_{n\to +\infty}\left(\sin(n^2+2n+1)-\sin(n^2-2n+1)\right)=0 $$or$$ \lim_{n\to +\infty}2\cos(n^2+1)\sin(2n)=0$$or $$\lim_{n\to +\infty}\left(\cos(n^2)\cos(1)\sin(2n)-\sin(n^2)\sin(1)\sin(2n)\right) = 0 $$so the sequence given by $b_n=\sin(2n)$ has at most two accumulation points, that is clearly contradicted by the density (or equidistribution) of $e^{2ni}$ in $S^1$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1846791', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/344362/']} | jdg_381020 |
stackexchange | llm_judgeable_groundtruth_similarity | 1923419 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know similar questions and answers have been posted here, but I don't understand the answers. Can anyone show me how to solve this problem in a simple way? This is a math problem for 8th grade students.Thank you very much! What is the sum of all positive even divisors of 1000?
Now provide the response and nothing else.
| First consider the prime factorization of $1000$. We have: $$1000=2^3\times 5^3$$ Now, how can we list all the factors of $1000$? We see that we can try listing them in a table: $$\begin{array}{c|c|c|} & \text{$5^0$} & \text{$5^1$} & \text{$5^2$} & \text{$5^3$} \\ \hline\text{$2^0$} & 1 & 5 & 25 & 125 \\ \hline\text{$2^1$} & 2 & 10 & 50 & 250 \\ \hline\text{$2^2$} & 4 & 20 & 100 & 500 \\ \hline\text{$2^3$} & 8 & 40 & 200 & 1000 \\ \hline\end{array}$$ We see that we can take $(2^1+2^2+2^3) \times (5^0 + 5^1 + 5^2 + 5^3) = 2184$. To get the sum of all factors, we would also include $2^0$ on the left side of the multiplication. We exclude $2^0$ because those would be odd factors. | {} | {'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1923419', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/311116/']} | jdg_381021 |
stackexchange | llm_judgeable_groundtruth_similarity | 266965 |
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:
This is what I learned from textbook. An insulator is insulate as the gap between the valence band and the conduction band and the fermi level lies in the gap. A superconductor is super electronically conductive because there is a gap between the BCS ground state with the first excited state. This gap prevents electrons from being backscattered. I'm trying to understand why both have gaps but one is insulator, the other is superconductor.
Now provide the response and nothing else.
| The difference is that in a normal conductor the current is carried by fermions (i.e. electrons) while in a superconductor the current is carried by bosons (i.e. Cooper pairs). Have a read through my answer to What is it about the "conduction band" of a material that is distinct from the valence band? where I explain why a full energy band cannot carry a current. In a conventional conductor any momentum eigenstate in the band can be occupied by at most two electrons (with opposite spins) so in a full band the net momentum of the electrons in the band is zero i.e. there is no net drift velocity and hence no current. In a superconductor the electrons pair up into Cooper pairs that obey Bose-Einstein statistics, so any number of Cooper pairs can occupy the same momentum state. That means the electrons joined into Cooper pairs can have a net momentum, and hence a net drift velocity, so they can carry a current. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/266965', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/109653/']} | jdg_381022 |
stackexchange | llm_judgeable_groundtruth_similarity | 57765996 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created 2 anchors within my pageAs of default , whenever one clicks on anchor link ,it directly jumps to the requested section One easy way of enabling smooth Scrolling is adding this in CSS file but it affects the whole html page , I don't want that i want this smooth Scrolling property to only apply to a single anchor within my page ( lets say the section 1 anchor for this example ) and not every anchors universally Html Codes are included below in snippets html { scroll-behavior: smooth;} <a href="#Section1">Section 1</a><br><a href="#Section2">Section 2</a><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><a class="anchor" id="Section1"> </a><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br><a class="anchor2" id="Section2"> </a>
Now provide the response and nothing else.
| Thanks for your answer. In the meanwhile, I solved it with another solution: In the main.dart file I now use ChangeNotifierProxyProvider instead of ChangeNotifierProvider for the depending provider: // main.dartreturn MultiProvider( providers: [ ChangeNotifierProvider(builder: (_) => Auth()), ChangeNotifierProxyProvider<Auth, Messages>( builder: (context, auth, previousMessages) => Messages(auth), initialBuilder: (BuildContext context) => Messages(null), ), ], child: MaterialApp( ... ), ); Now the Messages provider will be rebuilt when the login state changes and gets passed the Auth Provider: class Messages extends ChangeNotifier { final Auth _authProvider; List<Message> _messages = []; List<Message> get messages => _messages; Messages(this._authProvider) { if (this._authProvider != null) { if (_authProvider.loggedIn) fetchMessages(); } } ...} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57765996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11988417/']} | jdg_381023 |
stackexchange | llm_judgeable_groundtruth_similarity | 14791526 |
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'd like to declaratively listen for an ENTER key press in an input field, with Dart's Web UI? I only want to run a method if ENTER was pressed, and I don't care about any other key. How do I do this?
Now provide the response and nothing else.
| Summary Dart's Web UI package can declaratively register handlers for various events, like click and keyUp. The keyUp event will fire for every single keyboard up event. To filter those events, and to listen to only specific keys, you need to look at the keyCode attribute. Luckily, Dart has a convenience class for normalizing keycodes across browsers. You can use all of this inside your declarative bind attributes. Read on to learn how! Listening for key presses The InputElement class has a stream of events for the keyUp event, called onKeyUp ( docs ). The onKeyUp stream emits KeyboardEvent ( doc ) instances. final Stream<KeyboardEvent> onKeyUp; Old 'n Busted The KeyboardEvent provides a keyCode accessor that returns a system specific key code. Unfortunately, some systems have different key codes for the same semantic key. Luckily, Dart has a fix! New Hotness Use the KeyEvent.wrap(KeyboardEvent parent) ( doc ) to emulating KeyEvent and normalizing confusing key codes! new KeyEvent.wrap(keyboardEvent) Now that you have an instance of KeyEvent , you can query its keyCode for a rational look into what key was pressed. The keyCode getter returns an int , but you can compare that against a list of keys from the KeyCode ( doc ) class. var keyEvent = new KeyEvent.wrap(keyboardEvent);if (keyEvent.keyCode == KeyCode.ENTER) { // enter was pressed} Cross-browser key presses FTW The KeyEvent and KeyCode classes help to normalize key codes across systems and browsers, so you don't need to worry about various incompatibilities. With Web UI Web UI lets you declaratively register event handling. You can listen for key events and check if the enter key was pressed. Here is an example: <input type="text" id="new-todo" on-key-up="if (new KeyEvent($event).keyCode == KeyCode.ENTER) createNewTodo()"> Notice how on-key-up registers the if statement, which uses KeyEvent and KeyCode to normalize the key codes. The createNewTodo method is only called when the enter key was pressed. Ta da! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14791526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123471/']} | jdg_381024 |
stackexchange | llm_judgeable_groundtruth_similarity | 78768 |
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to make voltage divider, so I could read a battery voltage up to 14.4 V. Could I use very high resistance resistors for that, so the current would be very low (to not to discharge battery)? On the Internet there are examples with 500 - 2000 ohm resistors, but could I use hundreds of thousands to reduce the current to minimum? Would Arduino's analog input still read the value?
Now provide the response and nothing else.
| The most efficient is not to have a voltage divider at all. Or at least to only have a voltage divider when you actually need one. My preferred schematic is this: simulate this circuit – Schematic created using CircuitLab With this M1 is normally kept turned off by R3. When you want to take a measurement you turn on M2 by setting D3 HIGH (or whatever pin you attached it to) which pulls down the gate of M1 turning it on. This then connects the batter to the voltage divider R1/R2 and allows you to read the voltage at A0. The voltage divider of 20k / 10k allows you to read up to 15V on the battery, and gives you an output impedance of 6.67kΩ which is within the recommended maximum of 10kΩ for the ATMega's ADC. During "idle" times when M1 and M2 are both off the only current flowing is the minuscule leakage current through M2 tempered by the large 100kΩ resistor R3 (which itself pales into insignificance compared to the "off" resistance of M2 anyway). Selecting M1 so that the ON resistance is very small (<0.1Ω) allows you to essentially ignore it in your calculations since that will be swamped by the tolerance of R1 and R2 anyway. M2 needs to be selected so that it is "logic level" (i.e, with a gate threshold V_GS well below 5V). This double-FET arrangement should be used rather than just using an N-channel FET in the ground connection of the divider because when that simpler arrangement is turned off the Arduino will be seeing 12V directly connected to A0 which really is not good - you will kill the Arduino - so it is important that you switch the "high" side of the network not the "low" side, and to do that requires two FETs. | {} | {'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/78768', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/69282/']} | jdg_381025 |
stackexchange | llm_judgeable_groundtruth_similarity | 973679 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know the AM-GM inequality and its proof which is relatively complex, though the case for $n=2$ is quite simple. However, I don't know of any special easier proof for the case $n=3$, specifically: $$\frac{a+b+c}3\ge \sqrt[3]{abc}$$ What is the most elegant proof for this? :)
Now provide the response and nothing else.
| The case for $n=3$ can be proved by using the cases for $n=2,4$. For $p,q\gt 0$, we have$$(\sqrt p-\sqrt q)^2\ge0\iff \frac{p+q}{2}\ge\sqrt{pq}.$$So, we have for $s,t,u,v\gt 0,$$$s+t\ge 2\sqrt{st},\ \ \ u+v\ge 2\sqrt{uv}.$$Hence, we have$$s+t+u+v\ge 2\sqrt{st}+2\sqrt{uv}\ge 2\sqrt{2\sqrt{st}\cdot 2\sqrt{uv}}=4(stuv)^{1/4}.$$ Here, setting $s=a,t=b,u=c,v=\frac{a+b+c}{3}$ gives us$$a+b+c+\frac{a+b+c}{3}\ge 4\left(\frac{abc(a+b+c)}{3}\right)^{1/4}\iff \frac{a+b+c}{3}\ge\sqrt[3]{abc}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/973679', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/184352/']} | jdg_381026 |
stackexchange | llm_judgeable_groundtruth_similarity | 2777129 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $p(z)$ be a monic polynomial of degree $n$. Prove that $\max\limits_{|z|=1}|p(z)|\geq 1$ and that equlity holds if and only if $p(z)=z^n$. I first observed that $p^{(n)}(z)=n!$. Therefore by Cauchy's formula $$n!=p^{(n)}(0)=\frac{n!}{2\pi i}\int\limits_{|z|=1}\frac{p(z)}{(z-0)^{n+1}}dz\implies 1\leq\frac{1}{2\pi}\int\limits_{|z|=1}|p(z)|dz\leq\max\limits_{|z|=1}|p(z)|$$ Now, clearly if $p(z)=z^n$ then $\max\limits_{|z|=1}|p(z)|= 1$, but what about the converse?
Now provide the response and nothing else.
| Let $p(z)=z^n+a_{n-1}z^{n-1}+\cdots+a_0$ . Then, $\forall z\neq 0:p(\frac{1}{z})=z^{-n}+a_{n-1}z^{-n+1}+\cdots+a_0$ . Let $q(z)=z^n\cdot p(\frac{1}{z})=1+a_{n-1}z+\cdots+a_0z^n$ . Observe that $$\max\limits_{|z|=1}|q(z)|=\max\limits_{|z|=1}|z^n\cdot p(1/z)|=\max\limits_{|z|=1}|p(1/z)|=\max\limits_{|z|=1}|p(z)|$$ The last step is due to $\{1/z\mid z\in\mathbb{C}:|z|=1\}=\{z\mid z\in\mathbb{C}:|z|=1\}$ . Now, $q(0)=1$ , so $|q(0)|=1$ and, by the maximum principle, $\max\limits_{|z|=1}|q(z)|\geq1$ . Finally, $\max\limits_{|z|=1}|p(z)|\geq1$ . Now, if $p(z)=z^n$ then clearly $\max\limits_{|z|=1}|p(z)|=1$ . Suppose that $\max\limits_{|z|=1}|p(z)|=1$ , then also $\max\limits_{|z|=1}|q(z)|=1$ . Again, by the maximum principle, we have that $q\equiv 1$ . Therefore, $\forall z\neq 0:p(1/z)=1/z^n$ , so $\forall z\neq 0:p(z)=z^n$ . Finally from continuity $p(0)=0$ and we get that $\forall z\in\mathbb{C}:p(z)=z^n$ . | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2777129', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/329831/']} | jdg_381027 |
stackexchange | llm_judgeable_groundtruth_similarity | 64154002 |
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 my old code with VUE 2 in Tabs component: created() { this.tabs = this.$children;} Tabs: <Tabs> <Tab title="tab title"> .... </Tab> <Tab title="tab title"> .... </Tab> </Tabs> VUE 3:How can I get some information about childrens in Tabs component, using composition API? Get length, iterate over them, and create tabs header, ...etc? Any ideas? (using composition API)
Now provide the response and nothing else.
| This is my Vue 3 component now. I used provide to get information in child Tab component. <template> <div class="tabs"> <div class="tabs-header"> <div v-for="(tab, index) in tabs" :key="index" @click="selectTab(index)" :class="{'tab-selected': index === selectedIndex}" class="tab" > {{ tab.props.title }} </div> </div> <slot></slot> </div></template><script lang="ts">import {defineComponent, reactive, provide, onMounted, onBeforeMount, toRefs, VNode} from "vue";interface TabProps { title: string;}export default defineComponent({ name: "Tabs", setup(_, {slots}) { const state = reactive({ selectedIndex: 0, tabs: [] as VNode<TabProps>[], count: 0 }); provide("TabsProvider", state); const selectTab = (i: number) => { state.selectedIndex = i; }; onBeforeMount(() => { if (slots.default) { state.tabs = slots.default().filter((child) => child.type.name === "Tab"); } }); onMounted(() => { selectTab(0); }); return {...toRefs(state), selectTab}; }});</script> Tab component: export default defineComponent({ name: "Tab", setup() { const index = ref(0); const isActive = ref(false); const tabs = inject("TabsProvider"); watch( () => tabs.selectedIndex, () => { isActive.value = index.value === tabs.selectedIndex; } ); onBeforeMount(() => { index.value = tabs.count; tabs.count++; isActive.value = index.value === tabs.selectedIndex; }); return {index, isActive}; }});<div class="tab" v-show="isActive"> <slot></slot></div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64154002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4605338/']} | jdg_381028 |
stackexchange | llm_judgeable_groundtruth_similarity | 6081800 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="Black"> <!-- Rounded yellow border --> <Border BorderThickness="3" BorderBrush="Yellow" CornerRadius="10" Padding="2" HorizontalAlignment="Center" VerticalAlignment="Center"> <Grid> <!-- Rounded mask (stretches to fill Grid) --> <Border Name="mask" Background="White" CornerRadius="7"/> <!-- Main content container --> <StackPanel> <!-- Use a VisualBrush of 'mask' as the opacity mask --> <StackPanel.OpacityMask> <VisualBrush Visual="{Binding ElementName=mask}"/> </StackPanel.OpacityMask> <!-- Any content --> <Image Source="http://chriscavanagh.files.wordpress.com/2006/12/chriss-blog-banner.jpg"/> <Rectangle Height="50" Fill="Red"/> <Rectangle Height="50" Fill="White"/> <Rectangle Height="50" Fill="Blue"/> </StackPanel> </Grid> </Border></Page> This XAML is from WPF – Easy rounded corners for anything but it doesn't work form me =( <Border Canvas.Left="55" Canvas.Top="30" Width="100" Height="Auto" Margin="12,12,8,0" VerticalAlignment="Top" BorderBrush="#FF3B5998" BorderThickness=".5" CornerRadius="18"> <Border.Effect> <DropShadowEffect BlurRadius="5" Opacity=".5" ShadowDepth="3" /> </Border.Effect> <Border Name="ReceiverColor" BorderBrush="#FF96B2E4" BorderThickness="6" CornerRadius="15"> <Border Name="Mask" BorderBrush="#FF3B5998" BorderThickness=".5" CornerRadius="13"> <StackPanel> <StackPanel.OpacityMask> <VisualBrush Visual="{Binding ElementName=Mask}" /> </StackPanel.OpacityMask> <Image Name="Receiver" /> </StackPanel> </Border> </Border></Border> --- EDIT --- I make borders sizes to auto and change source of image to an image from a link when window loaded border size becomes as image size but image not shown !!!
Now provide the response and nothing else.
| You forgot the Grid that makes the mask and the image siblings and nested the image in the mask. and you forgot to set the background of the mask. This works: <Grid> <Border Canvas.Left="55" Canvas.Top="30" Width="100" Height="Auto" Margin="12,12,8,0" VerticalAlignment="Top" BorderBrush="#FF3B5998" BorderThickness=".5" CornerRadius="18"> <Border.Effect> <DropShadowEffect BlurRadius="5" Opacity=".5" ShadowDepth="3" /> </Border.Effect> <Border Name="ReceiverColor" BorderBrush="#FF96B2E4" BorderThickness="6" CornerRadius="15"> <Grid> <Border Name="Mask" Background="White" BorderBrush="#FF3B5998" BorderThickness=".5" CornerRadius="13"> </Border> <StackPanel> <Image Name="Receiver" Source="/Images/test.jpg" /> <StackPanel.OpacityMask> <VisualBrush Visual="{Binding ElementName=Mask}" /> </StackPanel.OpacityMask> </StackPanel> </Grid> </Border> </Border></Grid> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6081800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713777/']} | jdg_381029 |
stackexchange | llm_judgeable_groundtruth_similarity | 2006899 |
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 this question, we see a proof that the largest eigenvalue of a stochastic matrix is equal to 1: Proof that the largest eigenvalue of a stochastic matrix is 1 However, I think I've found a proof that every eigenvalue of a stochastic matrix is equal to 1. Can you tell me where my proof is wrong? Proof: Suppose ${\bf r}$ is an eigenvector of the column stochastic matrix $M$ (i.e. $M{\bf r} = \lambda {\bf r}$ for some $\lambda$), and assume without loss of generality that the entries of ${\bf r}$ sum to $1$. Then $$M{\bf r} =\begin{bmatrix}M_{11}\\M_{21}\\\vdots\\M_{n1}\end{bmatrix} r_1 +\begin{bmatrix}M_{12}\\M_{22}\\\vdots\\M_{n2}\end{bmatrix} r_2+ \dots +\begin{bmatrix}M_{1n}\\M_{2n}\\\vdots\\M_{nn}\end{bmatrix} r_n$$ Since $M$ is column stochastic, each column must sum to $1$, so the sum of the entries in $M {\bf r}$ is just $1 \cdot r_1 + 1 \cdot r_2 + \dots + 1 \cdot r_n = 1$. Therefore, $\lambda$ must be $1$, and $M$ can only have one eigenvalue. Thanks!
Now provide the response and nothing else.
| I think that you are assuming that the entries of $r$ are non-negative; in general, you cannot assume that the entries of $r$ add to 1, because they might add to zero. Take$$M=\begin{bmatrix}1/2&1/2\\1/2&1/2\end{bmatrix}.$$Eigenvalues are $1$ and $0$. The eigenvector for $0$ is $\begin{bmatrix}1\\-1\end{bmatrix}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2006899', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/88672/']} | jdg_381030 |
stackexchange | llm_judgeable_groundtruth_similarity | 311778 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Does the parity of the dimension of $\mathbb{R}^n$ affect its structure/properties? As in, does it make a difference if $n$ is even or odd?
Now provide the response and nothing else.
| Let me try to focus the question as follows: Suppose you wake up in a dark and empty space. Which properties can help you decide whether the space is even or odd-dimensional? In the context of wave propagation, there is the fundamental difference that Huygens principle is only valid in odd-dimensional space, see Wave Propagation in Even and Odd Dimensional Spaces . Sharply defined wavefronts need an odd number of spatial dimensions, in even-dimensional space the wavefront decays with a long tail. (The study of this difference goes back to Volterra and Hadamard.) So to test for even/odd dimensionality you only need to shout in empty space. If you hear an echo you live in an even number of spatial dimensions. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/311778', 'https://mathoverflow.net', 'https://mathoverflow.net/users/129597/']} | jdg_381031 |
stackexchange | llm_judgeable_groundtruth_similarity | 1451626 |
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 student interested in developing a search engine that indexes pages from my country. I have been researching algorithms to use for sometime now and I have identified HITS and PageRank as the best out there. I have decided to go with PageRank since it is more stable than the HITS algorithm (or so I have read). I have found countless articles and academic papers related to PageRank, but my problem is that I don't understand most of the mathematical symbols that form the algorithm in these papers. Specifically, I don't understand how the Google Matrix (the irreducible,stochastic matrix) is calculated. My understanding is based on these two articles: http://online.redwoods.cc.ca.us/instruct/darnold/LAPROJ/fall2005/levicob/LinAlgPaperFinal2-Screen.pdf http://ilpubs.stanford.edu:8090/386/1/1999-31.pdf Could someone provide a basic explanation (examples would be nice) with less mathematical symbols? Thanks in advance.
Now provide the response and nothing else.
| The formal defintion of PageRank, as defined at page 4 of the cited document, is expressed in the mathematical equation with the funny "E" symbol (it is in fact the capital Sigma Greek letter. Sigma is the letter "S" which here stands for Summation ). In a nutshell this formula says that to calculate the PageRank of page X... For all the backlinks to this page (=all the pages that link to X) you need to calculate a value that is The PageRank of the page that links to X [R'(v)] divided by the number of links found on this page. [Nv] to which you add some "source of rank", [E(u)] normalized by c (we'll get to the purpose of that later.) And you need to make the sum of all these values [The Sigma thing] and finally, multiply it by a constant [c] (this constant is just to keep the range of PageRank manageable) The key idea being this formula is that all web pages that link to a given page X are adding to value to its "worth". By linking to some page they are "voting" in favor of this page. However this "vote" has more or less weight, depending on two factors: The popularity of the page that links to X [R'(v)] The fact that the page that links to X also links to many other pages or not. [Nv] These two factors reflect very intuitive ideas: It's generally better to get a letter of recommendation from a recognized expert in the field than from a unknown person. Regardless of who gives the recommendation, by also giving recommendation to other people, they are diminishing the value of their recommendation to you. As you notice, this formula makes use of somewhat of a circular reference , because to know the page range of X, you need to know the PageRank of all pages linking to X. Then how do you figure these PageRank values?... That's where the next issue of convergence explained in the section of the document kick in. Essentially, by starting with some "random" (or preferably "decent guess" values of PageRank, for all pages, and by calculating the PageRank with the formula above, the new calculated values get "better", as you iterate this process a few times. The values converge , i.e. they each get closer and closer to what is the actual/theorical value. Therefore by iterating a sufficient amount of times, we reach a moment when additional iterations would not add any practical precision to the values provided by the last iteration. Now... That is nice and dandy, in theory. The trick is to convert this algorithm to something equivalent but which can be done more quickly. There are several papers that describe how this, and similar tasks, can be done. I don't have such references off-hand, but will add these later. Beware they do will involve a healthy dose of linear algebra. EDIT: as promised, here are a few links regarding algorithms to calculate page rank. Efficient Computation of PageRank Haveliwala 1999 /// Exploiting the Block Structure of the Web for Computing PR Kamvar etal 2003 /// A fast two-stage algorithm for computing PageRank Lee et al. 2002 Although many of the authors of the links provided above are from Stanford, it doesn't take long to realize that the quest for efficient PageRank-like calculation is a hot field of research. I realize this material goes beyond the scope of the OP, but it is important to hint at the fact that the basic algorithm isn't practical for big webs. To finish with a very accessible text (yet with many links to in-depth info), I'd like to mention Wikipedia's excellent article If you're serious about this kind of things, you may consider an introductory/refresher class in maths, particularly linear algebra, as well a computer science class that deal with graphs in general. BTW, great suggestion from Michael Dorfman, in this post, for OCW's video of 1806's lectures. I hope this helps a bit... | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1451626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140477/']} | jdg_381032 |
stackexchange | llm_judgeable_groundtruth_similarity | 7883835 |
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 spent some time to try to make a collection that: 1) is sorted by value (not by key) 2) is sorted each time an element is added or modified 3) is fixed size and discard automatically smallest/biggest element depending of the sort way 4) is safe thread So 3) and 4) I think it is quite ok. For 1) and 2) it was a bit more tricky. I spent quite a long time on this thread , experimenting the different sample, but one big issue is that the collection are sorted only once when object are inserted. Anyway, I try to implement my own collection, which is working (shouldn't be used for huge data as it is sorted quite often) but I'm not so happy with the design. Especially in the fact that my value objects are constrained to be Observable (which is good) but not comparable so I had to use a dirty instanceof + exception for this. Any sugestion to improve this ? Here is the code: import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Observable; import java.util.Observer; public class SortedDiscardingSyncArray<K, V extends Observable> implements Observer { // Comparison way (ascendent or descendant) public static enum ComparisonWay { DESC, ASC; } // this is backed by a List (and ArrayList impl) private List<ArrayElement> array; // Capacity, configurable, over this limit, an item will be discarded private int MAX_CAPACITY = 200; // default is descending comparison private ComparisonWay compareWay = ComparisonWay.DESC; public SortedDiscardingSyncArray(ComparisonWay compareWay, int mAX_CAPACITY) { super(); this.compareWay = compareWay; MAX_CAPACITY = mAX_CAPACITY; array = new ArrayList <ArrayElement>(MAX_CAPACITY); } public SortedDiscardingSyncArray(int mAX_CAPACITY) { super(); MAX_CAPACITY = mAX_CAPACITY; array = new ArrayList<ArrayElement>(MAX_CAPACITY); } public SortedDiscardingSyncArray() { super(); array = new ArrayList <ArrayElement>(MAX_CAPACITY); } public boolean put(K key, V value) { try { return put (new ArrayElement(key, value, this)); } catch (Exception e) { e.printStackTrace(); return false; } finally { sortArray(); } } private synchronized boolean put(ArrayElement ae) { if (array.size() < MAX_CAPACITY) { return array.add(ae); } // check if last one is greater/smaller than current value to insert else if (ae.compareTo(array.get(MAX_CAPACITY-1)) < 0) { array.remove(MAX_CAPACITY - 1); return array.add(ae); } // else we don't insert return false; } public V getValue (int index) { return array.get(index).getValue(); } public V getValue (K key) { for (ArrayElement ae : array) { if (ae.getKey().equals(key)) return ae.getValue(); } return null; } public K getKey (int index) { return array.get(index).getKey(); } private void sortArray() { Collections.sort(array); } public synchronized void setValue(K key, V newValue) { for (ArrayElement ae : array) { if (ae.getKey().equals(key)) { ae.setValue(newValue); return; } } } public int size() { return array.size(); } @Override public void update(java.util.Observable arg0, Object arg1) { sortArray(); } public static void main(String[] args) { // some test on the class SortedDiscardingSyncArray<String, ObservableSample> myData = new SortedDiscardingSyncArray<String, ObservableSample>(ComparisonWay.DESC, 20); String Ka = "Ka"; String Kb = "Kb"; String Kc = "Kc"; String Kd = "Kd"; myData.put(Ka, new ObservableSample(0)); myData.put(Kb, new ObservableSample(3)); myData.put(Kc, new ObservableSample(1)); myData.put(Kd, new ObservableSample(2)); for (int i=0; i < myData.size(); i++) { System.out.println(myData.getKey(i).toString() + " - " + myData.getValue(i).toString()); } System.out.println("Modifying data..."); myData.getValue(Kb).setValue(12); myData.getValue(Ka).setValue(34); myData.getValue(Kd).setValue(9); myData.getValue(Kc).setValue(19); for (int i=0; i < myData.size(); i++) { System.out.println(myData.getKey(i).toString() + " - " + myData.getValue(i).toString()); } } private class ArrayElement implements Comparable <ArrayElement> { public ArrayElement(K key, V value, Observer obs) throws Exception { super(); // don't know how to handle that case // maybe multiple inheritance would have helped here ? if (! (value instanceof Comparable)) throw new Exception("Object must be 'Comparable'"); this.key = key; this.value = value; value.addObserver(obs); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(key); sb.append(" - "); sb.append(value); return sb.toString(); } private K key; private V value; public K getKey() { return key; } public V getValue() { return value; } public synchronized void setValue(V value) { this.value = value; } @SuppressWarnings("unchecked") @Override public int compareTo(ArrayElement o) { int c; if (compareWay == ComparisonWay.DESC) c = ((Comparable<V>) o.getValue()).compareTo(this.getValue()); else c = ((Comparable<V>) this.getValue()).compareTo(o.getValue()); if (c != 0) { return c; } Integer hashCode1 = o.getValue().hashCode(); Integer hashCode2 = this.getValue().hashCode(); // we don't check the compare way for hash code (useless ?) return hashCode1.compareTo(hashCode2); } } } And the other class for testing purpose: import java.util.Observable; public class ObservableSample extends Observable implements Comparable <ObservableSample> { private Integer value = 0; public ObservableSample(int value) { this.value = value; setChanged(); notifyObservers(); } public String toString() { return String.valueOf(this.value); } public void setValue(Integer value) { this.value = value; setChanged(); notifyObservers(); } public Integer getValue() { return value; } @Override public int compareTo(ObservableSample o) { int c; c = (this.getValue()).compareTo(o.getValue()); if (c != 0) { return c; } Integer hashCode1 = o.getValue().hashCode(); Integer hashCode2 = this.getValue().hashCode(); // we don't check the compare way for hash code (useless ?) return hashCode1.compareTo(hashCode2); } }
Now provide the response and nothing else.
| zip, map and sum: first.view.zip(second).map(t => t._1 - t._2).map(x => x*x).sum zip combine elements of the two list into a tuple view is used to have the list computed lazily to not build a structure between the two map calls (edit to replace reduceLeft by sum ) After seeing the comments, I feel I had to come back and explain about views. Basically a view turns a Traversable into an iterator like structure so that multiple intermediate structures don't have to be created when apply methods like map , zip and a few others. The type members of GenIteratableViewLike gives a sense of what operations have special processing. So typically if you have a bunch of map, filter, drop, takeWhile applied in sequence, you can use view to gain some performance. The rule of thumb is to apply view early to minimize how many intermediate List are created and if necessary use force at the end to go back to List (or whatever collection you're using). Thus Daniel's suggestion. The thing about performance is that in practice if that's important you sort of have to do a reality check. Here are some numbers (lower is better): no view List(62, 62, 62, 62, 63) sum: 311view before zip List(32, 31, 15, 16, 31) sum: 125view after zip List(31, 46, 46, 31, 31) sum: 185iterator List(16, 16, 16, 16, 15) sum: 79zipped List(62, 47, 62, 46, 47) sum: 264 Code is here: import testing.Benchmarkdef lots[T](n: Int, f: => T): T = if (n > 0) { f; lots(n - 1, f) } else fdef bench(n: Int, id: String)(block: => Unit) { val times = (new testing.Benchmark { def run() = lots(10000, block) }).runBenchmark(n) println(id + " " + times + " sum: " + times.sum)}val first = List(1, 2, 3)val second = List(4, 5, 6)bench(5, "no view") { first.zip(second).map(t => t._1 - t._2).map(x => x*x).sum }bench(5, "view before zip") { first.view.zip(second).map(t => t._1 - t._2).map(x => x*x).sum }bench(5, "view after zip") { first.zip(second).view.map(t => t._1 - t._2).map(x => x*x).sum }bench(5, "iterator") { first.iterator.zip(second.iterator).map(t => t._1 - t._2).map(x => x*x).sum }bench(5, "zipped") { (first, second).zipped.map((a,b) => a - b).map(x => x*x).sum } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7883835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1010529/']} | jdg_381033 |
stackexchange | llm_judgeable_groundtruth_similarity | 4007439 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
First off, I intend no hostility nor neglegence, just want to know people's thoughts. I am looking into bi-directional communication between client and server; client being a web application. At this point I have a few options: MS-proprietary duplex binding, from what I hear unreliable and unnatural: comet, and web sockets (for supported browsers). I know this question has been asked in other ways here, but I have a more specific question to the approach. Considering web sockets are client-side, the client code sits in JavaScript. Is it really the intention to build a large chunk of an application directly in JavaScript? Why didn't W3C do this in web services? Wouldn't it be easier if we were to be able to use SOAP to provide a contract and define events along with the existing messaging involved? Just feels like the short end of the stick so far. Why not make it simple and take advantage of JS dynamic nature and leave the bulk of code where it belongs....on the server? Instead of mysocket.send("AFunction|withparameters|segmented"); we could say myServerObject.AFunction("that", "makessense"); and instead of ...mysocket.onmessage = function() { alert("yay! an ambiguous message"); }... we could say ...myServerObject.MeaningfulEvent = function(realData) { alert("Since I have realistic data...."); alert("Hello " + realData.FullName); }... HTML 5 took forever to take hold....did we waste a large amount of effort in the wrong direction? Thoughts?
Now provide the response and nothing else.
| Sounds to me like you've not yet fully grasped the concepts around Websockets. For example you say: Considering web sockets are client-side This is not the case, sockets have 2 sides, you could think of these as a Server and a Client, however once the connection is established the distinction blurs - you could then also think of the client and the server as "peers" - each can write or read in to the pipe that connects them (the socket connection) at any time. I suspect you'd benefit from learning a little more about HTTP works on top of TCP - WebSockets is similar / analogous to HTTP in this way. Regarding SOAP / WSDL, from the point of view of a conversation surrounding TCP / WebSocket / HTTP you can think of all SOAP / WSDL conversations as being identical to HTTP (i.e. normal web page traffic). Finally, remember the stacked nature of network programming, for instance SOAP/WSDL looks like this: SOAP/WSDL--------- (sits atop)HTTP--------- (sits atop)TCP And WebSockets look like this WebSocket--------- (sits atop)TCP HTH. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4007439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/194261/']} | jdg_381034 |
stackexchange | llm_judgeable_groundtruth_similarity | 45822242 |
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 Spark to read in records (in this case in csv files) and process them. The files are already in some order, but this order isn't reflected by any column (think of it as a time series, but without any timestamp column -- each row is just in a relative order within the file). I'd like to use this ordering information in my Spark processing, to do things like comparing a row with the previous row. I can't explicitly order the records, since there is no ordering column. Does Spark maintain the order of records it reads in from a file? Or, is there any way to access the file-order of records from Spark?
Now provide the response and nothing else.
| Yes, when reading from file, Spark maintains the order of records. But when shuffling occurs, the order is not preserved. So in order to preserve the order, either you need to program so that no shuffling occurs in data or you create a seq. numbers to the records and use those seq. numbers while processing. In a distribute framework like Spark where data is divided in cluster for fast processing, shuffling of data is sure to occur. So the best solution is create a sequential numbers to each rows and use that sequential number for ordering. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45822242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6899938/']} | jdg_381035 |
stackexchange | llm_judgeable_groundtruth_similarity | 16842 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Uber's main problem is that city governments are deeply connected with existing taxi structures - sometimes it's a matter of straight corruption, sometimes it's a matter of lobbying and existing relationships. But why can't Uber invest their money into convincing city governments into changing their regulations? Surely they have more cash to do so than individual taxi unions?
Now provide the response and nothing else.
| This is actually exactly what Uber does. The common Uber practice is for Uber to enter a city under circumstances that range from legal, to questionable, to clearly illegal. They will then rush in with lots of marketing and lobbying to sway both the general population and the local government and earn a foothold in the city. Once they have secured this they will push for local legislation if it is required. In generally they are very successful in practice as they operate in over 570 cities and are a multi-billion dollar company. For example in 2011 Uber received a cease and desist letter from its home town of San Francisco. However Uber remains legal to this day. This was in due to in large part its foothold in the populace, the work of its lobbyists and direct negotiations with the government. Obviously though that doesn't always work. The most famous case of failure here would be Prop 1 in Austin, Texas . Both Uber and Lyft spent over $5 million trying to legalize their practice there. Ultimately though they were rejected by voters and left the city. | {} | {'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/16842', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/7434/']} | jdg_381036 |
stackexchange | llm_judgeable_groundtruth_similarity | 6243778 |
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 can I split a string by a delimiter, but not if it is escaped? For example, I have a string: 1|2\|2|3\\|4\\\|4 The delimiter is | and an escaped delimiter is \| . Furthermore I want to ignore escaped backslashes, so in \\| the | would still be a delimiter. So with the above string the result should be: [0] => 1[1] => 2\|2[2] => 3\\[3] => 4\\\|4
Now provide the response and nothing else.
| Use dark magic: $array = preg_split('~\\\\.(*SKIP)(*FAIL)|\|~s', $string); \\\\. matches a backslash followed by a character, (*SKIP)(*FAIL) skips it and \| matches your delimiter. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6243778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/784815/']} | jdg_381037 |
stackexchange | llm_judgeable_groundtruth_similarity | 40349207 |
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 may sounds like I'm begging to start a flame war, but hear me out. In some languages laziness is expensive. For example, in Ruby, where I have the most recent experience, laziness is slow because it's achieved using fibers, so it's only attractive when: you must trade off cpu for memory (think paging through large data set) the performance penalty is worth it to hide details (yielding to fibers is a great way to abstract away complexity instead of passing down blocks to run in mysterious places) Otherwise you'll definitely want to use the normal, eager methods. My initial investigation suggests that the overhead for laziness in Elixir is much lower ( this thread on reddit backs me up), so there seems little reason to ever use Enum instead of Stream for those things which Stream can do. Is there something I'm missing, since I assume Enum exists for a reason and implements some of the same functions as Stream. What cases, if any, would I want to use Enum instead of Stream when I could use Stream?
Now provide the response and nothing else.
| For short lists, Stream will be slower than simply using Enum, but there's no clear rule there without benchmarking exactly what you are doing. There are also some functions that exist in Enum, but don't have corresponding functions in Stream. (for example, Enum.reverse ) The real reason you need both is that Stream is just a composition of functions. Every pipeline that needs results, rather than side effects needs to end in an Enum to get the pipeline to run. They go hand in hand, Stream couldn't stand alone. What Stream is largely doing is giving you a very handy abstraction for creating very complex reduce functions. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40349207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170876/']} | jdg_381038 |
stackexchange | llm_judgeable_groundtruth_similarity | 15470738 |
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 require a certain piece of encryption logic done in Java to be converted to C# What would be the C# equivalent for the MessageDigest update , Digest and reset functions ?
Now provide the response and nothing else.
| In C#, the class is HashAlgorithm . The equivalent to update is either TransformBlock(...) or TransformFinalBlock(...) , after the final block version is called (you can also use an empty input) you can call the Hash property that will give you the digest value. HashAlgorithm is likely to be reusable after final block is called (which means it is reset for the next time you call TransformBlock ), you can double check if your HashAlgorithm supports reusing at all by checking the property CanReuseTransform . The equivalent to your reset()/digest() combo is a one line byte[] ComputeHash(byte[]) . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15470738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253368/']} | jdg_381039 |
stackexchange | llm_judgeable_groundtruth_similarity | 10340762 |
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 NSXMLParser to grab information from an online XML file. My goal is to have one class do the XML parsing and another class to implement the variables. Below is the code for my project: Current.h & Current.m #import <Foundation/Foundation.h>@interface Current : NSObject { NSString *curTempF; IBOutlet NSTextField *textField;}@property (nonatomic, copy) NSString *curTempF;- (void)displayOutlets:(id)sender;@end and #import "Current.h"@implementation Current@synthesize curTempF;- (void)awakeFromNib { [self displayOutlets:self];}- (void)displayOutlets:(id)sender { [textField setStringValue:curTempF];}@end XmlParser.h & XmlParser.m #import <Foundation/Foundation.h>@interface XmlParser : NSObject <NSXMLParserDelegate> { NSString *urlString; NSURL *url; NSMutableString *xmlString;}- (IBAction)fetchXML:(id)sender;@end and #import "XmlParser.h"#import "Current.h"@implementation XmlParser- (void)awakeFromNib { [self fetchXML:self];}- (IBAction)fetchXML:(id)sender { urlString = @"http://api.wunderground.com/api/***/conditions/q/28173.xml"; url = [NSURL URLWithString:urlString]; NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url]; [parser setDelegate:self]; [parser parse];}- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if ([elementName isEqual:@"temp_f"]) { xmlString = [[NSMutableString alloc] init]; }}- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqual:@"temp_f"]) { Current *cTempF = [[Current alloc] init]; [cTempF setCurTempF:xmlString]; }}- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { [xmlString appendString:string];}@end When I run the program I am receiving an error about "Invalid parameter not satisfying: aString". It looks like the setStringValue for the IBOutlet is not working. Any suggestions?
Now provide the response and nothing else.
| You're going to kick yourself: query1.SelectMany(q => q);ABC002 1003 3/04/2012 12:00:00 AM Z 1 ABC002 1004 4/04/2012 12:00:00 AM X 1 ABC003 1006 4/04/2012 12:00:00 AM X 1 ABC003 1006 4/04/2012 12:00:00 AM Y 1 The return from query1 is an enumerable (I removed your lists) of IGrouping and IGrouping is itself an enumerable, so we can just flatten it directly. See here: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2007/09/28/9836.aspx Edit: Remembered I also simplified your code: var query1 = (from r in myList group r by new { r.Code , r.No , r.Date } into results group results by new { results.Key.Code } into results2 where results2.Count() > 1 from result in results2.OrderBy(i=>i.Key.Date).Skip(1) select result ); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10340762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1084875/']} | jdg_381040 |
Subsets and Splits