INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Pyschool: Topic 1 I am new to Python and i jumped right into python 3. However i am trying to use the learning practices from pyschools.com. I have run into a question that deals with using strings. They want this result: `"No, thanks, Mom," I said, "I don't know how long it will take."`. In Python 3 I can just type this out literal using the `"""` before and after. however in Python 2 that same line comes out as `\'"No, thanks, Mom," I said, "I don\'t know how long it will take."\'`. How do I format this correctly?
There is no problem; your python interpreter is echoing the string back to you in a manner that can be pasted back into the interpreter. Use `print()` instead if you want to just print the string value instead of the string literal: >>> '''"No, thanks, Mom," I said, "I don't know how long it will take."''' '"No, thanks, Mom," I said, "I don\'t know how long it will take."' >>> print('''"No, thanks, Mom," I said, "I don't know how long it will take."''') "No, thanks, Mom," I said, "I don't know how long it will take." Note that there is no difference between python versions in that regard; python 3 behaves in exactly the same manner.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, python 2.7" }
TYPO3 extbase - fluid variable to jquery How could one pass a fluid variable from the controller to jQuery or JavaScript? Inside my controller: public function tabs () { $this->view->assign('tab', 1); } Inside fluid I'd use the variable as {tab} But how can I pass to JavaScript? Any help would be appreciated...
JS in fluid templates behaviour is ... terrible in most cases, if your JS code contains any curly brackets you need to include external script instead placing the script in the view. The reason is that Fluid thinks, that all curly brackets belongs to its scope, so when you write: $('#mySelectBox').change(function() { // functions body code // next line // next line }); Fluid destroys the JS and renders it as just: $('#mySelectBox').change(function() Array); Then most often I use something like this: _in the view:_ <script>var TxMyExtKeyTabNumber = {tab}</script> <script src="path/to/static/script.js"></script> _in script.js:_ $("#container").val(TxMyExtKeyTabNumber);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "jquery, typo3, fluid, extbase" }
SQL Passing a List<int> as a SqlCommand Parameter can i pass a List into a SqlCommand as a paramter? DELETE FROM MyTable WHERE Key IN @MyParam command.Parameters.AddValue("MyParam",MyList); i realize i could just loop over the list but i was looking for a cleaner solution.
No, you can't in the current form There are several options using UDFs or XML or dynamic SQL to pass in lists. The most comprehensive article on how to do this is "Arrays and Lists in SQL Server 2005 and Beyond" by Erland Sommarskog
stackexchange-serverfault
{ "answer_score": 2, "question_score": 0, "tags": "sql server, sql, tsql, csv" }
Location getAccuracy() what this function do? I know that this function returns a float indicating the accuracy of a particular location. My question is: Is it right that greater the value returned by this function means more accurate the location is? Or it is the inverse what I am saying ?
The lower the number, the more accurate it is.
stackexchange-stackoverflow
{ "answer_score": 35, "question_score": 23, "tags": "android, location" }
A Java and PHP application Is it possible to build a Java web application which has a PHP front end ? I want all my web pages to be coded in PHP. Most of them will be forms. I want all the data submitted by a form to go to a Java Code. I want to do all manipulation in back end and all rendering of web content on the front end. This is just a general question as I was probing for different options for my java web application.
According to your edition, it looks like you don't need PHP at all. You confused it with HTML.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, php" }
Fast switch input source via CapsLock button in Ubuntu 17.10 I updated my Ubuntu version to 17.10 and I want to configure switching to next input source via CapsLock button. I tried to set CaspLock in keyboard setting, but I cant because nothing happening. I did actions explained here How to switch input language on Caps Lock in Ubuntu 15.10 Gnome 3.16 and it works, but now when I switching input source I see a pop-up (like as pop-up that shows switching application windows) and must wait a few seconds until it disappears. How I can resolve my problem?
By trial and (a lot of) error, this works for me (I'm not sure whether the first three steps are required). 1. Open `Settings` (the default system setting app). 2. Go to `Devices -> Keyboard` and press `Reset All...`. 3. Close the `Settings` app. 4. Install `gnome-tweak-tool` and open it. 5. Go to `Keyboard & Mouse -> Additional Layout Options` 6. Seek for `Switching to another layout` and unchecked every options under that setting. 7. Restart the `Tweaks` app. 8. Repeat step 5-6 again, only this time make sure you check the one and only `Caps Lock` option. 9. Close the `Tweaks` app, now you should use the caps lock button to switch language without popup menu to delay the input :D
stackexchange-askubuntu
{ "answer_score": 39, "question_score": 24, "tags": "keyboard, 17.10, capslock" }
Оставлять полную структуру документа после работы в CKEDITOR Когда загружаешь в редактор целый здоровый шаблон с полноценной структурой,то на выходе получаю все кроме прежней структуры.То есть было так перед работой с редактором: <html> <head><link src='путь'> <title></title> стили и так далее прописаны </head> <body><p>Куча тексту</p></body> </html> После: <link rel='путь'> <title></title> <p></p> И еще что интересно - `<title>` на выходе пустой Вопрос - как сделать так чтобы структура оставалась прежней
Для полного редактирования страницы используйте следующий код: CKEDITOR.replace( 'textarea_id', { fullPage: true, //включаем редактор страницы целиком allowedContent: true //отключаем фильтрацию контента }); Информация
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ckeditor" }
Migrating from AS2 to AS3 I would like to know from someone who have already done that, any recommendations and things I have to take a special look, I have seen some articles related to the topic, googled it, etc... but I would like the advice from stackoverflower x) I already know object oriented programming in c++, using classes and etc, but I can't quite understand AS3 packages and stuff, but i'm very familiarized with AS2. Thanks
1. Drop everything you know, start fresh. AS2 is different than AS3. Don't try to do the AS2 thing with AS3. 2. Read & Learn the Adobe LiveDocs 3. Learn how the display list works. 4. Learn AS3 coding standards, write clean readable code 5. Learn how to use common actionscript libraries, TweenLite, Gaia framework, RobotLegs, Temple Library, Pure MVC, Away3D, as3corelib etc. 6. Never ever code inside the Flash IDE actionspanel, there are really nice actionscript editors like FlashDevelop, FDT, FlashBuilder, IntelliJ.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "actionscript 3, flash, actionscript 2" }
Java's BigDecimal.power(BigDecimal exponent): Is there a Java library that does it? Java's `BigDecimal.pow(int)` method only accepts an integer parameter, no `BigDecimal` parameter. Is there a library, like Apache's commons-lang, that supports `BigDecimal.pow(BigDecimal)`? It should be able to do calculate `"1.21".pow("0.5")` to return `"1.1"`.
There is a Math.BigDecimal implementation of core mathematical functions with source code available from the Cornell University Library here (also you can download the library as a tar.gz). Here is a sample of the library use: import org.nevec.rjm.*; import java.math.BigDecimal; public class test { public static void main(String... args) { BigDecimal a = new BigDecimal("1.21"); BigDecimal b = new BigDecimal("0.5"); System.out.println(BigDecimalMath.pow(a, b).toString()); } } Prints out: 1.1 * * * # Update The license information is now clear in the May 2015 update: > The full source code is made available under the LGPL v3.0.
stackexchange-stackoverflow
{ "answer_score": 40, "question_score": 43, "tags": "java" }
Adding one Dictionary object to another Is it possible to add one dictionary to another like for example: Dictionary<string,int> d1=new Dictionary<string,int>() { {"abc",1} {"def",2} }; Dictionary<string,string> d2=new Dictionary<string,string>() { {"str","fgh"} {"uyz","ghi"} }; I need to add `d1` to `d2`. Please note that the dictionaries have different signatures.
If your values can have different types you could create third dictionary of type `DIctionary<String, Object>` and add all the items from your dictionaries into it. Dictionary<string,int> d1=new Dictionary<string,int>() { {"abc",1} {"def",2} }; Dictionary<string,string> d2=new Dictionary<string,string>() { {"str","fgh"} {"uyz","ghi"} }; Dictionary<String, Object> combinedDict = new Dictionary<String, Object>(); foreach(var d1Item in d1) combinedDict.Add(d1Item.Key, d1Item.Value); foreach(var d2Item in d2) combinedDict.Add(d2Item.Key, d2Item.Value);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "c#, generics, dictionary" }
count number of formats in a python string I'm reading a buffer from memory containing strings that may contain a number(up to 3) of formats within them(like `%d`, `%x` etc.) I need to know how many formats the string has so I can fetch them and print the string.. Is there any better way to do this but count the `%`'s in the string?
Use `str.count`: >>> fmt = '%d, %x, %%' >>> fmt.count('%') 4 To exclude `%%`: >>> fmt.count('%') - fmt.count('%%') * 2 2
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, string formatting" }
Topology on the extended real line In our real analysis class we are working through 'Real and Complex Analysis' by Rudin and covered topological spaces (but not bases, subbases and other ways of generating topologies, so I can't use these in the exercise). Let $\tau =$ the collection of sets $(a,b),[-\infty,a),(a,\infty]$ and any union of these types. Show that $\tau$ is a topology. Here's my approach: 1. $\mathbb{R} \in \tau$ since $\mathbb{R} = [-\infty,a)\cup(a,\infty]$. $\emptyset \in \tau$. 2. For any $A_1,A_2,\ldots \in \tau,$ we have $\bigcup_{i \in I} A_i = \bigcup_{i \in I} (a_i,b_i) \in \tau.$ 3. For any $A_1,\ldots,A_n \in \tau$, we have $\bigcap_{i=1}^n (a_i,b_i) \in \tau.$ However, I feel like my approach is too naive and I'm missing some details.
Ok here is my attempt at another answer, please comment if there are still some parts missing/wrong. Let $\overline{\mathbb{R}} = [-\infty,\infty]$ and let $b <a$. Then we have $\overline{\mathbb{R}} = [-\infty,a) \cup (b,\infty] \in \tau$. Next, let $a =b$ so that $(a,b) = \emptyset \in \tau$. Now, we define $A = \bigcup_{j \in J} A_j = \bigcup_{j \in J}\left(\bigcup_{i \in I}(a_i,b_i)\right)$. Then $A \in \tau$ since the unions of the unions of intervals is a union of intervals, which are in $\tau$. Last, we define $A = \bigcap_{j \in J} A_j = \bigcap_{j \in J} \left(\bigcup_{i \in I}(a_i,b_i)\right).$ Then, for any $x \in \bigcup_{i \in I} (a_i,b_i),$ $x \in A$ and so A is open. (this doesn't feel correct..)
stackexchange-math
{ "answer_score": 0, "question_score": 4, "tags": "general topology" }
NameError: uninitialized constant Twilio::JWT Getting an error while trying to generate access token for video Using twilio-ruby (4.11.1), ruby 2.4.1, rails 5.1.0. Code: # Create an Access Token token = Twilio::JWT::AccessToken.new(account_sid, api_key, api_secret, identity); following the twilio official Doc. < Error which am facing: NameError: uninitialized constant Twilio::JWT
Twilio developer evangelist here. That example code appears to be written for the upcoming version 5 of the Twilio Ruby gem. The version 5 gem is at rc23 so I recommend using that to create your access token as it has the methods required to make a Video Grant for the rooms API. Let me know if that helps at all.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, ruby, twilio, ruby on rails 5.1, ruby 2.4" }
Support for IMAP IDLE in PHP I have read through all PHP documentation on IMAP functions (www.php.net/imap), but didn't find anything on issueing an IDLE command over an IMAP connection. I want to establish an IMAP connection between my server and GMail, and be notified instantly that a new message has arrived. It's kind of GMail PUSH to my server. The way mobile devices are doing it is by connecting through IMAP and sending the IDLE command. But didn't find a word on IDLE in PHP-IMAP. Is it supported?
I've been working on modifying the ilohamail.org imap client to support the IDLE extension. My application however will be running with php cli and not through a web server. I can post the code when / if I have a working version. You may want to use the < imap library which is just modified from the ilohamail library.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "php, gmail, imap" }
"Extinguat et me, ne manu nostra cadat!" I've seen this quote appear in a few different places, ostensibly from Seneca's _Octavia_. (Or maybe not Seneca's, we're not sure.) > _Extinguat et me, ne manu nostra cadat!_ However, I don't have a copy of _Octavia_ , so I have no context for it. My translation would be: > And let it end my life; may it not fall from our hand! But this doesn't make very much sense. Am I missing some point of grammar?
This is line 174 of the _Octavia_. From context, the subject of _extinguat_ and _cadat_ is understood to be Nero. (In the preceding lines, the Nurse had traced the trail of blood that led to Nero's becoming emperor and to Octavia's current situation, where she has no family left.) In this instance, _cadere_ means 'die' (i.e., 'fall and not get up again'); the ablative _manu nostra_ is showing instrument/means, not separation/place from which. So Octavia is basicallly saying that Nero should either kill her too or be killed by her – literally, 'Let him snuff me out too, lest he fall by my hand.'
stackexchange-latin
{ "answer_score": 4, "question_score": 4, "tags": "latin to english translation, seneca iunior" }
JS not working without prototype We have this piece of code: <a class="loadbutton" onClick="$('checkout_form').submit(); $(this).update('<img src=\'images/loader/longLoad.gif\' /> Processing'); return false;">Pay now<br /><span class="vsmall">click once</span></a> Which seems to not work if I take out the prototype.js library: <script type="text/javascript" src=" But when I use this library, it conflicts with some other code we are using.. so we want to do it without this prototype library, but still have the same effect on the button. How can I go about doing this?
Am I right in assuming you're using jquery instead of prototype? If so, then here is how it may look: <a class="loadbutton" onClick="$('#checkout_form').submit(); $(this).html('<img src=\'images/loader/longLoad.gif\' /> Processing'); return false;">Pay now<br /><span class="vsmall">click once</span></a> As Ernest mentioned, jQuery.noConflict() may be your best option if you'd like to use both libraries. To do so, you must apply the $.noConflict() before including prototype.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, jquery, ajax, prototypejs" }
sortingOrder of custom sort-functions Ag-grid I use ag-grid and wrote 2 custom functions for sorting. In documentation I found sortingOrder. In example it is used like this: `sortingOrder: ["desc", "asc", null]`. If I add in array my own functions `sortingOrder: [() => customASC(), () => customDESC(), null]` it doesn't work. How i can use sortingOrder of custom functions?
Looking at the docs, you need to add your custom sorting functions as `comparator`. You don't need to put it in the `sortingOrder`, but next to it - within `columnDefs`. There isn't a concrete example for this, but you could try adding it to column definitions like this: var columnDefs = [ { headerName: "Date", field: "date", comparator: customComparator, // your custom comparing function sortingOrder: ['desc', 'asc'] // override default sorting order } ] function customComparator() { // your custom code here } You need to test whether the default behavior is as expected (i.e. 'asc > desc > null' according to your custom sorting, and then you should be able to re-arrange the order using `sortingOrder`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "reactjs, sorting, ag grid, ag grid react" }
close var XDocument.Load method/way how do I close this document that was called this way: var xmlDoc = XDocument.Load(new XmlTextReader(Server.MapPath("Nc.xml"))); thanks
XmlTextReader implements IDisposable. In general, you should call IDisposable.Dispose() as soon as you no longer need the resource to allow the system to close open handles, etc. The best use pattern for IDisposable is to use the `using` syntax, which will call IDisposable.Dispose() automatically in an implicit `try..finally` wrapper: using (var reader = new XmlTextReader(Server.MapPath("Nc.xml"))) { var xdoc = XDocument.Load(reader); { .. do xdoc work here .. } } // reader disposed here or if you want to keep the xdoc around a long time for other work but want to close the file as soon as possible, do it this way: XDocument xdoc = null; using (var reader = new XmlTextReader(Server.MapPath("Nc.xml"))) { xdoc = XDocument.Load(reader); } // reader disposed here { .. do xdoc work here .. }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, xml, linq to xml" }
Missing link and caption in review activity description for Tag Wiki edits The `reviews` tab of user activity show the suggested edits approved or rejected by that user with link to the suggested edit itself plus link to the post being edited. All good with questions and answers, but for tag wiki edit the link to the post being edited (in this case the tag info page) is missing: !missing link screenshot The first blank line should point for example to: < With caption like _terracotta tag wiki_.
My bad, fixed now. Left over from when I changed the post type id for tag wikis. Tag wiki edits are missing their title in the user activity tab
stackexchange-meta
{ "answer_score": 1, "question_score": 3, "tags": "bug, status completed, suggested edits, tag wiki" }
Odd harmonics only in Fourier transform If a function is even or odd, it implies that there are respectively only cos and sine terms in its Fourier expansion. But is there a condition for a function to have an expansion with only odd or even harmonics, like this: $\frac{a_0}{2} + \sum_{n=1,3,5,...}^\infty a_n \cos(nx)$
Yes, you have to consider symmetries around $\pi/2$. Let me show you an example. Let $f\colon[-\pi,\pi]\to\mathbb{R}$ be an odd continuous function. Then it's Fourier series has only sine terms: $$ f\sim\sum_{n=1}^\infty b_n\sin(n\,x),\quad b_n=\frac{2}{\pi}\int_0^\pi f(x)\sin(n\,x)\,dx. $$ Suppose further that $f$ satisfies $f(\pi-x)=f(x)$ if $0\le x\le\pi$. Then for all $n\in\mathbb{N}$ $$ \int_0^\pi f(x)\sin(2\,n\,x)\,dx=\int_0^\pi f(\pi-x)\sin(2\,n\,\pi-2\,n\,x)\,dx=-\int_0^\pi f(x)\sin(n\,x)\,dx. $$ This implies that $b_{2n}=0$. If $f(\pi-x)=-f(x)$, then $b_{2n+1}=0$. You can find similar conditions for cosine series.
stackexchange-math
{ "answer_score": 6, "question_score": 3, "tags": "trigonometry, fourier series" }
EasyNetQ rabbitMq update version Json error I was using EasyNetQ v0.27.1.216 with Newtonsoft.Json v4.5.11 and RabbitMq.Client v3.2.1 I update, to solve an issue of connection, now i have EasyNetQ v0.33.1.276, Newtonsoft.Json v6.0.3 and RabbitMq.Client v3.3.2 Before everything was fine but since the update I got error when i try to publish some object. > "Exception":"System.AggregateException: One or more errors occurred. \---> Newtonsoft.Json.JsonSerializationException: Error resolving type specified in JSON 'System.Linq.Enumerable+WhereSelectEnumerableIterator`2[[System.Linq.IGrouping`2[[Object1, Object2],[Object3, Object4]], Object5],[Object3, Object6]], Object5'. Path 'Object3.$type', line 1, position 464. ---> Newtonsoft.Json.JsonSerializationException: Could not find type... And it continue like that for 3 pages of word. I can post it all but i have to change all the names... Not sure what to do with that...
I finally found need to use List element and not IEnumerable (IEnumerable worked before). All work with .ToList()
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, rabbitmq, easynetq" }
How to create a textformfield with listTile that looks enabled So I got a listtile that can use a function on tap and the textformfield. How do I make it look like enabled but still prevent people from changing the value? I tried FocusNode but it also disabled on onTap function. ListTile( TextFormField( enabled: false, validator: (val) { if (val.isEmpty) return 'Please enter something'; }, controller: _controller, ), onTap: () => _doSomething(), )
You can wrap your `TextFormField` in an `IgnorePointer`: ListTile( onTap: () => _doSomething(), title: IgnorePointer( child: TextFormField( controller: _controller, validator: (val) { if (val.isEmpty) return 'Please enter something'; }, ), ), )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "flutter, flutter layout" }
What is PHP's processing order? If I place PHP code prior to the `<html>` tag I assume it will be executed prior to the page load. But if I place the same code inside the `<body>` tag, will the PHP wait for the page load to finish first?
The PHP runs, outputting anything outside the `<?php ?>` tags as it goes. The output might be buffered and then sent in one go once the script has finished. The output might be sent bit by bit as the script outputs it. (Which depends on how the script is written). If you have `<?php foo(); ?>` just after `<body>`, then it will send the body start tag to output, then execute `foo`, then output whatever follows.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, html, pageload" }
How to know if an atom is starting with a pattern? For example, if I got the following predicates : father('jim', 'Boby') father('rob', 'bob') and I would like to know who got father with is name starting with 'bo' ?
Another ISO option is `sub_atom/5`: `sub_atom(Atom, Before, Length, After, Sub_atom)` ?- sub_atom(bob, 0, _, _, bo). true. Compared to `atom_concat/3`, this avoids the generation of the unneeded atom to represent the suffix.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "string, prolog" }
Meaning of "he had a sense of her being very light, as if even the light puffs of breeze blowing this morning might send her sailing away" > "G'bye, Mom." > > "Goodbye, Ray. Be a good boy." > > She stood there for a moment and _**he had a sense of her being very light, as if even the light puffs of breeze blowing this morning might send her sailing away like a dandelion gone to seed**_. Then she got back into the car and started the engine. From "The Long Walk". I don't get what the sentence means. Can anyone help to spell it out?
> He had a feeling that she was very light [like e.g. a feather], as if even the light puffs of breeze blowing this morning might send her sailing away like a dandelion gone to seed. - Have you ever blown on a dandelion flower when it has lots of seeds? - @Michael_Harvey To add on, I think this "exaggeration" might be Ray's love towards his mother.
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "meaning, meaning in context, sentence meaning" }
Does Doran's Shield unique effect proc for shields? Taken from the League of Legends wiki: > UNIQUE: Restores 20 health over 10 seconds after taking damage from an enemy champion. Let's say I'm playing some marksman in the bottom lane, and my support is Janna. If Janna shields me, and then the enemy marksman autos me once but doesn't destroy the Janna shield, will I still get the +20 health effect? The reason I ask is because I have seen a handful of very rare occasions where (for example) champion A has a shield and tower dives, taking a bunch of turret shots, and then champion B attacks them once but is unable to pierce the shield. If the only damage done by champion B was to champion A's shield, champion A will be executed by the turret instead of killed by champion B.
Yes, any damage will proc it, even if the damage isn't to your health bar (eg: Shields, Grey Shields, Magic Shields, AD Shields).
stackexchange-gaming
{ "answer_score": 2, "question_score": 1, "tags": "league of legends" }
It's possible to set timer on poster node and other nodes in Roku..? I am working on a Roku app using scene graph component.I am trying to set timer node on poster node in Roku app playing on TV APP..i want to set timer on Poster Node And Other Nodes it is possible in Roku..? pls help me..
**Sure, it's possible.** You can add _Timer_ Node as child for _Poster_ etc. It will looks in next way: <Poster id = "poster"> <Timer id="timer"/> </Poster> For more detailed answer, please describe you purpose.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "roku, brightscript, scenegraph" }
Converting a Numeric column to Date column in snowflake I have a table with a column "VALUATION DATE NUM", which stores integer in '20210331' format. I have another column in the same table "VALUATION DATE" which is in date format, however is blank for now. I want to use the "VALUATION DATE NUM" column to update "VALUATION DATE" column in date format. Using the query "UPDATE SPRD_MGMT_INP_FUND_VALUES SET "VALUATION DATE" = TO_DATE("VALUATION DATE NUM",'YYYY/MM/DD');" is giving an error "SQL compilation error: invalid type [TO_DATE(SPRD_MGMT_INP_FUND_VALUES."VALUATION DATE NUM", 'YYYY/MM/DD')] for parameter 'TO_DATE'" Please help
Using spaces in column names is not a good practice. Do you need something like this? update yourtable SET "VALUATION DATE" = TO_DATE( "VALUATION DATE NUM"::VARCHAR,'YYYYMMDD' ) where "VALUATION DATE" is NULL; Note: Because you said blank values I added the WHERE condition.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, snowflake cloud data platform" }
How to access model in carrierwave? I did this the way it's below, but it's returning "no text". How to access model properly in carrierwave? # photo_uploader.rb process :poster def poster manipulate! format:"jpg" do |source| txt = Magick::Draw.new txt.pointsize = 20 txt.gravity = Magick::SouthGravity txt.fill = "white" source.border(50, 50, "black").annotate(txt, 0, 0, 0, 0, "#{model.title}" ) end end
You can access the model this way. All the error means is that there is actually no text in the title field of model. If you check the params hash, you'll probably see "my_model"=>{"title"=>"", "image"=> ...) So you can should check for a non-blank title in the controller: unless params[:title].blank? MyModel.create(params[:my_model]) end
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, carrierwave" }
Gauss Divergence Theorem finding limits Use Gauss Divergence Theorem to comput $$\int \int \limits_S F\cdot n dS$$ where $n$ is the outward normal for the following: $S$ is the surface of the unit sphere $\\{(x,y,z): x^2+y^2+z^2=1\\}$, $n$ is the outward normal and $$F(x,y,z)=(xz-z^2,-yz,z+x+y)$$ So if the $div(F)=1$ but what is $V$? If I make $V=\\{x,y \in [0,1], z \in [-\sqrt{1-x^2-y^2},\sqrt{1-x^2-y^2}]\\}$, would that work?
V is the whole volume of the ball. Since your divergence is $1$, the integral is just the volume of the unit ball, which is $\frac{4}{3}\pi$. Using integration, it is $$\int^1_{-1}\int^{\sqrt{1-x^2}}_{-\sqrt{1-x^2}}\int^{\sqrt{1-x^2-y^2}}_{-\sqrt{1-x^2-y^2}}dzdydx$$ You might have to use trig substitution to calculate it. Or you can use spherical coordinate, $$\int^{\pi}_{0}\int^{2\pi}_{0}\int^1_0 r^2\sin{\phi}dr d\theta d\phi$$ which is much easier to calculate.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "multivariable calculus, vector analysis" }
Linearizing power term in objective function I would like to linearize $x^2$ term in my objective function. I understand this can be solved using quadratic programming solver; however, for my use case linearization is necessary to convert it to MIP if possible. Any help is much appreciated.
There are two possibilities that come to mind, assuming that $x$ is a continuous variable. One is to do a piecewise-linear approximation (leading to an answer that is, well, approximate). The other is to replace $x^2$ with a new variable $z$ and then, on the fly, add constraints of the form $z \ge x_0^2 + 2x_0(x-x_0)$ when a solution is obtained containing $x_0$ and $z_0$ with $z_0 \lt x_0^2$. The latter method is potentially useful if the nature of the model precludes the solver choosing $z \gt x^2$. With CPLEX, you can add these constraints in a lazy constraint callback. With a solver that lacks the needed callback structure, you would be in a solve - cut - solve cycle until you got an optimal solution needing no further cuts.
stackexchange-or
{ "answer_score": 6, "question_score": 3, "tags": "mixed integer programming, linearization, quadratic programming" }
pandas change column type to datetime afterr group by This is related to a previous question which I asked here (pandas average by timestamp and day of the week). Here, I perform a groupby operation as follows: df = pd.DataFrame(np.random.random(2838),index=pd.date_range('2019-09-13 12:40:00', periods=2838, freq='5T')) # Reset the index df.reset_index(inplace=True) df.groupby(df.index.dt.strftime('%A %H:%M')).mean() df.reset_index(inplace=True) Now if I check the data types of the column, we have: index object 0 float64 The column does not retain its datetime data type. How can I still preserve the column data type?
I wouldn't do grouping like that, instead, I would do double grouping/indexing: days = df.index.day_name() times = df.index.time df.groupby([days,times]).mean() which gives (head): 0 Friday 00:00:00 0.524322 00:05:00 0.857684 00:10:00 0.593461 00:15:00 0.755158 00:20:00 0.049511 where the first level index is the (string) day names, and second level index are `datetime` type.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, pandas" }
Can I search from text saved to postgres using Knex I'm saving some texts to a Postgres table and would like to query them with Knex. That's easy, but I'd like to return only certain parts containing certain keywords. So, my simple question is, is there some good way to query the database from column "text" and return only some parts or should I just query the whole transcription and do the rest afterwards?
As I understand. You can use `like`. knex('table').where('text', 'like', `%${term}%`) Outputs select * from table where text like '%${term}%' Or you use `regexp_matches` on column. It should work.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, node.js, postgresql, knex.js" }
modify keyboard layout locally I haven't found the correct keyboard layout for my macbook pro yet. I've found one that looks like it though (in `.xinitrc`): setxkbmap -layout us -variant mac yet this has one difference: the `(',~)` key and the `(§,±)` keys are switched. I've always managed this by editing the corresponding file in §/etc/share/X11/xkb`but it is a drag to have to do this everytim`X11` updgrades. Can it be done from a local file e.g. `.xinitrc`?
The file you want is `.xmodmap` Have a look at `man xmodmap` for details on how to set it up. xmodmap uses the physical keycodes to make the change. You can get those from `xev`. Launch it, then tap the appropriate keys and see what keycode number pops up. You should only need two lines in your .xmodmap, both of them looking something like keycode 49 = grave asciicircum keycode 15 = <whichever keys are activated in first-level> section plusminus Those two keycodes, by the way, are wild guesses and probably wrong.
stackexchange-unix
{ "answer_score": 2, "question_score": 1, "tags": "x11, keyboard" }
How do I specify the files to include in a WAR file? I need to create a WAR file that just contains static content files (gifs, jpgs, html, js, etc). I have a directory structure that contains all the files and need to create the WAR file via an ANT (1.5.1) build task. Right now I just have this in the ANT task: <war destfile="${output.file}" webxml="WEB-INF/web.xml" basedir="${basedir}"> <fileset dir="${basedir}/sales" /> </war> The files I want to include are in C:/basedir/sales and its subdirectories. When I try to run this task I get "A zip file cannot include itself". So clearly putting that fileset in there is not the right way to do it. I am unclear as to what I need to put in the task and in the web.xml file to specify what files to include within the archive.
I think the basedir="${basedir}" is causing you the problems. Also, I think the way you have it written will require that web.xml exist inside WEB-INF dir relative to where you run ant from. So, try creating /WEB-INF/web.xml as follows: <?xml version="1.0" encoding="utf-8" ?> <web-app> </web-app> Then try updating /build.xml as follows: <?xml version="1.0" encoding="UTF-8"?> <project name="yourproject" basedir="." default="war" xmlns:ivy="antlib:org.apache.ivy.ant"> <target name="war" description="--> build war file"> <war destfile="./mywar.war" webxml="WEB-INF/web.xml"> <fileset dir="C:/basedir/sales" /> </war> </target> </project> Then you should be able to run "ant war" from command line and it should create "mywar.war" in your current directory.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ant, build, war" }
Dynamic Padding? (jQuery) Ok. What I would like to do is to use jQuery to go through all `<span>` tags with a certain class (`.link`) and to set their `padding-right` css value to 20% of current width of the span. I do not have any code to show because I am not good with jQuery and the rest is pretty much self-explanatory. Any help would be much appreciated. Thanks :)
You can use the `css()` method with a callback function that returns the width of the currently iterated element x 0.2 $('span.link').css('padding-right', function() { return $(this).width() * 0.2; }); In newer browsers you could do this with CSS as well span.link { padding-right: calc(20%); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, width, padding, html" }
How to compare symbols in javascript How to I compare symbols in javascript? I have a left arrow in my program and this is not working: <input type="button" id="backspace" value="&#8592" /> document.getElementById("backspace").onclick=function (){display_ctrl(this.value);}; function display_ctrl(parameter){ if (parameter=="&#8592"){alert("this is a left arrow");} How can I compare whether it is particular symbol?
Try using Unicode instead - `"\u2190"` is a left arrow. > "&#8592" "&#8592" > "\u2190" "←" Your code would then become (I have formatted it to be more readable): document.getElementById("backspace").onclick = function() { display_ctrl(this.value); } function display_ctrl(parameter) { if (parameter == "\u2190") { alert("this is a left arrow"); } }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript" }
How to simplify identical method call Hi I have the following Pig code: leafNodes = FOREACH records GENERATE 'buckets' AS bucket_url, MultiConcat(localziedName, ' in ', localizedLocation) AS title, ToJSONString( 'url', url, 'title', MultiConcat(localziedName, ' in ', localizedLocation) ) AS link_json; The same `MultiConcat(localziedName, ' in ', localizedLocation)` call is made twice. So, is there a way to use variable or something like that to reduce the call to once?
I found a way to do it. Basically, just create a variable right before the GENERATE statement. Here is the code: leafNodes = FOREACH records { title = MultiConcat(localziedName, ' in ', localizedLocation); GENERATE 'buckets' AS bucket_url, title, ToJSONString( 'url', url, 'title', title ) AS link_json; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "apache pig" }
How to access HttpContext.Current.User.Username in WCF service How can I access `HttpContext.Current.User.Username` from a web application in a WCF service?
Generally you don't - HttpContext is an ASP.NET concept and doesn't apply to WCF unless you run it with ASP.NET Compatibility turned on. If you want the current user in WCF then use `ServiceSecurityContext.Current.PrimaryIdentity` or get the security context via the OperationContext.
stackexchange-stackoverflow
{ "answer_score": 35, "question_score": 19, "tags": "wcf" }
Find $M⊥$, the orthogonal complement of $M$. The exercise is as follows: > Find the Orthogonal complement of $M = \\{x\in\mathbb{R}^2: 2x_2^2+x_1=0\\}$. I know that I have to find another vector such that the dot product between them results in zero, but what is it in the same group of exercises with projections? How do I find out what are the coordinates of my vector $\underline x$?
For a more familiar setting, let $x_2=y$ and $x_1=x$. Then when $2y+x=0$, this implies $y=-\frac{x}{2}$. The perpendicular line is $y=2x$ since the perpendicular line has slope of negative reciprocal. This line has basis $\\{[1,2]^T\\}$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "linear algebra" }
Query blocking entirely MySQL server I try to a run a specific query. However, when I execute it, the MySQL server doesn't respond anymore. There is approximately 30000 rows in the table `base_contrats_actifs` but I don't know if this is a problem. Here is the query : UPDATE base_contrats_actifs a SET a.code_indice = ( SELECT MAX(g.code_indice) FROM base_gid g WHERE a.num_version = g.num_version_contrat ), a.flag_bailleur_locataire = ( SELECT MAX(g.flag_bailleur_locataire) FROM base_gid g WHERE a.num_version = g.num_version_contrat ), a.compte_client = ( SELECT MAX(g.compte_client) FROM base_gid g WHERE a.num_version = g.num_version_contrat ) Can you see if there is an error ? If not, is there any way to debug the query ?
I don't know exactly why your update is non performant, but given the number of correlated subqueries you have, I'm not surprised. Try rewriting it as an update join: UPDATE base_contrats_actifs a INNER JOIN ( SELECT num_version_contrat, MAX(code_indice) AS max_code_indice, MAX(flag_bailleur_locataire) AS max_flag_bailleur_locataire, MAX(compte_client) AS max_compte_client FROM base_gid GROUP BY num_version_contrat ) g ON a.num_version = g.num_version_contrat SET a.code_indice = g.max_code_indice, a.flag_bailleur_locataire = g.max_flag_bailleur_locataire, a.compte_client = g.max_compte_client;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql, sql" }
python index() not working I am trying to print the filename '`xyz.0.html`' in the console. It is spitting out an error `"substring not found"` files in directory: xyz.0.html xyz.1.html xyz.2.html python for name in glob.glob('*html'): if name.index('.0.html'): print name
you probably want if '.0.html' in name: Or, if name.endswith('.0.html'): Your version raises an error if the substring isn't in the string (and it will evaluate to `False` if the substring is at the start of the string) since the `index` method returns the index in the string where the substring was found (or raises an exception if the substring wasn't found).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "python, indexing" }
Helper Data not found in magento2 i try to install this extension : < i do all steps, and when go to my site i see error 500. the message of error : [24-Jun-2019 08:04:59 UTC] PHP Fatal error: Class 'MGS\Core\Helper\Data' not found in /home/pt1byfxrpoja/public_html/app/code/MGS/Fbuilder/Helper/Data.php on line 15 I go to file Data.php and i see this 15: class Data extends \MGS\Core\Helper\Data Its true, but see error ,,, where is problem ?
Your class`\MGS\Core\Helper\Data` exists in the file but there is no such a file `Data.php` exist in your path `\MGS\Core\Helper\Data` see in your directory `Data.php is existed under `\MGS\Core\Helper\Data` path? **Solution:** You got this error because you have not installed the `MGS_Core` extension. and your extension `MGS_Fbuilder` class extends `class Data extends \MGS\Core\Helper\Data` so that class not found. So basically your extension `MGS_Fbuilder` dependent on `MGS_Core` extension. just install `MGS_Core` extension. your error will be solved. * * * **Update:** Maybe there is default extension issue I found the solution for that Check this link I hope it helps!
stackexchange-magento
{ "answer_score": 1, "question_score": 2, "tags": "magento2, page builder" }
why are there multiple layers of caches Does anyone know why in most of todays processors there are several layers of caches. Like L1 L2 and L3. Why cant a processor do with one big L1 cache? Isnt having multiple layers of cache increases the complexity of caching protocols?
Die size. L1 is usually on-die; there is not room for a large cache on-die. L2/3 gets its own die and can be bigger and processed differently. Also speed; L1 is built with tradeoffs for maximum speed, while L2/3 doesn't have to be as aggressively sped up. Also multi-core. Modern multi-core processors give each core its own L1 for speed, but they share some or all of the other caches for coherency. That said, PA-RISC processors _have_ been built with the "let's just make a big L1 cache" approach. They were expensive.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "caching" }
Changing a column's datatype before disabling foreign key constraint and index I want to change a column's data type. Because the column is referenced as a foreign key with 2 other tables, I need to drop the foreign key constraint on the other 2 tables. Also the current table has index which needs to be dropped. How can this be done?
You need to know the index and foreign key names, which can be pulled from the `sys` tables. The syntax to drop them is: **Foreign Key** IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[foreign_key_index_name]') AND parent_object_id = OBJECT_ID(N'[dbo].[tablename]')) ALTER TABLE [dbo].[tablename] DROP CONSTRAINT [foreign_key_index_name] **Index** IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[tablename]') AND name = N'index_name') DROP INDEX [index_name] ON [dbo].[tablename] WITH ( ONLINE = OFF ) This information is also available in BOL. You can find the index and foreign key names with these queries: select * from sys.indexes where object_id = object_id(N'[dbo].[tablename]') select * from sys.foreign_keys where parent_object_id = object_id(N'[dbo].[tablename]')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server, sql server 2008, constraints, indexing" }
javascript modal dialog aligning to middle of the page $("#divDisplayPopUp").dialog({ autoOpen: false, modal: true, height: 436, width: 939, }); This code doesnt align the popup into the center of the page. And its alignment differs in Firefox, IE and Chrome. Can anyone suggest how to align it to the centre, irrespective of browser? Thanks.
I think this your answer. $(document).ready(function(){ var maskHeight = $(document).height(); var maskWidth = $(window).width(); $('#divDisplayPopUp').css('top', (maskHeight - $('#divDisplayPopUp').height()) / 2); $('#divDisplayPopUp').css('left', maskWidth / 2 - $('#divDisplayPopUp').width() / 2); }); I use many times of this and never see any problem.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, user interface, modal dialog, alignment" }
How to edit excel value, example: I have value "12345 (POS) / 45678 (APOS) " in excel cell and i want to extract in this format "12345,45678" I have value "12345 (POS) / 45678 (APOS) " in excel cell and i want to extract the value in this format "12345,45678" using excel operation
`=SUBSTITUTE(SUBSTITUTE(A2," (POS) / ",",")," (APOS)","")`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "excel, excel formula" }
int or byte confusion public class Tester { public Tester(){ System.out.println("Hello"); } public Tester(byte b){ System.out.println("byte"); } public Tester(int i){ System.out.println("int"); } public static void main(String[] args) { Tester test=new Tester(12); } } Please advise why the print is int,I also tried other integer numbers,they all printed as int, but for example, 1 2 3 4 5 6 7....those numbers can also be called byte, right? So why only int is called?
The default type of `12` is `int` and so it chooses `int` constructor. To call the `byte` constructor _explicit cast_ is required. > but if I delete :public Tester(int i){ System.out.println("int"); }, it will not print byte either, instead, it has an error If you remove `int` constructor, then compiler will not be able to find any suitable constructor to call and hence it will be error.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "java, int, byte" }
What's the difference between these 2 SQL query involving round() and ceiling ()? SELECT ROUND(CEILING(36.3) / 4,2) SELECT ROUND(37 / 4,2) The first query returns 9.25. The second query returns 9. Ceiling(36.3) would have returned 37. Why would there be such differences then?
The difference is due to the return type from operations. When you call Ceiling on any number or expression, the return type is of same type as the expression. Let's look at the first one: Ceiling(36.3) -> returns a decimal This means that the division operation is also done on decimals which means you get a decimal result and thus could be rounded. In the second statement, you are dividing 2 integers which would also result in a integer result (just the quotient). Thus the value will only be 9. SELECT ROUND(CEILING(36.3) / 4,2) -- select round(decimal/int,int) => select round(decimal, int) SELECT ROUND(37 / 4,2) -- select round(int/int,int) => select round(int, int) You would get similar result when you do this: SELECT ROUND((CEILING(36.3) / 4),2) SELECT ROUND((cast(37 as decimal(10,2)) / 4),2)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql" }
Use conditional inside $.each function to create array I want to iterate over the elements of an array and if a condition is true I want to create a new array. Example: I have an array called Messages whose elements are objects and I want to check if the id attribute equals 5. If yes create a new array only consisting of this object. messages = [{ "id": 10, "body": "hello!" }, { "id": 21, "body": "hola!" }, { "id": 5, "body": "ciao!" }]; var message5 = []; var dataObj = {}; $.each(messages, function(index, value) { if (value.id == 5) { dataObj[index] = value; } }); message5.push(dataObj[index]); I want my result to be: message5 = [ { "id": 5, "body": "ciao!" } ]
Try to use `Array.prototype.filter` at this context, var message5 = messages.filter(function(itm){ return itm.id == 5; }); console.log(message5); //[{"id": 5,"body": "ciao!"}] If you want it to be more concise then you could use ES6 `Arrow function`, var message5 = messages.filter(itm => itm.id == 5); console.log(message5); //[{"id": 5,"body": "ciao!"}] But note that, the above code is similar to, var message5 = messages.filter(function(itm){ return itm.id == 5; }.bind(this)); //Arrow function will automatically bind its lexical scope to it.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 8, "tags": "javascript, jquery, arrays" }
Using ftp upload to site C# ASP.NET web form application I opened my ftp website and there I created web form. This is my .cs code where I get error: public partial class : System.Web.UI.Page {//here I get error:"Type expected" protected void Page_Load(object sender, EventArgs e) { } } What should I do? Please help. Thanks!!!
The ":" is the error. Try "something" like this. public partial class Jurnali : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "c#, asp.net, ftp" }
Is stdout a natively usable token in C++? Say I have a function like void printToSomewhere(FILE* stream, char* msg){ fprintf(stream, "%s", msg); } If I want the stream to be `stdout`, do I have to declare that before in the calling function: ... FILE* stdout; printToSomewhere(stdout, "printing to stdout"); ... or can I call the function without having to define/include/etc stdout explicitly? ... printToSomewhere(stdout, "printing to stdout"); ...
As with every variable, you have to declare `stdout` before using it. The variable `stdout` is declared in the header file `stdio.h` (or `cstdio` in C++). By including `stdio.h` (or `cstdio`), `stdout` becomes visible. On many platforms, you can also simply declare `stdout` as an extern variable: extern FILE *stdout; although doing so is discouraged, as the C standard requires `stdout` to be a macro and allows it to expand to something that is not even a variable. On most plaforms however, `stdio.h` defines this macro simply as #define stdout stdout but you should refrain from making this assumption in portable software.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -3, "tags": "c++, file, stream, stdout" }
jar selective file lising I list the contents of my jar file like this: jar -tf myjar.jar but I want to list selectively e.g. all files starting with 'm'. The following does not work: jar -tf myjar.jar m* I can list all files in a folder: jar -tf myjar.jar folder/ but not the files beginning with 'm': jar -tf myjar.jar folder/m* Is there a way for me to filter the listed files?
Use `grep` or `egrep` or similar command line utility, e.g., jar -tf myjar.jar | grep "folder/m" The `jar` command itself has no support for operations like this. Using tools like `grep`/`egrep`/etc are a canonical solution, and are essential tools anyway.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "java, jar, wildcard" }
Registering jQuery kills admin functions I recently added the following into my theme's `functions.php`, in order to load jQuery from the CDN: function my_init_method() { wp_deregister_script('jquery'); wp_register_script('jquery', ' } add_action('init', 'my_init_method'); However, this causes problems with the admin screens, notably the WYSIWYG editor which then refuses to allow HTML mode (via the tab). I get an error: jQuery is not defined from the wp-admin/load_scripts.php file. What am I doing wrong?
> jQuery is not defined This is because the Google CDN Jquery is not in no-conflict mode. Use the following to make sure the included WordPress no-conflict jquery is used in admin. if( !is_admin()){ wp_deregister_script('jquery'); wp_register_script('jquery', (" false, '1.4.2'); wp_enqueue_script('jquery'); }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "wp admin, jquery" }
Rotating a 4 bit integer I have an int `00000000000000000000000000001101` which represents 13 in base ten. I am trying to circular rotate the the bits by treating the 32 bit integer as a 4 bit integer because if I rotate the integer the value becomes very large. My desired answer after a right rotation of 2 for the above example would be `00000000000000000000000000000111` which is 7 in base 10. Any help on doing this is greatly appreciated.
To rotate the lower 4 bits to the right by `n`, where `n` is 1, 2, or 3: ((x >> n) | (x << (4-n))) & 0xF; The first part shifts the leftmost 4-n bits to the right; the second part shifts the rightmost n bits to the left. Then you `or` them together, and use `& 0xF` to zero extra bits that may have been set by the left shift.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java" }
How to find the distinct records when a value was changed in a table with daily snap shots I have a table that has a SNAP_EFF_DT (date the record was inserted into the table) field. All records are inserted on a daily basis to record any changes a specific record may have. I want to pull out only the dates and values when a change took place from a previous date. I am using Teradata SQL Assistant to query this data. This is what I have so far: SEL DISTINCT MIN(a.SNAP_EFF_DT) as SNAP_EFF_DT, CLIENT_ID, FAVORITE_COLOR FROM CUSTOMER_TABLE GROUP BY 2,3; This does give me the first instance of a change to a specific color. However, if a customer first likes blue on 1/1/2019, then changes to green on 2/1/2019, and then changes back to blue on 3/1/2019 I won't get that last change in the results and will assume their current favorite color is green, when in fact it changed back to blue. I would like a code that returns all 3 changes.
Simply use `LAG` to compare the current and the previous row's color: SELECT t.*, LAG(FAVORITE_COLOR) OVER (PARTITION BY CLIENT_ID ORDER BY SNAP_EFF_DT) AS prev_color FROM CUSTOMER_TABLE AS t QUALIFY FAVORITE_COLOR <> prev_color OR prev_color IS NULL If your Teradata version doesn't support `LAG` switch to MIN(FAVORITE_COLOR) OVER (PARTITION BY CLIENT_ID ORDER BY SNAP_EFF_DT ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS prev_color
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, teradata" }
Order of execution of static blocks and instance variable public class H { static final int x; static { x=2; } public static void main(String... args) { System.out.print(new H().x); } } This will print **2** as o/p. Now my question is: We know that the static block is called first. Now if the static block is called, we are having `x=2` in that block. So how does the compiler works, because until that time we do not have definition of `x`?
Static variables are initialized before static blocks are executed. `x` is defined with a value of `0` because it's a primitive. Then it is assigned the value of `2`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, static" }
Using SwiftyJSON, array cannot assign value of type AnyObject to type String I have this variable: var fetchedImagesArray: [String] = [] Then I fetch an array of images name from my server using Alamofire and SwiftyJson like this: if let fetchedImages = json["images"].arrayObject { fetchedImagesArray = fetchedImages } But I get the error here **fetchedImagesArray = fetchedImages** saying: cannot assign value of type anyobject to type string. The array returned loooks like this ["imgName1","imgName2","imgName3"] which is all strings to why cant I set fetchedImagesArray?
In `SwiftJSON` the property `arrayObject` returns `[AnyObject]?` so you have to downcast the array to its actual type if let fetchedImages = json["images"].arrayObject as? [String] { fetchedImagesArray = fetchedImages }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "ios, arrays, swift, alamofire, swifty json" }
How to export the same function but with different parameters by export I need to export the same pre-defined function, but with different parameters by export. What I'm trying to achieve: module.exports = { adminSaysHello: sayText("Hello", "admin"), adminSaysText: sayText(text, "admin"), sayText: sayText } function sayText(text, author){ console.log(`${author} said: ${text}`); } module.adminSaysHello(); module.adminSaysText("Good Bye"); module.sayText("Hello, my name is Foo", "Foo"); When executing above script I get the following error: adminSaysText: sayText(text, "admin"), ^ ReferenceError: text is not defined How to do this export correctly?
You'll need to create additional functions which then call the original function with specific parameters. That will look something like this: module.exports = { adminSaysHello: () => sayText('Hello', 'admin'), adminSaysText: (text) => sayText(text, 'admin'), sayText: sayText }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, node.js, module" }
How to change textbox border styles in AppMaker I am trying to change the border styles for inputfields that have the focus from the material design's blue border-color to green border-color, but the following CSS seems not be working: .app-TextArea.focus .app-TextArea-Input, .app-TextBox.focus .app-TextBox-Input { border-bottom-color: green; } Maybe someone can help me out.
This CSS variant should make a trick .focus.app-TextBox--Green::after { border-bottom-color: green; } ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "css, google app maker" }
Why i can't watch the expression a[1][1] after declare it by a[n][n] in c++? my code: #include <iostream> using namespace std; int main() { int n=5; int a[n][n]; a[1][1]=5; return 0; } I got this error when trying to watch the expression a[1][1] in eclipse on line 6: > Failed to execute MI command: -data-evaluate-expression a[1][1] Error message from debugger back end: Cannot perform pointer math on incomplete types, try casting to a known type, or void *. i guess it's returned from gdb? however, i don't know why i can't watch that value? Isn't "a" is a normal multi-dimensional array?
For some odd reasons this isn't valid C++ unless you make it const int n = 5; Otherwise the array size is formally unknown until runtime.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "c++, eclipse, gdb" }
Transforming Equations: Unable to change the equation from one form to other There is this one differentiation problem in my textbook. I solved it by using Quotient rule and the author solved it by rationalising the denominator first. Now, I have two equations (I plotted them on a graphing calculator and both have the same graph so they are essentially the same thing written in different forms). For other questions, I am able to manipulate one equation and change it to another form; however, I am unable to do this here. Could someone help? $$\dfrac14\left(\dfrac{1}{\sqrt{x+1}}+\dfrac{1}{\sqrt{x-1}}\right)=\dfrac14\left(\dfrac{\sqrt{x+1}-\sqrt{x-1}}{-x^2+1+x\sqrt{x^2-1}}\right)$$
After some easily understood transformations, we have to prove that : $$\dfrac{\sqrt{x+1}+\sqrt{x-1}}{\sqrt{(x-1)(x+1)}}=\dfrac{\sqrt{x+1}-\sqrt{x-1}}{-(\sqrt{(x-1)(x+1)})^2+x\sqrt{(x-1)(x+1)}},$$ Simplifying the denominators by the common factor $\sqrt{(x-1)(x+1)}$, we are reduced to prove that : $$\sqrt{x+1}+\sqrt{x-1}=\dfrac{\sqrt{x+1}-\sqrt{x-1}}{-\sqrt{(x-1)(x+1)}+x},\tag{1}$$ which is a relationship of the form $A=\frac{B}{C}$. Let us prove that $AC=B$ : $$(\sqrt{x+1}+\sqrt{x-1})(-\sqrt{(x-1)(x+1)}+x)=\sqrt{x+1}-\sqrt{x-1}$$ Expanding the LHS, we get : $$-(x+1)\sqrt{x-1}+x\sqrt{x+1}-(x-1)\sqrt{x+1}+x\sqrt{x-1}=\sqrt{x+1}-\sqrt{x-1}$$ a relationship which becomes evident by grouping terms containing $\sqrt{x+1}$ and $\sqrt{x-1}$ resp. in the LHS. **Remark** : (1) could have been proved as well by using relationship : $$x-\sqrt{x^2-1}=\left(\sqrt{\frac{x-1}{2}}-\sqrt{\frac{x+1}{2}}\right)^2$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "derivatives, linear transformations" }
How to add inner shadow to UIView with rounded corners I have to add an inner shadow to a `UIView` that has rounded corners. I saw several answers on SO that add inner shadows to UIViews but they don't work as I want to, because they add the shadow to the whole rectangle, not accounting for the rounded corners. See this image as an example of what I would like to achieve: ![enter image description here](
It's a trick. You give shadow and border to same view, the shadow will fall inside the view. please make sure the background color of view is clear. use the below code for reference. yourView.layer.shadowColor = UIColor.gray.cgColor yourView.layer.shadowOpacity = 0.3 yourView.layer.shadowOffset = CGSize.zero yourView.layer.shadowRadius = 6 yourView.layer.masksToBounds = true yourView.layer.borderWidth = 1.5 yourView.layer.borderColor = UIColor.white.cgColor yourView.layer.cornerRadius = imageView.bounds.width / 2
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "ios, swift, xcode, uiview" }
Dibujar solo las lineas horizontales de una tabla Buenas, he estado buscando porque pensaba que debía ser algo bastante fácil, pero no lo encuentro. ¿Que atributo de CSS se emplea para que solo se vean las líneas horizontales en una tabla? Ejemplo de una tabla que en su diseño solo hay líneas horizontales Gracias!
Creo que lo que buscas es esto: table { border-collapse: collapse; width: 80%; } tr { border-bottom: 1px solid #ccc; } <table> <tr> <td>Celda1</td> <td>Celda2</td> <td>Celda3</td> </tr> <tr> <td>Celda1</td> <td>Celda2</td> <td>Celda3</td> </tr> <tr> <td>Celda1</td> <td>Celda2</td> <td>Celda3</td> </tr> </table>
stackexchange-es_stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "css, css3" }
Validating URL paramaters How should one validate URL parameters in a view? Would this be accomplished using a a bunch of `ìf` statements or is there a better way to go about it? I'd like to validate the parameters when the request comes in rather than having it scattered across my view, model and manager. When I say validation I'm referring to basic checks such as existence of a key, checking the data type, integer ranges, etc. Thanks.
I think in this case it depends on the scale of your application if it's just a small application doing data validation via simple if statements would be the easiest route, but django does have features to support nicer form validation(< so it might be cleaner to do it that way, but it still boils down to if statements in the end.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, django" }
Clang + OpenMP on Linux uses only 1 CPU core I have the following code: int main(int argc, char** argv) { const int64_t N = 10000000000; float* data = new float[N]; int64_t i; omp_set_dynamic(0); omp_set_num_threads(4); #pragma omp parallel for for(i = 0; i < N; ++i) data[i] = i*i; return 0; } If I compile it with g++ then during runtime the code uses 4 cores: g++ -fopenmp -std=c++11 main.cpp If I compile it with clang++3.7 then during runtime the code uses only 1 core: clang++-3.7 -fopenmp -std=c++11 main.cpp In both cases I have set: OMP_NUM_THREADS=4 Both compilers have been installed from the Debian Testing repository: sudo apt-get install g++-5 sudo apt-get install clang-3.7 So, any ideas why the clang only uses one core? Thanks in advance.
See this: > OpenMP 3.1 is fully supported, but disabled by default. To enable it, please use the -fopenmp=libomp command line option. It looks like you missed the `-fopenmp=libomp` in your compilation flags.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 6, "tags": "clang, openmp" }
Box2D/Farseer - Moving fixtures on a Static Body I am attempting to create a Pool of Fixtures, in order to reduce memory consumption. My problem is that when I attempt to return a Fixture to the Pool and re-assign its position on the Parent Body, once it is repositioned the Fixture no longer provides any collision response with other world objects. It seems that if you want to move a Fixture on a Static body, it needs to be destroyed and re-created. This method doesn't allow me to use my Pool however. Does anyone know if it is possible to move a Fixture on a Static Body? I do not want to move the Body, but the Fixtures attached to it.
Velcro Physics (formerly Farseer Physics) is open source. > /// Warning: You cannot reuse fixtures. If you still want to do this, then try to reproduce some of the steps that the `Fixture.RegisterFixture()` private method does.
stackexchange-gamedev
{ "answer_score": 3, "question_score": 2, "tags": "xna, box2d, body" }
Why focus an input on page load instead of inline? Almost all web pages that I see designed to set the focus to an input box add the code into a body onload event. This causes the code to execute once the entire html document has loaded. In theory, this seems like good practice. However, in my experience, what this usually causes is double work on the user, as they have already entered data into two or three fields and are typing into another when their cursor is jumped back without their knowledge. I've seen a staggering number of users type the last 2/3 of their password into the beginning of a username field. As such, I've always placed the JS focus code immediately after the input to insure there is no delay. My question is: Is there any technical reason not to place this focus code inline? Is there an advantage to calling it at the end of the page, or within an onload event? I'm curious why it has become common practice considering the obvious practical drawbacks.
Google and Yahoo both suggest placing scripts at the bottom of the html page for performance reasons. The Yahoo article: < You should definitely place the script in the appropriate place if it means the correct user experience -- in fact I would load that part of the script (Used for tabbing inputs) before the inputs to ensure it always works no matter how slow the connection. The "document.ready" function allows you to ensure the elements you want to reference are in the dom and fires right when your whole document dom is loaded (This does not mean images are fully loaded). If you want you could have the inputs start out as disabled and then reenable them on document ready. This would handle the rare case the script is not ready yet when the inputs are displayed.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, html" }
ElasticSearch query_string text search on long field With the following query { "query": { "query_string": { "query": "james", "fields": ["briefdescription", "sonumber"] } } } I get `"reason": "failed to create query: For input string: \"james\"",` The problem I think it's `sonumber` is a `long` field, and it fails to search "james" on that field, but if I just use `default_field: "*"`, it doesn't throw the error. Why is that? Does `default_field` skips the incompatible types?
Yes that's probably the reason, you can also alleviate this using the `lenient` parameter to ignore those errors: { "query": { "query_string": { "query": "james", "fields": ["briefdescription", "sonumber"], --> "lenient": true } } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "elasticsearch" }
Find multiple array inside a single array $a = 'red'; $b = 'blue'; $colors = ['red', 'green', 'blue', 'black']; I am trying to check if **both** `$a`, and `$b` are present in `$colors` If yes, return `true` else return `false` I could obviously do if(in_array($a, $colors) && in_array($b, $colors)){ //true } But, I am hoping for an array function that can do both in on call, or any method simpler than that. I tried with `array_intersect()` to no avail.
`array_intersect()` should have worked, but you may also try `array_diff()`. If the result is an empty array, then every element of the first array was found in the second array. <?php if(count(array_diff(array($a, $b), $colors)) == 0) { // Both found } ?>
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, arrays" }
How do I reference a hidden input in a specifc form using jQuery? I have a series of forms on a page that all have a recordId value as a _hidden_ input. The form name/id is GPA-Entry-Form-1. I am trying to get the value of the hidden field this way: $('#deleteThisGPAEntry-1').click(function() { var recordId = $('GPA-Entry-Form-1 #recordId').val(); alert('You clicked me. ID: ' + recordId); return false; }); Unfortunately, I am doing something wrong. When the button is clicked the alert comes up with the message and the value of the recordId is showing as undefined. What am I doing wrong? Thanks, Josh
You forgot the pound sign! (Probably the most common jQuery mistake). Assuming your form has GPA-Entry-Form-1 as the ID then use: $('#GPA-Entry-Form-1 #recordId').val(); if it's the name then use: $('form[name=GPA-Entry-Form-1] #recordId').val(); Either way you are using the descendent selector correctly. It should work. Good Luck!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jquery, jquery selectors" }
Twitter Bootstrap dropdown determine what element is clicked I have a following code: <div id="dropdown" class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="#">Dropdown link 1</a></li> <li><a href="#">Dropdown link 2</a></li> </ul> </div> I am clicking on some link. How can I determine what link is clicked? $("#dropdown").click(function(e) { console.log(e); //how?? }); I am also using jQuery.
You should be able to use this: $('.dropdown-menu > li > a').on('click', function(e) { e.preventDefault(); //Disable href window.alert($(this).text()); //$(this).text() is what you want }); Update: Demo here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, twitter bootstrap, drop down menu" }
Call of default constructor with unexpected results I encountered unexpected behavior of default constructor. Having this class class Data { public: Data() { std::cout << "default ctor"; } }; and calling Data(x); calls the default constructor, whereas calling double x; Data(x); produces _conflicting declaration 'Data x'_. I suppose it is some kind of vexing parse, but I don't see the logic behind that. Can you please explain how the g++ compiler sees that?
The issue here comes from way back when C was introduced. When you write type(name); it is parsed as declaring a variable like type name; That means in Data(x); you declare a variable named `x` that is of type `Data` and in double x; Data(x); you declare a variable name `x` with the type `double` and then try to declare a variable named `x` with the type `Data`. You can't redefine a variable like that so you get an error. * * * If you want to just declare a temporary `Data` then the syntax would be Data();
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c++, default constructor" }
mysql - insert in two tables using autogenerate key from first insert table without using LAST_INSERT_ID I need to insert some values into two different tables, this tables need to be linked, let's supposed I have: * table product * id INT NOT NULL AUTO_INCREMENT PRIMARY KEY * name TEXT NOT NULL * table ingredients * id INT NOT NULL AUTO_INCREMENT PRIMARY KEY * productID INT NOT NULL * value TEXT NOT NULL so I need to insert in a commit both tables but table ingredients needs to be linked the productID autogenerated by product table, I DON'T want to use LAST_INSERT_ID because I'm inserting multiples rows at the same time and I may get and id from other row.
You can use `LAST_INSERT_ID()` since is multi-thread safe. MySQL's docs say: > For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, sql" }
Dependency parsing using spacy I have a code for dependency parsing which gives output in the form of arcs. Is there any other way to display the parse tree for a paragraph? Because for a paragraph, the parse tree is huge. Is there a better way to display the parse tree for a paragraph?
First of all, setting the compact flag in Displacy will reduce the size of tree shown. options = {'compact': True} svg = displacy.render(doc, style='dep',options=options) But only this won't work for large paragraphs. What I'll suggest is, instead of viewing the dependency parse of the whole paragraph, break the paragraph into sentences first. Then parse each sentence and view them. You can save the parse trees of each sentence as a SVG file and then see them one by one. Here is the code for saving SVG: svg = displacy.render(doc, style='dep',options=options) f = open('sample.svg', 'w') f.write(svg) f.close() Alternatively, you can save the whole parse tree of the paragraph as SVG and open it in a browser. Then you can easily view it with zoom and scroll.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, parsing, nlp, dependencies" }
Docker compose with up command recreate image unintentionally In docker-compose.yml there are two services. Those get the image from a repository. The first time the services are started with `docker-compose up -d`. It worked good and after some time the images were stopped because of Docker update and restart. Then with `docker start` only one of the images was started. It worked good and after another update and restart(months later), `docker-compose up -d` is executed. In this case the manually started service previously was recreated and data was lost. First, can this be recovered, and second, is this expected? Thanks
Well that your data is lost is expected. You need to mount a "volume" to your container and store your data in this volume to keep it. This way it doesn't matter if you destroy your container or use a completely different one. You always can mount your data volume and you are fine. < If there is a way to recover? I really don't think so but I'm not 100% sure... Also maybe check this out for more clarity why the container was rebuild the second time What is the difference between docker-compose up and docker-compose start?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "docker, docker compose" }
Handling click events inside ABPersonViewController I am implementing - (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier delegate in my custom class which subclasses `ABPersonViewController`. The delegate method is catching the click events inside the `ABPersonViewController` subclass. But how will I know which field exactly has been clicked. For eg. if I click on the home address field, how will I handle this case inside the delegate method.
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{ if(property == kABPersonAddressProperty){ ABMutableMultiValueRef multi = ABRecordCopyValue(person, property); CFStringRef address = ABMultiValueCopyValueAtIndex(multi, identifier); NSLog(@"Address %@", (NSString *)address); // Do your tasks here CFRelease(address); } return YES; } Just like `kABPersonAddressProperty` you can check all other properties like phone number, email, url etc.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "iphone, ios, abpersonviewcontroller" }
How to make Keywords section for IEEEtrans conf. document class TeX file I need to make below code as the Keywords of my paper in `IEEEtran` conference document class: \par \textbf{\textit{Keywords$—$}} Please help me with this. Thanks
The class provides the `IEEEkeywords` environment; the default header is "Index Terms", but you can change this with a redefinition of `IEEEkeywordsname` \documentclass[conference]{IEEEtran} \renewcommand\IEEEkeywordsname{Keywords} \begin{document} \begin{abstract} We will discuss the most important subject. \end{abstract} \begin{IEEEkeywords} Broad band networks, quality of service, WDM. \end{IEEEkeywords} \end{document} ![enter image description here](
stackexchange-tex
{ "answer_score": 9, "question_score": 4, "tags": "ieeetran, abstract, keywords" }
Set the height of a child div to parents height - siblings height I have 2 child divs within a parent div. Child1 is the header and Child2 is the body. I want the height of Child 2 to be set to height of Parent - Child1. Child2 has content so it should be scrollable I know I can set the height for Child2 via JS, but is it poss to do this via CSS?
If the height is fixed you can simply give the header negative `margin-bottom` equal to the height of the header, then give the content divider `padding-top` also equal to that height: HTML: <div id="wrapper"> <div id="header"></div> <div id="content"></div> </div> CSS: html, body { height:100%; margin:0; } #wrapper { height:100%; background:#000; } #header { height:100px; /* Fixed height header */ margin-bottom:-100px; /* Negative height of header */ z-index:2; position:relative; } #content { min-height:100%; padding-top:100px; /* Height of header */ box-sizing:border-box; z-index:1; position:relative; } JSFiddle example.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "css, html, height" }
Creating module on prestashop i need to create a module on prestashop on product page , im new in prestashop idk how to do that . This module should be on bottom of page ,it contains product technical description Can someone tell me how to do that Ps : i know nothing about prestashop Hooks .... Thanks in advance!
There is one hook that may fit you. `displayProductFooter` **First you have to add the hook registration in your module install function** public function install() { ... $this->registerHook('displayProductFooter'); } **Then create a function to display the content in the hook** Save the content you want to display and use the return to send a string with all the HTML you want to print in the product footer. In the params you will also find some useful variables like the product ID. public function hookDisplayProductFooter($params) { // Your content here return $output; } **The same procedure should work with any other hook** (as long as it's a display hook)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "module, prestashop, hook" }
Android app force closing I'm new to Android app development and Java in general. I have been watching some tutorials but decided it was time to start doing something on my own. I'm trying to make a fat caliper calculator where I insert all the info in one activity, calculate it and then pass the results on to another activity for displaying it. For some reason I'm getting a force close every time I hit the calculate button and I'm not sure what's causing it or which activity. Here's the code: MainActivity Display Can you see what's causing the force closes? Thanks.
The problem is you are starting display Activity but not passing bundle to the Display Activity. Change your code like this when you are starting Display Activity. Intent a = new Intent(MainActivity.this, Display.class); a.putExtras("giveResults",packet ); startActivity(a);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android" }
What is the rationale for not allowing temporaries bound to references in initialization lists to live past end of ctor? Simple example: struct A { A() : i(int()) {} const int& i; }; Error from gcc: > a temporary bound to 'A::i' only persists until the constructor exits Rule from 12.2p5: > A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. **Question** Does anybody know the rationale for this rule? It would seem to me that allowing the temporary to live until reference dies would be better.
I don't think the _not_ extending to the object lifetime needs justification. The opposite would! The lifetime extension of a temporary extends merely to the enclosing scope, which is both natural and useful. This is because we have tight control on the lifetime of the receiving reference variable. By contrast, the class member isn't really "in scope" at all. Imagine this: int foo(); struct Bar { Bar(int const &, int const &, int const &) : /* bind */ { } int & a, & b, & c; }; Bar * p = new Bar(foo(), foo(), foo()); It'd be nigh impossible to define a meaningful lifetime extension for the `foo()` temporaries. Instead, we have the default behaviour that the lifetime of the `foo()` temporary extends to the end of the full-expression in which it is contained, and no further.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++" }
Adding Port to Ping I am using VB.net to ping a domain/IP, using the following code; My.Computer.Network.Ping(Address, 1000) I now want to add a port to the domain/IP - e.g google.co.uk:21 How would I go about this?
You cannot ping a port but you can try to connect to a specific port using either TCP/IP or UDP. The port concept belongs to the transport layer of the protocol stack (either TCP or UDP) while the ping is at the lower network layer (the ICMP protocol).
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "vb.net" }
Does standardizing a random variable that is not normally distributed change the underlying distribution? For my analysis I am standardizing Response Times, which are usually known to be skewed and are in my data set, using the "classic" standardization method of substracting the grand mean and dividing by the standard deviation. Although I was wondering if standardizing for variable you know are not normally distributed is not actually operating some kind of filtering on the distribution. I compared the pre and post histogram of the variable, and even if the post histogram is still skewed, I am not sure if it not in fact smoother. Pre scaling histogram Post scaling histogram I guess my question is : is it relevant to standardize non normally distributed variables using the classic method ? If not, what are the best way to scale appropriately the distribution ? Thanks!
Your histograms look different because your stats package is binning the data. Normalization of a data set by subtracting its mean and dividing by its standard deviation doesn't really change the shape of the data set; it's only scaling the data and shifting the center to achieve a mean of zero and a sd of 1. If you want to confirm this, do a normal QQ plot of the pre data and a normal QQ plot of the post data: you'll see the plots look pretty much the same. The R command qqnorm(x) will produce a normal quantile-quantile plot of your data set `x`, which compares the shape of your data to a normal distribution. If you really want to change the shape of your data, you need to apply a nonlinear transformation, such as the log transformation (which will pull in a long right tail), or, less drastically, a square root function. (There are many other possibilities.)
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "normal distribution, standard deviation" }
How to call WCF service application from local html file? Is it possible to call a WCF service hosted in localhost from a file that is in a directory of our computer (like "C:\Test\") ?
Yes and no. Yes, by ajax to a remote WCF service. Otherwise, no, the file would need to be 'processed' by a webserver in order to connect to the service, such as running an .aspx page from IIS.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "wcf" }
Software Load Balancer for android i have H+ data network from my mobile phone network operator and 2Mb connection with Wi-Fi router connected to the DSL in home. i want to Combine this two in my android device (galaxy note II ) for faster and more reliable Internet. is there any software that do it for me?
There's an app called "Super Download" that seems to be what you're looking for. From the XDA page: > **DESCRIPTION** : > > Download web files much faster by using wifi and mobile data at the same time! Share or open a link from any program, like the web browser, and download it at speeds up to two times faster than usual. This is the only tool that can download using wifi and mobile data connection simultaneously*! It's a paid app on Play Store, but free on XDA.
stackexchange-android
{ "answer_score": 0, "question_score": -1, "tags": "internet, samsung galaxy note 2, 4g" }
does cassandra vnode increase disk seek time Cassandra 1.2 add new feature virtual node. Devide one physical node into multiple virtual nodes. Does increase disk seek time. Because different virtual nodes have different commit logs. When write into different commit logs, it increases disk seek time.
Virtual nodes do not have individual commit logs. There is only one commit log for each physical node.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "cassandra 2.0" }
Is there any standalone EJB container that drops into non-j2ee web servers? Right now I am using a web-server which does not contain EJB container. If my application needs EJB container, how could I add one?
Do you really mean _into_? If yes, then maybe have a look at OpenEJB (the EJB Container implementation for Apache Geronimo). But I can't say that it's widely used. Actually, why not just replacing your servlet container with a full Java EE server if you need EJBs, I don't get it, something like JBoss AS or GlassFish.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "java, webserver, ejb" }
How to split and find last index in Google Sheets? I need to achieve something like following in Google-sheets: tag_name A_B_C C A_B_C_D D I am using following formaula: =INDEX(SPLIT(B2, "__"), 0, 3) I want to dynamically pass last index of the set of values returned by split.
You can try **REGEXEXTRACT** formula, I am assuming your data range starts from "A1". Put this formula in "A1" and fill it down per your requirement =REGEXEXTRACT(A1,"\S$") ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "arrays, regex, google sheets, google sheets formula, array formulas" }
Group by number of occuring values I have a table `Customers` and a table `Customercards`. A customer can have multiple customercards. The table `Customercards` references the customer with customer_id. I would like to write a query which counts the customercards per customer and prints out the result, grouped by the count of cards, like this: cards count 0 50 1 37 2 13 3 5 4 1 Currently I have a query which counts the customers with a given count of cards using `group by` and `having`. But I have to use this query multiple times to count the different amounts of customercards. Example: SELECT c.customer_id FROM CUSTOMERS c JOIN CUSTOMERCARDS cc ON c.customer_id = cc.customer_id group by c.customer_id having count(*) = 2; Is there a way to put this into one query?
I call this a "histogram of histograms" query. You can use two aggregations: SELECT cnt, COUNT(*), MIN(customer_id), MAX(customer_id) FROM (SELECT c.customer_id, COUNT(*) as cnt FROM CUSTOMERS c JOIN CUSTOMERCARDS cc ON c.customer_id = cc.customer_id GROUP BY c.customer_id ) c GROUP BY cnt ORDER BY cnt; I include the minimum and maximum customer ids, just because I find it use to have examples when I do such a query. Note: You don't actually need the `JOIN`, so you can simplify this to: SELECT cnt, COUNT(*), MIN(customer_id), MAX(customer_id) FROM (SELECT cc.customer_id, COUNT(*) as cnt FROM CUSTOMERCARDS cc GROUP BY cc.customer_id ) c GROUP BY cnt ORDER BY cnt;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, db2" }
Confusion understanding the torque in FBD? I am confused by the sign and direction torques and forces in linked/attached photo especially that the gravitational force acting on the counter weight on left is having positive sign in torque equation below and gravitational force acting on the propeller actuator on the right has negative sign in below torque equation?![enter image description here](
It looks as though the torques about $O$ are being considered. ![enter image description here]( A convention has to be decided on and with no further information it looks as though anticlockwise torques are defined to be positive and clockwise torques are negative.
stackexchange-physics
{ "answer_score": 1, "question_score": 0, "tags": "newtonian mechanics, forces, rotational dynamics, torque, free body diagram" }
Moving /boot partition without messing up the system ![Partition layout]( I have deleted my old Linux Mint partition I had installed beside my new current Rafaela one. Thus, I have free space I want to add to my home partition. Above you can see the partition layout: sda4 is the system partition with /boot sda5 is the home partition I want to extend home with the unallocated space, but unfortunately the system partition is inbetween and I would need to move it to the beginning of the unallocated space. Since I got a warning message that the system might not boot anymore, if I move /boot, I would like to know how I can do it without breaking the system. It makes sense that the system cannot boot, if the bootloader cannot find the kernel anymore, so I guess after changing the partition layout I need to chroot on / and regenerate grub. Does anybody know how I can add the unallocated space to home safely?
The boot sector needs to find the boot partition, after that the boot loader goes off the partitions, it doesn't care were they're located at on the drive. I'm assuming you're using gparted live by the screen shot. After resizing you'll need to from the shell: 1. Mount your relocated root partition containing the boot directory 2. if /boot is a separate partition mount it in the root partition mount 3. Mount the /dev to the dev directory in your root mount using the --bind option 4. Chroot into the root mount 5. Run grub-install or liloconfig to reinstall the boot sector
stackexchange-unix
{ "answer_score": 7, "question_score": 11, "tags": "boot, partition, grub2" }
Is a computer mouse considered an embedded system? Can a computer mouse (optical) be considered an embedded device? Does it adhere to the definition of an embedded system? Is there any good reference for how a computer mouse is made?
An embedded system is a computer which is found inside another device to serve a specific purpose. Old mice (with balls) did not have all the components of a computer inside them, so they were equipped with logic devices but not a computer and if you don't have a computer it can't be an embedded system. The definition of a computer I'm using is of a device that can be programmed with some form of CPU, memory and perhaps some I/O. Other definitions exist and are more or less similar. Modern optical mice have a processor integrated into an ASIC that drives a camera that takes pictures of a surface, records them to memory, and compares them against newer pictures and decides in which direction the device was moved. This qualifies as an embedded system so a modern mouse is an embedded system. The fact you connect it as a peripheral is not contradictory.
stackexchange-electronics
{ "answer_score": 10, "question_score": 6, "tags": "embedded, mouse" }
can we use join inside join in mysql? i have 3 tables structure is below ### tbl_login login_id | login_name 1 | keshav ### tbl_role role_id | login_id( refer to tbl_login.login_id) 1 | 1 ### tbl_stuff stuff_id | role_id( refer to tbl_role.role_id) 1 | 1 i need data in follow format stuff_id | login_name 1 | keshav how to use JOIN to retrive the above data in mysql?
You can keep joining tables with eachother on (almost) whatever parameters you like. As far as the database engine is concerned, it doesn't care about the name or meaning of the parameters you are joining (you could be joining a name with a height for instance). It might be helpfull to read up on joins here. SELECT st.stuff_id , l.login_name FROM dbo.tbl_stuff st INNER JOIN dbo.tbl_role r ON r.role_id = st.role_id INNER JOIN dbo.tbl_login l ON l.login_id = r.login_id
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "mysql" }
What other games or chess variants are useful to improve your chess skills? I know about Chess960, and you can play that online at lichess.org. Furthermore, I like playing Go as well. But are there any good variants and other ways to train that you use, and you know to work well?
I believe that studying Shogi added 50 points to my chess game. They are related games and thus share some related concepts. I believe Shogi showed me things about chess I had not understood before.
stackexchange-chess
{ "answer_score": 13, "question_score": 21, "tags": "chess960, training, chess variants, learning" }
Which tense to use when writing a diary? For writing diary content every day, which English tense is appropriate to use? Things have all happened already. I usually write late at night (end of the day) or the next day. Should I use simple past, present perfect simple, or another tense?
Past tense is my instinct. Yet it depends on what you are writing and the writing's purpose. If it's an adventure story or something with more of a fast pace then clearly present tense might be best. "What was that? Rustling in the bushes nearby. Footsteps just beyond--sound like a person, a large person. I must move on. Now." That is more effective than: "Yesterday I discovered signs of a person having walked behind my trail during the night. I am being followed and better switch up my route." _The Blair Witch Project_ versus an Aldo Leopold work.
stackexchange-writers
{ "answer_score": 13, "question_score": 7, "tags": "tenses" }
Does the Alexa Skills Kit enable handling the main conversation in code? I have a basic model set up but it appears that the Alexa beta builder expects the design of the model to be up front with explicit lists of possible answers to requests. However, the Jeopardy game on that platform appears to allow new answers from day to day and I am supposing they don't need to update their model each day. Can someone shed light on this process? I would like to be able to: * Launch intent to start conversation * Handle back and forth within web service response and request * Handle basic stop/start from Alexa How does the middle portion (response/request) get modeled up front?
Currently, you need to provide a list of expected values for each of your slot types (a slot type may be question_response in this case). Not sure how Jeopardy works but I have a couple ideas: * They provide huge lists of possible answers (and they update them from time to time). I bet there is no one writing new questions every day, they have a pool of questions and they can anticipate the answers to those. * They have access to an API that is not open to the general public (as do people who are participating in the social bot challenge) or are allowed to use the deprecated LITERAL slot type.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "alexa skills kit, alexa skill" }
How to not "cut" / "flatten" lines when moving the spines in matplotlib? I want to move the spines of an axes outward a bit, as shown in the bottom example on < However, when I do this, the lines which are close to the axes borders are "cut": It seems like the lines drawn still accommodate for the spine (which isn't there any more). You can see the effect in the plots on the example page I linked above: In the bottom example, the blue line is "flattened" in its maximum and minimum. How can I avoid this?
The problem is that the lines are still clipping at the edge of the axes area, even though you have moved the spines away. You can turn clipping off: ln, = ax.plot(...,) ln.set_clip_on(False) but you will need to be careful that your axes range and your data range line up (as it will run off to the left and right as well).
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "matplotlib" }
How to interpret performance results of AWS Machine Learning Service? I am working on a pilot with Amazon Web Service Machine Learning service and I have some soubts. I have used a Binary Classifier model and, in my opinion, the histogram of the results obtained does not match the numerical results. According to the histogram, the distribution of False Positives is higher than the distribution of True Negatives but the numerical results do not present this behavior. ![Histogram]( * 778 true positives * 15,178 true negatives * 6,663 false positives * 173 false negatives Anyone can bring some insights into this matter? Thank you,
This is the answer to my question from the Amazon Web Services Support team through their forums: > After doing some digging around, I found that the Y-axis scaling is logarithmic for the histograms, which explains why a direct 1:1 area comparison of the true negatives and false positives would not be consistent with the numerical results. If we didn't display a logarithmic scale, my guess would be that most of your Y-axis would be dominated by the true negative and true positive results and the false positives and false negatives could be too small to noticeably see. Reference: < If the Y-axis is logarithmic the results DO match with the provided histograms.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "amazon web services, machine learning, classification, amazon machine learning" }
Enable/disable button depending on On Demand Resources tag I have some buttons linked to an `IBAction` that plays a sound. -(IBAction)listen { // play the audio } My files are organized with On Demand Resources, and I have 3 tags: * level1 * level2 * level3 So what I'd like to achieve is: **if the user is on level 1, he will only be able to play files with the`level1` tag**. If he clicks on a `level2` tag audio, an alert will appear. How can I check if a file has a specific tag?
I'm not aware of an API to access a resource's ODR tags, so you have to use some other way to map resources to access controls in your app code. Perhaps you can use `pathForResource(_:ofType:)` to inspect the path of the resource, and if it is in the directory "level2", prevent your user from accessing the resource until they are on the appropriate level?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, objective c, bundle, resourcebundle, on demand resources" }