INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Dict comprehension tip I am starting to use list comprehensions and i am a bit lost in the syntax, how can i translate this to dict comprehensions: dict_users = Counter() largo = len(wut) for user in wut: count = 0 for line in lines: if user in line: count += 1 dict_users[user] = count i have tried different variations but i keep getting it wrong. dict_users ={user: count for user in wut count = 0 for line in lines if user in lines}
You can't assign (`count = 0` or `count += 1`) in a generator expression/list or dict comprehension, you need to use `sum` for this kind of thing instead. I think what you wanted is: dict_users = {user: sum(user in line for line in lines) for user in wut } Note that this uses the fact that `True` (`'f' in 'foo'`) and `False` (`'f' in 'bar'`) evaluate to `1` and `0` respectively when summed, as the booleans are integer subclasses. A simple example: >>> lines = ['foo', 'bar', 'baz'] >>> users = ['ba', 'f'] >>> {user: sum(user in line for line in lines) for user in users} {'ba': 2, 'f': 1} But this is arguably less readable than the nested `for` loops you have now.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python, dictionary" }
Is it possible to use template tags in ValidationError's strings? I need to throw ValidationError containing anchor. if not profile.activated(): raise ValidationError('Your profile is not activated. <a href="{% url resend_activation_key %}">Resend activation key</a>.') What I need to modify to make this work?
Why do you want to use a template tag here? Template tags are for use in templates. If you want to find a reverse URL, use the `reverse` function.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, django, validation, django templates, django forms" }
Add value to hidden input field using jQuery I am dynamically adding input fields and I want to add a variation of those values of the input fields to hidden input array but I am struggling to do so. I have one hidden input in the html page: <input type="hidden" name="center_ids[]" value=""/> And the jQuery I am using to add the value I want is the value returned from my AJAX method: $(".autocomp_centers").autocomplete({ serviceUrl:'/suggest_centers', maxHeight:400, width:252, minChars:2, onSelect: function(value, data){ $("input[name='center_ids']").push(data) } }); But this does not add to the hidden input field. Anyone know what I am doing wrong?
be carefull with the name of you input. Your input is named `center_ids[]` and not `center_ids`. $(".autocomp_centers").autocomplete({ serviceUrl:'/suggest_centers', maxHeight:400, width:252, minChars:2, onSelect: function(value, data){ $("input[name='center_ids[]']").val(data); } }); Hope this fix your problem.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, html, forms" }
What should I be buying in the Magic Shop? The Magic Shop offers random loot that refreshes every hour. What should I be spending my Mana Stones on or what items are good to look out for? I currently don't need any of the runes it's offering me and I don't find that buying 1-3 Summoning Scrolls is worth it.
The most appreciated items in the magic store are mystical scrolls. These are quite rare, and the quality of shop items will increase with your level. Sometimes you'll also have the luck of seeing some good runes in the store, which are worth their price. There are also some monsters worth buying, such as : Ramagos, wind warbear, who is a good monster Shannon, wind pixie, who is also a very good monster Coleen, fire harpu, who is a good monster too The fire imp (Cogma) , who is fusion material Wind harpu (Seal), who is also fusion material A recent patch also added legendary pieces and light and dark pieces. I don't recommand using your mana on this early on because you need a lot of pieces before having your scroll.
stackexchange-gaming
{ "answer_score": 3, "question_score": 1, "tags": "summoners war" }
Что такое фадж? Читаю книгу Султана Шамши Путешествие Ибн-Фадлана на реку Итиль и встретил такое предложение: > Женщины там не закры­ваются ни от мужчин, ни от посторонних, тело тоже нескрывают ни от кого из людей. И действительно, как-то произошел с нами такой случай: когда мы остановились у одного из местных жителей и уселись побеседовать, жена хозяина была с нами. И вот во время разговора она от­крыла свой **«фадж»** и, нисколько нас не стесняясь, по­чесалась там. Мы от стыда закрыли лица и произнесли: «Прости нас, Аллах!» А муж ее засмеялся и сказал пе­реводчику: Что, собственно, такое фадж?
галина в общем правильно написала, но есть ошибки, я могу конкретно из словаря показать. пропущена буква р: * < * < * < не путать с утренней молитвой, с его временем, с событием его времени - рассветом: * < * < * <
stackexchange-rus
{ "answer_score": 1, "question_score": 1, "tags": "значение слов" }
Apache Kafka vs Oracle Goldengate for remote data streaming Regarding a data consolidation scenario, are there any comparative analysis that compares Apache Kafka and Oracle Goldengate for remote data streaming? In the scenario, we have to integrate sensory structured data from multiple (~100) sources to a single destination over internet. **Note:** If my question is general, your questions in comment may help me to describe the situation more accurately. Thanks in advance.
Presuming the 100 sources are all Oracle Databases then Oracle Goldengate would be the best choice if you want to configure vs code. You can use Oracle Goldengate to "replicate" the 100 sources to a single location for processing. Also remember that Oracle Goldengate and Kafka are not either or, Oracle Goldengate can deliver the changes to a Kafka topic.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "apache kafka, oracle golden gate" }
Simplifying the declaration of a dictionary where the value of a key is the property name as a string I have the following constant: const X = { x: 'x', y: 'y', z: 'z' } Is there a way to write this without repetitions? P.S: Found something like this in production code but way longer, don't know what the point is.
Maybe just a function that tales keys as parameters and returns an object? const getDictionnary = (keys: string[]): {[key: string]: string} => { return keys.reduce( (object: {[key: string]: string}, currentKey: string) => ({...object, [currentKey]: currentKey}) , {}); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "typescript" }
Use class method as `op` argument to `accumulate` I'm trying to create a class that calculates its variance from a `vector<float>`. It should do this by using its previously calculated `this->mean` in `diffSquaredSum`. I'm trying to call the method `diffSquaredSum` inside of `accumulate` but have no idea what the magical syntax is. What is the correct syntax to use the `diffSquaredSum` class method as the `op` argument to `accumulate` in `setVariance`? float diffSquaredSum(float sum, float f) { // requires call to setMean float diff = f - this->mean; float diff_square = pow(diff,2); return sum + diff_square; } void setVariance(vector<float>& values) { size_t n = values.size(); double sum = accumulate( values.begin(), values.end(), 0, bind(this::diffSquaredSum)); this->variance = sum / n; }
double sum = std::accumulate( values.begin(), values.end(), 0.f, &{ return diffSquaredSum(sum,x);} ); `bind` is only rarely useful. Prefer lambdas, they are easier to write and read. You could instead get fancy with binding, but why?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++11" }
Installing Flex Builder Plugin on Eclipse 3.5 (galileo) Mac Cocoa 64bit Is there a way to get the Flex Builder plugin working on the latest Eclipse running on the Mac? I've read that there is no hope with the Cocoa/64 bit version, but some report it works with the Carbon version. I need the 64bit/cocoa version on the Mac in order to have access to the JDK6 libraries via the embedded maven support in the Eclipse IAM plugin.
Unfortunately Eclipse 3.5 is unsupported by Flex Builder 3. There are a few bugs for this: < < Please comment on those bugs and vote for them.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "apache flex, eclipse plugin" }
Redirect from unsecured TLD to alternate secured TLD I am wondering what the impact is on a website visitor when the website has had a TLD change. Take for example, ` Let's say this domain changes to ` Visitors accessing the former, will be redirected to the latter. When the TLS certificate for the former expires, what is the impact on visitors? Will they be immediately redirected, or will they see the _untrusted_ page in their web browser? My specific use case is that I am changing a TLD from `.tv` to `.ai`. The `.tv` TLS certificate expires in April 2018. Do I need to renew that certificate _just_ to avoid the _untrusted_ warning, or will a redirect skip the TLS check?
TLD pointing to a new server will unfortunately break permalinks around, as well as robots permalinks and stat builders. So if you are talking HTTP redirection, TLS applies to the HTTP resource request, not to the server request. Therefore in that situation, you will have in order: 1. connection to port 443 on your first server. 2. consolidation of a TLS connection with that server. 3. request of the HTTP '/...' resource on that server. 4. redirection to another HTTP(S) resource. I would expect your users to get the untrusted page displayed at step 3.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "ssl, ssl certificate, domain, redirect, tld" }
IIS client certificates: do I need client certificates mappings? I created self-signed root certificate, ssl certificate and client certificate using **makecert** util. I created site in **IIS** , enabled settings " **Require SSL"** and **"Require client certificate"**. This site uses my ssl certificate. Then I installed client certificate on client PC and it works fine without any client certificate mappings. When it's required to configure mappings and when it's not needed?
Under the mapping, you can map individual users to tokens which can then have permission to see things or do tasks (Admins, Personnel, Customers, etc). Without that you're just testing to see if a user has a valid certificate regardless of who he is. You can authenticate the users further using mechanisms like form authentication but the mapping can automate this task for you.
stackexchange-security
{ "answer_score": 0, "question_score": 1, "tags": "authentication, certificates, iis" }
Bias-Variance Tradeoff with SVMs I know that larger values of C in SVM cause the classifier to attempt to classify more points at the expense of a wider margin (and vice versa for smaller values of C). Therefore, is it correct to say that, in terms of a bias-variance tradeoff, larger values of C increase the variance and decrease the bias of the model?
Yes. This can be related to the "regular" regularization tradeoff in the following way. SVMs are usually formulated like $$ \min_{w} \mathrm{regularization}(w) + C \, \mathrm{loss}(w; X, y) ,$$ whereas ridge regression / LASSO / etc are formulated like: $$ \min_{w} \mathrm{loss}(w; X, y) + \lambda \, \mathrm{regularization}(w) .$$ The two are of course equivalent with $C = \tfrac{1}{\lambda}$. I think it's more intuitive to see in the latter case, though, that as $\lambda \to \infty$ your solution is determined entirely by the regularization term, so that your bias is very high and variance very low; as $\lambda \to 0$, you take away all the regularization bias but also lose its variance reduction.
stackexchange-stats
{ "answer_score": 8, "question_score": 4, "tags": "variance, svm, bias" }
Regular expression to check for cookies with no name I want to create an IIS rewrite rule that runs for any request where there is a cookie with no name (as Classic ASP can't handle these). I need a regular expression that looks for an equals sign either at the beginning of the cookie string or after a semi colon, and possibly with white space (space, tab, line feed, carriage return, etc) before it. (; or beginning)(optional white space)= I'm crap at regular expressions but here's my proposed one: ^|;\s*= Is this right, or how would this best be done?
You're almost there, just put `^|;\s*` inside a group, so that the `|` OR applies to the both. (^|;)\s*=
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "regex, cookies" }
Преобразовать тип данных в запросе select Можно ли не меняя тип данных в таблице, вывести через select столбец с иным типом данных? К примеру, в столбце varchar, а я хочу int (в столбце нет других символов кроме 0-9).
SELECT CAST(ColumnName AS INT) AS ColumnName FROM TableName
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, sql server" }
Derivation formula for sum including newton symbol So i was asked to derive formula for given sum: > $$ {n\choose0} +\frac 12 {n\choose1}+\frac 13{n\choose2}+...+\frac 1{n+1}{n\choose n} $$ So i made few attempts, but not for all steps i'm sure that are correct. 1. $S=\sum_{k=0}^n \frac1{k+1}{n\choose k} $ 2. $ S(n+1)= \sum_{k=0}^n \frac{n+1}{k+1}{n\choose k}= \sum_{k=0}^n {n+1\choose k+1} \quad $ 3. $S(n+1)=2^{n+1}-1 $ 4. So $S =\frac{2^{n+1}-1}{n+1} $ Thanks in advance
Your proof is both elegant and correct! Here's another way: $$ \sum_{k=0}^n\frac 1 {k + 1}{n \choose k} = \sum_{k=0}^n{n \choose k}\int_0^1x^kdx=\int_0^1(1+x)^ndx=\frac{2^{n+1}-1}{n+1} $$
stackexchange-math
{ "answer_score": 2, "question_score": 4, "tags": "summation, proof writing, solution verification" }
Get Zipfile as Bytes in php? Using php, how can I read a zip file and get its bytes, for example something like $contents = file_get_contents('myzipfile.zip'); echo $contents; // outputs: 504b 0304 1400 0000 0800 1bae 2f46 20e0 Thank you!
`file_get_contents` gets the raw bytes, your `echo` outputs those raw bytes. If you expect to output a _hexadecimal notation_ of the raw byte contents instead, use `bin2hex`: echo bin2hex($contents); If you want that arbitrarily grouped with a space every two bytes, you can do something along these lines: echo join(' ', str_split(bin2hex($contents), 4)); (Note that this is all rather inefficient, modifying the entire, possibly many megabyte large file in memory. I'm expecting this is just for debugging purposes, so won't go out of my way to write super efficient code.)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Use js plugin from node modules in vuejs How can import cal-heatmap(< to my project after saving it with npm install? I tried to use it like this: <script> import calHeatmap from 'cal-heatmap' export default { name: 'heatmap', props: { inspection: Object }, data () { return { current: new Date().getFullYear() } }, beforeMount () { var cal = new CalHeatMap() cal.init({}) } } </script> And I get that CalHeatMap() is not defined.
You can write it like this directly in the component: import CalHeatmap from 'cal-heatmap'
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "import, vue.js, vue component, node modules" }
Returning only part of match from Regular Expression Say I have the string "User Name:firstname.surname" contained in a larger string how can I use a regular expression to just get the firstname.surname part? Every method i have tried returns the string "User Name:firstname.surname" then I have to do a string replace on "User Name:" to an empty string. Could back references be of use here? Edit: The longer string could contain "Account Name: firstname.surname" hence why I want to match the "User Name:" part of the string aswell to just get that value.
I like to use named groups: Match m = Regex.Match("User Name:first.sur", @"User Name:(?<name>\w+\.\w+)"); if(m.Success) { string name = m.Groups["name"].Value; } Putting the `?<something>` at the beginning of a group in parentheses (e.g. `(?<something>...)`) allows you to get the value from the match using `something` as a key (e.g. from `m.Groups["something"].Value`) If you didn't want to go to the trouble of naming your groups, you could say Match m = Regex.Match("User Name:first.sur", @"User Name:(\w+\.\w+)"); if(m.Success) { string name = m.Groups[1].Value; } and just get the first thing that matches. (Note that the first parenthesized group is at index `1`; the whole expression that matches is at index `0`)
stackexchange-stackoverflow
{ "answer_score": 41, "question_score": 25, "tags": "c#, regex" }
Display custID for customers who ordered the exact book > 1 The goal is to find customers who ordered the same book > 1 on an order. For example: order_id |order_line |book_id | quantity | order_price --------- ----------- -------- --------- ----------- 33034 1 1619 10 $35 33034 2 1619 5 $16 Is this correct? SELECT distinct cust_id ,(SELECT cust_name_last FROM bkorders.customers AS CS WHERE CS.cust_id = OH.cust_id) AS cust_name_last FROM bkorders.order_headers AS OH WHERE EXISTS (SELECT 1 FROM bkorders.order_details AS OD WHERE order_id > 1 AND OD.order_id = OH.order_id HAVING COUNT(distinct order_line) > 1) I have attached a screenshot of the three tables I am using. !enter image description here Edit: We are only to use subqueries for this task
try this: SELECT distinct cust_id ,(SELECT cust_name_last FROM bkorders.customers AS CS WHERE CS.cust_id = OH.cust_id) AS cust_name_last FROM bkorders.order_headers AS OH WHERE EXISTS (SELECT 1 FROM bkorders.order_details OD WHERE OD.order_id = OH.order_id GROUP BY order_id, book_id HAVING count(*)>1)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server 2008, tsql" }
PHP: Does xmlrpc_encode_request() need allow_url_fopen? How does PHP's function xmlrpc_encode_request() work? Does it need the value of allow_url_fopen set to true? Well, you access external URLs with this function, so does it need this configuration? I can't test it myself at the moment, unfortunately. Thanks in advance!
No, it does not. This function is just for marshalling the requested function name and its parameters. It builds an XML string. Therefore it does not need to retrieve external URLs itself. So this function in itself is not particular useful. Later on you will need to send the XML-encoded RPC request over an HTTP stream. And in this step 2, you need either allow_url_fopen, the curl extension, or the pecl http functions. Most XML-RPC libraries however provide a means to transmit the RPC request in HTTP via PHPs native socket functions. So in essence, allow_url_fopen is not required.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, file, url, xml rpc" }
Thymeleaf doesn't render variables within messages in some locales I have a text for a key in my `messages.properties` file with variables in it: some.key=You'll need to pay {0} {1} in order to continue. and I have it in both locales that my application supports: `messages.properties` for English, and `messages_tr.properties` for Turkish (the default `Locale`). So this works when I render the page with Turkish locale: and I get: Some Turkish words 10 USD some other Turkish words. So, `{0} {1}` gets replaced with the amount and currency. But it doesn't when I render the page in English: You'll need to pay {0} {1} in order to continue. What am I doing wrong? Thanks.
Looks like the problem is in the single quote. From here: > The single quote is used to represent a section within the message pattern that will not be formatted. A single quote itself must be escaped by using two single quotes ('') So your message in messages.properties should be: `You''ll need to pay {0} {1} in order to continue.`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "spring, spring boot, thymeleaf, locale" }
union of different vectors at each iteration in matlab Pseudocode: for each iteration i select n vectors from a matrix's columns (say:1,5,7 for n=3) based on a rule united=union(mat(:,1),mat(:,5),mat(:,7)) ...do some stuff. Update n based on a rule next i As you can see, my `n` value changes over time. And the vectors which are going to `union()`, change also. I couldn't find any way to get union of vectors which are changes over time. Any solution? Thanks in advance.
Assumed that `n` updates randomly any you want to extract `n` columns randomly so you can use `unique` function to get unique values from those columns. r = 5; c = 7; mat= rand(r,c); for i = 1:10 %update n randomly n = randi(c); %generate indexes of n columns randomly idx = randperm(c,n); %set union of selected columns united = unique(mat(:,idx)); end
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "matlab, union" }
Is this a linear transformation? in the context of group representations > Let $G$ be a group. A regular representation is given as $V=\mathbb{C}[G]$, a vector space, where $l: G \to GL(V)$ be the action is given by $l(g)(\alpha)(h) = \alpha (g^{-1}h)$ for all $g,h\in G, \alpha \in V$. The professor asked us to find a trivial sup-representation for the sub-representation $U=\\{ \alpha \in V | \sum_{g\in G}{\alpha(g) = 0}\\}$. What I did, is define a trivial linear transformation $\pi_0 : V\to U$ (and here is my question, is this really a linear transformation from $V$ to $U$?) $\pi_0(v) = 0$ if $v \notin U$ and $\pi_0(v) = v$ if $v \in U$, and then normalized it.
No, $\pi_0$ is not linear (unless $G$ is trivial so $U=0$ and $\pi_0=0$). For instance, let $u\in U$ and $v\in V\setminus U$ be any two nonzero vectors. Then $u+v\not\in U$ (otherwise $v=(u+v)-u$ would be in $U$), so $\pi_0(u+v)=0\neq u=\pi_0(u)+\pi_0(v)$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "linear algebra, abstract algebra, group theory, representation theory" }
To document house rules, or no? Or, how much documentation should your "campaign world" provide? This is a fairly generic (and subjective) question, but there is a genuine purpose behind it: I have a set of "house rules" for Tales from the Floating Vagabond, which I've documented fairly well. However, for the group which will be adventuring in it (initially designed as a one-off), I've taken the liberty of adding items, shticks, skills and rules from other TF2V supplements which were released after the core set. The "House Rules" and "Errata" portions of the document are about 5.5 pages long. The new stuff, shticks, skills and optional rules are over 15 pages long and counting (likely to be about 20 - 23 by the time I'm done). How much is enough? How much is "too much?" Should house rules or campaign setting even be documented at all?
Documentation for house rules is not only important, it's convenient. Remembering everything is hard, and having to repeatedly explain/rediscover things takes more effort then writing it down and making it available for everyone. As for the level of documentation, I've found that minimalism works best. Everyone knows the context, and you don't have to explain terminology. Official system documentation has to be very elaborative because it's written for people who might not have any relevant background. Your house rules are only written for a small group of people who you already know. A summary is easier for you to write, and easier for them to read.
stackexchange-rpg
{ "answer_score": 21, "question_score": 17, "tags": "house rules, campaign development, organization, tales from the floating vagabond" }
IF - condition with char comparison not working in C **I really don't know what's the mistake. It seems to be right, doesn't it?** #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char op; printf("Type in operator (+,-,/,*):"); scanf("%i",&op); if(op == '+') { printf("You entered a plus"); } system("pause"); return 0; } I expected it to print "You entered a plus" when entering a +. It does not. _I'm kinda new to C. Thanks in advance :)_
The `if` condition is fine. The problem is the `scanf()` format, which should be scanf("%c",&op); (`%i` reads an integer whereas `%c` reads a `char`.)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "c" }
how to set firebase cloud firestore security rules with firebase authentication I have created a database cloud firestore. In this database I want anyone to be able to read and write `if: request.auth.uid != null` now an facing a permission problem when someone is trying to login or sign up using email and password with firebase authentication. I get insufficient permission. How can I let any of my users sign up and login at the same time protect the other part of the database
This rule should be good enough. service cloud.firestore { match /databases/{database}/documents { match /YOUR_COLLECTION_NAME/{doc} { allow write, read: request.auth.uid != null } } } But are you sure you are setting your authentication properly? Check Authentication -> Sign-in Method and make sure you enable the providers you need. Using the Firebase sdk for auth you will be able to pass this validation after you log in your user. Take a look a this
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "firebase, firebase authentication, google cloud firestore, firebase security" }
How to create initial zoom on Plotly express bar chart? (categorical) I have a categorical axis in plotly express, it contains around 100 different categories. What I want to do is that when I create it, it will be zoomed only on the first 10 categories and then the user will be able to zoom out using the plotly controls. how can I do that?
Set the x range but treat each category as an integer starting at 0. import plotly.express as px df = px.data.iris() fig = px.bar(df, x = 'species', y = 'sepal_length', range_x = [-0.5, 1.5], barmode = 'overlay', )
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, plotly, plotly dash" }
How to get rid of \ character inside a JSON key (java) Before you downvote, the problem stands as it is. I am making something for my customer and I must meet his requirements, even if they don't comply with the best practices. I am sure you have been in that situation sometime, and you understand. I am populating a JSONObject in Eclipse (an android app): jtappedRow="{"label":"red","key":"3"}"; jactionresult.put("value",jtappedRow); jactionresult.put( bla bla bla..... ) but when, print jactionresult on a LOG, like this: Log.e(tag,"TAP THIS TO ENGINE!: "+jactionresult.toString()); I get this: TAP THIS TO ENGINE!: {"value":"{\"label\":\"green\",\"key\":\"1\"}","result":"success","action":"displayClickableList"} How to I get rid of those \ characters??? The result I need is exactly this: TAP THIS TO ENGINE!: {"value":"`{"label":"green","key":"1"}","result":"success","action":"displayClickableList"}`
Assuming that you have the String you posted, you can use `String#replace`: String res = jsonStr.replace("\\\"", "\"");
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "java, android, json, eclipse, escaping" }
Will JVM always create instance of Object class suppose with the following code, does JVM always create instance of Object class, since Object is parent for all the classes the in Java. class MyTestclass{ void printMe(String name){ System.out.println('I am '+name); } public static void main(String args[]){ MyTestclass obj = new MyTestclass(); obj.printMe("stackOverFlow.com"); } } Another class say TestClass2 class TestClass2{ void printMe(String name){ System.out.println('I am '+name); } public static void main(String args[]){ MyTestclass obj = new MyTestclass(); TestClass2 obj2 = new TestClass2(); obj.printMe("stackOverFlow.com"); obj2.printMe("stackOverFlow.com"); } } Will JVM creates two object instances if i run these two classes?
No. There is only one object created and all the memory allocated in the name of Child, even for the field inherited from Parent. > does JVM always create instance of Object class, since Object is parent for all the classes the in Java. No. But instead JVM calls the parent constructors until it reaches the top most Object constructor which calls as constructor chaining.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, jvm, classloader" }
add a class when div over another div I have this jquery code that adds a class to a div(#menu) after the user scrolled that far on a page. But I am searching for a way to change that code into adding that class when the div(#menu) is on top of another div with the class(.remove) and remove the class again when it's on a div with the class(.add). Here is my code: jQuery(window).scroll(function(){ var fromTopPx = 400; // distance to trigger var scrolledFromtop = jQuery(window).scrollTop(); if(scrolledFromtop > fromTopPx){ jQuery('#menu').addClass('scrolled'); }else{ jQuery('#menu').removeClass('scrolled'); } });
You need to find the position of the div that you want to "be on top of". To do that you can use `$('.remove').offset().top;` Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, html" }
Как остановить resizable пишу функцию чтоб при дваном клике на элемент он становиться растягиваемым $(".newElement").on('dblclick', function () { $(this).resizable({containment: "#contener"}); }); здесь все работает, а как сделать чтоб при одинарном клике он прекращал быть растягиваемым? $(".newElement").click(function () { $(this)??????; }); Кто знает как дописать следующию функцию?
$(this).resizable('destroy');
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, javascript, ui" }
Use dynamic programming to find a subset of numbers whose sum is closest to given number M Given a set A of n positive integers a1, a2,... a3 and another positive integer M, I'm going to find a subset of numbers of A whose sum is closest to M. In other words, I'm trying to find a subset A′ of A such that the absolute value |M - Σ a∈A′| is minimized, where [ Σ a∈A′ a ] is the total sum of the numbers of A′. I only need to return the sum of the elements of the solution subset A′ without reporting the actual subset A′. For example, if we have A as {1, 4, 7, 12} and M = 15. Then, the solution subset is A′ = {4, 12}, and thus the algorithm only needs to return 4 + 12 = 16 as the answer. The dynamic programming algorithm for the problem should run in O(nK) time in the worst case, where K is the sum of all numbers of A.
You construct a Dynamic Programming table of size n*K where `D[i][j] = Can you get sum j using the first i elements ?` The recursive relation you can use is: `D[i][j] = D[i-1][j-a[i]] OR D[i-1][j]` This relation can be derived if you consider that ith element can be added or left. Time complexity : O(nK) where K=sum of all elements Lastly you iterate over entire possible sum you can get, i.e. D[n][j] for j=1..K. Which ever is closest to M will be your answer.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "dynamic programming, knapsack problem, subset sum" }
The series $\sum\limits_ {k=1}^{\infty} \frac{1}{(1+kx)^2}$ converges for $x>0$ $$ \sum_ {k=1}^{\infty} \dfrac{1}{(1+kx)^2}$$ $$x\in (0,\infty) $$ This series converges on given interval but how exactly can I show this is true?
$$x>0\implies(1+kx)^2\ge k^2x^2\implies\frac1{(1+kx)^2}\le\frac1{k^2x^2}$$ and now use the comparison test.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "real analysis, sequences and series, convergence divergence" }
Ruby difference in two string arrays and pass to the method I've got following array of strings with nicknames of owners: OWNERS = %w[test1 test2 test3].freeze I want to detect any differences in the list of owners (e.g. when new user was granted owner role). To do so I'm getting list of `current_owners` which represents array of strings: current_owners = %w[test1 test2 test3] How to fetch changes when `current_owners` will be not the same as `OWNERS` and pass this difference to another method? Example: OWNERS = %w[test1 test2 test3].freeze current_owners = %w[test1 test2 test3 newuser test10] I want to pass `'newuser'` and `test10` as a parameter to the method `new_owner_alarm(string)` to be like `new_owner_alarm('newuser')`, `new_owner_alarm('test10')`
(current_owners - OWNERS).each { |new_owner| new_owner_alarm(new_owner) }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, ruby" }
Jsonapi query to return specific field In a simple article content type, is there a way we can have a jsonapi query to return specific field only? The same as how REST export view is doing, we can select what field to be displayed in the output. E.g. ` body field value>` If not, is there a method I can create a list of string then I would want to call a jsonapi to get that list. Thanks in advance!
Yes, with the caveat it still contains the JSONAPI document payload around your requested field. This is mandated by the spec so you can't just have an arbitrary JSON structure that contains **only** the field data you want. This is called a sparse fields query. When you add a `?fields[$RESOURCE_ENTITY]=field1,field2...` to a: * index endpoint (`/jsonapi/node/article`) * resource endpoint (`/jsonapi/node/article/$UUID`) endpoint It will trim down the list of fields to the comma-delimited list you've specified. To use your example, ` will return a JSONAPI document with all `article` nodes with only the `body` property in the `attributes` object. See the JSONAPI docs about fetching resources for more info.
stackexchange-drupal
{ "answer_score": 3, "question_score": 1, "tags": "8" }
inline functions within an inline function for the following function: inline void A() { ... B(); ... } is _B_ also inlined by the compiler? If not, should I make _B_ inline to increase performance?
No, the inline keywords will only cause the A code to be inlined inside the caller code. This will not affect inlining of B. Besides this, in c++, the inline keyword is only a hint to the compiler, which is allowed to ignore it. Modern compilers decide when the functions need to be inlined, even if the keyword is not used.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "c++, inline" }
No visible @interface for 'GIDSignIn' declares the selector 'handleURL: I implemented the delegate method of Google SignIn in objective C. But I am getting the below error `Error - No visible @interface for 'GIDSignIn'` - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *, id> *)options{ return [[GIDSignIn sharedInstance] handleURL:url]; }
replace this and try again once , ref : Google Sign-In quick migration guide [[GIDSignIn sharedInstance] handleURL:url sourceApplication:sourceApplication annotation:annotation]; full answer - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [[GIDSignIn sharedInstance] handleURL:url sourceApplication:sourceApplication annotation:annotation]; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "ios, objective c, gidsignin" }
Any solution to convert .yuv file to h264 file on Mac? I want to develop an app for mac which can record the current screen.But now I have trouble on not knowing how to encode .yuv file I got from CGImage.Somebody told me to encode with x264 or ffmpeg,I am not sure if these are the right choice for OS X development.If anyone has any experience in doing this,I really appreciate that you could tell me.Thanks.
x264 is a great library and I highly recommend it. On mac you also have the option to use the built in encoder. Part of AVFramwork I believe. It should uses less power and CPU then x264, but produce slightly larger files.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "macos, cocoa, yuv, x264" }
Logic behind the two javascript function behaviour Please explain what is the logic behind this two types of behaviour to understand easily. var a = 10; function foo(){ a = 20; } foo(); console.log(a); Prints---> a = 20; var a = 10; function foo(a){ a = 20; } foo(); console.log(a); Prints---> a = 10;
Because of the scope In Javascript, when you assign a parameter in a function you define it in the scope of that function, regardless if a variable already exists with the name in the outer/global scope. Update: It is worth mentioning that with ES6's arrow functions you could still access the outer var if your function was defined in a parent class or function, using the this keyword. Example class Bar { this.a = 10; this.foo = function(a) { this.a = 20; }; this.foo2 = (a) => { this.a = 20; }; } Not exactly the same but it is about scopes
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript" }
Number Of Components in CGColorCreate() if colorspace is Indexed colorspace? I am trying to use CGColorSpaceCreateIndexed() to Create ColorRef. I want to understand rule for passing component array when we use indexed color space. CGColorRef CGColorCreate ( CGColorSpaceRef colorspace, const CGFloat components[] ); Apple doc says, The array should contain n+1 values that correspond to the n color components in the specified color space, followed by the alpha component. unsigned char colorTable[] = {2,120,150,180,200,220,10, 30}; CGColorSpaceRef cs = CGColorSpaceCreateIndexed(CGColorSpaceCreateDeviceCMYK(), 1, colorTable); now, if I create a color using this colorspace, const CGFloat myComponentArray[] = ??; CGColorRef colorref = CGColorCreate (cs, myComponentArray); what should be myComponentArray? Should it depend upon the base colorspace passed in while creating indexed color space?
For an indexed color space, the color has one component, which is the index into the color table: CGFloat myComponentArray[] = { index, alpha }; In your case, the color table has 2 entries, therefore the index must be 0 or 1.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "objective c, macos, cocoa, quartz graphics" }
Delphi 10.2.2 popup position procedure TForm1.Button1Click(Sender: TObject); begin Popup1.Position.X := (Self.Width + Popup1.Width) / 2; Popup1.Position.Y := (Self.Height + Popup1.Height) / 2; Popup1.Popup(False); end; I'm trying to center the popup on the mobile device. Even after setting the Position in code, the popup still appears wherever the user clicks on the button. How do I get the popup to appear centered on the screen? Or wherever I want it to appear?
The documentation was confusing to me but it made it clear that setting the TPopup's position would do nothing. I ended up changing the TPopup's Placement to Center in the designer. Then in the form's FormResize() I added... Popup1.VerticalOffset := Self.Height / 2; Popup1.HorizontalOffset := Self.Width / 2; This works on mobile.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "delphi, popup, firemonkey" }
Htaccess wrong rewriterule overriding correct one I've been facing this issue for quite a while but I've always simply changed the file names, but I can't do that this time I have the following two RewriteRules set: RewriteRule ^register-company register-company.php RewriteRule ^register register.php Same applies for RewriteRule ^register/company register-company.php RewriteRule ^register register.php No matter what I do, change the order, add flags, escape the hypen, it always redirects to register.php and not register-company, as it should (the link being domain.com/register-company) The only thing that actually works is completely changing the name, for example to company-register. Do note that if I remove the register register.php line it works just fine and redirects correctly to register-company.php
Issue that your target URI `register-company.php` also matches next rule's pattern i.e. `^register` hence second rule always executes after first rule. You need to use end anchor in your rules: RewriteRule ^register-company/?$ register-company.php [L,NC] RewriteRule ^register/?$ register.php [L,NC] Now 2nd rule won't trigger because `register-company.php` won't match `^register/?$`. Also `/?$` makes trailing slash optional in both rules.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "apache, .htaccess, mod rewrite, url rewriting" }
How to avoid connection errors to an api in flutter? (breakpoint type appears in VS code) I am purposely causing this error. ![enter image description here]( var response = await http.post(url,headers: {"Content-Type": "application/x-www-form-urlencoded"},body: args); //die here //not continues print(response); I have turned off the execution of my server, so the web request cannot be executed. I want to know how I can control this error, since the application dies at this point. how can I do it?
To catch an exception, you need to wrap the line that causes it with a try/catch block : try { var response = http.post(url); } catch(exception){ print(exception); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "flutter" }
Checking input with an if statement (bash) I am trying to write a file that mimics the cat -n bash command. It is supposed to accept a filename as input and if no input is given print a usage statement. This is what I have so far but I am not sure what I am doing wrong: #!/bin/bash echo "OK" read filename if [ $filename -eq 0 ] then echo "Usage: cat-n.sh file" else cat -n $filename fi
I suggest to use `-z` to check for empty variable `$filename`: if [ -z $filename ] See: `help test`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "bash, if statement, input" }
Limit of parametric definite integral with discontinuity How to find this limit? $$ I = \lim_{t \to 0+0} \int_1^3 \frac{\sin(tx)}{t} \sqrt{x^2 + t^2 + tx + 1} dx $$ The problem is that it is impossible to make the limit transition $$ I = \int_1^3 \lim_{t \to 0+0} \frac{\sin(tx)}{t} \sqrt{x^2 + t^2 + tx + 1} dx, $$ because the integrand function has a discontinuity in $t = 0$, therefore, the previous statement is incorrect, generally speaking.
$$ \frac{\sin(t\,x)}{t}=x\,\frac{\sin(t\,x)}{t\,x}=x\,\text{sinc}(t\,x), $$ and the function $$ \text{sinc}(z)=\begin{cases}\dfrac{\sin z}{z} & z\ne0\\\ 1 & z=0 \end{cases} $$ is continuous.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "integration, limits, definite integrals" }
Does Android have a 2.1GB file size limit? I have tried many voice recording type applications and the best I have found only allows me to do a recording upto a maximum file size of 2.1GB. I can do many of these 2.1GB recordings as I have a fairly large SD card. On one of the applications I have tried, the developer has specifically said that his/her app has no recording length limit So my question, does Android have a built in 2.1GB limit per file?
Short Answer: Yes More Detailed Answer: The file size limit is not something specific to Android, it is a limit of the File System. It may "technically" be a bug in Android though, as FAT32, which is what the file system is for the sdcard, should have a file size limit of 4GB ((2^32)-1 = 4,294,967,295B) but it looks like the filesystem on Android is android is actually using a limit of ((2^31) - 1 = 2,147,483,647B). Which means they could be using signed integers, instead of unsigned integers for the addressing on the filesystem.
stackexchange-android
{ "answer_score": 13, "question_score": 9, "tags": "file system" }
Call either of two different functions based on a variable I have two different functions `cd_0` and `cd_90` which return a floating point variable. I am using `curve_fit` function in which I call either one of these function. I want to call either one of these functions using an `var` value (`cd_<var>`) which can be either 0 or 90. The `var` value is known at the beginning of the program and does not get modified. This being the case, I do not want to introduce a `if` check since it will slow down the optimization function calling these either of two functions. How to achieve this?
cd_func = cd_0 if var == 0 else cd_90 Later, when you want to call the chosen function: my_float = cd_func() Note that a dict will also solve the problem, but you still make a check on every reference. It's faster than your original `if`, but slower than the direct reference of `cd_func`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python" }
python matplotlib histogram specify different colours for different bars I want to colour different bars in a histogram based on which bin they belong to. e.g. in the below example, I want the first 3 bars to be blue, the next 2 to be red, and the rest black (the actual bars and colour is determined by other parts of the code). I can change the colour of all the bars using the color option, but I would like to be able to give a list of colours that are used. import numpy as np import matplotlib.pyplot as plt data = np.random.rand(1000) plt.hist(data,color = 'r')
One way may be similar to approach in other answer: import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() data = np.random.rand(1000) N, bins, patches = ax.hist(data, edgecolor='white', linewidth=1) for i in range(0,3): patches[i].set_facecolor('b') for i in range(3,5): patches[i].set_facecolor('r') for i in range(5, len(patches)): patches[i].set_facecolor('black') plt.show() Result: ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 31, "question_score": 12, "tags": "python, matplotlib, histogram" }
Create HTML spans for spaces in a string Given a string of text, I want to create spans for each group of spaces. How can I do this? **Example** var myString = " foo bar" **Result** <p><span class="spaces"> </span>foo<span class="spaces> </span>bar</p> **What I've tried:** var myString = " foo bar" var $p = $('p'); for (var i = 0; i < myString.length; i++) { if (myString[i] == ' ') { $p.append('<span class="spaces"> </span>'); } else { $p.append(myString[i]); } }
A simple `replace` should do the trick. " foo bar".replace(/(\s+)/g,'<span class="spaces">$1</span>');
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "javascript, jquery" }
Minimum size of spanning tree or seperator Given a graph $G$ on $n$ vertices and vertex subsets $A_1, A_2, ... A_k$, is it always the case that there is either a tree of size at most $\sqrt{n}$ that intersects every $A_i$, or a set $S$ of size at most $\sqrt{n}$ which intersects every such tree? (In other words, no connected component of $G-S$ intersects every $A_i$). For the case of $k = 2$, this is implied by Menger's theorem. In fact, creating a larger graph with $k-1$ copies of $G$ and identifing the vertices in $A_i$ on the $i$ and $i+1$th layer shows that the bound is at most $\sqrt{(k-1)n}$. However, I haven't been able to get any better than that. Does anyone know if this is true, or if this is unknown, what approaches I could take? I've tried searching online, but I haven't been able to find anything that helps.
Unfortunately, it turns out the answer is no. For example, a $k-1$ dimensional simplex grid with sides of length $x$ has ${x+k-2}\choose{k-1}$ vertices with a minimum spanning tree of size $x$ and a minimum seperating set of size ${x+k-3}\choose{k-2}$. The product of these is approximately $(k-1)n$, meaning that the trivial bound is also tight. In particular, for $k=3$, it is impossible to do better than $\sqrt{2n} - \frac{1}{2}$.
stackexchange-math
{ "answer_score": 1, "question_score": 4, "tags": "graph theory" }
Codeigniter DB with slug I'm in trouble when trying to get DB data passing **slug** in URL. public function news($slug = "") { $query = $this->db->get_where('news', array("slug", $slug)); $row = $query->row_array(); } If i try to 'echo' information, e.g `echo $row["message"];` I see blank page. =/ What I'm doing wrong?
$query = $this->db->get('news', array("slug", $slug))->row_array(); or $query = $this->db->where( "slug", $slug)->get('news')->row_array(); var_dump($query);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, codeigniter" }
Not getting BOUNDARY from the header while using postman to upload a file in asp.net core I am trying to send a file using postman to upload it on a webservice using asp.net core. ![enter image description here]( ![enter image description here]( Now, the generated snippet from postman looks like this after the request ![enter image description here]( and in my controller method request.ContentType.Value is null ![enter image description here]( What am I doing wrong?
Remove the content-type header you added manually and instead select form-data in POST request > Body
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, http, postman, asp.net core webapi" }
GameTime is always 0 - MonoGame (XNA) - C# Currently, my sprites loop at the same speed that MonoGame loops through it's code. I want to slow this process down by creating a delay using GameTime. It never worked, however, so I decided that I would use debug.WriteLine() to check if GameTime updated. It didn't, ever. abstract class Entity { protected GameTime _gameTime; public TimeSpan timer { get; set; } public Entity() { _gameTime = new GameTime(); timer = _gameTime.TotalGameTime; } public void UpdateTimer() { timer += _gameTime.TotalGameTime; Debug.WriteLine("Timer: " + timer.Milliseconds); } } UpdateTimer() runs continously in the game loop, but always writes "0" in the debug output. What am I doing wrong? Or is there a better way to do this?
Your `_gameTime` is `0` because it is just initalized, thats it. Your Game class (which inherits from `Game`) got an Update method, with the parameter type `GameTime`. This parameter is your current frametime. So your `UpdateTimer` should have also an `GameTime` parameter and should be called in your `Game.Update` public void UpdateTimer(GameTime gameTime) { timer += gameTime.ElapsedGameTime; Debug.WriteLine("Timer: " + timer.TotalMilliseconds); }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, xna, monogame, xna 4.0" }
Find UTC time zone using offset I find rawoffset from google API(< Now i want to find UTC timezone not UTC time. For example: I have New York City rawoffset and Wana to result UTC-5:00. It is possible in php or javacript?
You can use moment-timezone. Then you can use like this to get timezone moment.tz([2012, 0], 'America/Denver').format('Z z'); It will results -> -07:00 MST
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, php" }
Disable show response document in hierarchy for browser I have a view of lotus notes and web browser. I have enabled show response documents and both notes and web browser showing response documents. Notes are for Admin view while web browser for employee view. So I want to create Admin can view all response document on notes but the employee cannot view response document on a web browser. Below here my view for notes. ![Lotus]( Below here my view for a web browser. ![web]( My question is, can I disable show response document just for a web browser? It means, my notes still showing response document but my browser will not showing response document. Thanks for any help!
You can create two views: one for Notes users (hidden for web users ) and response hierarchy disabled and vice versa one for the web users which is hidden for notes Users with response hierarchy enabled.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "lotus notes, lotus domino, lotus, domino designer eclipse" }
Asp.net Compressing pages problem I have some pages in my web application that use Ms Ajax (update panel,script manager,...).when I want to add compressing module for my application I get this error : ASP.NET Ajax client-side framework failed to load. I searched in the internet and found that compressing has conflict with ms ajax. Is there any way to solve that? If I use IIS 7.x can I use compressing with that pages? thanks
You can disable compression by folder or mime type in IIS 7. To disable compression for a single folder, browser to that folder in IIS, click Compression in the right pane and uncheck the checkmarks for Compress Static Content and Compress Dynamic Content. This answer will show you how to enable/disable mime types at the server level if you wish to go that route.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, iis, c# 4.0, iis 7, compression" }
Why a 200 MB text file overloads 4gB ram I wrote a simple program in c++ that does some calculations, outputs a number to a textfile, and repeats. Several million times. The final text file was around 215 megabytes, yet when I opened it, gedit took over 5 minutes to open all of it, and I went over my 4 Gb of ram and into the linux swap. Why does this happen when the original file size is only 200 MB?
Searching around on Google, `gedit` seems to handle large files very badly * < * < I would try opening the files in something like `less` `vim` by default does not behave as well as I thought it did on large files, if you want to use `vim` you should use something like <
stackexchange-superuser
{ "answer_score": 4, "question_score": 3, "tags": "memory, c++, textfiles" }
How to add List to SharePoint from Console App? I am trying to add List to a site via console App. Here is what I have so far. namespace spConsole { class Program { static void Main(string[] args) { using (SPSite site = new SPSite(" { SPWebCollection webcoll = site.AllWebs; SPWeb web = webcoll["SubSite1"]; SPList newList = web.Lists.Add("New List", "Description", SPListTemplateType.GenericList); } } } } I am getting the following error: Cannot implicitly convert type 'System.Guid' to 'Microsoft.SharePoint.SPList' Can some one please tell me what I am doing wrong?
You have not created the instance of SPSite Please follow this link to create new list programatically < OR <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sharepoint, console application" }
ActivitySceneTransitionBasicSample setViewName has anyone compiled ActivitySceneTransitionBasicSample project, this is a error"cannot find symbol method setViewName(String)",I can't find this method.
`setViewName` method was removed from the time L-Preview and API 21 were released. It looks like ActivitySceneTransitionBasicSample was setup with L-Preview, but you are using API 21. Check this link to see the change log showing where the method was removed: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android" }
Minimum absolute sum of 2 elements from 2 different lists I am currently stuck on this problem, it is from a very highly competitive contest and so it is highly difficult as well. Below is the statement: There are 2 lists of integers with the same length. Pick an integer from each list and calculate the absolute value of their sum. Return the minimum value for the value. Example: list1 = [1, 2]; list2 = [-2, 3] => result = 0 Explanation : take 2 and -2 Can anyone help? Problem Source: 2008 Vietnamese National Student Competition ("Kì thi học sinh giỏi quốc gia"), question 1 I know that there is a brute force solution, but I got Time Limit Exceed (TLE), which means this MUST be done with less than $O(n^2)$ time complexity.
**An $O(n\log n)$ solution:** Sort the second list. For every element of the first, let $e$, find the two elements just smaller and just larger than $-e$, by dichotomic search. Then keep the smallest absolute sum. It is possible that one of the two elements does not exist. E.g. $-7,-3,4, 6$ vs. $-2,-1,4,9$. $\begin{align}-7&\to4<7<9&\to2\\\\-3&\to-1<3<4&\to1\\\4&\to.<-4<-2&\to2\\\6&\to .<-6<-2&\to4\end{align}$
stackexchange-cs
{ "answer_score": 2, "question_score": -1, "tags": "algorithms, arrays" }
What would I call a "do not buy from" list? I would prefer not to use _nigralisto_ , which I assume but cannot confirm is the Esperanto term for 'blacklist'.
Mi proponas _bojkotlisto_. Bojkoto estas bona esperanto vorto kaj internacia komprenebla.
stackexchange-esperanto
{ "answer_score": 12, "question_score": 6, "tags": "translation" }
How to enforce maps of the same order using spock framework The following test passes while I actually would like to see it fail. The order is important for my use case. However I thought groovy is always using linked lists so ordering should be testable. def "test foo"() { given: def a = [a: 1, c: 3, b: 2] when: def b = [a: 1, b: 2, c: 3] then: a == b }
If you want to test order of keys in those two `LinkedHashMap` instances you can do the following: def "test foo"() { given: def a = [a: 1, c: 3, b: 2] when: def b = [a: 1, b: 2, c: 3] then: "make sure maps are equal" a == b and: "make sure entries are defined in the same order" a.collect { it.key } == b.collect { it.key } } `LinkedHashMap` does not override `equals` method (it uses the one defined in `AbstractMap` class, the same one used by e.g. `HashMap`) and it only defines order of the iteration (order in which entries are added to the map). Both assertions can be simplified to a single: def "test foo"() { given: def a = [a: 1, c: 3, b: 2] when: def b = [a: 1, b: 2, c: 3] then: "compare ordered list of map entries" a.collect { it } == b.collect { it } }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "groovy, spock" }
Android - Calculate deciBel from sound volume Is it possible to calculate the decibel value from the sound volume level? Suppose a sound is playing, (it could be any track, but I'm using a generated sound with AudioTrack). While the sound is playing, the volume of the sound is increased from 0 (mute) to 99 (maximum). Now I want to retrieve the decibel value, when the volume level is 50, for example. Is it possible? I found how to calculate decibel value in this thread: Calculate Decibel from amplitude - Android media recorder power_db = 20 * log10(amp / amp_ref); but here it uses the amplitude, not sound volume.
For your calculations, you can probably assume that more amplitude = more volume. They're very closely related: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "java, android, audio, android emulator, android ndk" }
CSS media query on iPhone I'm trying to use a CSS media query, specifically targeting the iPhone. It works when I use a regular link rel: <link rel="stylesheet" type="text/css" href="css/mobile.css" /> However, when I try this media query it doesn't work: <link rel="stylesheet" type="text/css" href="css/mobile.css" media="only screen and (max-width: 640px)" /> How can I use a CSS media query to target the iPhone?
Try: <link rel="stylesheet" type="text/css" href="css/mobile.css" media="only screen and (max-device-width: 480px)" /> The difference is `max-device-width` instead of just `max-width`. Also see 2) on <
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 7, "tags": "iphone, css, mobile safari, media queries" }
How do you run Google Test through the command line? I have a sample project with Google Test up and running. I have a simple test class that looks like: #include <gtest/gtest.h> TEST(FirstTest, TestNumberOne){ EXPECT_NE(2, 1); } This is in a directory on my computer at /home/dave/Desktop/sandbox/black-test/src/code/Tester.cpp I'm working in Eclipse with Ubuntu. The test class runs fine out of Eclipse (right click, run as C++). But I can't find documentation on how to run via the command prompt? Secondarily, do most people who do unit testing for C++ keep their test project separate from their production code or coupled (like most Java projects)?
Inside your test program, you will have a `main()` function which looks something like this: int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } This allows you to invoke the test program like any other: just type the name of the executable in a shell. Depending on how you have things organised, you could have multiple c++ source files containing tests which are linked together, in which case there should be only one main function. Google test provides command line options to specify which tests to execute. The wiki has lots of info on this. I personally prefer to keep tests in a separate directory tree but it is really up to personal preference.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 9, "tags": "c++" }
How to return HTML directly from a Rails controller? One of my model objects has a 'text' column that contains the full HTML of a web page. I'd like to write a controller action that simply returns this HTML directly from the controller rather than passing it through the .erb templates like the rest of the actions on the controller. My first thought was to pull this action into a new controller and make a custom .erb template with an empty layout, and just `<%= modelObject.htmlContent %>` in the template - but I wondered if there were a better way to do this in Rails.
In your controller `respond_to` block, you can use: render :text => @model_object.html_content or: render :inline => "<%= @model_object.html_content %>" So, something like: def show @model_object = ModelObject.find(params[:id]) respond_to do |format| format.html { render :text => @model_object.html_content } end end
stackexchange-stackoverflow
{ "answer_score": 107, "question_score": 79, "tags": "ruby on rails" }
Bitbake: How to only fetch the sources? There is a project in which we use project yocto, and our metas fetch source from some remote git repositories. The problem is that these repositories are only accessible in some particular situations/specific times. Therefore, I need a way to fetch the repos (when they are available), as to have them locally, but not build anything at that time. Is this possible?
Starting from Yocto 2.5, it has changed: bitbake <target> --runall=fetch Previously it was: bitbake <target> -c fetchall Bitbake Usage-and-syntax
stackexchange-stackoverflow
{ "answer_score": 19, "question_score": 9, "tags": "yocto, bitbake" }
Why do .ftl file are exactly same have different file size? I have two ftl files that are exactly same (in terms of the content of the file and file name) but differ by quite a margin on file size. One file is 9502 bytes while the other is 9647 kbps. The only difference I can see is the files are located in different folders. I don't know why there is such a small difference. Is there some sort of history or something that is stored with the file that is not visible to the user? If so, how would you delete this?
If there's no trailing whitespace that's visible just hard to spot, then my guess is that the longer file uses CRLF (Windows convention) for line breaks, while the shorter uses LF (UN*X convention). Some text editors, like Notepad++, has modes that show that. And it's not a FreeMarker thing, it's just a text file thing. There's no hidden history or hidden anything that's FreeMarker-specific.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "freemarker, filesize" }
Using jQuery or just plain Javascript is it possible to change to a custom cursor? I know it is possible to use jQuery to do something like: $('body').css('cursor','wait'); What I want to know is: is it possible to change the cursor to a custom loading animation, such as a simple 'spinner' gif? Many thanks in advance.
You are just manipulating CSS on the fly here. See the spec — URIs are acceptable. Browser support is variable. I haven't tried it in years, but last time I did Internet Explorer required the cursors to be in .cur format. That said, while it is possible, there are a good set of standard cursors that users **recognise**. It is rare that you will have thing usefully represented by a cursor that isn't covered by the standard list, and when that list does cover things it should be used so users don't have to learn a new icon.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, jquery" }
Mac OS X - Problems with file permission into NTFS usb drive I can read/write files within an NTFS external USB drive. I have some problems with large files like AVI/MKV stored on an NTFS external drive. Those files appears greyed into Finder and, always using Finder, when I "Open With" my video player I receive a strange error: > Item “file.avi” is used by Mac OS X and cannot be opened. Well, I found a workaround: if I drag & drop `file.avi` into my video player everything works fine. But really I cannot figure out why this problem appears. Please consider I haven't any NTFS custom drivers installed (i.e. MacFUSE or NTFS-3g). To mount my NTFS USB drive in R/W I have modified only `/etc/fstab`, adding the following line: LABEL=WD320 none ntfs rw
I've found a thread that deals with the very same subject. Files appear greyed out and can not be opened with the same error message. Here are the steps to (hopefully) resolve it: * Open a Terminal and run xcode-select --install * The above will install the XCode command line tools * Then, run GetFileInfo /Volumes/WD320/yourfile.avi * There should be information about the file type and creator and other file attributes * Now, change those attributes by calling SetFile -c "" -t "" /Volumes/WD320/yourfile.avi * Now the file should play I obviously couldn't try it (which I'd normally do), but maybe it helps.
stackexchange-superuser
{ "answer_score": 27, "question_score": 10, "tags": "macos, usb, external hard drive, ntfs" }
Grails and Spring Security: How do I get the authenticated user from within a controller? I recently moved from the JSecurity plugin to Spring Security. How do I get the authenticated user from within my controllers?
I'm using 0.5.1 and the following works for me: class EventController { def authenticateService def list = { def user = authenticateService.principal() def username = user?.getUsername() ..... ..... } }
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 12, "tags": "grails" }
Does there exist a bijective differentiable function $f:\mathbb{R^+}\rightarrow \mathbb{R^+}$, whose derivative is not a continuous function? > Does there exist a bijective differentiable function $f:\mathbb{R^+}\rightarrow \mathbb{R^+}$, whose derivative is not a continuous function? $x^2\sin \dfrac{1}{x}$ is a good example for non-continuous derivative function, that will not work here, I guess.
The function $$f(x):=x^2\left(2+\sin{1\over x}\right)+8x\quad(x\ne0), \qquad f(0):=0,$$ is differentiable and strictly increasing for $x\geq-1$, and its derivative is not continuous at $x=0$. Translate the graph of $f$ one unit $\to$ and eight units $\uparrow$, and you have your example.
stackexchange-math
{ "answer_score": 12, "question_score": 7, "tags": "real analysis, derivatives, examples counterexamples" }
How to know if a button is enabled or disabled I have a 2 buttons Previous/Next changing their states if there are more rows to read or not. So they are enabled/or disabled with conditions. Is it possible to read their state? On WFA Here below how I check I look for a better way if (nextbutton.Enabled) NextBtnState = true; else NextBtnState = false; if (prevbutton.Enabled) PrevBtnState = true; else PrevBtnState = false;
if(buttonName.Enabled)// if button is enabled { //do this } else { //do that } As you updated your question, if you want it be more concise you can write, nextbutton.Enabled ? (NextBtnState = true) : (NextBtnState = false);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "c#" }
XPath to select all nodes that have text in them that is different to the text in their child nodes What is the most performant way to select all nodes where the text within that node is different to its child nodes. So let’s say there is a h1 tag with a span within it. I don’t want to capture the H1 tag at all if it as like: `<h1><span>hello</span></h1>` I would only want to catch the span. If it was `<h1><span>Hello</span> World</h1>` I need to capture them separately. So the H1 text would only be World and the span text would be Hello. So far I have tried `//*[normalize-space()]` but that’s gets all the elements which isn’t the desired outcome. Is it possible maybe to to make every element an orphan so the html just becomes a 0-root document where every node is in its own node and has no parent?
Your question isn't entirely clear: what do you want to do with <p><b>Hello</b><i>World</i></p> and with <p><b>Hello</b> <i>World</i></p> ? But I think you're essentially looking for elements that have text node children (or perhaps, non-whitespace text node children) which would be //*[text()] or //*[text()[normalize-space()] respectively
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "php, html, xpath, webdriver" }
FME: Join attributes in text file with attributes in shapefile I have a shapefile with points and different attributes - one attribute `MyID`. I also have a plain text file with several attributes - each in a separated column: MyID MyValue 1 A 2 B 3 C : : I would like to use FME to append my attributes in the text file using the attribute key/value `MyID`. **Is this possible, and in that case how?**
The **Feature Merger** transformer will allow you to Join by attributes !enter image description here Using FME Desktop 2012 SP2 here < Search 'Feature Merger' A good blog post 'Joiner vs Feature Merger' by Mark Ireland <
stackexchange-gis
{ "answer_score": 4, "question_score": 7, "tags": "shapefile, fme, attribute joins, fields attributes" }
Plot multiple lines on subplots with pandas df.plot Is there a way to plot multiple dataframe columns on one plot, with several subplots for the dataframe? E.g. If df has 12 data columns, on subplot 1, plot columns 1-3, subplot 2, columns 4-6, etc. I understand how to use df.plot to have one subplot for each column, but am not sure how to group as specified above. Thanks!
This is an example of how I do it: import pandas as pd import numpy as np import matplotlib.pyplot as plt fig, axes = plt.subplots(1, 2) np.random.seed([3,1415]) df = pd.DataFrame(np.random.randn(100, 6), columns=list('ABCDEF')) df = df.div(100).add(1.01).cumprod() df.iloc[:, :3].plot(ax=axes[0]) df.iloc[:, 3:].plot(ax=axes[1]) ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "python 2.7, pandas, group by" }
Cant login to my sites on AWS but I CAN login with the same database on my local machine I've loaded two different Drupal 7 sites on Amazon Web Services (AWS) Ubuntu instances. They both work fine and are configured mostly correctly. **The only problem i** s, I can't login to either site using my Drupal username/password combinations! (either site). I've double and triple checked my passwords/making sure CAPS LOCK isn't on, etc. I cleared cookies and even tried the permissions suggestion given in this article. No matter what I do when I try to login to either site on AWS I get a silent login fail. No errors, the browser just reloads and prompts me to login again. I know the username/password work because on my local machine for both sites I can login easily using the same database. _Note: I, of course, imported the databases for both projects so they SHOULD have the same user data._ Anyone know what else I can try?
Well, I fixed it. I had to run the following command: sudo a2enmod rewrite
stackexchange-drupal
{ "answer_score": 1, "question_score": 1, "tags": "7" }
LISP программа.Где ошибка в коде? ОС: Windows 7, LISP: Common LISP 2.6.7. Пытаюсь выполнить вот этот код: `(defun summa-digits (n) (if (eq n 0) 0 (+ (rem n 10) (summa-digits (truncate (/ n 10)))) ))` Получаю вот эту ошибку: ![Ошибка](
Он же вам белым по черному пишет "Cannot open the file p1.lsp", в переводе на русский это значит "Не могу открыть файл p1.lsp".
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "lisp, gnu" }
How do I detect that a JComboBox is empty? How do I detect that a JComboBox is empty? Is it something like: `combobox.isEmpty()`
What's wrong with `JComboBox.getItemCount()`? If this method returns `0`, the component is empty.
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 6, "tags": "java, swing, jcombobox" }
How can I display table.column=$variable? Couldn't find an answer myself. My first question here. I try to be as precise as I possibly can. Question: What i want basically is that the number from 'imagedisplay.number' and 'image.number' is a variable. Is this even possible or should i do it differently? What i got: SELECT image.image FROM image INNER JOIN imagedisplay ON imagedisplay.number = image.number What i want: $x = 1 SELECT image.$x FROM image INNER JOIN imagedisplay ON imagedisplay.$x = image.$x
Your Join is right SELECT image.image FROM image INNER JOIN imagedisplay ON imagedisplay.number = image.number As to your comment: _I want to search number 1 in the database_ You just have to add a `where` condition where you filter the results by `$x` respectively `1` SELECT image.image FROM image INNER JOIN imagedisplay ON imagedisplay.number = image.number WHERE image.number = $x But thats not nice, you should use Prepared Statements
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql" }
CodeIgniter's form_hidden How do I achieve this: //view.php <input type="hidden" name="Name" value="<?php echo $variable->id; ?>" using CodeIgniter’s form_hidden helper: //view.php <?php echo form_hidden('Name','<?php echo $variable->id; ?>') ?> The first one works fine when I display $variable->id but CI's form_hidden doesn't work.
The form helpers are evaluated when the script is run, just like any other script, so you do this: `<?php echo form_hidden('Name', $variable->id); ?>` If you have shorttags enabled, you could do: `<?=form_hidden('Name', $variable->id);?>`
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "php, codeigniter" }
How to get page view data like stackoverflow? I want to get and display how many times a page is viewed, just like stackoverflow. How to do it by php? Thanks!
if (file_exists('count_file.txt')) { $fil = fopen('count_file.txt', r); $dat = fread($fil, filesize('count_file.txt')); echo $dat+1; fclose($fil); $fil = fopen('count_file.txt', w); fwrite($fil, $dat+1); } else { $fil = fopen('count_file.txt', w); fwrite($fil, 1); echo '1'; fclose($fil); } ?> For any "decent" counter I would recommend to use a database (mysql, redis ) and trace IP address to have even deeper analytics (e.g how many unique visits, where they are comming from etc)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, pageviews" }
Error Creating Sequence In PostgreSQL I have following PostgreSQL create script CREATE SEQUENCE seq_tbl_ct_yr2_id START (select max(ct_tran_id)+1 tranid from tbl_ct); this doestnt create sequence arising folloeing error: > ERROR: syntax error at or near "(" LINE 1: create sequence test_1 start (select 1) for test purpose i tested following scripts create sequence test start 1 -- this works create sequence test_1 start (select 1) -- this doesnt work how to overcome this ?? Note : `PostgreSQL 9.2`
DO $$ declare start_id int; begin select max(ct_tran_id)+1 from tbl_ct into start_id; execute 'CREATE SEQUENCE seq_tbl_ct_yr2_id START '||start_id||''; end; $$ test using select nextval('seq_tbl_ct_yr2_id') **sql-do**
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "postgresql, sequence" }
mysql passing array into LIKE without loop $serach=array('abc','def','ghi'); $num=count($search); for($n=0, $n<$num, $n++){ $sql .= LIKE % $search[$n] % OR ; } $sql=substr_replace($sql,"",-3);//REMOVE LAST OR SELECT * FROM store_main WHERE name :sql... i need pass an array into query LIKE, i have use loop to create the statement and put into the query, my question is, is any way do it without loop, so i can make my query more simple.
Try $array = array('lastname', 'email', 'phone'); echo "%".str_replace(",","% OR %",implode(",", $array))."%"; **Output** > %lastname% OR %email% OR %phone% Refer implode and str-replace
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, mysql" }
Characterization of linear fractional transformations that maps the unit disc into itself I am reading the paper "ADJOINTS OF COMPOSITION OPERATORS ON HILBERT SPACES OF ANALYTIC FUNCTIONS" by MARIA J. MARTIN AND DRAGAN VUKOTIC. In Section 1.1 they say the linear fractional transformation $\phi(z)=\frac{az+b}{cz+d}$ maps the unit disc into itself if and only if $$|b\overline{d}-a\overline{c}|+|ad-bc|\leq |d|^2-|c|^2 .$$ I can't neither prove it nor see the reference. Could anyone please suggest something. Thanks in advance
You must have $|d|^2-|c|^2>0$ or else there is a pole inside the disk. To get the formula (I remember doing this long time ago, it slowly comes back) there is a little trick, to precompose by a suitable conformal map preserving the disk but making our transformation linear. So define $$ M(z) = \frac{z-\alpha}{1-\bar{\alpha} z} $$ using the value: $\alpha = \bar{c}/\bar{d}$ (modulus <1). Then $M\in {\rm Aut} ({\Bbb D})$ and we get (you should carry out this calculation on a piece of paper): $$ f\circ M(z) = \frac{ b\bar{d}-a \bar{c}}{d\bar{d}-c\bar{c}} + z \frac{d a-cb}{d\bar{d}-c\bar{c}}=q+rz$$ The image of ${\Bbb D}$ is now clearly a disk with center $q$ and radius r. The condition then reads $|q|+r\leq 1$ which translates into the inequality that you stated above.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "complex analysis, mobius transformation" }
Android BottomSheetDialogFragment that does not take whole width How do I make BottomSheetDialogFragment that does not cover entire width of the screen (something like "Share via" sheet in Chrome on tablets)?
Looks like this is not possible right now: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 7, "tags": "android, android layout, android fragments" }
How does the coordinate system work in OpenGL? I'm learning OpenGL and I've been told there are different coordinate systems: one for the model and another one for the application, but I'm not sure when should I use each one. Can someone help me?
The model's coordinate system is used when creating the different objects in a scene. The application's coordinate system is used to represent the entire scene. By multiplying the vertices of an object by the transformation matrix you are placing the object in the scene you want to represent, along with all the other objects. I hope this answers your question.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "opengl" }
Prove that the limit is zero Prove that $\lim_{n \to \infty} \frac {1}{\sqrt n}=0$. Attempy: $\forall \varepsilon>0 $, we have to find $M\in N$ such that $|\frac {1}{\sqrt n}-0|<\varepsilon$ for $n \ge M$. Let $\varepsilon > \frac 1{\sqrt M}$. We can do this since $M \in N$, and note that $n\ge M \rightarrow \sqrt n \ge \sqrt M \rightarrow 1/\sqrt n \le 1/\sqrt M.$ Then, for $n \ge M$, we have that $|\frac {1}{\sqrt n}-0| = |\frac {1}{\sqrt n}| = \frac {1}{\sqrt n}$ (because $n\ge M \in N) = \frac 1{\sqrt M} <\varepsilon$. Therefore, by definition of convergence, $\lim_{n \to \infty} \frac {1}{\sqrt n}=0$. This is an assignment question, and marking criteria is quite strict. So, could you pick any minor mistake? Thank you in advance.
Almost there. I suggest writing in this way: Given $\epsilon>0$, by Archimedean Principle, we can choose some $M\in{\bf{N}}$ such that $\dfrac{1}{M}<\epsilon^{2}$, then for all $n\geq M$, we have $\sqrt{n}\geq\sqrt{M}$, so $1/\sqrt{n}\leq 1/\sqrt{M}$, and hence $\left|\dfrac{1}{\sqrt{n}}-0\right|\leq\dfrac{1}{\sqrt{M}}<\sqrt{\epsilon^{2}}=\epsilon$.
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "real analysis, limits" }
Spine.js clear model records on fetch There is `refresh` function in Spine.js which has this option: You can pass the option {clear: true} to wipe all the existing records. but let's say i'm implementing pagination and want all records be cleared on every fetch, because now when i fetch next page, then new records are just appended to current recordset and page bloats, wchich is undesirable. Unfortunately `fetch` has no such useful option. So is it possible to achieve similar functionality for `fetch` ?
The approach I would take is to override the default fetch by adding your custom fetch method on your model
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "coffeescript, spine.js" }
Automatically formatting punctuation using biblatex field format Customising a biblatex style, I’d like to use ‘traditional’ typography where the format of punctuation follows that of the preceding text, for example > _J. Organomet. Chem._ **691.** 13 with the full stop after ‘691’ in bold. I'm pretty sure that `biblatex` can do this automatically, but cannot find how to achieve it. From the documentation, `\setpunctfont` seems to be the function I want, but something like \documentclass{article} \usepackage[style=numeric]{biblatex} \DeclareFieldFormat*{volume}{\mkbibbold{#1}\setpunctfont{\textbf}} \bibliography{biblatex-examples} \begin{document} \nocite{*} \printbibliography \end{document} fails (my example text is in ref. 3 in the resulting output). I’d rather not have to code the formatting in by hand, as it make maintenance awkward: how is this supposed to be done?
Re-reading the manual, I find what I'm after is the `punctfont` option: \documentclass{article} \usepackage[style=numeric,punctfont]{biblatex} \DeclareFieldFormat*{volume}{\mkbibbold{#1}} \renewbibmacro*{volume+number+eid}{% \printfield{volume}% \setunit*{\addcomma}% \printfield{number}% \setunit{\addcomma\space}% \printfield{eid}} \bibliography{biblatex-examples} \begin{document} \nocite{*} \printbibliography \end{document}
stackexchange-tex
{ "answer_score": 8, "question_score": 11, "tags": "biblatex, punctuation" }
jQuery, insertBefore, validation, Placement of error message I am using insertBefore under errorplacement to add validation messages, each one below each other as I want the order of the messages to go from top to bottom. I am using a hidden input at the very bottom of a parent element in order to supply an element for the insertBefore argument. **Is there a way to insert from the bottom without using the dummy hidden element?** If I use absolute positioning, there is a possibility for white space, for example 3 stacked messages, the middle one missing since there is no collapsing with absolute positioning. **Update** So if I want to insert before "zzz", is there a way do it without "zzz"? <div> <input id="zzz" type="hidden"> </div>
I tried append and also appendTo. I agree that they should work, and they do, kind of, but in the context of the validation plugin, for some reason, both functions use the parent of the matched element instead of the matched element and append to the wrong element. Also, the validation wrap function stopped working with append. I wound up replacing the dummy element and moved up an element that was in use in its place and stuck with insertBefore. This worked: errorPlacement: function(error, element) { error.insertBefore("#zz") error.wrap("<p>") This didn't - it appended to the parent of #zz and the wrap function didn't work. errorPlacement: function(error, element) { ("#zz").append(error); error.wrap("<p>");
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript, jquery, css, validation, asp.net 2.0" }
SQL - Retrieve closest value DOWN here is my current sql: SELECT * FROM items WHERE trumped = 1 ORDER BY ABS( `value` - 12110433 ) limit 3 This correctly returns the row with the closest value: **12313672**. However, I need to be able to pull the closest lower number value. (The closest number below 12110433) I've tried using methods with `top 1` however this errors for me so I cannot use it. I also need to run this very often and quickly, will it be taxing on my database? Thank you
One way to do it with `union all`. (SELECT * FROM items WHERE trumped = 1 AND `value`>=12110433 ORDER BY `value`-12110433 limit 1) UNION ALL (SELECT * FROM items WHERE trumped = 1 AND `value`<12110433 ORDER BY 12110433-`value` limit 1) If you are using MariaDB versions 10.2 and later, this can be achieved with `row_number` function. select * from (select i.*, row_number() over(order by case when 12110433-`value`<0 then 1 else 0 end,`value`) as rnum_above, row_number() over(order by case when 12110433-`value`>0 then 1 else 0 end,`value`) as rnum_below from items i ) t where 1 in (rnum_below,rnum_above)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, mariadb" }
How to add a constraint on all the columns of a table in a single query? I have a database named dbapp. I need to add the constraint 'NOT NULL' to all the columns of all the tables in this database. I am unable to form this query. Even if I am able to perform it individually on each table, it would be fine. Please help.
It is not a trivial task. But you may try - * Read information from `information_schema.columns` table * Generate ALTER TABLE statements for each table Note, that you should take into consideration all field properties, not only NULL/NOT NULL. Another variant is to edit fields one by one, using one of the MySQL GUI tools.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, database, constraints, unique" }
Если множественного наследования не существует, то это что? Является ли это множественным наследованием? Если нет, то что это? Странный синтаксис, я до этого с таким не сталкивался. public class DbSet<TEntity> : DbQuery<TEntity>, IDbSet<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>, IEnumerable, IQueryable, IInternalSetAdapter where TEntity : class
Наследование, действительно, может быть только от одного базового класса, в вашем случае это `DbQuery`. Все остальные аргументы в списке это интерфейсы, которые обязан реализовывать класс, их может быть сколько угодно. В именовании интерфейсов принято в начале приписывать заглавную букву I и на вашем примере вы можете убедиться в полезности такой практики - в описании класса сразу видно что есть что.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, entity framework" }
Write string to a stream using utf16 encoding My code: public static void DoStrumienia (string pString, Stream pStream) { if (pStream == null) throw new ArgumentNullException (); BinaryWriter bw = new BinaryWriter (pStream); int rozmiar = pString.Length; bw.Write (rozmiar); for (int i = 0; i < rozmiar; i++) { bw.Write (pString[i]); } bw.Flush (); } It writes string to a stream, but it writes using UTF8 encoding. How to it with UTF16?
System.Text.Encoding encoding = System.Text.Encoding.Unicode; BinaryWriter bw = new BinaryWriter (pStream, encoding); See here.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 1, "tags": "c#, string, utf 8, stream" }
Read document from AngularFireStore i'm so new in firebase, so i need some very basic help. I have collection "Users" in firestore, whene i have documents with key (user id) and every document have some fields. ![enter image description here]( In my component i have variable `userData: Observable<any[]>` After user login i want find his id in documents and get his info to userData variable. ... .then(user => { this.authState = user; // Here i want get user data and set it to my variable this.userData = this.afs.collection('Users').document(user.uid); this.router.navigate(['/']); }) But obviously, this is does not work. I will be gratfull for any help or tips with my question, thanks&
Rather than doing all of this in the `.then` after the login Promise; map the `AngularFireAuth`'s `authState` observable in your `init`. this.userData = this.afAuth.authState .switchMap { user => user ? this.afs.document("Users/${user.uid}").valueChanges() : of(null) } So now that we have an Observable of the current user's data over time or null.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "typescript, firebase, google cloud firestore, angularfire2" }
how to use asp.net Identity 2.0 with old database I saw a lot toturial about asp.net Identity 2.0 with esixting database, but they still use the same table name(AspNetUsers) and column name, and some of column I don't wanna use, so I just want to implement IUser, I don't need to inherit the IdentityUser, and I just need 3 table (User, Roles, UserRole). how do I use the asp.net Identity 2.0 with the old customized database
It's certainly possible. There are basically two options if you are using Entity Framework for your existing database. 1. Provide your own mapping to the built in classes, by using your own `OnModelCreating` override on the DB Context. 2. Provide an own storage for ASP.NET Identity by implementing `IUserStore`, `IRoleStore` and `IUserRoleStore` in one storage class. This way you can map to existing classes in your data model. If you are using another DB access than EF Code First you have to use option 2
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "asp.net, asp.net mvc, asp.net mvc 5, asp.net identity" }
Git: How to reuse commit rev across commit --amend? My release file's name depends on `commit=$(git rev-parse --short HEAD)`, and I want to put the release file to my git repo. When do some amend commit, the `$commit` changed, is it possible to reuse the `$commit` after `git commit --amend`?
No, it's not possible. Here are some of the things that goes into the sha-1, the value returned by `git rev-parse --short` and that will cause the sha-1 to change: * Name of author * Date of commit * Commit message * List of parents and, most important * **the sha-1 of all the files and directories in the repository**. Adding even a space character to one of the files will make it impossible to get the same sha-1 again.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "git" }
SFML Vector2 usage In SFML, I understand `Vector2`s as pair or points. There are: sf::Vector2f float sf::Vector2i int(signed) sf::Vector2u unsigned int Am I correct? What about `long int`s and `long long int`s and `double`s and `long double`s? I think there is only these three kinds of `Vector2`s. I don't need to use it anywhere, but I'm just wondering. Thanks.
From the doc : > You generally don't have to care about the templated form (`sf::Vector2<T>`), the most common specializations have special typedefs: > > `sf::Vector2<float>` is `sf::Vector2f` > > `sf::Vector2<int>` is `sf::Vector2i` > > `sf::Vector2<unsigned int>` is `sf::Vector2u` You can use `sf::Vector<T>` instead of `sf::Vector2f`/`sf::Vector2i`/`sf::Vector2u` if you want to specialize it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c++, vector, sfml" }
AVURLAsset can't get mp3 duration in documents directory, but it works well with mp3 in app bundle I have two mp3 files. One is in app bundle, the other is in user's Documents directory. I want to get the duration of mp3 file. AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:newPath] options:nil]; [audioAsset loadValuesAsynchronouslyForKeys:@[@"duration"] completionHandler:^{ CMTime audioDuration = audioAsset.duration; float audioDurationSeconds = CMTimeGetSeconds(audioDuration); NSLog(@"duration:%f",audioDurationSeconds); }]; Those codes work well with the mp3 file in app bundle, but it doesn't work with the mp3 in Documents directory which only log "duration:0.000000". Why?
The following is a way to compose a path associated to the mp3 file in document directory. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Professor_and_the_Plant.mp3"]; NSURL *mp3_url = [[NSURL alloc] initFileURLWithPath:path];
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, avfoundation" }