INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Can anything be done to improve performance in VS 2010? I'm using VS 2010 since we're developing an app in .Net 4 and the performance is driving me crazy. It's mostly bad when I don't view the IDE for a while (such as when I get pulled away for a help desk call or come in in the morning). I realize it's probably built in WPF which unloads its resources when unused, but the few minute delay while it loads everything back up is really annoying. I've also noticed some significant delays when opening files or compiling.
I've experienced this problem with VS2008 also esp on virtual machines. I believe it might be related to other services which are making use of the system while in a non-interactive state. For example virus scans and remote backups. It might not just be the VS system but some other system that is hogging the machine.
stackexchange-superuser
{ "answer_score": 1, "question_score": 2, "tags": "performance, visual studio 2010" }
Cake php root directory file access Hello community I want to Create custom sitemap in root/public_html directory and i want to view as raalic.us/sitemap.xml So how can i access root directory any file or specific file in cake php?
* You have set the cakephp based web app to **root/public_html** * CakePHP has its own root directory and it is called **webroot** * .htaccess redirects all http requests to that directory * it contains publicly available files (css, js, img, ..) * you can put your sitemap.xml in it so the correct path to the xml file is: `root/public_html/webroot/sitemap.xml`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "cakephp, xml sitemap" }
How to round decimal value in rdlc reports I using a simple formula in rdlc report. I want to use the forward rounding for example i have value 25.17 and i want to convert into 26 not 25. But following formula giving me the result = 25. =ROUND(Sum(Fields!Total.Value, "DataSet1") + First(Fields!Shipping.Value, "DataSet1") - First(Fields!Discount.Value, "DataSet1"),0) Thanks in advance
In your `Expression`, use `Ceiling` function instead of `Round`. =Ceiling(Sum(Fields!Total.Value, "DataSet1") + First(Fields!Shipping.Value, "DataSet1") - First(Fields!Discount.Value, "DataSet1"))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "vb.net, rdlc" }
LINQ Querying Collection with different parameters I have a list that I need to query based on about 10 different parameters that user pass to my program. What s the best way to do it ? ex: List<Users> Query params can be : username and/or user id and/or age etc.
What you are trying to achieve is composing a dynamic query in LINQ. You could do this in two ways: * using dynamic LINQ; * using PredicateBuilder by Joseph Albahari (recommended in this case); Briefly, this is how to use PredicateBuilder in your case: var predicate = PredicateBuilder.True<User>(); if (!string.IsNullOrWhitespace(username)) predicate = predicate.And(a => a.Username == username); if (!string.IsNullOrWhitespace(whatever)) predicate = predicate.And(a => a.Whatever == whatever); /* etc. etc. */ var filteredUsers = myUsers.Where(predicate);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, .net, linq, dynamic" }
tllocalmgr reports "command install is not defined". What does it mean? When I run the command $ tllocalmgr install nicecolors Initializing ... Error: command install is not defined Why does tllocalmgr report that the command `install` is not defined? The syntax is clearly `tllocalmgr install <package>`.
Apparently `tllocalmgr` reports that error message when the package is not defined. Which happens when you make a typo in the package name, in this case it's probably `ninecolors`.
stackexchange-tex
{ "answer_score": 1, "question_score": 0, "tags": "errors, bash, command line" }
Did Rowan Atkinson's character purposely distract the check-in agent? In Love Actually, Rowan Atkinson saves Sam (and Daniel) whilst he helps Sam run and talk to Joanna to express his 'love' for her at Heathrow Airport. Rowan Atkinson's character turns up at the check-in desk and asks the check-in staff to hold several items after then declaring that he has left his boarding pass where he was having a cup of coffee (all whilst Neeson's character Daniel is saying to his son: Sam, that he can't see Joanna, because they won't allow it): _ROWAN'S character:_ > I'm sorry, I must have left it where I was having a cup of coffee Only, Rowan's exit in that scene is left with a very slight eyebrow raise to Daniel, Liam Neeson's character. Did Rowan's character do this on purpose? Stall the check-in worker on purpose? Is this supported by any further evidence that I have missed, or was it intentionally 'leave it for the audience'?
Angel, actually. According to the DVD commentary Atkinson's character initially was an angel named Rufus who was supposed to help all the characters in their romantic pursuits, courtesy of Mental Floss #15... > Rather than just an overenthusiastic gift wrapper with a good Samaritan streak at the airport, Atkinson's Rufus was initially written as a heavenly helper in disguise. A scene was even shot were he'd evaporate after helping Sam get past security at Heathrow. "But in the end," Curtis said in commentary, "the film turned out so sort of multiplicitous that the idea of introducing an extra layer of supernatural beings was (too much)." Odds are this scene was shot early in the process and Rufus was still an angel.
stackexchange-movies
{ "answer_score": 23, "question_score": 20, "tags": "plot explanation, analysis, dialogue, love actually" }
change viewport meta tag with jquery I was wondering if it is possible to add a meta tag using jquery to an html page before the page loads. The reason why I ask, is because I have a page with no viewport meta tag on and it should have it only when the resolution drops below 700px - `<meta name="viewport" content="width=device-width, initial-scale=1"/>` The reason being, I have html markup for mobile site (using media queries) & also html markup for desktop version ( I don't have one for tablets). I want to make sure html markup designed for desktop is rendered properly on tablet on page load and also when we change the device orientation. Thanks in advance!
Using jQuery you can do it like the following: if ($(window).width() < 700) { $('head').append('<meta name="viewport" content="width=device-width, initial-scale=1"/>'); } **EDIT** To have the viewport tag by default, then remove it above 699px: HTML: <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> </head> jQuery: if ($(window).width() > 699) { $('head').remove('<meta name="viewport" content="width=device-width, initial-scale=1"/>'); }
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "javascript, jquery, html, css, media queries" }
Can you use MLE to estimate a model with correlated errors? For a simple linear model such as $y_i = X_i\beta + \epsilon $ for i = 1,2... and we assume that $E[\epsilon_i | X] = 0$ and that $E[\epsilon_i^2|X] = \sigma_i^2 I_T$ for i=1,2...,n and that $E[\epsilon_i,\epsilon_j'] = \sigma_{ij} I_T$ for $i \neq j$ Can I use MLE to estimate this model? Will the correlation between errors cause problems with the standard errors of the MLE estimates of $\beta$?
The error (correlation) structure you assume simply needs to be incorporated in the likelihood function that you are trying to maximize. Remember that the logarithmic Gaussian likelihood function is generally written $$ \ell(\mathbf{\beta},\mathbf{\Sigma}) = -\frac{n}{2} \log ( 2 \pi) - \frac{1}{2} \log \left| \mathbf{\Sigma} \right| -\frac{1}{2}\left( \mathbf{y} - \mathbf{X} \mathbf{\beta} \right)^{\mathsf{T}} \mathbf{\Sigma}^{-1} \left( \mathbf{y} - \mathbf{X} \mathbf{\beta} \right) $$ where in the homoskedastic model we assume spherical errors, i.e. $\mathbf{\Sigma} = \sigma^{2} \mathbf{I}_{n}$, such that the variance-covariance matrix of the error has a constant $\sigma^{2}$ on the diagonal and zeros off-diagonally. But nothing prevents us from assuming (and estimating) a more complex variance-covariance matrix, including heteroskedasticity and/or serial correlation.
stackexchange-stats
{ "answer_score": 7, "question_score": 4, "tags": "maximum likelihood" }
What is the purpose of stopwords? I've just started learning about fulltext indexing and searching in MySQL and I've stumbled upon this list containing all of the "stop words" used in MySQL. I cannot understand what is tue purpose of these stop words, since this list contains a lot of actual words that I may want to search for, such as if I had a post on my blog titled "My first hello", if I searched for any of these words I wouldn't get the post since all of them are in the list. Can you please explain to me why these are what they are and what can I do in this situation because fulltext appears to be so useful but I find these stop words as such a bummer. I must be missing something.
The Stop Words are words which under most circumstances are noise to a full text search. Indexing them is pointless since they're expected to occur so frequently that they will not help narrow down a result. You do not have to use the default list, or any list at all if you don't want to. < has a couple of answers that will help you and links to the MySQL documentation. The only caveat is that you have to restart and reindex after changing the list.
stackexchange-softwareengineering
{ "answer_score": 9, "question_score": 3, "tags": "mysql" }
If I install a new ROM does that erase all my installed apps and dat? If I have a rooted (Razr M in this case) and want to install an updated ROM (e.g., to upgrade to a new 'Droid OS version) will I need to reinstall my apps and restore my data?
Unless you wipe all your data before the update, you do not need to Reinstall applications or Restore application data. But when flashing a completely different new ROM, it's recommended to do a full wipe before proceed. Further more, If you are planing to do a full wipe you can use a application like My Backup Pro or Titanium Backup to back up all your applications and data.
stackexchange-android
{ "answer_score": 2, "question_score": 1, "tags": "updates, root access" }
Proving $\overline{a}b|c|=|a|\overline{b}c$ for equation $az^2+bz+c=0$ If $a,b,c \in \mathbb{C},\ a\neq0$ such that the equation $az^2+bz+c=0$ has roots with equal modules, prove that $$\overline{a}b|c|=|a|\overline{b}c$$ * * * I tried to let $z_1,\ z_2$ the roots with $|z_1|=|z_2|=k$ and from Vieta $z_1+z_2=-\frac{b}{a}$ and $z_1z_2=\frac{c}{a}$. From the latter $k^2|a|=|c|$. So I was thinking, it is enough to prove: $\overline{a}bk^2=\overline{b}c$, but I don't how to use the first equation from Vieta and I am stuck.
Let $$ z_1=re^{i\theta_1}, z_2=re^{i\theta_2} $$ where $r>0$ and $\theta_1,\theta_2$ are real. By Vieta's Theorem, $$ re^{i\theta_1}+re^{i\theta_2}=-\frac{b}{a}, r^2e^{i(\theta_1+\theta_2)}=\frac{c}{a} $$ which gives $$ b=-ar(e^{i\theta_1}+e^{i\theta_2}), c=ar^2e^{i(\theta_1+\theta_2)} $$ So $$ \overline{a}b|c|=\overline{a}\bigg[-ar(e^{i\theta_1}+e^{i\theta_2})\bigg]|a|r^2=-|a|^3r^3(e^{i\theta_1}+e^{i\theta_2})$$ and $$ |a|\overline{b}c=|a|\bigg[-\bar{a}r(e^{-i\theta_1}+e^{-i\theta_2})\bigg]ar^2e^{i(\theta_1+\theta_2)}=-|a|^3r^3(e^{i\theta_1}+e^{i\theta_2}) $$ and hence $$ \overline{a}b|c|=|a|\overline{b}c. $$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "complex numbers" }
wcf and inserting information into the web.config Why does WCF not insert basic information about my service into the web.config? Is there a way to make it to that? I'm talking about when you add a wcf service to project explorer
You can always use SvcConfigEditor to configure your services or clients. This has a _nicer_ (but far from perfect) UI which can help you going quickly.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, asp.net, wcf, web services, web config" }
Type Mismatch in conditional I am new at VBA, but i have been programming a lot of C#. My issue here is that i keep getting "Runtime error 13. Type Mismatch" error in my VBA function. I am extracting data from a Table in access and then trying to filter some of the data. My function looks like this: Function FlowType(deliveryAdrID As String, deliverType As String, note As String) As String If (note = "*J") Then FlowType = "Weekend" ElseIf (deliveryAdrID = "62242" & deliverType = "H") Then FlowType = "AirGotland" ElseIf (deliveryAdrID <> "62242" & deliverType = "H") Then FlowType = "Air" Else FlowType = "Standard" End If End Function Why do I get this error? The error occurs on this line: ElseIf (deliveryAdrID = "62242" & deliverType = "H") Then
Your problem is because you use `&`, instead of `And`. The ampersand symbol is an operator to concatenate strings, whereas `And` is a Boolean operator. So, change your comparisons like so: ElseIf ((deliveryAdrID = "62242") And (deliverType = "H")) Then With `&`, (assuming both conditions are satisified) the expression you are using will evaluate to ElseIf ("TrueTrue") Then which doesn't make sense since "TrueTrue" is not Boolean.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, function, vba, ms access" }
Pasar por parámetro JSON Javascript Tengo el siguiente componente html al cual le paso un Json: <a href="javascript:abreModal('{ 'name':'John', 'age':'30', 'city':'New York'}');"> Pulsador </a> Y la función Javascript: function abreModal(text) { //var text = '{ "name":"John", "age":"function () {return 30;}", "city":"New York"}'; obj = JSON.parse(text); alert(obj.name); } El error que me lanza firebug es: > SyntaxError: missing ) after argument list Sospecho que el error esta en las comillas del `abreModal(...)` he probado a cambiar las comillas sin resultado. ¿Alguna sugerencia?
abreModal('{ 'name':'John', 'age':'30', 'city':'New York'}'); ^ ^ Tu cadena está entre las dos marcas que te puse, y lo siguiente que escribes es `name` en lugar de una coma (`,`) o el cierre del paréntesis. Lo que te recomiendo es que no mandes un Json sino el objeto: <a href="javascript:abreModal({ 'name':'John', 'age':'30', 'city':'New York'});"> Pulsador </a> Y así no es necesario parsear ni nada: function abreModal(obj) { alert(obj.name); } Recuerda que Json sirve para intercambiar datos entre servidor y cliente, no tiene mucho sentido que transformes un objeto en Json y después lo parsees en el mismo script. Ahora bien, si la situación es que recibes ese Json desde otro lado, entonces te recomiendo que lo parsees antes de mandarlo y mandes la variable que lo contenga.
stackexchange-es_stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "javascript, jquery, html, json" }
How to show all names for identical contract in T-SQL I have query like this, and i shows me sort of good results select vup.UgovorId, count(P.Naziv) as BROJNAZIVA from [TEST_Ugovori_Prod].dbo.VezaUgovorPartner as vup inner join [TEST_MaticniPodaci2].[dbo].[Partner] as p on vup.PartnerId = p.PartnerID group by vup.UgovorId Results are like this (first row is vup.UgovorId, second is p.Naziv): 1264 1 1265 3 But I want to show all p.Naziv when that row has more then one for that vup.UgovorId like string so I would be like this: 1264 "Mark" 1265 "Jerry, Philip, Tom"
I think this is the issue you are trying to solve? I am not sure what technology you are using, but this may at least provide you some guidance. So your code would look something like this: select vup.UgovorId, substring( ( Select ','+ P.Naziv AS [text()] From [TEST_MaticniPodaci2].[dbo].[Partner] as p Where vup.PartnerId = p.PartnerID ORDER BY P.Naziv For XML PATH ('') ), 2, 1000) [Names] from [TEST_Ugovori_Prod].dbo.VezaUgovorPartner as vup group by vup.UgovorId
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql server, tsql, group by" }
Align objective function in latex I am writing the following optimization model: \documentclass{article} \usepackage[cmex10]{amsmath} \DeclareMathOperator*{\Min}{min} \begin{document} \begin{align} &Q_t(v_{t-1},a_{ti\omega}) = \notag \\ &\min_{\substack{g_t,~y_t,f_t,~\theta_t,~\\\Delta u^{up},~\Delta u^{dn},\\\Delta g^{up},~\Delta g^{dn},\\g_t^c,~y_t^c,~f_t^c,~\theta_t^c}} c^\top_{t}g_{t,i}+\sum_{i \in \mathcal{I}^T}(c^{U}_i \Delta g^{up}_{t,i}+c^{D}_i \Delta g^{dn}_{t,i})+ \notag \\ &\hspace{19mm}\sum_{i \in \mathcal{I}^H}(c^{U}_i \Delta u^{up}_{t,i}+c^{D}_i \Delta u^{dn}_{t,i})+\mathcal{Q}_{t+1}(v_t) \end{align} \end{document} However, I wanted both parts of the objective function to be close. I do not want that vertical space between them. Is there a way around? ![the model](
If you really want `align`, you can add or remove space when breaking a line. In this case, at the second line break, replacing `\\` with `\\[-2em]` reduces the vertical spacing: \documentclass{article} \usepackage[cmex10]{amsmath} \DeclareMathOperator*{\Min}{min} \begin{document} \begin{align} &Q_t(v_{t-1},a_{ti\omega}) = \notag \\ &\min_{\substack{...} c^\top_{t}g_{t,i}+\sum_{i \in \mathcal{I}^T}(c^{U}_i \Delta g^{up}_{t,i}+c^{D}_i \Delta g^{dn}_{t,i})+ \notag \\[-2em] % here &\hspace{19mm}\sum_{i \in \mathcal{I}^H}(c^{U}_i \Delta u^{up}_{t,i}+c^{D}_i \Delta u^{dn}_{t,i})+\mathcal{Q}_{t+1}(v_t) \end{align} \end{document} ![enter image description here]( This works in environments other than `align`, too, in case you want to switch.
stackexchange-tex
{ "answer_score": 2, "question_score": 9, "tags": "spacing, align" }
Are all numbers that have a non-repeating, non-terminating continued fraction sequence transcendental? (By continued fraction sequence, I'm specifically talking about the one kind where the numerator of every fraction is 1.) As a kid in middle school, I learned that all irrational numbers have non-repeating, non-terminating positional notation (o.k.a. "decimal") expansions. However, as a kid in first-year university, I learned that some irrational algebraic numbers have repeating continued fraction expansions (and, of course, that all rationals have a finite continued fraction expansion). So my question now is, do _all_ algebraic numbers have a repeating continued fraction expansion? Are there some transcendentals that have a repeating expansion, or algebraic numbers that have a non-repeating expansion?
No, continued faction expansions repeat only for the so-called "quadratic irrationals", numbers $x$ satisfying $ax^2 + bx + c = 0$ for some integers $a, b$ and $c$. In particular, the continued fraction expansion for the algebraic number $\sqrt[3]2$ does not repeat. Continued Fractions periodicity and convolution on this site has a proof.
stackexchange-math
{ "answer_score": 7, "question_score": 5, "tags": "continued fractions" }
Does IsNull() guard against references to null objects? In my PowerBuilder application, the following code segment causes an R0002 error at runtime (a null object is being referenced): Window w = windows[idx] IF NOT IsNull( w ) THEN MessageBox( "", "ClassName is " + w.GetClassName() ) // This line crashes END IF Does anybody know why that is? I was under the impression that IsNull() is specifically meant to test for null values.
I think these are different kinds of NULL. One is a variable with the value of NULL The other is an object that doesn't exist or hasn't been instantiated. In the second case, you may want to use isValid().
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "powerbuilder" }
How can I open a web page from an Android app? I am trying to open a web page from my Android app. This is what I did: successCallback = { url-> runOnUiThread{ val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("$url")) startActivity(browserIntent)} } But it doesn't work. Any thoughts? This the error message
Please check your **URL** is correct or not i.e URL contain proper link or value, then parse it. successCallback = { url-> runOnUiThread{ if (url!= null && !url.isEmpty()){ val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("$url")) startActivity(browserIntent)}}
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, web, networking" }
Packing items into fixed number of bins I am looking for an algorithm that will solve my problem in the most efficient way. **Problem description:** I have a list of items (only positive integers are allowed) and fixed number of bins of identical capacity. So far, I thought about branch-and-bound algorithm, but I am not quite sure if it is the best approach in this case. **Example:** Given a list of items: (3, 4, 4, 2, 3, 9, 2) and three bins of capacity 9 each I need to pack them this: (order of items is irrelevant) [3, 4, 2], [4, 3, 2], [9] I think this is a variant of the bin-packing problem (which I know is NP-complete), but since I am not trying to minimize number of bins used I wonder if there is a better solution.
This is the multibin packing problem: > Given a set of items, each of a specific size, and a set of bins, each of a specific size as well – is there a distribution of items to bins such that no item is left unpacked and no bin capacity is exceeded? In general it is NP-hard. However, there are several special cases that may be solved efficiently, either approximately or even optimally. see Wolfgang Stille aus Göppingen's thesis
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 7, "tags": "algorithm, packing, bin packing, branch and bound" }
Thread Jobs in Java I want to spawn 200 threads simultaneously in Java. What I'm doing right now is running into a loop and creating 200 threads and starting them. After these 200 gets completed, I want to spawn another 200 set of threads and so on. The gist here is that the first 200 threads I spawned need to be FINISHED before spawning the next set. I tried the code below, but its not working for(int i=0;i<200;i++){ Thread myThread = new Thread(runnableInstance); myThread.start(); } for(int i=0;i<200;i++){ Thread myThread = new Thread(runnableInstance); myThread.start(); } Note: I have intentionally put the for loop Twice, but the desired effect I intend is not happening simply because the second for loop is executed before the first set of threads end their execution. Please advise
You should keep a list of the threads you have created. Then once you have started all of them, you can loop over the list and perform a `join` on each one. When the join loop finishes, all of your threads will have run to completion. List<Thread> threads = new List<Thread>(); for(int i=0;i<200;i++){ Thread myThread = new Thread(runnableInstance); myThread.start(); threads.add(myThread); } //All threads are running for(Thread t : threads) { t.join(); } //All threads are done
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 4, "tags": "java, multithreading" }
What is an average header height for mobile websites? What is recommended/average header height for mobile websites. Browsers such as Chrome and Safari have an address bar at the top which takes space so in terms of UX how big the header (eg bootstrap navigation header) should be? !enter image description here
The correct answer is: **it depends on your app**. But here are some important considerations for mobile websites to help you make the decision: * **OS guidelines**. Mobile OS's publish guidelines around header heights. IOS has guidelines for menu and nav bar layouts (for example, see this). Google also publishes guidelines for Material Design sites (here). * **Ergonomics**. Whether or not you decide to follow guidelines, minimum bar height should be design so that it's touch friendly. This article has some excellent guidelines on touch-friendly heights based on specifications from Apple, Microsoft, Nokia and others. Although it's a bit dated, it notes: * Apple's iPhone Human Interface Guidelines recommend 44px minimum dimension. Microsoft recommends 34px, and Nokia has a minimum of 28px. Hope that helps.
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "header, bootstrap" }
Long click for right click emulation? (XFCE) I'm looking for a way to emulate a right click press when I hold down my left mouse click. I've seen some questions like this on askubuntu, and a raspberry pi forum, but I can't adapt them to work in XFCE. I'm using an X230t, so preferably it would be better to have this only apply to the touchscreen, but it's also fine if this is a global setting. Raspbery pi forum: < I tried to adapt the xorg config file from the link above, but I couldn't figure it out. Any help is appreciated.
There is a brilliant program for this: < Not sure how I missed it, but it works great and on other DEs as well.
stackexchange-unix
{ "answer_score": 1, "question_score": 0, "tags": "xorg, xfce, manjaro, touch screen" }
Composite functions, Inverse functions, and bijections Let $f: A \rightarrow B$. Suppose $g, h:B \rightarrow A$ so that $f \circ g = I_B$ and $h \circ f = I_A$. Show that $f$ is a bijections and $g=h=f^{-1}$. $I_A $ and $ I_B$ denote the identity functions for sets $A$ and $B$. I've been working on this one for a while now, and don't really understand how to show it
$$h=h\circ I_B=h\circ(f\circ g)=(h\circ f)\circ g=I_A\circ g=g$$ surjectivity: > $b=f(g(b))$ for each $b\in B$ injectivity: > If $f(a_1)=f(a_2)$ then $a_1=h(f(a_1))=h(f(a_2))=a_2$
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "functions, elementary set theory" }
ObjectOutputStream(FileOutputStream) pointer modification I can't understand if doing what is said in the title with the streams, if I use the object stream to write an object to a file, does it shift the filestream's pointer and when I use it, after, to write something, it writes it after the aforementioned object? And the same for input streams Thanks a lot
yes, when wrapping streams (called the decorator pattern, by the way) writing to the outer-most stream (actually a shell) will propagate the write down the chain. an important thing to note here is that various Stream objects along the chain might have their own buffers so the write wont immediately go down the pipe. good examples of this are buffered output streams and zip output streams. if you intend to write something to a wrapping stream and then write something directly to one of the streams deeper down the chain the recommended thing to do is call flush() on the outer-most stream to make sure any buffers in the chain will be flushed out - else you risk writing bits out of order.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, fileoutputstream, objectoutputstream" }
SQL Syntax Error Exception I am trying to execute the following statement: String sql = "INSERT INTO `ad`.`ad` (`imgURL`, `linkURL`, `client`, `idx`) VALUES (" + a.getImgURL() + " , " + a.getLinkURL() + " , " + a.getClient() + " , " + a.getIdx() + ");"; But I am getting an error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'fooUrl' in 'field list' But `fooUrl` is one of the values - it is the result of calling `a.getImgUrl()`. I'm new to working with databases and I'm sure that a simple syntactical error is causing this.
You will avoid these kind of problems and you will write safer code if you use a prepared statement. String sql = "INSERT INTO `ad`.`ad` (`imgURL`, `linkURL`, `client`, `idx`) VALUES (?, ?, ?, ?)"; final PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, a.getImgURL()) ; statement.setString(2, a.getLinkURL()) ; statement.setString(3, a.getClient()) ; statement.setString(4, a.getIdx()); final ResultSet results = statement.executeQuery();
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "java, mysql" }
Redirecting query string for any search query for all URLs I want to ask if it is possible to redirect example.com/something?query=hell to example.com/something/hell with the help of htaccess. I want to do it for all query i pass with `GET` method. Does anyone has any idea??
You can do this with the following rule in your htaccess RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)/?$ /something?query=$1 [L] With the rule above you can just type `example.com/foobar` into your browser to access the page at `example.com/something?query=foobar` .
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": ".htaccess" }
Locating specific file types in a column One column in report is titled 'Filename' and there are several possible options 'xxxx.pdf', 'xxxx.Empty'. How do I get Python to locate only files that are '.Empty' for example? I've been trying the following code which doesn't produce an error but also brings up no results when it should df3.loc[df3['Filename'] == '.Empty'] Thanks in advance
Suppose you have a dataframe like this df = pd.DataFrame([['a.Empty'], ['b.pdf']], columns=['file']) file 0 a.Empty 1 b.pdf To get all the files that are Empty use `str.contains` df[df['file'].str.contains('.Empty')] file 0 a.Empty If you want all files except empty then df[~df['file'].str.contains('.Empty')] file 1 b.pdf
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, locate" }
remove words from string by position php I want to remove the words from a string by a given position from input, also the following words with the position from input. EXAMPLE: position = 2 string = `aa bb cc dd ee ff gg hh` Will become: `aa cc ee gg` I have: $delete = $position - 1; $words = explode(" ", $string); if(isset($words[$delete])) unset($words[$delete]); $string = implode(" ", $words); echo $string;} That displays aa cc dd ee ff gg hh
$position = 2; $string = 'aa bb cc dd ee ff gg hh'; $arr=explode(' ', $string); $final_str=''; for($i=0;$i<count($arr);$i++) { if($i%$position==0) { $final_str.=$arr[$i].' '; } } echo $final_str;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, string" }
Counting Number Of Specific Record In Database I have a application which needs to aware of latest number of some records from a table from database, the solution should be applicable without changing the database code or add triggers or functions to it ,so I need a database vendor independent solution. My program written in java but database could be (SQLite,MySQL,PostgreSQL or MSSQL),for now I'm doing Like that: In a separate thread that is set as a daemon my application sends a simple command through JDBC to database to be aware of latest number of the records with condition: while(true){ SELECT COUNT(*) FROM Mytable WHERE exited='1' } and this sort of coding causes DATABASE To lock,slows down the whole system and generates huge DB Logs which finally brings down the whole thing! how can i do it in a right way to always have latest number of certain records or only counting when the number changed?
A `SELECT` statement should not -- by itself -- have the behavior that you are describing. For instance, nothing is logged with a `SELECT`. Now, it is possible that concurrent `insert`/`update`/`delete` statements are going on, and that these cause problems because the `SELECT` locks the table. Two general things you can do: 1. Be sure that the comparison is of the same type. So, if `exited` is a number, do not use single quotes (mixing of types can confuse some databases). 2. Create an index on `(exited)`. In basically all databases, this is a single command: `create index idx_mytable_exited on mytable(exited)`. If locking and concurrent transactions are an issue, then you will need to do more database specific things, to avoid that problem.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, database, jdbc" }
kendo ui on editable pop up window load event Is there a load window event on kendo ui grid editable popup window. I want to write some code when the window has loaded successfully .Editable(ed => ed.Mode(GridEditMode.PopUp).TemplateName("CustomEditors/CustomEditor").Window(w => w.Title("Account").Name("MyCustomWindow").Resizable().Width(800).Height(600))) In this case when the MycustomWindow is loaded and the CustomEditor view is rendered, then I want to write some code Is this possible ??
Use the Edit event of the Grid .Events(ev=>ev.Edit("onEdit") ... <script> function onEdit(e){ //your logic goes here } </script>
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "kendo ui" }
Count characters starting at zero? I need to write a for-each loop that lists each character in `mystery_string` with its index. Example below: `mystery_string= "Olivia,"` output would be: 0 O 1 l 2 i 3 v 4 i 5 a I cannot use the range function on this problem. This is my code, but the number starts at 1. What am I doing wrong? mystery_string = "CS1301" count = 0 for current_letter in mystery_string: count = count + 1 print (count , current_letter) I have been getting this as output: 1 C 2 S 3 1 4 3 5 0 6 1 but it needs to start at zero.
Just add the count (`count += 1`) after you print in the for loop Note: Also, please format your code in a code block surrounded with a tick(`) or multiline code with 3 tick (```)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "for loop, charactercount" }
StaticArray efficient max size in Julia? What is the maximum efficient size of `StaticArray`? I Mean if there exists size, when `StaticArray` is less efficient than ordinary `Array`? And one more similar question. I should use `StaticArray` **every** time my array is not supposed to change it's size? Or there is any performance caveats? Thx
As i found later, doc says: > A very rough rule of thumb is that you should consider using a normal Array for arrays larger than 100 elements. For example, the performance crossover point for a matrix multiply microbenchmark seems to be about 11x11 in julia 0.5 with default optimizations. As mentioned chris-rackauckas, there is some issues with this "rule" in later julia versions. See <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "arrays, package, julia" }
Does the seed function in numpy and random work need to be set in every module? I am calling np.random.seed(seed) random.seed(seed) in the `__main__` module `foo.py`. That module calls out to another module `bar.py` that also uses results from `np.random` and `random`. Does the latter also need to set the seed?
No. Using `np.random.seed(...)` sets a global random state. Usually this is not desirable. You may prefer to use a `np.random.RandomState()` instance in your code, so that you don't also seed the PRNGs for all other library code within your runtime.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, numpy, random, random seed" }
ImageView radius with background I have an `ImageView` that has a background. I need to set `border-radius` to my `ImageView`. I use the below code in another XML file and set it as `android:src` but it doesn't work when I set the background. <shape xmlns:android=" > <corners android:radius="10dp"/> </shape> How I can set background and radius at the same time ?
You can set the background together with the border-radius xml. <shape xmlns:android=" > <corners android:radius="10dp"/> <!-- background --> <solid android:color="@android:color/white" /> </shape>
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "android, imageview" }
.Net application standard icon set We are developing a completely standard WPF application with a menu and toolbar. Both the menu and toolbar contain standard Windows application items like save, load, undo, redo, delete, connect etc. We want to use the standard Windows icons, like the ones Visual Studio is using. Where can I find, buy or download the standard icon set from?
Most icons are available with Visual Studio: `C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\VS2010ImageLibrary`. (or wherever your Visual Studio is installed). You should find what you are looking for here. Regards, Eric.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": ".net, wpf, windows, icons" }
How to best represent a description field load from Database, never editable In a old mfc application i've some fields that are the decodification of others fields. For example, in the image below, i can edit the "title" dropdown with values Mr, Mrs ecc, and in the field next to it, i see the entire description "Mister"(this field is never editable): !Title code and decodification Now, i want give my app a look more modern (flat), so I would remove sunken style. I have the doubt how to change it: \- if i leave border in the control, the field description could be interpreted as an editable textbox disabled -if i remove border, it seems a label Any idea to make clear the concept that the field description is not editable, but is different from a label and from a textbox?
I wouldn't use input fields for description or helper text. It's not a matter of styling as much as semantics. Input fields are meant for data entry, they might conditionally be disabled in some cases, but if that input field is always going to be disabled, then maybe it's not supposed to be an input field. There are a few ways you can show helper text. Typically I would put it right underneath the relevant input field and use slightly smaller font size. The case you describe sounds a bit different than a typical help text though. I would consider using full words instead of the abbreviations in the dropdown. Or perhaps show both together. !mockup download bmml source - Wireframes created with Balsamiq Mockups
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "disable" }
Hidden variable declaration VBA **Question :** Is it possible that the declaration of some variables is "hidden" in VBA ? **Situation :** I have an Excel file with lots of modules but for some reasons whenever we open it this message shows up ![]( and I tried some "solutions" found on some forums with no success -> I decided to copy sheet by sheet and module by module the whole thing in a new "clean" excel file. **Issue :** A code doesn't run saying that variable XXX is not declared (ok...makes sense), but I checked in the corrupted file and even though it is not declared anywhere neither (I checked with the Finder in the whole project) the code in question can run...Confusing ! Any explanations for this ?
**Worst case, quick and dirty scenario** \- remove `Option Explicit` from each module, class, workbook and worksheet. It makes sure, that all variables are declared. E.g., try running the following code: Option Explicit Sub TestMe() k = 5 Debug.Print k End Sub You cannot. Then add `dim k as long` after `Sub TestMe()`. Or remove the `Option Explicit`. Now you can run it. **Slow and clean solution:** Check all variables, which are highlighted when you try to run the code and declare them. Your code would run faster.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "vba, excel, variables, variable declaration" }
What is the difference between procedure and #'procedure in Lisp/Clojure? What is the difference between the evaluation of double and #'double in Clojure/Lisp? 1:2 user=> double #<core$double__4077 clojure.core$double__4077@1acd47> 1:3 user=> #'double #'clojure.core/double
In Clojure, `#'foo` is a shorthand for `(var foo)`, which returns the _variable object_ `foo` refers to, as opposed to its value. Look it up in the reference: * Macro Characters * var. I am not sure if you also want to know the meaning in Lisp: In Common Lisp, `#'foo` is a shorthand for `(function foo)`, which is used to access the _function value_ bound to the name `foo` when not in operator position. * Sharpsign Single-Quote * function.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "lisp, clojure" }
Why are the data in the database not filtered? When entering dates in string format, filtering in the database using Contains should be performed, but it returns null. What could be the problem? I compared the output String values from the database with the string entered by the user, they are absolutely identical. var find = fg.Users .Where(r => r.CreationDate.ToString().Contains(searchclientregdate)) .ToList();
convert the string to a date and then use it in the comparison make a conditional filtering if needed DateTime.TryParse(searchclientregdate, out dateVar) var find = fg.Users .Where(r => r.CreationDate<= dateVar && r.CreationDate>= dateVar) .ToList();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, list, entity framework, linq" }
Zurb Foundation 4 ORBIT slider: turn Off circular / infinte As i understand Orbit used to have an option `singleCycle: true`, so that it doesnt continuously loop. How can we do this in Foundation 4 (ideally without hacking the core)?
This would be nice to have in the options, and it looks like it's being addressed. Until then you can add some JS to fix the problem without the need to hack the core. Here's the JS you'll want to add: $("ul[data-orbit]").on("orbit:after-slide-change", function(event, orbit) { if (orbit.slide_number==$(this).children().length-2) { self._stop_timer(); } }); And here's a working JSFiddle.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "zurb foundation" }
cannot convert from 'System.Threading.Tasks.Task<string>' to 'string' I am fetching data from API and trying to convert it into deserialized form. But gettting this error. public static async Task<List<Movie>> GetAllMovies(int pageNumber, int pageSize) { var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty)); var response = httpClient.GetStringAsync(AppSettings.ApiUrl + String.Format("api/movies/AllMovies?sort=asc&pageNumber={0}&pageSize={1}",pageNumber,pageSize)); return JsonConvert.DeserializeObject<List<Movie>>(response); }
Use await before response return JsonConvert.DeserializeObject<List<Movie>>(await response)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "asp.net mvc, model view controller, asp.net mvc viewmodel" }
Qt - Recursive repaint needed, how? I have the following code: paintGL() { if(mouse_was_clicked) { ... do the color picking with openGL to identify a clicked element ... !!! now I need to call again paintGL() to switch the selected element from the old one to the new one but I can't create a recursive cycle! } else { ... normal code to draw the scene and the selected element in red ... } } As the lines suggest, I need a way to call once more the paint event.. is there any way to accomplish this without creating a potential livelock? Something like deferring a new paint event?
If the control flow within your `paintGL()` is that simple, just make sure that the contens currently being in the `else` block are executed in every case: void MyWidget::paintGL() { if(mouse_was_clicked) { ... do the color picking with openGL to identify a clicked element } ... normal code to draw the scene and the selected element in red ... }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c++, qt, opengl, graphics" }
Fiware Orion Context Broker-Send notifications after a period of time I want to create a subscription for an entity and to be notified by context broker after a change of measure after a specific time. For example if humidity reaches a threshold i don't want to be notified. But if humidity measurement is changed and reaches or is uppon a threshold for 5 days continuously then i would like to be notified. Is there any pattern for Orion Context Broker Subscriptions for such a purpose? Essentially, i would like to avoid being notified after some peaks of a measurement .
Orion is ~~mainly stateless~~ focused in _current_ context and doesn't keep a _history_ of the context, so it can be difficult to set conditions on "time windows" like the one I understand you describe. However, the FIWARE ecosystem provides components (GEs in FIWARE parlance) that can do that work and interoperate with Orion. In particular, the Perseo Complex Event Processor can connect to Orion as notifications receiver and trigger rules based on time window conditions. How to configure and use Perseo is out of the scope of this answer but in the above link you will find information about the component, documentation and examples.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "publish subscribe, fiware, fiware orion, fiware perseo" }
A big list of Narayana-enumerated objects By a Narayana-enumerated object I mean an object whose count is given by the Narayana number $N(n,k)=\frac{1}{n} {n \choose k} {n \choose k-1}$. Can you give me a reference to some good big list of Narayana-enumerated objects? I have found two Narayana-enumerated objects (the two objects being closely related one to another) and would like to see whether my two objects are in the list.
Elements of the sets enumerated by super-Catalan numbers contains many Narayana-enumerated objects. (The super-Catalan number $s_n$ is related to the Narayana numbers by $s_n=\sum_{k=1}^n 2^{k-1}N_{n,k}$.) Some examples: The following five parameters of Dyck paths are enumerated by Narayana numbers: (i) number of high peaks; (ii)number of valleys; (iii)number of doublerises; (iv) number of rises at an even level; (v) number of nonfinal ascents and descents of length greater than 1. 132-avoiding permutations with given number excedances ($a_i > i$) are counted by Narayana numbers, as well as those with given number descents ($a_i<i$).
stackexchange-mathoverflow_net_7z
{ "answer_score": 1, "question_score": 1, "tags": "reference request, enumerative combinatorics, catalan numbers" }
How to provide autocomplete street addresses functionality in django? Is there any way to provide automatic street address suggestion when user tries to enter their address in the input box using so they start getting automatic address suggestions in django. I was searching autocomplete light but could not find specially anything related to that.
I've implemented this functionality with Google's Place Autocomplete. The sample code in the link is pretty spot on from memory. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "django, autocomplete, openstreetmap, geodjango" }
Run Visual Studio unit tests in a specific folder from command line I am aiming to find a way to run the tests contained in a group of assemblies from command line. The tests have been built using Visual Studio Testing Framework and the assemblies are all located in the same folder. What I want to extract are the tests results (especially the list of failed ones) and possibly the code coverage.
You can use the vstest.console.exe program, it is documented here: < It outputs the results to the console, which you can pipe to a file if you like. It can also log the output to a trx test file, which can be opened in Visual Studio and viewed there. Use it as: vstest.console file1.test.dll file2.test.dll /logger:trx > testresults.txt It does not accept wildcards for the filenames, but you can wrap it in a powershellscript to achieve that, if you like. If you add the /EnableCodeCoverage option, you also get a .coverage file, which you also can open up in Visual Studio.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "unit testing, visual studio 2013, vstest" }
How to mute Gmail thread on Android? I muted the message on web browser on my pc. I can see Muted tag is applied to the thread. I no longer receive notification on this thread from browser on pc. But I keep getting notifications on my Android. I am not the only person on the to/cc list of its messages. I searched old questions and answers. They mentioned a `Done` button. But this button is gone on the Gmail android app I'm using. Please advise.
1. Long-press or open the conversation. 2. Click the 3-dot, select Mute.
stackexchange-android
{ "answer_score": 0, "question_score": 0, "tags": "gmail, inbox by gmail" }
Bamboo Trigger Deployment plan with variables Im trying to deploy a plan that has artefacts from external service for this I want to download via curl those files that I will pass as variables... however I am not able to set programmaticly the variables with the deploymet call curl -k -u user:passord -X POST -d "bamboo.myVariable=someurl" BASE_BAMBOO_URL/bamboo/rest/api/latest/queue/PROJECT-ID Trying to do the same with the deployment API fails curl BASE_BAMBOO_URL/bamboo/rest/api/latest/deploy/project/1321123123 -u user:passord-X POST -d "bamboo.myVariable=callMEwithDATA" Trying to add that into the API fails as does trying to pass it thru JSON curl -X POST BASE_BAMBOO/bamboo/rest/api/latest/deploy/project/1320058 -u user:passord -H "Accepts: application/json" -H "Content-Type: application/json" -d '{"name":"release-1", "myVariable":"ARTEFACT_URL"}'
To continue with a request the variables have to be passed as query params... a sad sad reality is that the Bamboo API is very messed up bamboourl&executeAllStages=true&bamboo.variable.MYVAR=1234
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "bamboo" }
Fibonacci Sequence golden ratio big O proof Fibonacci numbers are defined as $F(0) = 0, F(1) = 1$ and $F(i) = F(i-1) + F(i-2)$ for $i≥2$. $Θ = (1 + \sqrt{5}) / 2$. $F(x) = x^2 - x- 1$. 1) Show that $F(Θ)$ = 0 and that $F'(x) > 0$ for any integer $x≥ 1$. For any $a, b$ such that $1 ≤ a < Θ < b$ we have $a + 1>a^2$ and $b + 1 < b^2$. 2) Prove that for any $a,b$ such that $1 ≤ a < Θ < b$ we have $F(n) = O(b^n)$ and that $F(n) = Ω(a^n).$ My initial thought was to look at the theta and find $c2$ and $c1$ for it, however I am lost as what values of $a$ and $b$ am I looking for? Any help to steer me in the right direction would be appreciated.
Hint. As regards 1) by solving the quadratic equation $q(x):=x^2 - x - 1=0$, we obtain that the roots are $$x_{\pm}=\frac{1\pm\sqrt{5}}{2}.$$ Hence $q(x)=(x-x_+)(x-x_-)$ and it follows that $q(x)>0$ iff $x>x_+$ or $x<x_-$. For 2), note that from $x_\pm^{n}=x_\pm^{n-1}+x_\pm^{n-2}$, we get $$F(n)=\frac{x_+^n-x_-^n}{\sqrt{5}}.$$ Can you take it from here?
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "recurrence relations, asymptotics, fibonacci numbers" }
installing vmware-tools for windows guest i have downloaded the required file `vmware-tools-windows-9.2.3-1031769.x86_64.component.tar` but i don't understand how to install it. It untars to `vmware-tools-windows-9.2.3-1031769.x86_64.component` and `descriptor.xml`.How do i install a `.component` file? the host is raring ringtail and the guest is windows 8 in vmware player. Also under the ubuntu environment
This workaround worked for me: <
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "installation, vmware" }
how to add time picker using react materialize? I am using react materialize time picker and I am getting this error: !error image > `TypeError: $(...).pickatime is not a function`
According to this github comment > pickatime doesn't work with certain version of materialize-css Update materialize-css version accordingly
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "reactjs" }
Why do most sites require email activation Most popular applications nowadays require account activation by email. I've never done it with apps that I've developed so am I missing some crucial security feature? By email activation I mean when you register to a site they send you an email that contains a link that you have to click before your account gets activated.
Activation confirms the email is yours. It's not so much about being bogus or non-existent, as it is about being yours and they need it for an alternative/plan-b way of authentication, in first place.
stackexchange-softwareengineering
{ "answer_score": 25, "question_score": 13, "tags": "security, email" }
Angle (degree) symbol with siunitx under XeLaTeX and mathspec Consider the following example: \documentclass{article} \usepackage{mathspec} \usepackage{siunitx} \begin{document} \ang{30}, \SI{20}{\celsius} \end{document} Compiling with XeLaTex, I get: ![Missing degree]( The angle misses the degree symbol. With the package `fontspec` instead of `mathspec` it works fine (but I need `mathspec`). Is there any solution?
\documentclass{article} \usepackage{mathspec} \usepackage{textcomp} \usepackage{siunitx} \sisetup{math-degree=\mbox{\textdegree},text-degree=\textdegree} \sisetup{math-celsius=\mbox{\textdegree}C,text-celsius=\textdegree C} \begin{document} \ang{30}, \SI{20}{\celsius} \end{document} > ![enter image description here](
stackexchange-tex
{ "answer_score": 4, "question_score": 3, "tags": "xetex, siunitx, mathspec" }
Django get_or_create on reverse relationship I'd like to use `get_or_create` instead of doing this: cart = client.cart cartitems_cart = cart.__cartitem_set if not cartitems_cart.filter(item=stockitem).exists(): cartitem = CartItem.objects.create(item=stockitem) else: cartitem = cartitems_cart.objects.get(item=stockitem) is it possible somehow? The models look like this: class CartItem(models.Model): item = models.ForeignKey(StockItem, blank=True) quantity = models.IntegerField(default=1, null=True) class Cart(models.Model): items = models.ManyToManyField(CartItem, blank=True) So, I need to get or create a `CartItem` that is related with a `Cart`. I'm not sure how to write that query.
First off, your design is flawed. M2M relation allows a cart item to have more than one cart when it shouldn't. You should add a FK field to CartItem model instead of adding a M2M field to Cart model: class Cart(models.Model): user = models.ForeignKey(User) class CartItem(models.Model): item = models.ForeignKey(StockItem, blank=True) quantity = models.IntegerField(default=1, null=True) cart = models.ForeignKey(Cart, related_name="items") so you can do the following: cartitem, created = client.cart.items.get_or_create(item=stockitem) or cartitem, created = CartItem.objects.get_or_create(cart=client.cart, item=stockitem) Please look at the documentation for more information regarding what other parameters `get_or_create` takes.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "django, django models, django orm" }
UpdateLayeredWindow blues on Windows XP I have a NET 2.0 Winforms app based partly on this code. It features a form transparency using `UpdateLayeredWindow` API. It works perfectly on Vista and Windows 7 but fails on Windows XP. I have narrowed it down to `UpdateLayeredWindow` failing with last error 8 (not enough memory). While experimenting I also found out that swapping (desired) `ULW_ALPHA` for either `ULW_COLORKEY` or `ULW_OPAQUE` works on XP but produces the wrong effect (the image shows but the transparency is wrong). I am wondering if something is wrong the way PNG bitmap is being loaded and handled by NET internally and that there is something about it `UpdateLayeredWindow` dislikes.
Looks like it's working, but the layered windows are not actually visible, I guess the opacity settings are wrong. With the code you linked to, changing line 67 in LayeredForm.cs from "BlendOp = 255" to "BlendOp = 0" fixes the issue for me (running on Windows XP SP3).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, .net, .net 2.0" }
Use bash EXIT trap to confirm or cancel ctrl+d Is there a simple way to require confirmation before logging out of a shell, and to prevent the shell from exiting if confirmation is denied? This would be useful to avoid accidentally terminating an SSH session used for tunneling. The problem with `trap ... EXIT` is it still exits after completing the trap. The most promising solution I found so far is described in confirmed exit using trap, which discusses ctrl+c but seems like it could be made to work for ctrl+d instead.
set -o ignoreeof This will cause the interactive shell to ignore `EOF` (`Ctrl+D`). The `bash` shell will print Use "exit" to leave the shell. if you press `Ctrl+D`. You may also set the shell variable `IGNOREEOF` to some positive integer value. The value determines how many times `Ctrl+D` has to be pressed until the shell actually exits. The effect of doing `set -o ignoreeof` in `bash` is the same setting `IGNOREEOF=10` (and the other way around too). The `ignoreeof` shell option is a POSIX option that should be available in all POSIX-like shells. Related: * How to remove "exit" command from Linux shell
stackexchange-unix
{ "answer_score": 7, "question_score": 0, "tags": "bash, shell script, shell, ssh tunneling, trap" }
Curl GET on CMD line with spaces in file name Trying to download a file through CMD line but I have spaces in the filename preventing the download. curl --request GET -v --user user$site:password With Spaces.csv > /users/kanye_west/desktop/FilenameWithSpaces.csv Tried escaping the spaces with backslash `\` already to no avail
Put the URL in quotes. curl --request GET -v --user user$site:password " With Spaces.csv" > /users/kanye_west/desktop/FilenameWithSpaces.csv Backslashes would work on Unix, but they aren't used as an escape charater on Windows because they're the original form of directory separator.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "curl, cmd" }
Proving an Identity involving $4^N$ I am trying to prove the following identity: $$\sum_{k=0}^N\left({2 \, N - 2 \, k \choose N - k}{2 \, k \choose k}\right)=4^N$$ I have tried writing $4^N=2^{2N}=(1+1)^{2N}=(1+1)^N(1+1)^N$, and expanding each of these as a binomial expansion, but I have found nothing but dead ends so far. Any ideas? I am currently working through a Ch. 3 "Generating Functions" from Analysis of Algorithms by Sedgewick/Flajolet. This is problem #30. Thanks.
Let, $f(x)=\displaystyle\sum_{n=0}^{\infty}{2n \choose n}x^n=(1-4x)^{-1/2}$. Then your LHS will be coefficient of $x^N$ of $f^2(x)=(1-4x)^{-1}$ which is $4^N$=RHS.
stackexchange-math
{ "answer_score": 5, "question_score": 3, "tags": "combinatorics, binomial coefficients, generating functions" }
Как сгенерировать список Есть функция var result = Messenger.Get(VersionCode.V1, new IPEndPoint(IPAddress.Parse(device.Ip), 161), new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.4.1.42019.3.2.2.2.1.1.3.2")), new Variable(new ObjectIdentifier("1.3.6.1.4.1.42019.3.2.2.5.1.1.2.4")), new Variable(new ObjectIdentifier("1.3.6.1.4.1.42019.3.2.2.5.1.1.3.4")) }, 100); Как мне сгенерировать переменную new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.4.1.42019.3.2.2.2.1.1.3.2")), new Variable(new ObjectIdentifier("1.3.6.1.4.1.42019.3.2.2.5.1.1.2.4")), new Variable(new ObjectIdentifier("1.3.6.1.4.1.42019.3.2.2.5.1.1.3.4")) } имея список OIDов List<string> device.OIDs ?
Если я правильно понял вопрос то так: void Main() { var oidsList = new List<string> { "1.3.6.1.4.1.42019.3.2.2.2.1.1.3.2", "1.3.6.1.4.1.42019.3.2.2.5.1.1.2.4" }; var result = oidsList.Select(x => new Variable(new ObjectIdentifier(x))).ToList(); } // Define other methods and classes here public class ObjectIdentifier { public string MyProperty { get; set; } public ObjectIdentifier(string a) { this.MyProperty = a; } } public class Variable { public string MyProperty { get; set; } public Variable(ObjectIdentifier b) { this.MyProperty = b.MyProperty; } } ![введите сюда описание изображения](
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, списки" }
Set height of an element on multiples of a number? Is there any way via jquery or javascript to make an element stretch its height to a certain set of numbers? I mean, as it accommodates more content, its height would only follow a pattern of numbers (multiples of a number). Let's say in multiples of 100... a div's height as it extends taller would only be in this series -- 200px, 300px, 400px, etc. Hence, if it exceeds by just even 1 pixel off 200, it would automatically resize to 300. It's hard to explain. I need this because I made a vertically seamless pattern with torn edges and it would totally look perfect if it shows each tile completely. I only know basic jquery and I don't have a bit of an idea on how to work this out. My sincerest gratitude to whoever tends to my query!
var h = $('div').height(); $('div').height( Math.ceil(h/100) * 100 );
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery, html, css" }
release jar file download from snapshot locatoin On spring cloud dataflow getting started page, (< It says run command below, but Error 404(Not found). wget < as you can see, snapshot location and RELEASE version jar file. This is not the only case, so I think there could be some reason. I needs the meaning. Thanks
Thanks for reporting it. This is indeed a bug in the data flow site configuration. This is fixed via:< I will post an update once the fix is applied to the site. Thanks again.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, spring, spring cloud, snapshot, spring cloud dataflow" }
Is bullet character (U+2022) safe to use? In a reporting services report, I'm displaying a bullet point by using the expression : =ChrW(&H2022) This is in a TextBox setup to use Arial font. Now, it seems to work fine, but how safe is it ? i.e. is it likely to work on all PCs ? (The application is a web application).
It should work in every Unicode enabled web browser.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "reporting services, fonts" }
Stuck with relation Here is a question, A = {1,2,3,4,6} = B, $aRb$ iff $a$ is a multiplier of $b$ . Now I think the whole cartesian product of AxB should be the relation as every number is somehow a multiplier of another. Please help me out by sharing your review. Thanks
I have Kolman and Busby, Discrete Mathematical Strucxtures in Computer Science. Problem 9 on page 100 is $A=\lbrace\,1,2,3,4,6\,\rbrace=B$; $a\,R\,b$ if and only if $a$ is a multiple of $b$. I'm sure that what is intended is $a$ is an _integer_ multiple of $b$. So for example $(6,3)$ will be in the relation, but $(3,6)$ won't be.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "relations" }
What is damage window? On sliphroad's site there's a section with moves pokemon could have. As with DPS, power and duration everything is clear, I've got no idea what Damage window means and how it affects battle. What is it? And why it varies from 0 to more that 2000? And why quick moves all have 200?
This is the amount of time in milliseconds at which you can get hurt by the attack, when fighting a Pokemon. Thus you want to put Pokemon with attacks with bigger damage window, when defending gyms, so you'll be able to output more damage.
stackexchange-gaming
{ "answer_score": 1, "question_score": 3, "tags": "pokemon go" }
What is the most efficient way to implement a facebook / twitter style feed in the MEAN stack? Should I consider socket.io? I was thinking about using angular's $interval to periodically query and check for new post, but then I've also read about socket.io. This made me curious as to the best way to accomplish this from a cost-effective / scalable / efficient view point. Can implementing socket.io in your build greatly increase the cost of hosting (on a platform such as heroku)? Just wondering if someone can help my weigh relevant pros and cons.
socketio is a good solution for what you want to achieve. I don't know well heroku, but I use it with amazon aws and nodejs and it works fine. you can use interval and the http service of angular, but you will waist a lot of time for the heavy handshake of http protocol. socketio is trying to use websockets first (ws or secure wss) and it is much lighter when considering "network waist". it has a fallback to use the regular http long polling....go for it with socketio. you'll have a little work to do (really easy) to adjust sock.on listeners and emitters inside a service, and bind your view to this service, or use rootscope broadcast instead... enjoy :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "angularjs, node.js, mongoose, socket.io, mean stack" }
Best practice for reading multiple databases SQLite My goal with this project is to create a quiz app that has the ability to quiz from different banks of data. I would like the user to have the option to select which subjects they wish to be tested on, and then once selected the different banks can be combined and randomized for testing purposes. This is my first time utilizing databases and I was wondering if I could get a little input on the most economic way for this to happen. Are multiple tables my best option? Later down the road I hope to implement the ability to keep records of how well was done on each subject. If someone could point me in the right direction or give me suggestions for this I would be very appreciative.
I literally just finished creating my quiz app and I created one table to manage the questions and another to manage the scores. As long as you use a category column, you can set the cursor to read through questions with the categories you've selected. The cursor can return how many questions are in the categories selected, and you can also quite easily shuffle the numbers to get a random assortment of questions. If you've got any specific questions, just ask (As for the how well people have done, I suggest putting that in another different database. It's easier as that database is probably never going to be upgraded, you don't have to modify it once it is created).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android, database, sqlite" }
Rails Security Patch: SQL Injection Flaw I need to apply the latest Rails security patch from the newly discovered SQL injection flaw. I'm using Rails 3.2.3 and found this patch file ( ) but I'm unsure how I use this file to patch my Rails code. How do I get to the files mentioned in the git change set? Is there a simple way to implement this patch?
Type `git help am` to get the details on how to apply these type of patches. Should be as simple as downloading the file, cd'ing into the activerecord directory and typing `git am < filename`. But if you can... update the gems... more PITA now, but better down the road...
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "ruby on rails, ruby on rails 3, security, ruby on rails 3.2, sql injection" }
insert query while select am trying to insert a data via single query. `select seg_id from seg where product_id='177' and variant_id='527'; insert into main(main_id,main_name,segment_id) values('3333','4444','***')` I want to replace that *** and place selected seg_id. Also,main_id,main_name will be taken from user along with product_id and variant_id while segment_id should be fetched from DB. DB Structure: Segment table: `segment_key(PK) segment_id product_id variant_id` main table: `main_id main_name segment_id creationdate`
Use `insert . . . select`: insert into main(main_id, main_name, segment_id) select '3333', '4444', seg_id from seg where product_id = '177' and variant_id = '527';
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "mysql, sql, database" }
RPi2 PsSession: "Command 'iotstartup' cannot be found" I am in the process of deploying a Windows Universal App to my Raspberry Pi 2. I am following a very handy guide published here. Everything's fine but I get a peculiar warning when trying to run the `iotstartup` command after having established the `PsSession`. !ps snippet If I simply press return again, the message disappears and the command seems to work fine... Am I doing something wrong here? Is it a known powershell thing, or has something gone awry on my device? (If it's of any significance, I had to re-flash the OS once or twice in order to get anything to deploy remotely). I hope it's not my device; but I would be interested to hear of any clarification on this sort of issue.
iotstartup as setcomputername are executables. Use the invoke command, see this article. & iotstartup list will do.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "powershell, iot, raspberry pi2" }
BDD testing a Node.js , Express.js , Socket.io and mongo with mocha What is the best method to test a node.js application using express , sokcet.io and mongoose , by using mocha ? EDIT : i should mention that i am writing tests with mocha and zombie.js .. but there are some errors with socket.io i cannot figure out what is the source of it ! such as the following error Cannot call method 'onClose' of null
How about casperjs with yadda. Its quite flexible and yadda gives option to write your own definitions.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "node.js, express, socket.io, mongoose, mocha.js" }
Seeking advanced 3D trigonometry textbook or other books or media. In a prior question about the altitude of an irregular triangular pyramid, I got two good answers that solved the problem but I don't understand the concepts as well as I think I should. Can anyone recommend one or more sources from which I can learn how the equations were developed? I really like real books, by the way, and I'm willing to buy more than one or two if that's what it takes for me to learn 3-dimensional trigonometry in depth.
Trigonometry is an inherently planar tool. If you want to be able to solve problems in geometry in $\mathbb{R}^3$, then you want to look at vector and matrix algebra, and maybe some multivariate calculus. That should give you the tools to solve problems such as the one you linked.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "reference request" }
Memory mapping and file I/O If i have memory mapped a file of size 10GB in a 1GB machine and if i trigger a file i/o, after making sure that the data requested is not in physical memory, will the fetched data get mapped to the corresponding virtual address in mmap? When i access the same location using mmap, will it again do an i/o (or will it make use of the data that was fetched using file i/o) Thanks in advance, Gokul.
It depends on the platform, but in general it'll be treated like other memory (swapped out when not in use, swapped in when required), except that instead of using the normal swap files/partitions it swaps from the original file on disk.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "mmap" }
Absolute Value in an Integral I have a problem that asks for the $\int_3^8 |g(x)| {\rm d}x$. Instead of a value given for $g(x)$ I was given a graph and told to figure it out geometrically. Does the absolute value sign mean that I first add all the values and then take the absolute value or do I first take the absolute value and then add? The difference would be when the $g(x)$ goes below the $x$-axis and I have both positive and negative values.
In $\int_3^8 |g(x)| {\rm d}x$, the value which you are integrating is $|g(x)|$. As Hendrix says in a comment, this is always non-negative. As such, based on what integration means, you need to always take the absolute values of anything you're using first and then add those over the region of integration, i.e., $3$ to $8$. Doing it the other way around would give you the wrong answer if you subtract any values (in particular, the result would be too small). Note doing this would be equivalent to solving $|\int_3^8 g(x) {\rm d}x|$ instead.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "calculus, integration, definite integrals" }
Print over last line in terminal When using `wget` in a Linux terminal, the last line printed in the terminal is being overwritten as the download progresses, to reflect the progress. Can I overwrite the last line of the terminal in Python? (targeting Linux only)
You could use `blessings` module to write on the last line in a terminal on Linux: from blessings import Terminal # $ pip install blessings t = Terminal() with t.location(0, t.height - 1): print('This is at the bottom.')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, terminal" }
Inverse of special upper triangular matrix Consider the following $n \times n$ upper triangular matrix with a particularly nice structure: \begin{equation}\mathbf{P} = \begin{pmatrix} 1 & \beta & \alpha+\beta & \dots & (n-3)\alpha + \beta & (n-2)\alpha + \beta\\\ 0 & 1 & \beta & \dots & (n-4)\alpha + \beta & (n-3)\alpha + \beta\\\ 0 & 0 & 1 & \dots & (n-5)\alpha + \beta & (n-4)\alpha + \beta\\\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\\ 0 & 0 & 0 & \dots & \beta & \alpha+\beta\\\ 0 & 0 & 0 & \dots & 1 & \beta\\\ 0 & 0 & 0 & \dots & 0 & 1 \end{pmatrix} \end{equation} i.e. \begin{equation} p_{i,j}=\begin{cases} 0, &i>j,\\\ 1, &i=j,\\\ (j-i-1)\alpha+\beta, &i<j. \end{cases} \end{equation} Would it be possible to find an explicit expression for the elements of the inverse of $\mathbf{P}$?
Let $A$ be the nilpotent matrix $$\begin{pmatrix}0 & 1 & 1 & \cdots & 1 \\\ & 0 & 1 & \cdots & 1 \\\ & & \cdots & \cdots & \cdots \\\ & & & 0 & 1 \\\ & & & & 0\end{pmatrix},$$ then the matrix $P$ is equal to $1 + \beta A + \alpha A^2$. This gives the inverse: \begin{eqnarray*}P^{-1} & = & (1 + \beta A + \alpha A^2)^{-1} \\\ & = & (1 - \lambda A)^{-1} (1 - \mu A)^{-1} \\\ & = & \sum_{k \geq 0} \frac{\lambda^{k + 1} - \mu^{k + 1}}{\lambda - \mu} A^k,\end{eqnarray*} where $\lambda$ and $\mu$ are the two roots of the equation $x^2 + \beta x + \alpha = 0$. Since we have $A^n = 0$, the sum essentially ranges through $0 \leq k < n$.
stackexchange-mathoverflow_net_7z
{ "answer_score": 20, "question_score": 9, "tags": "linear algebra, matrices, matrix analysis, matrix inverse" }
Prolog custom operator to evaluate I expect the following code to print out [9 4], but this isn't working :- op(20,xfx,i). i(X,Y, Z) :- Z=[X,Y]. main:- RESULT is 9 i 4, write(RESULT). Where am I getting wrong?
an operator is basically syntactic sugar; instead of writing `+(1,2)` we simply write `1+2`. therefore, `9 i 4` is equivalent to `i(9,4)` now, +/2 is not only an operator but also an arithmetic function note that the result should be a number so you cannot use it to return a list (and cannot use is/2 either)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "prolog, logic" }
MailBee Imap.Connect throws an Arithmetic operation resulted in an overflow error I have an old program that I have been asked to update. It was originally built using .NET framework 2. I have updated this to version 4.5. The code uses MailBee to connect to an email account and the old version works. The updated version however throws an "Arithmetic operation resulted in an overflow" error when I call the Connect function of the Imap object. MailBee.Global.SafeMode = true; Imap imap = new Imap(); imap.Log.Enabled = true; imap.Log.Filename = control.MailBeeLogDir + "MailBee_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log"; imap.SslMode = MailBee.Security.SslStartupMode.OnConnect; imap.Connect(control.EmailServer, control.EmailPort); The log file has no errors and seems to connect successfully. Any suggestions?
You're using a very old version of MailBee.NET Objects (v3). The up-to-date version is v12. Update to the latest version and try again.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, email, imap" }
Can't push view controller from UISearchDisplayController delegate I have created a UISearchDisplayController which uses a separate UITableViewController as the delegate to display the results of the search. In this view controller, I have the 'didSelectRowAtIndexPath' method which allocates and initializes a detailViewController then uses: [[self navigationController] pushViewController: detailViewController animated: YES]; to push it onto the stack. However, this line doesn't work. When a cell is tapped, nothing happens. 'didSelectRowAtIndexPath' is being called, but the 'pushViewController' method call isn't working. Am I not in the context of my navigationController any more? How can I fix this problem? Any help would be much appreciated.
your table's navigationController is probably the wrong one, I think that you might want to push it on the navigationController of your UISearchDisplayController. To do this, you can create a protocol in your tableviewcontroller with a method "pushViewController" for instance and have UISearchDisplayController implement it. Then your register this delegate in your table view and you call your delegate on pushViewcontroller in your 'didSelectRowAtIndexPath'
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "iphone, objective c, cocoa touch, uinavigationcontroller, uisearchdisplaycontroller" }
3 Events, probability of 2 being a specific value? I have a probability problem but maths is not my strongest field. I usually use online calculators but I have a specific problem. I have three variables in my code which randomly generate a number between 0 to 255. a = 0 to 255 b = 0 to 255 c = 0 to 255 All three variables are generated at the same time, I am trying to work out the chance of either one of them being 0, or two of the variables being 0. I have the probability of one of these variables being 0 as a single event = 0.39% Then based on this: Chance of all 3 variables being 0 = 0.0000059% Chance of at least one variable out of three being 0 = 1.17% Chance of at least two variables out of three being 0 = ???? Any help would be appreciated, thanks.
The probability of (exactly) two of them being $0$ is $$\binom 3 2 \left(\frac 1 {256}\right)^2 \left(\frac {255} {256}\right),$$ while the probability of all of them being $0$ is $$\left(\frac 1 {256}\right)^3.$$ Now, observe that the result you are looking for is simply the sum of these two probabilities. Also, as mentioned in a comment, your problem is closely related to the binomial distribution.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "probability, binomial distribution" }
Accumulating plot in ggplot2 Is it possible to create a graph form 0% to 100% on the x axis and units on the y, and accumulate from y=0 to y=max, so I can say "X of my elements occured within the first Y units". Is there a predefined stat in ggplot2 which allows me to do that? Here's some data: <
You can either apply it before processing with ggplot or during: For example: library(ggplot2) library(scales) library(XML) x <- eval(parse(file(" # Your data d <- data.frame(x=x,y=1:length(x)) d$z <- cumsum(d$x) / sum(d$x) # As percent ggplot(d, aes(z,y)) + geom_line() + scale_x_continuous(label=percent) OR library(ggplot2) library(scales) d <- data.frame(x=x,y=1:100) ggplot(d, aes(cumsum(x)/sum(x),y) + geom_line() + scale_x_continuous(label=percent) I'm assuming this is sales data or something like that. So putting it in that context, 50% of revenue occurs from the first 5000 transactions.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, ggplot2" }
Is this Xbox 360 controller fake? How can I tell? Just bought it on ebay from a chinese seller with high rating. The item description said it was GENIUNE. But I'm still skeptical. Even thought It works well on my pc the box looks suspicious on the backside. What should I look for to verify the authenticity of this controller? Please take a look at these photos, and use them as an example if possible. !front of controller !top of controller !back of controller !bottom of controller !controller cable !back of box !front of box !instructions
There are quite a few ways to check if you have a genuine Microsoft product. * The best way to tell is to check if it has a holographic Microsoft sticker on it. All genuine Microsoft products have this quality (watch this video for a demonstration of this) * In addition, you must remember that Microsoft has changed the design of their controllers over time, and therefore the one that you have may be different from the one your friend has. Wikipedia is helpful in identifying which controller you and your friend have. * The logo should look like this. The "Microsoft" logo on the top of the controller should have a split "o" and connected "ft" * Check the weight of the controller with another controller you are sure is real.
stackexchange-gaming
{ "answer_score": 7, "question_score": 6, "tags": "xbox 360, controllers" }
How to sort a Vector of String in java-me? I have a Vector of Integer ( primary key of a database table ) ; and I implemented a method which returns a String based on this primary key Integer. My problem is that I want to put these String's into a Vector and they are "sorted" in the Vector. How to achieve this String sort ?
Use the following code for sort the vector in java-me. public Vector sort(Vector sort) { Vector v = new Vector(); for(int count = 0; count < e.length; count++) { String s = sort.elementAt(count).toString(); int i = 0; for (i = 0; i < v.size(); i++) { int c = s.compareTo((String) v.elementAt(i)); if (c < 0) { v.insertElementAt(s, i); break; } else if (c == 0) { break; } } if (i >= v.size()) { v.addElement(s); } } return v; }
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "java, java me, sorting" }
How transform JSX code in browser Which answer is correct * With Babel stand alone build * Standard Babel and react preset * JSX transformer is recommended by Facebook starting from ReactJs v0.15 * You cant use JSX in browser, must transpile it to ES5 before sending to browser i choose 4 option (You cant...) but in right answer is 2(Standard B..), Can you explain WHY?
JSX is a syntax sugar over JavaScript. When you use jsx in browser, JSX transformer needs some time to transform jsx to javascript. Using babel library you transpile your jsx to javascript, so in browser it will work faster than non-compile jsx
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "reactjs, testing" }
UITextView background image is scrolling for multiple lines I have created extension for UITextView, where I set image to the textview using below code. let backgroundImage = UIImageView(frame: ....) backgroundImage.image = UIImage(named: "textarea.png") self.addSubview(backgroundImage) self.sendSubview(toBack: backgroundImage) At start it looks fine as showing below image (left side), however as I add multi-line text, image also starts scrolling (right side), which is incorrect. ![enter image description here]( Any idea how to make image fixed as it is?
Below is what I did let backgroundImage = UIImageView(frame: ....) backgroundImage.image = UIImage(named: "textarea.png") mainView.insertSubview(backgroundImage, belowSubview: self) `mainView` is nothing but the main view (self.view) of view controller. This is like we are **_not going to add backgroundImage in the subview of textview, instead we will be adding in the mainview (self.view)_**.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "swift, uitextview, background image, swift4" }
Integer programming : linearize product of constants given conditions I have some constant values $c_i$ in $(0.5, 2)$. I also have binary variables $x_i$. For my integer program, for a particular constraint, I need to multiply only those $c_i$ when $x_i$ takes the value 1. So basically, $\Pi_i \big[(c_i - 1)x_i + 1\big]$. I'm trying to linearize this. I can put a continuous variable $\gamma_i = (c_i - 1)x_i + 1$ and try to use piecewise linear functions, but since $(c_i - 1)x_i + 1$ can only take two values, i.e., $c_i$ and $1$, is there any way to use this property to have a more efficient linearization?
Depending on how you want to use the resulting product, you might be able to use a log transformation, which yields the linear function $\sum_i \log(c_i)x_i$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "optimization, nonlinear optimization, integer programming, constraints, mixed integer programming" }
Why shouldn't an object be cloneable? I read lots of threads about the clone() method of Object and the Cloneable Interface but I couldn't find a legitimate answer to my question. Long story short: What I figured out is that Object has a method clone() which can "magically" clone your object. But you can't use that method without implementing Cloneable Interface because this interface allows Object to use the clone() method. So why did they do that? Why shouldn't every object be cloneable from the start?
Cloneable makes sense for some mutable data. It doesn't make sense for * immutable data * where you might need a shallow or a deep copy. * objects which represent resources such as threads, sockets, GUI components * singleton and enumerated types * mutable state where data should only be copied to avoid creating new objects. Some coding styles suggest keeping new mutable data object to a minimum. Cloneable doesn't suit all situations and if you made all objects Cloneable you wouldn't be able to turn it off cleanly. Note: There are many projects which avoid using Cloneable anywhere.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "java, interface, clone, cloneable" }
Pyramid_beaker: session.type = cookie is not secure? I've launched my site few days ago on Pyramid framework and I've choosed `session.type = cookie` with **pyramid_beaker** in perfomance reasons. So in cookie I have encrypted user_id, it's look like this: usr: "d79c098d69c26a4a85459acf03104ad74f3a22de1!userid_type:int" # for example here is encrypted id 1 And than I've tried to substitute cookie. I've logged in under id 2, changed it's cookie on previous one and now I'm automatically logged in under id 1!!! Is it normal? Is it safe??? What for than encryption with it's super algorithms? So, some virus can steal some user's cookie and log in under his id? And where is the Security??? Could anyone explain me? Thanks!
Yes, session cookies are vulnerable to being stolen and being used to impersonate the logged-in user. You can minimize this risk to some extent by giving sessions a short lifespan, and/or by tying them to the client's IP address, but these are mere stumbling blocks to a dedicated hacker. The only real solution is to fully encrypt the session using SSL. This is why many popular sites (Gmail, Facebook, etc.) offer or require HTTPS sessions, and why the Firefox extension HTTPS Everywhere exists.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "python, pyramid, beaker" }
cakephp 3 [RuntimeException] Unable to configure the session, setting session.cookie_path failed I try to transfer a cakephp3 application from my local server to a webspace. I get the following error-message: > [RuntimeException] Unable to configure the session, setting session.cookie_path failed What does this mean and how can I fix it? <
So I applied a workaround: following the stacktrace I opened the file > /app/vendor/cakephp/cakephp/src/Network/Session.php(212): Cake\Network\Session->options(Array) and scrolled to line 212 there I changed if (!empty($config['ini']) && is_array($config['ini'])) { $this->options($config['ini']); } to if (!empty($config['ini']) && is_array($config['ini'])) { //$this->options($config['ini']); } My website loads now and I can login and logout
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, session, cakephp, cookies" }
Get load time of javascript and css files for a website in chrome extension I am a beginner with chrome extension development. I am trying to create and extension which will fetch the javascript and CSS file load time for a particular website and display in the chrome extension popup. However, I am unsure about the CHROME.API to achieve it Please kindly suggest
You can fetch the HAR log using this chrome.devtools.network.getHAR(function callback) **What are HAR logs?** A HAR file contains a JSON data structure that describes the network "waterfall", which also contains the loading time of every resource of that page. So you will need to parse the HAR JSON, extract time for the js and css files. More on HAR structure : <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, google chrome, google chrome extension" }
Wrong type argument: keymapp, emacs-lisp-mode-map I have the following lines in my init.el: (dolist (map '(emacs-lisp-mode-map lisp-interaction-mode-map)) (define-key map (kbd "C-c C-e") 'eval-and-replace)) When I eval it, I get an error: Wrong type argument: keymapp, emacs-lisp-mode-map But if I check with: (keymapp emacs-lisp-mode-map) the result is: t I have no idea what's wrong with that I have also tried another version of mapcar: (mapcar '(lambda (map) (define-key map (kbd "C-c C-e") 'eval-and-replace)) '(emacs-lisp-mode-map lisp-interaction-mode-map)) but the result is the same.
`define-key` expects an actual keymap as its first argument. You are passing it a **symbol** (variable) whose **value is a keymap**. You need to use this: (dolist (map (list emacs-lisp-mode-map lisp-interaction-mode-map))...) `list` is a normal function, so it evaluates its arguments. In this case, that gives you a list of two keymaps, not two keymap variables (symbols). In the code you used, `quote` just returns the list `(emacs-lisp-mode-map lisp-interaction-mode-map)`. You tested `(keymapp emacs-lisp-mode-map)`. But if you had tested `(keymapp 'emacs-lisp-mode-map)` then the result would have been `nil`: a symbol is not a keymap.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "emacs, elisp" }
Where to find input placeholder style Couldn't find default placeholder style for input element. There are no any `webkit-input-placeholder`, `-moz-placeholder`, `-moz-placeholder`, or `-ms-input-placeholder` style settings in any css files. UPDATE: Guys, don't hurry to judge me. I have the legacy code (tones of css files). The one placeholder style (font-weight, color and so on) is not properly shown in IE 11. I started to find where the placeholder style is defined. And I didn't find any placeholder style declaration you all mentioned. So I assume there is a default style for placeholder in browser.
Webkit's User Agent Stylesheet (Chrome & Safari) can be found here: < Their CSS shows: ::placeholder { -webkit-text-security: none; color: darkGray; pointer-events: none !important; } input::placeholder, isindex::placeholder { white-space: pre; word-wrap: normal; overflow: hidden; } I can't find any other sources that have the defaults for other browsers, but I imagine they would be close to this.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 11, "tags": "html, css" }
is it possible to get deadlock when accessing the field directly Usually for thread safety, we access the field using synchronized(lock). If without using synchronized(lock) and access the field directly, can we encounter deadlock in some case?
Without synchronization, there is no deadlock, only data corruption and undefined behaviour.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "java" }
date comparison in mongoosejs Comparing dates in mongoose seems to be failing for me. My Date comparison always returns false even if I set the date to far in the future. TaskSchema = new Schema({ description: String, end: { type: Date, required: true, index:true} }) task.end >= Date()
Not sure I exactly understand the answer but the following works if I new an instance of the Date instead of just calling Date() task.end >= new Date() I thought Date() was a static factory method that creates a date object, but I guess I could be wrong. If I console.log Date() and new Date(), they both print out dates, so not sure what the difference is, but regardless it works if I new the Date.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "mongoose" }
SQLite3 — Predetermined set of values for a field? I'm working with SQLite3. In my schema, is it possible to require that a given field only contain values from a predetermined set? If not, I suppose the thing to do is populate a separate table with the allowed values and then use one of the ids from that table in the field in question.
You could add a check constraint: CREATE TABLE MyTable( MyField TEXT CHECK(MyField IN ('a', 'predetermined', 'set')) );
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sqlite" }
List all surveys programmatically in SharePoint 2010? I need to change some permissions for all surveys in a SharePoint 2010 site collection, how can I list them? For example to list document libraries I can do SPSite oSiteCollection = SPContext.Current.Site; SPWebCollection collWebsite = oSiteCollection.AllWebs; foreach (SPWeb web in collWebsite) { SPListCollection collList = web.Lists; foreach (SPList oList in collList) { if (oList is SPDocumentLibrary) { // Do something } } } Thanks in advance.
As your if statement use if (oList.BaseType == SPBaseType.Survey)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sharepoint, sharepoint 2010" }
Loading images list from sub directories of document directory I have set of images in iphone document directory, Eg: document_directory/sub_directory_1/sub directory_2 So how to retrieve all images from sub directory_2 as a NSArray or some sort of a data structure. Thank you
Assuming you have the path as a NSString*, use NSFileManager NSFileManager *fileManager = [NSFileManager defaultManager]; for (NSString *fileName in [fileManager contentsOfDirectoryAtPath:directoryPath error:NULL]) { NSLog(@"Found file %@", fileName); }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "iphone, objective c, cocoa touch, iphone sdk 3.0, ios4" }
Displaying user specific Form Fields in TCA TYPO3 Is there a way I can change the Form fields and options depending on the current user? Like for instance, if the current user is just a Simple_User he/she should not be shown the option "evaluate". But for an Admin, the evaluate option should be available. How can I achieve this using TCA for creating backend forms for a plugin ?
In the TCA there is the option "exclude", which gives you the option to set the permission for BackendUser or BackendGroup if the user is allowed to view/edit the field.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "forms, typo3, backend" }
package net.proteanit.sql does not exist I am unable to import net.proteanit.sql.DbUtils, Getting this error package net.proteanit.sql does not exist. What library am i missing and where to get it? import net.proteanit.sql.DbUtils;
This means you need to add that external `.jar` file which has this package. You can refer here for seeking help in adding external jar to your project.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "netbeans" }
Why do my photos look like they're painted? I'm not an expert, but all the photos I take look like they've been painted. It doesn't look like normal blur. I'm using a FinePix S2500HD and the following photo was taken at 1/2000 exposure. I should note that it doesn't seem to matter what exposure I set it at, they all have this painted look. < Is it the camera? A setting? Or just me...
This looks like the effect of noise reduction at high ISOs. Heavy NR is common in compact cameras with small sensors. Fujifilm cameras of that generation did it very well compared to others of the time, but there's only so much blood you can get from a stone. On most modern high-megapixel point and shoot cameras, you'll see this even at low-ISOs if you pixel peep. It's important to note that in most cases, this is actually okay, because for printing or at common display sizes it'll look just fine. Better quality gives you more room to crop, of course. And in this case the sky looks particularly bad, so with this camera I'd try to stick to lower ISOs. More advanced models often have the option to turn off noise reduction, and I usually do, because I prefer the look of noise to this "painted" blur. Or, if you shoot RAW, you have many, many options for more flexible noise reduction in post.
stackexchange-photo
{ "answer_score": 19, "question_score": 11, "tags": "sharpness, artifacts, blur, noise reduction" }