source
sequence
text
stringlengths
99
98.5k
[ "english.stackexchange", "0000115007.txt" ]
Q: "To dress less attractive/flashy" to not "make yourself stand out as being more important than someone else" I'm looking for (phrasal) verbs that describe these two actions. Imagine in a music concert, if yor're a guest singer that is invited by the main singer, you're usually going to want to dress less attractive/flashy than the main singer because you don't want to stand out as being more important and draw all the attention to yourself. So is there a verb/phrasal verb that describes "to dress less attractive or make yourself look less attractive", and a verb that describes "to make yourself stand out as being more important than someone else" or "make someone else appear less important/worse than yourself"? I.e. He is [...] because he doesn't want to [...] the main singer. A: He is dressed/behaving/acting unobtrusively because he doesn't want to [upstage] the main singer. The synonym inconspicuously fits nicely too. There are a number of words following that approach, each carrying different nuance, that may also work. humbly modestly circumspectly simply There are also words that better capture the relative aspect of the behavior but are less descriptive, such as deferentially. The words suggested so far for the second missing word work, although if you are still dissatisfied with what you have I can think of a few more. A: 'He is [...] because he doesn't want to [...] the main singer.' He is dressing down because he doesn't want to upstage the main singer. A: Here are my suggestions: She dressed understated... She demured herself... She blended into the background... She arrived incognito... ... because she doesn't want to upstage the main singer. ... because she doesn't want to overshadow the main singer. ... because she doesn't want to eclipse the main singer. ... because she doesn't want to overpower the main singer.
[ "stackoverflow", "0000843247.txt" ]
Q: type/value mismatch in template C++ class declaration I am trying to compile the following code on Linux using gcc 4.2: #include <map> #include <list> template<typename T> class A { ... private: std::map<const T, std::list<std::pair<T, long int> >::iterator> lookup_map_; std::list<std::pair<T, long int> > order_list_; }; When I compile this class I receive the following message from gcc: error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’ error: expected a type, got ‘std::list<std::pair<const T, long int>,std::allocator<std::pair<const T, long int> > >::iterator’ error: template argument 4 is invalid I have removed file names and line numbers , but they all refer to the line declaring the map. When I replace the pair in these expressions with an int or some concrete type, it compiles fine. Can someone please explain to me what I am doing wrong. A: You need to write typename before std::list<...>::iterator, because iterator is a nested type and you're writing a template. Edit: without the typename, GCC assumes (as the standard requires) that iterator is actually a static variable in list, rather than a type. Hence the "parameter type mismatch" error. A: Your code needs a "typename" keyword. std::map<const T, typename std::list<std::pair<T, long int> >::iterator> lookup_map_;
[ "quant.stackexchange", "0000045960.txt" ]
Q: relationship between notional amounts of volatility swaps and variance swaps Taking volatility swap payoff as $$( \sigma_F - \sigma_S ) * volatility~notional $$ and Taking variance swap payoff as $$( \sigma_F^2 - \sigma_S^2 ) * variance~notional $$ I am trying to understand the origin of the relationship; $$variance~notional = \frac{vega}{(2\sigma_s)}$$ I understand that vega is volatility notional as $\frac{\delta f} {\delta \sigma_F}$ is the change of payoff with respect to volatility point I understand that variance notional is $\frac{\delta f} {\delta \sigma_F^2}$ as this is the change of payoff with respect to variance point and $2\sigma_s$ is obviously the derivative of $\sigma_s^2$ A: Look at the infinitesimal version of the change in variance: $$ d\sigma^2 = 2\sigma d\sigma + (d \sigma)^2 $$ The Ito term $(d\sigma)^2$ is non-zero for stochastic processes, and is of order $dt$, but if we ignore that then we get the approximate relation $$ d\sigma^2 \approx 2 \sigma d\sigma $$ which is where the factor $2 \sigma$ comes from in the translation between variance and vega notional. As AlexC wrote it is based on a linearization of the P/L (the Ito term is a "convex" term if you will)
[ "stackoverflow", "0008634652.txt" ]
Q: Linux/php require parent directory I am on Ubuntu 11.10 and installed apache server to host my local website before i host it from a company. My website root location is "/home/a1a4a/www/" I have a php file in /home/a1a4a/www/account/account_info.php" That i want him to include a file in "/home/a1a4a/www/include/fg_membersite.php" It's what i did from account_info.php require_once('./include/fg_membersite.php'); And i got this error Warning: require_once(./include/fg_membersite.php): failed to open stream: No such file or directory in /home/a1a4a/www/account/account_info.php on line 10 Fatal error: require_once(): Failed opening required './include/fg_membersite.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/a1a4a/www/account/account_info.php on line 10 So what have i done wrong ? How to fix . I have full permissions ( sudo chown -R www-data ). Thanks and Happy Holidays :) A: Always use the absolute path or you will face errors depending on the calling script. require_once('./include/fg_membersite.php'); should actually be require_once(dirname(dirname(__FILE__)).'/include/fg_membersite.php');
[ "stackoverflow", "0025516986.txt" ]
Q: Add value in textarea before existing textarea value Currently when i click on Add Value it adds value after existing textarea value. but i want it to add New Value before existing textarea value. $('#add_value').click(function() { $(this).next().val($(this).next().val()+'New Value'); }); <div id="add_value">Add Value</div> <textarea>(want to add new value here) Existing value...</textarea> A: Change: $(this).next().val($(this).next().val()+'New Value'); to: $(this).next().val('New Value' + $(this).next().val());
[ "stackoverflow", "0035014631.txt" ]
Q: How to swap values by changing one of them via javascript? There are three fields with numbers from 1 to 3. I am trying to make it so if a person uses only the arrows there should always be one "1", one "2", and one "3". Why is it not always working and how could I make it work? jQuery(document).ready(function($) { var prevNumber; $(".numbers").focus(function() { prevNumber = $(this).val(); }).change(function() { curNumber = $(this).val(); $('.numbers[value="' + curNumber + '"]:not(:focus)').first().val(prevNumber); prevNumber = curNumber; }); }); <input type="number" value="1" min="1" max="3" step="1" class="numbers" /> <input type="number" value="2" min="1" max="3" step="1" class="numbers" /> <input type="number" value="3" min="1" max="3" step="1" class="numbers" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> Here is a jsfiddle. A: Why that approach doesn't work The value attribute is not connected to the value of the input. I know that sound surprising. :-) The value attribute is the default value of the input. It doesn't change (unless you use setAttribute("value", x); or .defaultValue = x; to change it). Your selector uses the attribute: $('.numbers[value="' + curNumber + '"]')... So it'll work on inputs whose value hasn't been changed by the user, but will fail once they have, selecting the wrong input. How you could fix it You could change the default value as well as the value by setting both defaultValue and value (being sure to update the defaultValue on the one that changed, too), like this (see comments): jQuery(document).ready(function($) { var prevNumber; $(".numbers").focus(function() { prevNumber = $(this).val(); }).change(function() { // Get the element wrapper var $this = $(this); // Get the current value var curNumber = $this.val(); // Make sure the default value on this element is updated this.defaultValue = curNumber; // Update both the value and default value on the other // input that used to have this number $('.numbers[value="' + curNumber + '"]:not(:focus)').first().val(prevNumber).prop("defaultValue", prevNumber); prevNumber = curNumber; }); }); <input type="number" value="1" min="1" max="3" step="1" class="numbers" /> <input type="number" value="2" min="1" max="3" step="1" class="numbers" /> <input type="number" value="3" min="1" max="3" step="1" class="numbers" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> What I'd do instead (maybe -- your approach is growing on me) I think I'd approach it without trying to remember state, e.g., just in the change: Get the number of the one that changed, then assign any other numbers to its siblings. See the comments: var numbers = $(".numbers").map(function() { return this.value; }).get(); jQuery(document).ready(function($) { $(".numbers").change(function() { // Get a wrapper for this input var $this = $(this); // Get this number var thisNumber = $this.val(); // Get the unused numbers var unused = numbers.filter(function(num) { return num != thisNumber; }); // Assign them to the siblings, in order $this.siblings().val(function(index) { return unused[index]; }); }); }); <input type="number" value="1" min="1" max="3" step="1" class="numbers" /> <input type="number" value="2" min="1" max="3" step="1" class="numbers" /> <input type="number" value="3" min="1" max="3" step="1" class="numbers" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> I kept that general, rather than assuming the values would only be 1, 2, and 3 (and rather than assuming there'd only be three numbers).
[ "mathematica.stackexchange", "0000033506.txt" ]
Q: CustomTicks - Changing NumberPoint -> "," How can I change the number point from . to , in CustomTicks ? The Mathematica built-in function NumberForm[Plot[…],NumberPoint -> ","] doesn't work any more, if you use e.g. LinTicks. A: Update Here is a better way. FixedPointForm is used to format the tick numbers. Its default options include NumberPoint -> ".": Options[FixedPointForm] (* {NumberSigns -> {"-", ""}, NumberPoint -> ".", SignPadding -> False, Debug -> False} *) Reset the NumberPoint option as desired: SetOptions[FixedPointForm, NumberPoint -> ","]; Plot[E^x Sin[10 x], {x, -1, 1}, Ticks -> LinTicks] Original The question, CustomTicks and small ranges, shows one can pass a formatting function to LinTicks: Plot[E^x Sin[10 x], {x, -1, 1}, Ticks -> (LinTicks[##, TickLabelFunction -> (NumberForm[#, {2, 1}, NumberPoint -> ","] &)] &)] [A weakness in the original solution is having to set the number form explicitly instead of automatically.] A: Unless the number point is explicit in this tick package can't you just use Style to override the global setting? e.g and Style[ Plot[E^x Sin[10 x], {x, -1, 1}], NumberPoint -> "CC"]
[ "stackoverflow", "0023439679.txt" ]
Q: Drawing a clock timer with a fill I'm trying to make a timer that mimics a clock, with a ticking hand. I have no problem drawing a clock texture and then a line for the hand, but I also want the space behind the clock hand to have a fill. So as time goes on, I want the clock to "fill up" starting at the origin (0:00) all the way up to the clock hand. I basically want to do this: What's the best way for me to do this? I have the foundation, just don't know how to add the fill part. A: You should aproximate it building a triangle fan. int n=0; VertexPostionColor[] V = new VertexPositionColor[num_triangles+2] V[0] = Center; for (var angle = start ;angle<=end; angle += (end - start) / num_triangles) { V[++N].Position = new Vector3( Math.Cos(angle), Math.Sin(angle)) * radius + Center; V[N].Color = CircleColor; } Short[] Index = new Short[num_triangles*3]; for (int i = 0; i< num_triangles; i++) { Index[i*3] = 0; Index[i*3+1] = i+1; Index[i*3+2] = i+2; } GraphicsDevice.DrawUserIndexedPrimitives(...); If you want to get complicated using a spritebatch, you have to use a small sector texture, and draw it multiple times rotating it about the center. this is an example, it need to be tuned to be precise. float SectorAngle = Mathhelper.ToRadians(10); Texture2D SectorTex; Vector2 Origin = new Vector2(SectorTex.Width/2, SectorTex.Height); for (var angle=start; angle<=end; angle+=SectorAngle) { spriteBatch.Draw(SectorTex, Center, null, Color.White, Origin, angle, scale,...) }
[ "stackoverflow", "0020713241.txt" ]
Q: Selecting an element based on the child inner text I have a script which adds a filter field to the top of each column. However, there's a column called "Type" that I'm trying to get it to skip. For example in the image below there's a type field with pdf icons. I'm trying to prevent a textfield from being added to this column. This is the script: $(this).children("th,td").each(function() { if($(this).hasClass("ms-vh-icon") || $(this).hasClass("ms-vh-group") ) { // attachment + Group (SLN) tdset += "<td></td>"; } else { // filterable tdset += "<td><input type='text' class='vossers-filterfield' filtercolindex='" + colIndex + "' placeholder='Filter...'/></td>"; } colIndex++; }); This is what it looks like: A: You can find the anchor with that text using this if ($(this).find('a').text()=='Type') but it could be that there are spaces in the text so you would need to trim or use replace or a regex to make sure you're catching it, for example var $a=$(this).find('a'); // add empty to prevent null if ($a.length && $a.text().replace('Type', '')!=$a.text())... But having seen at the code it seems you can just search for #diidSortDocIcon tdset=''; $(this).children("th,td").each(function(colIndex){ if ($(this).find('#diidSortDocIcon').length || $(this).is('.ms-vh-icon, .ms-vh-group')){ tdset += "<td>&nbsp;</td>"; }else{ tdset += "<td><input type='text' class='vossers-filterfield' filtercolindex='" + colIndex + "' placeholder='Filter...'/></td>"; } }); You can also set colIndex in the each rather than use colIndex++ and you hadn't set tdset=''; http://jsfiddle.net/v7brU/2/
[ "stackoverflow", "0008881163.txt" ]
Q: Mysql Collation for arabic using php I am facing problem with mysql database. I cant save arabic text into the mysql data even i change the collation to cp1256_general_ci and tried other collation. I cant get much help from search. Anyone who can help me out please help I have change collation at database level as well as colum level to cp1256_general_ci for some fields. Please suggestion how should i set this as i am NEW PHP and MySQL I also write simple INSERT statement to insert input data in mysql do i have to take any case while inserting data into mysql if it is in arabic A: The short answer is: Use UTF-8 everywhere. "Everywhere" means In all forms that are used to store data in your database The database connection The database tables and columns In all pages that output data from the database. if you have existing CP-1256 data (or incoming data in that character set that you can't change) you can use iconv() to convert it into UTF-8. Note that if using UTF-8, you need to make sure you use multibyte-safe string functions. This is often already the case because standard function like strlen() get mapped to mb_strlen(). To find out whether this is the case on your server, see the manual entry on the issue.
[ "stackoverflow", "0023840385.txt" ]
Q: How to compile and run .cpp files after writing them in sublime text? I really prefer writing code in sublime text or anything else. So, naturally that's what I want to use. However, when I try to open the file in Netbeans, I get an error. So, I want to know how I can save a .cpp file from sublime text and then go about running it through the command prompt. I know I have to set up a path or something, but I'm not exactly sure how to do it. Thanks for any help at all. Also, I am new to C++ and programming in general(have dabbled in Python a bit). EDIT: Really sorry, I meant how do I actually execute/run the file afterwards. Like if the program were to just print out "Hello World". A: The following build system should suit your needs, assuming that you're using the GNU Compiler Collection and g++ for compiling your .cpp files: { "cmd": ["g++", "${file}", "-o", "${file_base_name}"], "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "working_dir": "${file_path}", "selector": "source.c, source.c++", "variants": [ { "name": "Run", "cmd": ["${file_base_name}"] } ] } Please note that the following instructions are for Sublime Text 2 only... To use it, select Preferences -> Browse Packages... to open the Packages folder in Windows Explorer. It should be located in C:\Users\YourUserName\AppData\Roaming\Sublime Text 2. Or not, depending on your install. In either case, browse to the C++ directory and open the file C++.sublime-build in Sublime and set the syntax to JSON if you want it to look prettier. Replace its entire contents with the code above, then save the file. The old code is kind of convoluted, and also runs some commands needlessly. Now, set the build system by going to Tools -> Build System and selecting Automatic. Assuming that g++ is in your PATH, you can build your executable using the CtrlB keyboard shortcut, also available via Tools -> Build. If your binary has already been compiled, you can run it by pressing CtrlShiftB. One final note: if your program asks for any kind of input, or has a graphical user interface, this Run command won't work. Instead, replace it with the following: "name": "Run", "cmd": ["start", "cmd", "/k", "${file_path}/${file_base_name}"], "shell": true This will open a new instance of the command line and run your program from there, instead of inside Sublime. The /k switch means that the window will be kept open after your program has run, so you can examine output, errors, etc. If instead you want the window to close immediately, simply change the /k to /c. Good luck!
[ "stackoverflow", "0013896089.txt" ]
Q: adding JLabel properties to anonymous variable types? I'm trying to add borders to JLabels but I don't have names for them, they're created within a loop and the "this" keyword does not do what I want. for(int i = 1; i < first; i++){ this.setBorder(BorderFactory.createLineBorder(Color.black)); dayBoxes.add(new JLabel("")); } I want the blank JLables to have properties beyond just having no text. If the JLabels all had names I could easily do name.setBorder but that isn't the case here and I think it would be very inefficient to name them all in an array. Is there a way to accomplish this? A: for(int i = 1; i < first; i++) { JLabel label = new JLabel(""); label.setBorder(BorderFactory.createLineBorder(Color.black)); dayBoxes.add(label); }
[ "stackoverflow", "0002206823.txt" ]
Q: What's the ANT version in iPhone 3Gs and how can I access it? I want to build up an ANT network (e.g. see wikipedia article ) and develop sport accessories using the iPhone 3Gs with integrated ANT Controller (used by Apple for Nike+iPod devices) to communicate with them. I need to know which ANT version the controller is (ANT or ANT+), what it's able to do (receiver/transeiver) and how I can acces the controller with software on iPhone. Until know I was able to access the serial interface and open a socket over WLAN but the only information for this topic was this one. It's one year old before the 3Gs with integrated ANT and External Accessory Framework was released. Changed that something? Are there new efforts of other groups? Every information would be helpful. Thanks. A: the apple / nike footpod is not an ANT compatible device. It works with a nordic transceiver nRF2402 but with a different protocol. I reverse engineered it: The Apple foot pod works with a nRF2402 transmitter and a PIC16F688 microcontroller. Repetition rate: 1000ms Number of configuration bytes: 2 Number of address bytes: 2 Number of raw data bytes: 28 Remark: the configuring is sent just before power down, i.e. 2 bytes are transmitted at that time, first 0xe7 then 0x99. The device remains active for approximately 5 seconds after a step has been detected. The device works with a simple piezo sensor to detect footsteps. A fully transaction is made by sending 3 blocks of 9 bytes, then 11bytes then 10 bytes (almost no gap between each byte within a block, bit clock is below 2us) with a gap of 1.5ms between each block. A crosscheck with the configuration frame of the receiver shows the following: 0x00 0xe0 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0xc2 0xbd 0x43 0x4f 0x33 This means (see datasheet of nRF2401; configuration): - channel 0x19 -> 2425MHz - RF power max; 16MHz clk; shock burst; 250kbps; 1 RX channel active - CRC enabled; CRC 16bit; address length 16bit - Address for channel 1: 0xc2bd (high byte first) - Address for channel 2: all 0x00 - 0xe0 -> 224 data bits for channel 1 - 0x00 -> 0 data bits for channel 2 The address length is 16 bit, and 224 bits of raw data are transmitted. The standard device address is 0xc2 0xbd anyway the data sent via link starts with the following pattern: Address: 0xC2 1. byte of block 1 0xBD 2. byte of block 1 Data: 0x0D 3. byte of block 1 0x01 4. byte of block 1 0x47 5. byte of block 1 0xA0 6. byte of block 1 0x54 7. byte of block 1 0x22 8. byte of block 1 0xA0 9. byte of block 1 . 10.byte of block 2 . 11.byte of block 2 . hope this helps a little
[ "stackoverflow", "0030288546.txt" ]
Q: Finding a string by looping through an array php I have this array $filelist Array ( [0] => . [1] => .. [2] => .DS_Store [3] => 11-96.eml [4] => 11-97.eml ) Which is a list of all files in a particular directory... Sometimes there is no .DS_Store file, sometimes there is, sometimes there are 2 eml files, sometimes there are as many as 6. I'm trying to loop through and find the first array position a .eml file exists so that I can work out how many file are eml and where to start referencing the array.. I have tried... function firstFileInList($filelist) { $x = 0; foreach ($filelist as $value) { if(strpos($filelist, ".eml") == false) { $x = $x + 1; //break; } } return $x; } This returns 5, if I include the break it returns 1 and I was expecting to get 4. Please could somebody point me in the right direction or even if there is a completely better way to do this then I would be more than grateful to see that... Thanks Paul, A: break exists every PHP loop directly when it is called, even if there are other elements. Use continue to get to the next element. Based on your question I'm trying to loop through and find the first array position a .eml file exists function firstFileInList($filelist) { foreach($filelist as $k => $v) if(strpos($v, ".eml") !== false) return $k; return false; }
[ "softwareengineering.stackexchange", "0000165406.txt" ]
Q: When is using stdio preferable to fstream? I work on a well-established, embedded C++ code base. We have been using a proprietary API to our filesystem. For better integration with third-party C libraries, we are currently in the process of implementing most of stdio.h and fcntl.h. I made what I thought was a non-controversial proposal that we should also implement the fstream class and encourage new C++ code to use it instead of the new (to our code base) C-style API. We already have the stdout parts of iostream available, although it is not widely used. Given a choice between using stdio and fstream, what are good reasons to choose stdio for embedded software development in C++? A: My top reason would be familiarity with the library. Back in my embedded days (a little over a decade ago), most C++ developers in several companies where I worked came from a strong C background. C-style input and output did not require any learning, while dealing with advanced concepts of manipulating streams often required checking a book. As far as purely technical reasons go, I don't think there are any: properly implemented stream I/O should be as fast as the C-style I/O, and use roughly the same amount of memory.
[ "stackoverflow", "0056589169.txt" ]
Q: How to flatten out tab key value pair text format file in a table where key is column and value is data for the cell I have a text file where 1 single row is split in multiple rows in key-value pair. The data looks like below: 1,800001348 2,IDEAL OPTION 27,Place of Service 39,IDEAL OPTION 400,123 MAIN STREET 400,Ste G 410,SEATTLE 420,Washington 423,BENTON 430,99336 and the whole block repeats again: 1,850000900 2,INVITAE CORPORATION 27,Place of Service 39,INVITAE CORPORATION 400,XYZ 1st AVENUE 410,SAN FRANCISCO 420,California 423,SAN FRANCISCO 430,94103 I have loaded this file in Oracle using SQL Loader. The integrity is maintained since I have a sequence number attached to all rows so I can traverse the table row by row and tell where the 1st row begins and ends. KEY VALUE SEQNUM 1 800001348 1 2 IDEAL OPTION 2 27 Place of Service 3 39 IDEAL OPTION 4 400 123 MAIN Street 5 400 Ste G 6 410 KENNEWICK 7 420 Washington 8 423 BENTON 9 430 99336 10 1 850000900 11 2 INVITAE CORPORATION 12 27 Place of Service 13 39 INVITAE CORPORATION 14 400 XYZ 1st AVENUE 15 410 SAN FRANCISCO 16 420 California 17 423 SAN FRANCISCO 18 430 94103 19 select case when KEY = '1' then value else null end as FACILITY_ID, case when KEY = '2' then value else null end as Unknown_num, case when KEY = '27' then value else null end as TYPE_OF_LOCATION, case when KEY = '39' then value else null end as EXTERNAL_NAME, case when KEY = '400' then value else null end as ADDRESS, case when KEY = '410' then value else null end as CITY, case when KEY = '420' then value else null end as STATE, case when KEY = '423' then value else null end as COUNTY, case when KEY = '430' then value else null end as ZIP_CODE, value, SEQNUM from MDM_ODS.EAF_EPIC_IMPORT order by SEQNUM; I get the transposed result but as expected they are all on different rows and have a lot of nulls, any way to combine them to make them in 1 row? FACILITY_ID UNKNOWN_NUM TYPE_OF_LOCATION EXTERNAL_NAME ADDRESS CITY 800001348 IDEAL OPTION Place of Service IDEAL OPTION 8514 W Gage Blvd Ste G KENNEWICK A: Something like this could work: SELECT facility_id, unknown_num, type_of_location, external_name, address, city, state, county, zip_code FROM ( SELECT key, value facility_id, LEAD(value, 1) OVER (ORDER BY seqnum) unknown_num, LEAD(value, 2) OVER (ORDER BY seqnum) type_of_location, LEAD(value, 3) OVER (ORDER BY seqnum) external_name, LEAD(value, 4) OVER (ORDER BY seqnum) address, LEAD(value, 5) OVER (ORDER BY seqnum) city, LEAD(value, 6) OVER (ORDER BY seqnum) state, LEAD(value, 7) OVER (ORDER BY seqnum) county, LEAD(value, 8) OVER (ORDER BY seqnum) zip_code FROM MDM_ODS.EAF_EPIC_IMPORT ORDER BY seqnum) WHERE key=1; LEAD(X, N) OVER (ORDER BY <sort-order>) means return the value of column "X" that is "N" number of rows ahead of the current row with the rows ordered by <sort-order>.
[ "stackoverflow", "0014729981.txt" ]
Q: MS Word not trusted by Outlook? a Delphi app automating Word mail merge and emailing via Outlook (Office 2007). Windows XP2 Anti Virus Software Status -Valid Trust Center Programmatic Access NEVER WARN ME. (A different app not using Word but using Outlook emails without warning). Yet Outlook Security Guard Warning Messages appear. 2 alerts per email x 700 email addresses = One angry customer. Why? Without using a 3rd parry add-in, is there a way round this? Is there a way to merge one record and the run some delphi code then another record merge? I can then bypass Outlook altogether A: Outlook has no idea where the call comes from. Outlook VBA and COM add-in are explicilty trusted, any external code is not. You will not see the prompt if you have up-to-date antivirus software. Otherwise your option are listed at http://www.outlookcode.com/article.aspx?id=52 In your case (Mail Merge), try to do the mail merge to a file, then mail the files in your code using the workarounds listed at the URL above.
[ "travel.stackexchange", "0000109324.txt" ]
Q: Visa required for marrying an Australian citizen in Australia, when neither party is or intends to be resident I am an Austrian (EU) citizen, and my fiancée is an Australian/British dual-citizen. We cohabit in the UK. We intend to get married and honeymoon in Australia next month and then return to the UK. Which visa do I need to fly to Australia next month? I had been pretty sure that an eVisitor (subclass 651) was all that was required, but some online searching has put this into doubt, since "getting married" seems to be a non-tourist purpose of visit. However, the Partner visa appears to only be necessary if we intend to migrate to Australia, which we do not. If the 651 is the correct visa, am I running an uncomfortable risk of being refused entry if I am asked by the border agent about my purpose of visit and I state "getting married and honeymooning"? (We have filed our NIM, which we arranged last year via a UK notary public.) A: The Australian Marriage Law does not require residency so, yes, you may get married on a tourist visa (subclass 651). A Notice of Intended Marriage form must have been submitted, along with the other required documents, which you’ve done. As your fiancée also has Australian citizenship and must enter (and leave) on that passport, you may want to bring along proof that you and she live in the UK and intend to return there afterwards (e.g., property, employment, etc.). Australia destination weddings are a quite popular, and that is very much the purpose of your visit: celebrating your union with family and friends, and an idylic honeymoon in fabulous Oz. In Australia, the Attorney-General's Department is responsible for the laws setting out the requirements for getting married in Australia. Getting married in Australia To be legally married in Australia, a person must: not be married to someone else not be marrying a parent, grandparent, child, grandchild, brother or sister be at least 18 years old, unless a court has approved a marriage where one party is aged between 16 and 18 years old understand what marriage means and freely consent to marrying use specific words during the ceremony give written notice of their intention to marry to their authorised celebrant, within the required time frame. The celebrant you choose will help you understand these requirements. You don't have to be an Australian citizen or a permanent resident of Australia to legally marry here. You can find marriage visa information on the Department of Immigration and Border Protection website, if you hope to live in Australia after your marriage.
[ "unix.stackexchange", "0000162526.txt" ]
Q: Apt-get failing in bash script? I have several machines (running Ubuntu LTS 12.4 64-bit) which need to be configured in the same way, so I created a shell script which will run automatically the first time the machine boots. It works for the most part, but any call to apt-get fails. As an example, here are two commands I want to execute. debconf-set-selections ./files/ldap.preseed apt-get -y install ldap-auth-client Here is the result if I type those lines directly: root@spare:/tmp/scripts# debconf-set-selections ./files/ldap.preseed root@spare:/tmp/scripts# apt-get -y install ldap-auth-client Reading package lists... Done Building dependency tree Reading state information... Done The following packages will be installed: ldap-auth-config libnss-ldap libpam-ldap The following NEW packages will be installed: ldap-auth-client ldap-auth-config libnss-ldap libpam-ldap 0 upgraded, 4 newly installed, 0 to remove and 67 not upgraded. Need to get 0 B/200 kB of archives. After this operation, 877 kB of additional disk space will be used. Preconfiguring packages... [and so on...] But if I execute a shell script containing only those lines, this happens: root@spare:/tmp/scripts# ./ldap.cr Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package ldap-auth-client The same thing occurs when I run the script using sudo, or chown it to root first. What is the difference, to the program, if it is being called directly or through a shell script? And is it possible to convince it otherwise? EDIT: More information: root@spare:/tmp/scripts# apt-cache policy ldap-auth-client ldap-auth-client: Installed: (none) Candidate: 0.5.3 Version table: 0.5.3.0 500 http://us.archive.ubuntu.com/ubuntu/ precise/main amd64 Packages A: Running the script through dos2unix before executing it caused it to work properly. I'm guessing that apt-get was reading the extra \r at the end of the line as part of the package name, and thus looking for ldap-auth-client\r (which doesn't exist) instead of ldap-auth-client (which does).
[ "stackoverflow", "0016209113.txt" ]
Q: Push segue in xcode with no animation I am using normal storyboarding and push segues in xcode, but I want to have segues that just appear the next view, not slide the next view (as in when you use a tab bar and the next view just appears). Is there a nice simple way to have normal push segues just "appear" and not "slide", without needing to add custom segues? Everything is working completely fine, I just want to remove that slide animation between the views. A: I was able to do this by creating a custom segue (based on this link). Create a new segue class (see below). Open your Storyboard and select the segue. Set the class to PushNoAnimationSegue (or whatever you decided to call it). Swift 4 import UIKit /* Move to the next screen without an animation. */ class PushNoAnimationSegue: UIStoryboardSegue { override func perform() { self.source.navigationController?.pushViewController(self.destination, animated: false) } } Objective C PushNoAnimationSegue.h #import <UIKit/UIKit.h> /* Move to the next screen without an animation. */ @interface PushNoAnimationSegue : UIStoryboardSegue @end PushNoAnimationSegue.m #import "PushNoAnimationSegue.h" @implementation PushNoAnimationSegue - (void)perform { [self.sourceViewController.navigationController pushViewController:self.destinationViewController animated:NO]; } @end A: You can uncheck "Animates" in Interface Builder for iOS 9 A: Ian's answer works great! Here's a Swift version of the Segue, if anyone needs: UPDATED FOR SWIFT 5, MAY 2020 PushNoAnimationSegue.swift import UIKit /// Move to the next screen without an animation class PushNoAnimationSegue: UIStoryboardSegue { override func perform() { if let navigation = source.navigationController { navigation.pushViewController(destination as UIViewController, animated: false) } }
[ "tridion.stackexchange", "0000015157.txt" ]
Q: Setting Multiple Deployer On Web8 We upgraded to Web8 . We would like to setup two website "staging and testing" on a single server for this i need to configure two deployer service. will this setup require separate discovery service as well for both website?? A: Yes - even though you're on a single machine, each environment is completely independent of each other, so everything needs to be duplicated. Deployer, Discovery, Website, etc, must all be duplicated (and make sure to use different ports for the services). In a nutshell, it's not different from doing it in multiple machines.
[ "stackoverflow", "0035783011.txt" ]
Q: Resize a textarea on load I'm using the autosize plugin (but wouldn't mind alternatives) and I need to resize the textarea I have on its load, and it should also automatically resize as you type (like what autosize.js allows you to do). My question is, does autosize come with this option out of the box? I didn't find such info on its webpage and I tried both $(el).trigger('autosize.resize') and autosize.update($(el)) after my text areas are loaded and neither worked. Also, my textareas are original hidden, which will be toggled show with a CSS class. I wonder if that's hindering the process. Any ideas is appreciated, thanks! A: With a display: none you can't calculate anything because the height & width of the textarea is 0x0px. You must update the size after textarea has been shown. Edit : or toggle it shown first then apply autosize.
[ "stackoverflow", "0014756026.txt" ]
Q: How to downgrade Xcode to previous version? I have to use Xcode occasionally, and have now come across a problem where I've upgraded to Xcode 4.6, but another piece of software I'm using doesn't support it, so I need to go back to Xcode 4.5. I'm not used to the way Macs work in general, so if the answers provided could be written with that in mind, that'd be helpful. :) A: I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac. Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal. A: When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools
[ "stackoverflow", "0050002129.txt" ]
Q: Read multiple *.rtf files in r I have a folder with more than 2,000 rtf documents. I want to import them into r (preferable into a data frame that can be used in combination with the tidytext package). In addition, I need an additional column, adding the filename so that I can link the content of each rtf document to the filename (later, I will also have to extract information from the filename and save it into seperate columns of my data set). I came across a solution by Jens Leerssen that I tried to adapt to my requirements: require(textreadr) read_plus <- function(flnm) { read_rtf(flnm) %>% mutate(filename = flnm) } tbl_with_sources <- list.files(path= "./data", pattern = "*.rtf", full.names = TRUE) %>% map_df(~read_plus(.)) However, I get the following error message: Error in UseMethod("mutate_") : no applicable method for 'mutate_' applied to an object of class "character" Can anyone tell me why this error occurs or propose another solution to my problem? A: I finally solved the problem, with some workaround. 1) I converted the *.rft files to *.txt files by using the textutil command in the MacOSX terminal: find . -name \*.rtf -print0 | xargs -0 textutil -convert txt By doing so, I get also rid of formatting. 2) I then used the read_plus function of Jens Lerrssen. However I now use read.delim instead of read_rtf and included two options (stringsAsFactors and quote) to get rid of warnings and/or errors: read_plus <- function(flnm) { read.delim(flnm, header = FALSE, stringsAsFactors = FALSE, quote = "") %>% mutate(filename = flnm) } 3) Finally, I read in all the *.txt files and renamed the columnn V1 at the end. df <- list.files(path = "./data", pattern = "*.txt", full.names = TRUE) %>% map_df(~read_plus(.)) %>% rename(paragraph = V1)
[ "stackoverflow", "0017018154.txt" ]
Q: Codification in JSP Imports Good night. I'm having trouble import static html page to a JSP page with UTF-8. My JSP is UTF-8. I Write my HTML fragment with UTF-8, but I include with <%@include file="includes/menu.html"%>, the text is with the wrong encoding. My JSP is complex, but my html is, an simple example: <div> <ul> <li>Text with Á (acentuation)</li> </ul> </div> Is very simple html, containing the application menu, but this error is occurring. A very simple JSP is: <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <head> <meta charset="UTF-8" /> <title>Example</title> </head> <body> <%@include file="includes/menu.html"%> </body> PS: if I put directly in JSP, it works normally. A: The solution to this problem is to change the menu.html to menu.jsp and on the top of the new file add <%@page contentType="text/html" pageEncoding="UTF-8"%> and then include this jsp in your page <body> <%@include file="includes/menu.jsp"%> </body>
[ "stackoverflow", "0028659865.txt" ]
Q: MapReduce Job (written in python) run slow on EMR I am trying to write a MapReduce job using python's MRJob package. The job processes ~36,000 files stored in S3. Each file is ~2MB. When I run the job locally (downloading the S3 bucket to my computer) it takes approximately 1 hour to run. However, when I try to run it on EMR, it takes much longer (I stopped it at 8 hours and it was 10% complete in the mapper). I have attached the code for my mapper_init and mapper below. Does anyone know what would cause an issue like this? Does anyone know how to fix it? I should also note that when I limit the input to a sample of 100 files it works fine. def mapper_init(self): """ Set class variables that will be useful to our mapper: filename: the path and filename to the current recipe file previous_line: The line previously parsed. We need this because the ingredient name is in the line after the tag """ #self.filename = os.environ["map_input_file"] # Not currently used self.previous_line = "None yet" # Determining if an item is in a list is O(n) while determining if an # item is in a set is O(1) self.stopwords = set(stopwords.words('english')) self.stopwords = set(self.stopwords_list) def mapper(self, _, line): """ Takes a line from an html file and yields ingredient words from it Given a line of input from an html file, we check to see if it contains the identifier that it is an ingredient. Due to the formatting of our html files from allrecipes.com, the ingredient name is actually found on the following line. Therefore, we save the current line so that it can be referenced in the next pass of the function to determine if we are on an ingredient line. :param line: a line of text from the html file as a str :yield: a tuple containing each word in the ingredient as well as a counter for each word. The counter is not currently being used, but is left in for future development. e.g. "chicken breast" would yield "chicken" and "breast" """ # TODO is there a better way to get the tag? if re.search(r'span class="ingredient-name" id="lblIngName"', self.previous_line): self.previous_line = line line = self.process_text(line) line_list = set(line.split()) for word in line_list: if word not in self.stopwords: yield (word, 1) else: self.previous_line = line yield ('', 0) A: The problem is you have more number of small files. Add bootstrap step using s3distcp to copy files to EMR. while using s3distcp try to aggregate small files into ~128MB file. Hadoop is not good with large number of small files. Since you are manually downloading files to your computer and running hence it run faster. Once you copy file to EMR using S3distCP use file from HDFS.
[ "stackoverflow", "0055987082.txt" ]
Q: Selecting Most Recent Date Relative to Another Table Just stumped on syntax for this... I have Two tables in mysql & I need to fetch records from Table A when following criteria are met: 1) Name in Table A matches the name in Table B AND 2) The price for the most recent day in Table B is less than the record in Table A So...running the query on example tables below would fetch me these two records: 03-17-2019 Bob 8 03-20-2019 John 10 Essentially, I need to evaluate each row in Table A, check the matching name in Table B that has the most recent date relative to the record under evaluation in Table A, and then determine if the price in Table A is greater than the price for the most recent matching name in Table B. After that, I need to calculate the difference between the prices. So, in the two records above, the difference would be 2 and 4 Table A Date | Name | Price 03-08-2019 Bob 6 03-25-2019 Bob 2 03-17-2019 Bob 8 03-20-2019 John 10 Table B Date | Name | Price 03-16-2019 Bob 4 03-28-2019 Bob 9 03-02-2019 Bob 12 03-10-2019 John 6 Thank you for the help! A: Join twice the tables, once to get the min date difference and then to get the row with the min date difference: select a.* from tablea a inner join tableb b on b.name = a.name inner join ( select a.name, min(abs(datediff(b.date, a.date))) mindatediff from tablea a inner join tableb b on b.name = a.name group by a.name ) g on g.name = a.name and abs(datediff(b.date, a.date)) = g.mindatediff See the demo. or: select a.* from tablea a inner join tableb b on b.name = a.name where abs(datediff(b.date, a.date)) = ( select min(abs(datediff(x.date, y.date))) from tablea x inner join tableb y where x.name = a.name and y.name = b.name ) See the demo. Results: | date | name | price | | ---------- | ---- | ----- | | 2019-03-17 | Bob | 8 | | 2019-03-20 | John | 10 |
[ "stackoverflow", "0008572344.txt" ]
Q: cURL in PHP not retrieving a response I'm trying to load a page from another website in PHP so that I can scrape its content. This works with pretty much any other web page, but for some reason it doesn't work with this one: http://www.bkstr.com/webapp/wcs/stores/servlet/CourseMaterialsResultsView?catalogId=10001&categoryId=9604&storeId=10161&langId=-1&programId=562&termId=100022286&divisionDisplayName=Stanford&departmentDisplayName=CS&courseDisplayName=103&sectionDisplayName=01 Anybody know why? Is it a firewall or something? Or know of another way to go about doing this? Even in another language? Here's the cURL code I'm using: $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $theurl); $response = curl_exec($ch); curl_close($ch); I've tried these cURL options: curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_PORT , *ports 22 and 433*); ** Know of any other ports to try? Or a way to figure out which port the host is using? I'm trying to loop thru possible ports right now. I've tried getting the info and here's what I've got: $info = curl_getinfo($ch); print_r($info); returns Array ( [url] => http://www.bkstr.com/webapp/wcs/stores/servlet/CourseMaterialsResultsView?catalogId=10001&categoryId=9604&storeId=10161&langId=-1&programId=562&termId=100022286&divisionDisplayName=Stanford&departmentDisplayName=CS&courseDisplayName=103§ionDisplayName=01 [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 289 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.602861 [namelookup_time] => 0.226121 [connect_time] => 0.285047 [pretransfer_time] => 0.285149 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => 0 [upload_content_length] => 0 [starttransfer_time] => 0.602824 [redirect_time] => 0 ) Thanks a bunch! A: I realize now that the web admins must not have enabled CORS. To scrape the page I wrote a Java bot that loaded the page in my browser and saved it to a file. Messy but it ultimately worked...
[ "stackoverflow", "0030085951.txt" ]
Q: Add external UI component to Storyboard I wanna add an external UI component to storyboard in Xcode 6 (for instance, a custom button from https://github.com/a1anyip/AYVibrantButton). Is it possible to add it to storyboard directly by drag and drop? If not, where shall I call the init function and how do I specify its position in the code? Thanks a lot. A: If you look at the code, and the ReadMe for the AYVibrantButton, it says that you should add the button to a UIVisualEffectView, and that it must be instantiated with initWithFrame:style:. When you add a button to the storyboard and set its class to AYVibrantButton, the init method called will be initWithCoder:, so none of the setup that the author does in initWithFrame:style: takes place. If you want to add the button in the storyboard, you need to update the code to include an initWithCoder: method. Replace the initWithFrame:style: implementation in the Author's code with the following, - (instancetype)initWithFrame:(CGRect)frame style:(AYVibrantButtonStyle)style { if (self = [super initWithFrame:frame]) { self.style = style; [self commonSetup]; } return self; } -(instancetype)initWithCoder:(NSCoder *)aDecoder { if (self = [super initWithCoder:aDecoder]) { self.style = AYVibrantButtonStyleFill; // need to add add a style here. Change it to one of the other styles to match your needs [self commonSetup]; } return self; } -(void)commonSetup { self.opaque = NO; self.userInteractionEnabled = YES; // default values _animated = YES; _animationDuration = kAYVibrantButtonDefaultAnimationDuration; _cornerRadius = kAYVibrantButtonDefaultCornerRadius; _roundingCorners = kAYVibrantButtonDefaultRoundingCorners; _borderWidth = kAYVibrantButtonDefaultBorderWidth; _translucencyAlphaNormal = kAYVibrantButtonDefaultTranslucencyAlphaNormal; _translucencyAlphaHighlighted = kAYVibrantButtonDefaultTranslucencyAlphaHighlighted; _alpha = kAYVibrantButtonDefaultAlpha; _activeTouch = NO; // create overlay views [self createOverlays]; #ifdef __IPHONE_8_0 // add the default vibrancy effect self.vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; #endif [self addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown | UIControlEventTouchDragInside]; [self addTarget:self action:@selector(touchUp) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchDragOutside | UIControlEventTouchCancel]; }
[ "tex.stackexchange", "0000098303.txt" ]
Q: Table with several dimensions I have several dimensions to put in a table in LaTeX, these are actually results of an experiment. I am not sure what is the best way to do it in LaTeX. Here is a snapshot of one of the possibilities: What is the syntax of obtaining such a table or if there is a better way to present tables with multi dimensions. A: I think the syntax might be straight forward, but the layout of your columns should highly depend on what your trying to explain/show/tell. Just straight taking your tabular and putting it into LaTeX using booktabs for style and floatrow to center the tabular and putting the caption above using the code \documentclass[a4paper,12pt]{scrartcl} \usepackage[utf8]{inputenc} \usepackage{booktabs,floatrow} %center tables \floatsetup[table]{objectset=centering,capposition=top} \begin{document} For a straight forward thingy see Table~\ref{Tab1}. \begin{table} \begin{tabular}{lllll}\toprule &&\textbf{Backward} & \textbf{Forward} & \textbf{Bidirectional}\\\midrule atis & Training & 345 & 235 & 345\\ & Test & 356 & 252 & 345\\ brown & Training & 465 & 345 & 346\\ & Test & 456 & 342 & 253\\ wsj & Training & 345 & 235 & 254\\ & Test & 4336 & 634 & 3434 \\\bottomrule \end{tabular} \caption{The Results}\label{Tab1} \end{table} \end{document} results in the tabular as seen here But to me it looks like you want to compare Training and Test for certain methods, each applied to one „Object of interes“ (artis, brown & wsj) - so maybe you want to spend one column for each object and get a better way to compare those two by using something like „subcolumns“ as in the following MWE \documentclass[a4paper,12pt]{scrartcl} \usepackage[utf8]{inputenc} \usepackage{booktabs,floatrow} %center tables \floatsetup[table]{objectset=centering,capposition=top} \begin{document} But maybe also the Table~\ref{Tab2} might be nice? \begin{table} \begin{tabular}{lrrrrrr}\toprule &\multicolumn{2}{c}{\textbf{Backward}}&\multicolumn{2}{c}{\textbf{Forward}}&\multicolumn{2}{c}{\textbf{Bidirectional}} \\\cmidrule(r){2-3}\cmidrule(r){4-5}\cmidrule(r){6-7} &Training&Test&Training&Test&Training&Test\\\midrule atis & 345 & 356 & 235 & 252 & 345 & 345\\ brown & 465& 456 & 345 & 342 & 346 & 253\\ wsj & 345 & 4336 & 235 & 634 & 254 & 3434 \\\bottomrule \end{tabular} \caption{The Results}\label{Tab2} \end{table} \end{document} Where i used \cmidrow additionally to group each of the Training-Test-Pairs and used \multicolumn to give these two columns a common title. The result is But that of course depends on your data, I assumed here, that Training and Test belonged to the same object, (atis for example) hence putting them in one row seems to be a good idea. Edit: For the first idea i just used l as left for the column layout, the second one is the one i prefer (r for right), but of course egreg's answer using siunitx is quite nice, too. A: You should load the booktabs package and siunitx; the former provides nice rules for tables, the latter is essential for typesetting correctly quantities with their unit of measure and numeric tabular data. \documentclass{article} \usepackage{booktabs} % for better looking tables \usepackage{siunitx} % for units of measure and data in tables \begin{document} \begin{tabular}{ l % left aligned column l % left aligned column *{3}{S[table-format=4.0]} % three columns with numeric data } \toprule &&\textbf{Backward} & \textbf{Forward} & \textbf{Bidirectional}\\ \midrule atis & Training & 345 & 235 & 345\\ & Test & 356 & 252 & 345\\ brown & Training & 465 & 345 & 346\\ & Test & 456 & 342 & 253\\ wsj & Training & 345 & 235 & 254\\ & Test & 4336 & 634 & 3434\\ \bottomrule \end{tabular} \end{document} I used 4.0 as the format because the numbers have four digits in the integral part and no decimal part. Of course you can specify as many columns as you wish, the *{3}{...} shortcut avoids multiple specifications. The headers for the numeric columns are automatically centered. You'll probably insert the tabular environment in a table float; there's plenty of examples in the site.
[ "stackoverflow", "0054172489.txt" ]
Q: JavaScript - "Combining" two similar arrays of objects Let's say I have the following two arrays: let arr1 = [ { id: "1234567890", name: "Someone", other: "unneeded", props: 123 } ... ]; let arr2 = [ { id: "1234567890", points: 100, other: "unneeded", props: 456 } ... ]; I need to combine these based on the name and points by id which looks like: [ { id: "1234567890", name: "Someone", points: 100 } ... ] One option would be to map them like so: let final = arr1.map(u => ({ id: u.id, name: u.name, points: arr2.find(uu => uu.id === u.id) })); However, this is inefficient for larger arrays (thousands of entries), since find() iterates through the array each time. I'm trying to make this more efficient. I read over Array.reduce(), but that doesn't seem like the answer (unless I'm wrong). How can I do this? A: You can create a Map from the objects of the second array so that you can access the corresponding object directly by id in constant time: let arr1 = [ {id: 1234567890, name: "Someone", other: "unneeded", props: 123}, {id: 1234567891, name: "Someone1", other: "unneeded1", props: 124}, {id: 1234567892, name: "Someone2", other: "unneeded2", props: 125} ]; let arr2 = [ {id: 1234567890, points: 100, other: "unneeded", props: 456}, {id: 1234567891, points: 101, other: "unneeded", props: 457}, {id: 1234567892, points: 102, other: "unneeded", props: 458} ]; let arr2Map = arr2.reduce((a, c) => { a.set(c.id, c); return a; }, new Map()); let final = arr1.map(({id, name, points}) => ({id, name, points: arr2Map.get(id).points || points})); console.log(final);
[ "math.stackexchange", "0001651081.txt" ]
Q: Let $F : X → X$ be continuous. Prove that the set $\{x ∈ X : F(x) = x\}$ of fixed points of F is closed in X Here X is a Hausdorff Space. I know that singleton sets, {x}, are closed in a Hausdorff space. Although Im not sure if thats how to use the Hausdorff property. Should I investigate $h=F(x)-x$? Can anyone give a hint A: In general you can’t investigate $F(x)-x$, since the operation of subtraction may not make any sense in the space $X$. HINT: One straightforward approach is to show that the set of non-fixed points of $F$ is open. Suppose that $F(x)\ne x$. $X$ is Hausdorff, so there are open sets $U$ and $V$ such that $x\in U$, $F(x)\in V$, and $U\cap V=\varnothing$. Use these open sets and the continuity of $F$ to show that there is an open nbhd $W$ of $x$ such that $F(y)\ne y$ for each $y\in W$. If you get completely stuck, there’s a further hint in the spoiler-protected block below. Show that you can find $W$ such that $x\in W\subseteq U$ and $F[W]\subseteq V$.
[ "stackoverflow", "0049850929.txt" ]
Q: Can not implicitly convert type 'System.Colections.Generic.IEnuerable' to 'product'. An explicit conversion exist I am new to asp.net MVC. i am getting the following the error while trying to assign : Can not implicitly convert type 'System.Colections.Generic.IEnuerable' to 'product'. An explicit conversion exist My Code is ILookup<string,product> productList = Model.ToLookup(x=>x.parentId,x=>x); IEnumerable<string> roots =Model.Select(x=>x.parentId).Except(Model.Select(x=>x.id)); foreach(var id in roots){ product pr = productList[id].Select(item => item);//Error here } where product is a class with properties int paretId;int id; Any help will be appreciated. A: change this product pr = productList[id].Select(item => item); to product pr = productList[id].Select(item => item).First(); or, more simply, product pr = productList[id]; Whenever write code like this: something.Select(t=>t) , it should remove the Select statement and become something
[ "stackoverflow", "0024923021.txt" ]
Q: SwipeRefreshLayout Tab layout. Webview can't scroll up Okay so I have a Tab view going inside of which I have a webview, a listview and a few other pages. I want to be able to do a SwipeRefreshLayout to refresh each item. I have this working on each page. But, when I scroll down in a webview I can't scroll back up. It triggers the refresh and rebuilds it. I'd like to be able to scroll up in my webview. Layout stuff <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swipe_container" android:layout_width="match_parent" android:layout_height="20px" android:layout_weight="1" android:nestedScrollingEnabled="true"> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Splash$PlaceholderFragment"> <TextView android:id="@+id/section_label" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/webView" android:layout_alignParentTop="true" android:layout_alignParentStart="true" android:overScrollMode="ifContentScrolls" android:nestedScrollingEnabled="false"/> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progressBar" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/listView" android:layout_centerVertical="false" android:layout_centerHorizontal="true" android:visibility="visible" /> </RelativeLayout> </android.support.v4.widget.SwipeRefreshLayout> The SwipeRefreshLayout is being used inside the fragment for my tabbed layout. swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container); swipeLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); swipeLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if(getArguments().getInt(ARG_SECTION_NUMBER) == 4 ) { stringArrayList.clear(); new updatetheQueue().execute(ctx); } else { swipeLayout.setRefreshing(false); } }}); A: You can use an OnScrollChangedListener to disable SwipeRefreshLayout when the WebView is not scrolled to the top. // Only enable swipe to refresh if the `WebView` is scrolled to the top. webView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if (webView.getScrollY() == 0) { swipeRefreshLayout.setEnabled(true); } else { swipeRefreshLayout.setEnabled(false); } } });
[ "french.meta.stackexchange", "0000000629.txt" ]
Q: Will this site eventually be accessible in French as well? + would a certain site request be viable I realize that this is only a beta version of the website, but if it gets finished, will they publish a French interface of this Stackexchange website as well? It only makes sense, as maybe native French speakers would like to help and answer questions, but can't because they aren't fluent enough in English yet. This brings me onto my new site request question: Would it be reasonable to start of a side for the English language for French speakers, or is Stackexchange too English-based to do something like that? I'm not asking for myself, as I'm learning French and not English, but I know many people who have the problem the other way around (who need to improve their English and are native French speakers). A: Six years ago, Stack Exchange founder Joel Spolsky wrote Our mission is to make the Internet a better place to get expert answers to your questions. Nothing about that mission says the questions have to be in English. It is our long term goal to make the Stack Exchange Network a great, planetary resource for all the world's citizens no matter what language they speak. Unfortunately, this vision is taking an extremely long time in coming. Although Stack Exchange has opened a few sites in languages other than English (with both questions and an interface in that other language), this is reserved to sites about programming. When Stack Exchange designed a localization framework, we put in a request for a user interface in French on this site but we have not had any answer from Stack Exchange. In the meantime, you can certainly ask questions in French on French Language, and you can get community support about the site itself in French here on meta. However, this does not solve the issue of making the site attractive to native speakers. For learners of English, there is a site English Language and Learners. You need to ask in English, and answers will be in English, but answerers do make an effort to adjust to the level of English that the asker should be able to understand. Il y a six ans, le cofondateur de Stack Exchange Joel Spolsky écrivait (traduction personnelle) : Notre mission est de contribuer à un meilleur Internet en offrant un lieu où des experts répondent à vos questions. Il n'y a rien dans notre mission qui la limite à la langue anglaise. Notre but à long terme est de faire du réseau Stack Exchange une ressource d'intérêt planétaire pour tous les citoyens du monde quelle que soit leur langue. Malheureusement cette vision tarde beaucoup à être réalisée. Stack Exchange a bien ouvert quelques sites dans d'autres langues que l'anglais (pour ce qui est des questions comme de l'interface utilisateur), mais c'est réservé aux sites sur la programmation. Quand Stack Exchange a mis en place une infrastructure de localisation, nous avons émis la demande d'une interface en français sur ce site, mais Stack Exchange n'a toujours pas répondu à notre demande. En attendant, vous pouvez poser des questions en français sur French Language, et vous pouvez demander de l'aide en français sur le fonctionnement du site ici-même sur meta. Mais cela ne résout pas le problème de l'attractivité du site pour les locuteurs natifs. Pour ceux qui apprennent l'anglais, il existe un site English Language and Learners. Les questions et les réponses y sont en anglais, mais les gens qui répondent font en général attention à ajuster leur anglais en fonction de ce que le demandeur est susceptible de comprendre.
[ "stackoverflow", "0050481609.txt" ]
Q: what is the purpose of BitSet valueOf in fromString method I would appreciate an explanation of what this line does exactly. BitSet.valueOf(new long[] { Long.parseLong(s, 2) }); While this code example posted by FauxFaus really helped me understand BitSet usage, I don't find the purpose of the above line or why. here is the full example: package com.tutorialspoint; import java.util.*; import java.util.BitSet; public class TimeZoneDemo { public static void main(String[] args) { BitSet bits1 = fromString("1000001"); BitSet bits2 = fromString("1111111"); System.out.println(toString(bits1)); // prints 1000001 System.out.println(toString(bits2)); // prints 1111111 bits2.and(bits1); System.out.println(toString(bits2)); // prints 1000001 } private static BitSet fromString(final String s) { System.out.println(BitSet.valueOf(new long[] { Long.parseLong(s, 2) })); return BitSet.valueOf(new long[] { Long.parseLong(s, 2) }); } private static String toString(BitSet bs) { return Long.toString(bs.toLongArray()[0], 2); } } Please note that I can't comment on the original answer to ask the OP. A: Long.parseLong(s, 2) parses the String s as a binary String. The resulting long is put in a long array and passed to BitSet.valueOf to generate a BitSet whose bits represent the bits of that long value. The reason BitSet.valueOf takes long array instead of a single long is to allow creation of BitSets having more than 64 bits.
[ "serverfault", "0000499701.txt" ]
Q: General advice about Network Application running on EC2 I've written a network application and deployed it on a single EC2 instance (M1-large). The application serves like a sort of a chat room (only it enables other stuff besides sending messages), which allows smartphone owners at close (physical) proximity, say up to 5 meters communicate. This is my first network application and I have some doubts and questions about it: Since this is a very selective chat room (you will only see people who are very near) I have no idea how I can do load-balancing: If I take for example 2 instances, one in Europe and one in the US, I would like to redirect people from Europe to the former, and people from the US to the latter, If I cannot guarantee this redirection, the whole application is worthless. Is there a way to do this using Route 53? Is there a point in doing it? Isn't one massive instance enough? I've tried to test heavy-load performance of the instance. So I've written my own application which simulated 200K requests per hour, and lunched it on other EC2 instances. There seemed to be no problem (other than increased latency for some requests, which sound normal for high CPU utilization in accepting a large quantity of connections simultaneously) My question is, does it seem like a good load-test if I expect to have 500K users. I know this is a rather vague question, but a rather vague answer will be sufficient as well. Security wise. Which general precautions should I take for reducing the risk of a security breach? Is disabling all ports (other than my application listening port) in the firewall a good idea? or is it redundant. Again, a rather vague question. I will appreciate any general answers. Thanks A: Since your application is proximity-based, you can set up servers in different regions with little-to-no need for cross-talk. Take advantage of Route53's feature "Latency Based routing". For the most part, this should result in people getting to the closest server. However, since it's not "geo-based routing", it's not guaranteed. The benefit of multiple world-wide servers compared to a single massive instance is that you'll reduce the latency between client and server. If your simulation properly represents the usage of your users, then your results should tell you a lot. If 200K requests per hour properly represents activity for 500K users, then you should be fine. If it does not, then adjust your tests. The key is to ensure your test properly represents 500K users, then your results will too. Close the ports in the security group for anything not essential to your application. Do not leave RDP, SSH, or database ports open. Only keep your application port open.
[ "stackoverflow", "0047971466.txt" ]
Q: Python for Web, do I need nginx/apache.. I'm making a web application for trading based on python (FLASK) and nodejs. Is it critical to use webserver (nginx in my case) for python? Currently im using webserver only for images and files and running it on subdomain at port 80, and using main domain for python. Could it work ? If not why do I need to use webserver? Thanks A: Why should you use a webserver instead of Flask's built in web server: It is not as efficient as a standalone one as it runs in a thread alongside the workers and they compete for CPU time inside a single process. It's also very inflexible and doesn't let you adjust the interfaces:workers ratio, which is how you can tune performance (based on if your site has a high number of open connections versus a high number of requests per second). The development server could just fail outright. It is not designed to be used as a long-running process (days, weeks, months), and so it has not been well tested to work in this capacity. If you are concerned at ALL about security (and not just the security of the data in the application itself, but the security of the box that will be running it as well) then you should not use the development server. It is not ready to withstand any sort of attack. Here's an example of how you can configure an nginx server for your Flask application.
[ "stackoverflow", "0015201171.txt" ]
Q: Use Custom dialog from outside the Activity I am working on to use the custom dialog from outside the activity, i have written the dialog code in a class and then call that dialog in the Activity on click of the button. But that is not working for me Application crashes when i click on the showDialog Button. Below is the code Activity code package com.Customers; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.res.Resources.Theme; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { Context context; int theme; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog); Button showDialog=(Button)findViewById(R.id.show_dialog); showDialog.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Custom_Dialog calcDialog=new Custom_Dialog(context,R.style.myCoolDialog); calcDialog.dailogCalculator(); } }); } } Custom Dialog Class package com.Customers; import android.app.Dialog; import android.content.Context; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; public class Custom_Dialog extends Dialog implements android.view.View.OnClickListener{ Context mContext; protected Custom_Dialog(Context context, int theme) { super(context, theme); } public boolean TouchEvent(int actionOutside) { return false; } public void dailogCalculator(){ Custom_Dialog alertbox = new Custom_Dialog(mContext, R.style.myCoolDialog); alertbox.requestWindowFeature(Window.FEATURE_NO_TITLE); alertbox.setContentView(R.layout.calculator); EditText calcDisplay=(EditText)alertbox.findViewById(R.id.editText1); Button value1=(Button) alertbox.findViewById(R.id.button1); value1.setOnClickListener(this); Button value2=(Button) alertbox.findViewById(R.id.button2); value2.setOnClickListener(this); Button value3=(Button) alertbox.findViewById(R.id.button3); value3.setOnClickListener(this); Button value4=(Button) alertbox.findViewById(R.id.button4); value4.setOnClickListener(this); Button value5=(Button) alertbox.findViewById(R.id.button5); value5.setOnClickListener(this); Button value6=(Button) alertbox.findViewById(R.id.button6); value6.setOnClickListener(this); Button value7=(Button) alertbox.findViewById(R.id.button7); value7.setOnClickListener(this); Button value8=(Button) alertbox.findViewById(R.id.button8); value8.setOnClickListener(this); Button value9=(Button) alertbox.findViewById(R.id.button9); value9.setOnClickListener(this); Button value00=(Button) alertbox.findViewById(R.id.button00); value00.setOnClickListener(this); Button value0=(Button) alertbox.findViewById(R.id.button0); value0.setOnClickListener(this); Button backspaceBtn=(Button) alertbox.findViewById(R.id.backspace); backspaceBtn.setOnClickListener(this); Button Ok_dialog=(Button)alertbox.findViewById(R.id.ok_dialog); Ok_dialog.setOnClickListener(this); Button Qty_btn=(Button)alertbox.findViewById(R.id.btn_qty); Qty_btn.setOnClickListener(this); alertbox.show(); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.button1: break; case R.id.button2: break; case R.id.button3: break; case R.id.button4: break; case R.id.button5: break; case R.id.button6: break; case R.id.button7: break; case R.id.button8: break; case R.id.button9: break; case R.id.button0: break; case R.id.button00: break; case R.id.backspace: break; case R.id.btn_qty: break; case R.id.ok_dialog: break; } } } Logcat 03-04 16:54:47.293: E/AndroidRuntime(275): at java.lang.reflect.Method.invokeNative(Native Method) 03-04 17:16:22.793: E/AndroidRuntime(332): FATAL EXCEPTION: main 03-04 17:16:22.793: E/AndroidRuntime(332): java.lang.NullPointerException 03-04 17:16:22.793: E/AndroidRuntime(332): at android.app.Dialog.<init>(Dialog.java:141) 03-04 17:16:22.793: E/AndroidRuntime(332): at com.Customers.Custom_Dialog.<init>(Custom_Dialog.java:13) 03-04 17:16:22.793: E/AndroidRuntime(332): at com.Customers.MainActivity$1.onClick(MainActivity.java:24) 03-04 17:16:22.793: E/AndroidRuntime(332): at android.view.View.performClick(View.java:2408) 03-04 17:16:22.793: E/AndroidRuntime(332): at android.view.View$PerformClick.run(View.java:8816) 03-04 17:16:22.793: E/AndroidRuntime(332): at android.os.Handler.handleCallback(Handler.java:587) 03-04 17:16:22.793: E/AndroidRuntime(332): at android.os.Handler.dispatchMessage(Handler.java:92) 03-04 17:16:22.793: E/AndroidRuntime(332): at android.os.Looper.loop(Looper.java:123) 03-04 17:16:22.793: E/AndroidRuntime(332): at android.app.ActivityThread.main(ActivityThread.java:4627) 03-04 17:16:22.793: E/AndroidRuntime(332): at java.lang.reflect.Method.invokeNative(Native Method) 03-04 17:16:22.793: E/AndroidRuntime(332): at java.lang.reflect.Method.invoke(Method.java:521) 03-04 17:16:22.793: E/AndroidRuntime(332): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 03-04 17:16:22.793: E/AndroidRuntime(332): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 03-04 17:16:22.793: E/AndroidRuntime(332): at dalvik.system.NativeStart.main(Native Method) Please guide me that where i am doing wrong. It really helps the others as well. A: Change Custom_Dialog constructor as : Context mContext; protected Custom_Dialog(Context context, int theme) { super(context, theme); this.mContext=context; //<<<<<< initialize mContext here } and also inside MainActivity onCreate initialize context with Activity Context before passing it to Custom_Dialog constructor as : //......your code here @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog); context=MainActivity.this //<<<<< initialize context here //......your code here
[ "stackoverflow", "0023082586.txt" ]
Q: Simple way to average all elements of all vectors in a list using R I'm an R beginner. I have a list containing numerical vectors of differing lengths. I would like to find the average of all the entries in all the vectors (not the average of each vector). Is there a simple way to do this? A: Simple as this: mean(unlist(yourlist))
[ "math.stackexchange", "0001900928.txt" ]
Q: Number of Dyck Paths that touch the diagonal exactly $k$ times? What is the number of Dyck Ppaths from $(0,0)$ to $(n,n)$ which touch the diagonal exactly $k$ times? The only permissible moves are from $(x,y)$ to $(x+1,y)$ or $(x,y+1)$. I know that when there is no restriction on the number of times we are allowed to touch the diagonal, the result is the $n^{th}$ Catalan Number. If we touch the diagonal after $2*i_1, 2*i_2, \dots, 2*i_k$ moves respectively such that $2 \sum_{j=1}^{k} i_j = 2n$ then the result seems to be the Catalan $k$-fold convolution formula as given here. This link claims that we can derive this formula in a simpler way by showing a bijection to paths related to the Catalan Triangle but the explanation seems to be rather unclear. Any help or pointers in literature or hints? A: Have a look at Rukavicka's proof of $C_n=\frac{1}{n+1}\binom{2n}{n}$. He introduces the combinatorial concept of exceedance of a path and a path transform the increases/decreases the exceedance by one. Now consider what happens to the the number of crossings of the main diagonal when applying such transform, and the solution will be at hand. As an alternative, we may consider Vandermonde's convolution. For instance, the following sum $$ \sum_{a+b=n}\frac{1}{a+1}\binom{2a}{a}\frac{1}{b+1}\binom{2b}{b}, $$ is the coefficient of $x^n$ in $$ \left(\sum_{m\geq 0}\binom{2m}{m}\frac{x^m}{m+1}\right)^2 = \left(\frac{1-\sqrt{1-4x}}{2x}\right)^2 =\frac{1-2x-\sqrt{1-4x}}{2x^2}$$ i.e. the coefficient of $x^{n+1}$ in $\frac{1-\sqrt{1-4x}}{2x}$, that is again a Catalan number. A: I find it easier to work with up-down paths, defined as sequence of up-steps (e.g., from $\langle m,n\rangle$ to $\langle m+1,n+1\rangle$) and downsteps (e.g., from $\langle m,n\rangle$ to $\langle m+1,n-1\rangle$). A Dyck path is then an up-down path that does not go below the $x$-axis, and there are $C_n$ Dyck paths from $\langle 0,0\rangle$ to $\langle 2n,0\rangle$. If $n,n'\ge 0$, $m<m'$, and $t\ge 0$, let $\mathscr{D}(m,n,m',n',t)$ be the set of Dyck paths from $\langle m,n\rangle$ to $\langle m',n'\rangle$ that hit the $x$-axis exactly $t$ times, and let $d(m,n,m',n',t)=|\mathscr{D}(m,n,m',n',t)|$. Thus, $d(0,0,2n,0,2)=C_n$. Suppose that $t\ge 1$, and $0\le k<t$. Let $P\in\mathscr{D}(m,n,m',n',t)$. Let the points where $P$ hits the $x$-axis be $\langle\ell_i,0\rangle$ for $i=1,\ldots,t$, where $\ell_1<\ldots<\ell_t$. Since $P$ is a Dyck path, $P$ has an up-step immediately after each of these points except possibly the last. Remove the first $k$ of these up-steps, and translate the resulting path upwards $k$ units to get a path $\hat P$; it’s straightforward to check that $\hat P\in\mathscr{D}(m,n+k,m'-k,n',t-k)$: the path has been shortened by $k$ steps, and the first $k$ hits have been eliminated. This procedure is reversible. If $P\in\mathscr{D}(m,n+k,m'-k,n',t-k)$, we first shift $P$ down by $k$ units to get an up-down path $P'$. For $i=1,\ldots,k$ let $\ell_i$ be minimal such that $\langle\ell_i,1-i\rangle$ is on $P'$. Let $Q$ be the up-down path obtained from $P'$ by inserting an up-step immediately after each of the points $\langle\ell_i,1-i\rangle$. Then $Q\in\mathscr{D}(m,n,m',n',t)$, and $Q=\hat P$. It follows that $$d(m,n,m',n',t)=d(m,n+k,m'-k,n',t-k)\;.$$ In particular, $$d(0,0,2n,0,k+1)=d(0,k,2n-k,0,1)=d(0,0,2n-k,k,1)\;.$$ This bijection between paths $P$ and $\hat P$ is the up-down version of the correspondence that is very, very badly described at your CodeChef link, where its author writes ‘This mapping is same as decreasing value of $y$ for a path when it touches a diagonal’. Each path in $\mathscr{D}(0,0,2n-k,k,1)$ must begin with an up-step; if we remove this up-step and shift the path one unit down and to the left, we get a Dyck path from $\langle 0,0\rangle$ to $\langle 2n-k-1,k-1\rangle$. Conversely, any Dyck path from $\langle 0,0\rangle$ to $\langle 2n-k-1,k-1\rangle$ becomes a path in $\mathscr{D}(0,0,2n-k,k,1)$ if we shift it one unit up and to the right and prepose an up-step. Thus, $$d(0,0,2n-k,k,1)=\sum_{t\ge 1}d(0,0,2n-k-1,k-1,t)\;.$$ Each up-down path from $\langle 0,0\rangle$ to $\langle 2n-k-1,k-1\rangle$ corresponds to a possible sequence of $2n-k-1$ votes, $n-1$ of them for candidate $A$ and $n-k$ of them for candidate $B$. On this interpretation the Dyck paths in $\mathscr{D}(0,0,2n-k-1,k-1,1)$ correspond to the sequences in which candidate $A$ is never behind candidate $B$. Calculating the number of such paths is essentially the ballot problem. Clearly there are $\binom{2n-k-1}{n-1}$ up-down paths from $\langle 0,0\rangle$ to $\langle 2n-k-1,k-1\rangle$. If $P$ is one of these paths that is not a Dyck path, there is a least $\ell$ such that $\langle\ell,-1\rangle$ is on the path $P$. Reflect the initial segment of $P$ between $\langle 0,0\rangle$ and $\langle\ell,-1\rangle$ in the line $y=-1$; the result is a path $P'$ from $\langle 0,-2\rangle$ to $\langle 2n-k-1,k-1\rangle$ that first hits the line $y=-1$ at $x=\ell$. Note that if this initial segment has $u$ up-steps, then it has $u+1$ down-steps, and the rest of $P$ has $n-1-u$ up-steps. As a result, $P'$ has $(n-1-u)+(u+1)=n$ up-steps and $n-k-1$ down-steps. Conversely, if $P$ is an up-down path from $\langle 0,-2\rangle$ to $\langle 2n-k-1,k-1\rangle$ that first hits the line $y=-1$ at $x=\ell$, reflecting the first $\ell$ steps of $P$ in the line $y=-1$ produces an up-down path $Q$ from $\langle 0,0\rangle$ to $\langle 2n-k-1,k-1\rangle$ that first hits the line $y=-1$ at $x=\ell$, and it’s clear that $Q'=P$. Every up-down path from $\langle 0,-2\rangle$ to $\langle 2n-k-1,k-1\rangle$ hits the line $y=-1$, and there are $\binom{2n-k-1}{n}$ such paths (since each has $n$ up-steps and $n-k-1$ down-steps). Thus, the number of up-down paths from $\langle 0,0\rangle$ to $\langle 2n-k-1,k-1\rangle$ that are not Dyck paths is $\binom{2n-k-1}n$, and $$\begin{align*} d(0,0,2n,0,k+1)&=\binom{2n-k-1}{n-1}-\binom{2n-k-1}n\\ &=\binom{2n-k-1}{n-k}-\binom{2n-k-1}{n-k-1}\\ &=\binom{2n-k-1}{n-k}\left(1-\frac{n-k}{n}\right)\\ &=\binom{2n-k-1}{n-k}\frac{k}n\;. \end{align*}$$ The Dyck paths in $\mathscr{D}(0,0,2n,0,k+1)$ correspond naturally to the paths in the plane from $\langle 0,0\rangle$ to $\langle n,n\rangle$ using only right-steps and up-steps that hit the diagonal exactly $k-1$ times between the two endpoints, or $k+1$ times including the endpoints.
[ "stackoverflow", "0046650444.txt" ]
Q: JavaFx-when fxml inject object field? I'm new to javaFx,and I have found only within the @fxml function and initialize function the @fxml field not be null otherwise the @fxml field will always be null,is it true? If so,how can i use a @fxml field immediately after i load a fxml(do not use lookup),just like this?(the code follow will throw a null exception) @FXML Label resultTF; .... FXMLLoader loader=new FXMLLoader(); loader.setController(this); Parent pane = loader.load(getClass().getResource("/fxml/Main.fxml")); this.resultTF.setText(""); All i want to do is to declare a field with id in the fxml,and use it immediately after load the fxml,something like wpf,flex A: You are calling the static FXMLLoader.load(URL) method. Since it's a static method, it knows nothing about the instance you are using to invoke it (which is bad practice anyway; your IDE should issue a warning about this). Specifically, it doesn't have a controller set. You need to invoke an instance load() method, e.g. FXMLLoader loader=new FXMLLoader(); loader.setController(this); loader.setLocation(getClass().getResource("/fxml/Main.fxml")); Parent pane = loader.load();
[ "stackoverflow", "0044864509.txt" ]
Q: Find a cumulative sum of one column until a conditional sum on another column is met I would like to find the preceding cumsum (i.e. cumsum minus the present row) for those rows of column B until the sum of the previous rows of column A including present row is <= 7. I was able to find an answer using a traditional for loop. A vectorized implementation would be very helpful as I need to run it on a large dataset. Sharing my simple code in case it helps. dt <- data.frame(A = c(0, 2, 3, 5, 8, 90, 8, 2, 4, 1, 2), B = c(1, 0, 4, 2, 3, 4, 2, 1, 2, 3, 1), Ans = c(0, 1, 1, 4, 0, 0, 0, 2, 3, 5, 6), new=rep(0,11)) dt3 <- dt for (i in 2:nrow(dt3)){ set<-0 count<-0 k=i-1 for (j in k:1){ count=count+dt3$A[j+1] if(count<=7){ set<-set+dt3$B[j] if(j==1){ dt3$new[i]=set } } else{ dt3$new[i]=set } } } Here are the 3 conditions to be satisfied: If A > 7, then Ans resets to 0 If cumsum(A)<=7, then Ans is cumsum() of lagB If cumsum(A) > 7, then Ans is cumsum() of lagB for the range of previous rows of A for which the sum is <=7 Here is a simplified version of the data (Column A and B) and the desired output is the Column Ans: dt <- data.frame(A = c(0, 2, 3, 5, 8, 90, 8, 2, 4, 1, 2), B = c(1, 0, 4, 2, 3, 4, 2, 1, 2, 3, 1), Ans = c(0, 1, 1, 4, 0, 0, 0, 2, 3, 5, 6)) dt A B Ans Reason for value in Ans: 1 0 1 0 There are no preceeding rows in B so Ans is 0 2 2 0 1 Sum of value of A from row 2 to 1 is 2 <=7. So Ans is the value of B from first row = 1 3 3 4 1 Sum of value of A from row 3,2 and 1 is 5 <=7. So Ans is the sum of value of B in row 1 and 2, which is 1. 4 5 2 4 Value of A from row 4 is 5 which is <=7. So Ans is value of B from row 3, which is 4 5 8 3 0 Value of A in row 5 is 8 which is >7. So Ans is 0 (Value of Ans resets to 0 when A > 7). 6 90 4 0 7 8 2 0 8 2 1 2 Value of A in row 8 is 2 which <=7, so Ans is value of B in row 7 which is 2 9 4 2 3 Sum of value of A from row 9 and 8 is 6<=7, so Ans is sum of value of B in row 8 and 7 = 3 10 1 3 5 Sum of value of A from row 10,9 and 8 is 7<=7, so Ans is sum of value of B in row 9,8 and 7 =5. 11 2 1 6 Sum of value of A from row 11,10 and 9 is 7<=7, so Ans is sum of value of B in row 10,9 and 8 =6. Any help on how can I code this in R? A: Please see the edit below which tries to answer the updated question. If I have understood OP's intention right, then there are 3 rules: if A is greater 7 then Ans is zero and grouping is restarted if cumsum(A) within the group is less or equal 7 then Ans is the cumsum() of lagged B if cumsum(A) within the group is greater 7 then Ans is lagged B The code below produces the expected result for the given sample data set: # create sample data set DF <- data.frame(A = c(0, 2, 3, 5, 8, 90, 8, 2, 4, 1), B = c(1, 0, 4, 2, 3, 4, 2, 1, 2, 3), Ans = c(0, 1, 1, 4, 0, 0, 0, 2, 3, 5)) # load data.table, CRAN version 1.10.4 used library(data.table) # coerce to data.table DT <- data.table(DF) # create helper column with lagged values of DT[, lagB := shift(B, fill = 0)][] # create new answer DT[, new := (A <= 7) * ifelse(cumsum(A) <= 7, cumsum(lagB), lagB), by = rleid(A <= 7)][ , lagB := NULL][] A B Ans new 1: 0 1 0 0 2: 2 0 1 1 3: 3 4 1 1 4: 5 2 4 4 5: 8 3 0 0 6: 90 4 0 0 7: 8 2 0 0 8: 2 1 2 2 9: 4 2 3 3 10: 1 3 5 5 rleid(A <= 7) creates unique group numbers for all consecutive streaks of A values not greater or greater of 7, resp. The ifelse() clause implements rules 2 and 3 within the grouping. By multiplying the result with (A <= 7), rule 1 is implemented., thereby using the trick that as.numeric(TRUE) is 1 and as.numeric(FALSE) is 0. Finally, the helper column is removed. Edit With the additional information provided by the OP, I believe there is only one rule left: for each row find a window extending backwards which contains as many rows as sum(A) does not exceed 7. The answer is the sum of lagged B in the same window. For clarification, if the window has zero length because A in the inital row already exceeds 7, then the answer is zero. The variable length of the sliding window is the tricky part here: # sample data set consists of 11 rows after OP's edit DF <- data.frame(A = c(0, 2, 3, 5, 8, 90, 8, 2, 4, 1, 2), B = c(1, 0, 4, 2, 3, 4, 2, 1, 2, 3, 1), Ans = c(0, 1, 1, 4, 0, 0, 0, 2, 3, 5, 6)) DT <- data.table(DF) DT[, lagB := shift(B, fill = 0)][] # find window lengths DT[, wl := DT[, Reduce(`+`, shift(A, 0:6, fill = 0), accumulate = TRUE)][, rn := .I][ , Position(function(x) x <= 7, right = TRUE, unlist(.SD)), by = rn]$V1][] # sum lagged B in respective window DT[, new := DT[, Reduce(`+`, shift(lagB, 0:6, fill = 0), accumulate = TRUE)][ , rn := .I][, wl := DT$wl][, ifelse(is.na(wl), 0, unlist(.SD)[wl]), by = rn]$V1][] A B Ans lagB wl new 1: 0 1 0 0 7 0 2: 2 0 1 1 7 1 3: 3 4 1 0 7 1 4: 5 2 4 4 1 4 5: 8 3 0 2 NA 0 6: 90 4 0 3 NA 0 7: 8 2 0 4 NA 0 8: 2 1 2 2 1 2 9: 4 2 3 1 2 3 10: 1 3 5 2 3 5 11: 2 1 6 3 3 6
[ "stackoverflow", "0022639670.txt" ]
Q: Apache: Multiple ProxyPassReverse, Multiple ServerNames, Single vhost I am working on a particular set-up as follows: Several applications in multiple hosts and different ports A server (assume balancer.local) running nginx listening on port 8080 for localhost, which acts as a proxy/load balancer for the applications running on the previous hosts An apache2 server running on the same machine as nginx, listening on port 80 (open to the public), serving some contents directly for some ServerName and forwarding some other ServerName to localhost:8080, to let nginx do the load balancing work The problem I have is that the number of hostnames to be redirected to nginx is growing fast, and I have an annoying list of vhosts which is becoming hard to maintain. So, the question is: Is there a way I can define a default vhost in apache, without ServerNames, and make it redirect all the traffic which has not matched any other vhost to localhost:8080? I already tried removing the ServerName directive, but the problem I have is that then ProxyPassReverse inserts its hostname into the outgoing URL. At the moment, the only thing I was able to do is to reduce the number of rows in each vhost to the minimum, but it's still too much. Here you have some configuration examples: Nginx: upstream foo { server foo1.local:9999 max_fails=3 fail_timeout=30s; server foo2.local:9999 max_fails=3 fail_timeout=30s; } upstream bar { server bar1.local:8888 max_fails=3 fail_timeout=30s; server bar2.local:8888 max_fails=3 fail_timeout=30s; } server { listen *:8080; server_name foo.public.com; access_log /var/log/nginx/foo.public.com-access.log proxy; error_log /var/log/nginx/foo.public.com-error.log; location / { proxy_pass http://foo/; include /etc/nginx/proxy_app.conf; } } server { listen *:8080; server_name bar.public.com; access_log /var/log/nginx/bar.public.com-access.log proxy; error_log /var/log/nginx/bar.public.com-error.log; location / { proxy_pass http://bar/; include /etc/nginx/proxy_app.conf; } } Apache: <VirtualHost *:80> ServerName foo.public.com ErrorLog /var/log/httpd/nginx-redirect.sis.service-error.log CustomLog /var/log/httpd/nginx-redirect.sis.service-access.log combined ProxyPreserveHost On ProxyPass / http://localhost:8080/ ProxyPassReverse / http://%{HTTP_HOST}:8080/ </VirtualHost> <VirtualHost *:80> ServerName bar.public.com ErrorLog /var/log/httpd/nginx-redirect.sis.service-error.log CustomLog /var/log/httpd/nginx-redirect.sis.service-access.log combined ProxyPreserveHost On ProxyPass / http://localhost:8080/ ProxyPassReverse / http://%{HTTP_HOST}:8080/ </VirtualHost> <VirtualHost *:80> ServerName baz.public.com DocumentRoot /some/local/path <Directory "/"> some irrelevant options </Directory> </VirtualHost> In this example there are only two vhosts forwarded into nginx, but in my real set-up there's more than 30! As I said, I already tried to use a single vhost without the ServerName tag to forward the traffic, but I ended up obtaining http://balancer.local/some/path in my redirections, which obviously didn't work. I also tried to use a single ServerName and multiple ServerAlias, but in that case, ProxyPassReverse used always the ServerName in the response. Any suggestion? A: I also tried to use a single ServerName and multiple ServerAlias, but in that case, ProxyPassReverse used always the ServerName in the response. Probably you have UseCanonicalName On somewhere in your Apache config. Try to set it Off explicitly in your VirtualHost.
[ "superuser", "0001089723.txt" ]
Q: Cannot install afpfs-ng On Xubuntu 16.04LTS amd64, I cannot install afpfs-ng. This is a HUGE problem for me since my school uses macs and an afp file server, and I only have a PC running Linux and I need a file for the summer. When I try through the software center (both i386 AND amd64), it simply does not work. The install button literally does nothing. Through the command line (sudo apt-get install afpfs-ng) I get that the package has no installation candidate. A: Ubuntu 16.04, afpfs-ng : sudo apt-get install g++ libfuse-dev libreadline-dev libncurses5-dev git git clone https://github.com/simonvetter/afpfs-ng cd afpfs-ng/ ./configure && make && sudo make install sudo ldconfig
[ "stackoverflow", "0043959105.txt" ]
Q: Check if a number is between a range using SQL & C# I have a table with the following info: ID Name Range Checked 1 Jennifer 000-100 0 2 Louis 101-200 0 3 Michael 201-300 0 The range are the numbers of the tickets they have, and the checked column are the number of tickets that have been used. What I want to do is to add +1 to the column Checked when a ticket is used, so I want to check where the ticket belongs. I mean, if I use ticket number 103, I want to add 1 to the column checked in the row number 2. And so on if I use more tickets. ID Name Range Checked 1 Jennifer 000-100 0 2 Louis 101-200 1 3 Michael 201-300 0 So, is there a way to check if the ticket I have submitted is between one of the ranges? PD.: I know how to check if a number is between two numbers in SQL, and I do also know how to get info from specific rows using C#, what I don't know how to do is to check the entire table to see if the number is between the ranges column. A: If the Range Values are 3 digits, left() and right() would do the trick without having to find the dash. Example Update YourTable Set Checked=Checked+1 Where 103 between left(Range,3) and Right(Range,3) Select * from YourTable Results ID Name Range Checked 1 Jennifer 000-100 0 2 Louis 101-200 1 3 Michael 201-300 0 EDIT - CharIndex() option For Variable Ranges Update @YourTable Set Checked=Checked+1 Where 103 between left(Range,charindex('-',Range+'-')-1) and Right(Range,len(Range)-charindex('-',Range+'-'))
[ "stackoverflow", "0046122513.txt" ]
Q: Color switching in Unity (with script) I want to increase alpha channel on every hit taken by an object. But i cant use my Alpha variable as it's an integer and color32 needs byte value. I know about color, which is float, but it's not working for me, I need color32. How can i do that? void OnCollisionEnter2D (Collision2D col) { Alpha += 255 / maxHits; currentHit++; gameObject.GetComponent<SpriteRenderer> ().color = new Color32(159,86,86,Alpha); if (currentHit == maxHits) { Destroy (gameObject); } } A: Make sure Alpha is a float. try this: float Alpha = 0; void OnCollisionEnter2D (Collision2D col) { Alpha += 1f / maxHits; currentHit++; gameObject.GetComponent<SpriteRenderer> ().color = new Color(159f/255,86f/255,86f/255,Alpha); if (currentHit == maxHits) { Destroy (gameObject); } }
[ "stackoverflow", "0031113446.txt" ]
Q: Accessing type data wrapped in another type I am modelling a protocol in F#. The protocol states that there is a login command that takes a username and a password as parameters, and there is a logout that takes no parameters. The commands must be wrapped in some string post- and prefix before the protocol accepts them as a commands. So far I have got the following model. A Command has some data associated with it, and at some point I want to wrap a given command with the post- and prefix. To do this, I have have a new type called FormattedCommand which has a command, and a string representation of the command and the parameters along with the post/prefixes called SendString. When I what to format a command by calling formatCommand: command:Command -> FormattedCommand I want to access the command's CommandString so I can attach the post/prefixes. How can I achieve this? type CommandData = { CommandString : string; Parameters : string; } type Command = | Login of CommandData | Logout of CommandData type FormattedCommand = { Command : Command; SendString : string; } let formatCommand (command:Command) = { Command = command; SendString = ?? } A: If I understand your requirements correctly, I think that you can make it somewhat simpler. The protocol states that there is a login command that takes a username and a password as parameters, and there is a logout that takes no parameters. I would model that like this: type Command = | Login of username:string * password:string | Logout The commands must be wrapped in some string post- and prefix before the protocol accepts them as a commands. I would model that like this: type FormattedCommand = FormattedCommand of string I don't see why the formatted command needs to know the original command at all. It seems like you're mixing concerns. If you do need to pass them both around, use a tuple or make a simple record type. I want to wrap a given command with the post- and prefix. I would create a function that serializes the command like this: let toFormattedCommand prefix postfix command = let commandStr = match command with | Login (username,password) -> sprintf "%s|Login|%s|%s|%s" prefix username password postfix | Logout -> sprintf "%s|Logout|%s" prefix postfix FormattedCommand commandStr I've just used bars to separate the fields. Obviously, the real protocol would be different. The function above is generic, but you can bake in the default prefix if you like: // bake in the defaults let toFormattedCommandWithDefaults = toFormattedCommand "pre" "post" And then you can create examples like this: let loginStr = Login("alice","123") |> toFormattedCommandWithDefaults // FormattedCommand "pre|Login|alice|123|post" let logoutStr = Logout |> toFormattedCommandWithDefaults // FormattedCommand "pre|Logout|post" A: you do it like this: let formatCommand (command:Command) = let sendString = match command with | Login data -> // use data.CommandString and data.Parameters to format your result | Logout data -> // dito { Command = command; SendString = sendString } by the way: you wrote that your Logout should have no parameters, yet you use CommandData too Command and FormattedCommand share quite a lot - maybe you should use a ADT here too
[ "stackoverflow", "0062931391.txt" ]
Q: plus operator in c++ I have read that the plus operator adds its Rvalues to its Lvalues. For example, if we write x + 1; the plus operator finds the variable x in the memory and adds 1 to it. But this operator doesn't work like that because, in the code below, it doesn't add 1 to its Lvalue (x). int x = 4; x + 1;// now the + operator adds 1 to x variable. std::cout << x << std::endl;// this line must print 5 but doesn't. If it doesn't work like how I explained, then how does it work? A: the plus operator add it's Rvalues to it's Lvalues This is correct. It does that, but it stores the temporary result in memory, and returns the result for you to use. This result needs to be explicitly saved, by you, to some variable that you manage. For example, if you want to change x, you can do x=x+1, otherwise you can use a new variable, for example int result = x+1. Here there is extensive explanation. Quoting: All arithmetic operators compute the result of specific arithmetic operation and returns its result. The arguments are not modified.
[ "stackoverflow", "0006701230.txt" ]
Q: Call R function in Linux command line Is there a way to directly call R functions from Linux command line without going into R environment? It doesn't work for me by just running a R file, since I need to specify the parameters of the function every time I run it. A: A simple built-in is the following BASH commands: export NUM=10 R -q -e "rnorm($NUM)" A: Yes, there is -- littler was written for exactly that purpose. R itself added Rscript shortly thereafter, but as one of the two dudes behind littler I still like it better.
[ "stackoverflow", "0013976679.txt" ]
Q: Function to count how many numbers are there with the digits and division value specified I started making a function that will be able do the following: Count how many 6 digit numbers you can make with the digits 0,1,2,3,4 and 5, that can be divided by 6? How I currently try to start, is I make an array of all the possible numbers, then take out every number that has any of the numbers' arrays elements in it, then remove the ones that are not dividable with 6. I got stuck at the second part. I tried making 2 loops to loop in the array of numbers, then inside that loop, create an other one for the length of the allnumbers array to remove all matches. Then I would use the % operator the same way to get every element out that doesn't return 0. The code needs to be flexible. If the user asks for eg. digit 6 too, then the code should still work. Any way I could finish this? My Code is: var allnumbers = [],j; var biggestnumber = "999999999999999999999999999999999999999999999999999999999999"; function howmanynumbers(digits,numbers,divideWith){ if (digits && numbers && divideWith){ for (var i = 0; i < 1+Number(biggestnumber.substring(0,digits)); i++ ){ allnumbers.push(i); } for (j = 0; j < numbers.length; j++ ){ var matchit = new RegExp(numbers[j]); } //not expected to work, I just had this in for reference if ( String(allnumbers[i]).match(matchit) != [""]){ j = 0; allnumbers.splice(i,1); var matchit = new RegExp(numbers[j]) } } else { return false; } } A: This is my take on the entire solution: var i; var allowedDigitsPattern = /^[0-5]+$/i; var numbers = []; for (i = 100000; i < 555555; i++) { if (allowedDigitsPattern.test(i.toString()) && i % 6 === 0) { numbers.push(i); } } And you can look at your results like this: document.write('There are ' + numbers.length + ' numbers<br>'); // write out the first ten! for (i = 0; i < 10; i++) { document.write(numbers[i] + '<br>'); } Update based on comments... The configurable version of this would be: var i; var lowestDigit = 0; var highestDigit = 5; var numberOfDigits = 6; var allowedDigitsPattern = new RegExp('^[' + lowestDigit + '-' + highestDigit + ']+$', 'gi'); var smallestNumber = '1'; for (i = 1; i < numberOfDigits; i++) { smallestNumber += '0'; } var biggestNumber = ''; for (i = 0; i < numberOfDigits; i++) { biggestNumber += highestDigit.toString(); } var numbers = []; for (i = smallestNumber; i < biggestNumber; i++) { if (allowedDigitsPattern.test(i.toString()) && i % 6 === 0) { numbers.push(i); } } document.write('There are ' + numbers.length + ' numbers<br>'); You need to change the smallest and largest numbers based on the configuration. I have made both the allowable digits and the length of the number configurable.
[ "pt.stackoverflow", "0000360526.txt" ]
Q: Contagem acumulada de ocorrências de grupos em datas Estou com um conjunto de dados similar ao abaixo. Ele tem uma coluna com datas e outra com ocorrências de grupos nestas datas. data grupo 1 2019-01-01 a 2 2019-01-01 a 3 2019-01-01 a 4 2019-01-01 a 5 2019-01-02 b 6 2019-01-02 b 7 2019-01-02 a 8 2019-01-03 a 9 2019-01-03 a 10 2019-01-03 a 11 2019-01-04 a 12 2019-01-04 b 13 2019-01-04 b 14 2019-01-05 a 15 2019-01-05 a 16 2019-01-05 a 17 2019-01-05 b 18 2019-01-06 b 19 2019-01-06 a 20 2019-01-06 a 21 2019-01-07 b 22 2019-01-07 b 23 2019-01-07 a 24 2019-01-08 b 25 2019-01-08 a 26 2019-01-08 a 27 2019-01-09 a 28 2019-01-09 a 29 2019-01-09 b 30 2019-01-10 a Eu desejo calcular a soma acumulada das ocorrências dos grupos em relação às datas presentes. Por exemplo, em 2019-01-01, o grupo a ocorreu 4 vezes. Em 2019-01-02, a ocorreu uma vez, o que dá uma ocorrência acumulada igual a 5. E assim por diante, para cada grupo e cada data. As datas estão em sequência, mas algumas estão faltando. Os grupos não estão presentes em todas as datas. Isto posto, a resposta que procuro para o conjunto acima é a seguinte: data grupo acumulada 2019-01-01 a 4 2019-01-01 b 0 2019-01-02 a 5 2019-01-02 b 2 2019-01-03 a 8 2019-01-03 b 2 2019-01-04 a 9 2019-01-04 b 4 2019-01-05 a 12 2019-01-05 b 5 2019-01-06 a 14 2019-01-06 b 6 2019-01-07 a 15 2019-01-07 b 8 2019-01-08 a 17 2019-01-08 b 9 2019-01-09 a 19 2019-01-09 b 10 2019-01-10 a 20 2019-01-10 b 10 Abaixo estão os dados do exemplo para facilitar a vida de quem tentar resolver meu problema. structure(list(data = structure(c(17897, 17897, 17897, 17897, 17898, 17898, 17898, 17899, 17899, 17899, 17900, 17900, 17900, 17901, 17901, 17901, 17901, 17902, 17902, 17902, 17903, 17903, 17903, 17904, 17904, 17904, 17905, 17905, 17905, 17906), class = "Date"), grupo = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L), .Label = c("a", "b"), class = "factor")), class = "data.frame", row.names = c(NA, -30L)) A: Dentro do tidyverse existe a função tidyr::complete() para realizar o desejado. Os passos para isso são: Contar a ocorrência de cada grupo em cada data com count(). Completar com 0 (zero) os casos em que não há observações Fazer a soma acumulada desta contagem para cada grupo. Isso pode ser feito com o código que segue: library(tidyverse) dados %>% count(data, grupo) %>% complete(data, grupo, fill = list(n = 0)) %>% group_by(grupo) %>% mutate(n = cumsum(n)) A: Usando data.table: library(magrittr) library(data.table) setDT(dados) dados <- dados[, .(N = .N), by = c("data", "grupo")] %>% dcast(data ~ grupo, value.var = "N", fill = 0) %>% melt(., id.vars = "data", measure.vars = c("a", "b"), variable.name = "grupo", value.name = "N", ) %>% setorderv(., c("data", "grupo")) %>% .[, acumulada := cumsum(N), by = c("grupo")] Resultado: > dados[] data grupo N acumulada 1: 2019-01-01 a 4 4 2: 2019-01-01 b 0 0 3: 2019-01-02 a 1 5 4: 2019-01-02 b 2 2 5: 2019-01-03 a 3 8 6: 2019-01-03 b 0 2 7: 2019-01-04 a 1 9 8: 2019-01-04 b 2 4 9: 2019-01-05 a 3 12 10: 2019-01-05 b 1 5 11: 2019-01-06 a 2 14 12: 2019-01-06 b 1 6 13: 2019-01-07 a 1 15 14: 2019-01-07 b 2 8 15: 2019-01-08 a 2 17 16: 2019-01-08 b 1 9 17: 2019-01-09 a 2 19 18: 2019-01-09 b 1 10 19: 2019-01-10 a 1 20 20: 2019-01-10 b 0 10
[ "stackoverflow", "0047629972.txt" ]
Q: Bash-shell two file match successfully , but output wrong cat file1.txt cheng 600 huang 500 pan 400 yin 300 cat file2.txt 600 a 300 c when I execute the command: awk 'NR==FNR{a[$1]=$2;next}($2 in a){print $1,$2,a[$1]}' f2.txt f1.txt The output is below: cheng 600 yin 300 But i expected should be like this: cheng 600 a yin 300 c what's wrong? A: You can use: awk 'NR==FNR{a[$1]=$2; next} $2 in a{print $0, a[$2]}' f2.txt f1.txt cheng 600 a yin 300 c
[ "stackoverflow", "0053327107.txt" ]
Q: How to plot a 3-D plot with 3 input variables in R? I am writing a log-likelihood surface for the function: ln[Pr(Y_A=186,Y_B=38,Y_{AB}=13,Y_O=284)] = ln(G+186*ln(A^2+2*A*O)+38*ln(B^2+2*B*O)+13*ln(2*A*B)+284*ln(O^2)) constraint by A+B+O=1 A = seq(0.0001, .9999,length=50) B = A O = A G = 1.129675e-06 f = function(A,B,O){F = ifelse(A+B+O==1, G+186*log(A*A+2*A*O)+38*log(B*B+2*B*O)+13*log(2*A*B)+284*log(O*O), O)} Z <- outer(A, B, O, f) png() persp(A,B,Z, theta=60, phi=30 ) dev.off() The error told me that there isn't object "O". Error in get(as.character(FUN), mode = "function", envir = envir) What I mean to do is to input A, B and O under the constraint that A+B+O=1, and then to plot the log-likelihood surface letting A:x-axis, B:y-axis, log-likelihood:z-axis. I cannot get rid of "O" cause the instruction commands that the parameter of the function should be a 3-dimensional vector: A,B,O. So what should I do to improve my current code? If I need to change a function, can anyone suggest a function to use? (I think maybe I can use barycentric coordinates but I consider it as the last thing I want to do.) A: The outer function does not work the way you try to use it. outer takes two numeric arguments X and Y and a function argument FUN to which the first two arguments are applied. See ?outer. So it is not that there is no object O at all. Rather the error message in Z <- outer(A, B, O, f) #Error in get(as.character(FUN), mode = "function", envir = envir) : # object 'O' of mode 'function' was not found means that the function O was not found. Indeed there is no such function. There are also some problems with your f definition. First, it does not return anything. It saves a result as F but never returns it. Secondly, even if it returned F, the output would not always satisfy your constraint. When your constraint is not met, it simply outputs the value of O. Lastly, the comparison A+B+O==1 is a bad test as it may not evaluate to TRUE even if you'd expect it to due to floating point precision (try to run 3 - 2.9 == 0.1). The grid based evaluation makes things worse. Probably, you should be testing abs(A+B+O-1) < epsilon instead if you insist have three arguments for f. I.e. I would have expect something like: f <- function(A, B, O){ G <- 1.129675e-06 epsilon <- 1e-3 ifelse(abs(A+B+O-1) < epsilon, G+186*log(A*A+2*A*O)+38*log(B*B+2*B*O)+13*log(2*A*B)+284*log(O*O), NA) } Then you can do something like: dat <- expand.grid(A = A, B = B, O = O) # All combinations of A, B, O dat$Z <- f(dat$A, dat$B, dat$O) # Apply function head(dat) # A B O Z #1 0.00010000 1e-04 1e-04 NA #2 0.02050408 1e-04 1e-04 NA #3 0.04090816 1e-04 1e-04 NA #4 0.06131224 1e-04 1e-04 NA #5 0.08171633 1e-04 1e-04 NA #6 0.10212041 1e-04 1e-04 NA But I do not see how you readily plot Z as a function of A and B from this. You'd need to subset to remove NAs and it seems very wasteful computationally. Also note any(dat$A + dat$B + dat$O == 1) returns FALSE, so your original constraint test indeed always fails on this grid. With that said, why do you not determine O given A and B using your constraint within the function? A <- seq(0.0001, .9999,length=50) B <- A f <- function(A, B){ G <- 1.129675e-06 O <- 1 - A - B out <- G+186*log(A*A+2*A*O)+38*log(B*B+2*B*O)+13*log(2*A*B)+284*log(O*O) return(out) } Z <- outer(A, B, f) #Warning messages: #1: In log(A * A + 2 * A * O) : NaNs produced #2: In log(B * B + 2 * B * O) : NaNs produced Z[is.infinite(Z)] <- NA persp(A, B, Z, theta=60, phi=30, zlim = range(Z, na.rm = TRUE)) Does that look right? That is how persp and outer is intended to be used at least. Of course, you can modify f so the warning messages are avoided. Just keep in mind that f needs to be vectorized.
[ "stackoverflow", "0038962592.txt" ]
Q: MySQL sales per Day, Week and Month Im trying to create a sales report in which the user can see sales per Day, Week and Month. This is my table: CREATE TABLE IF NOT EXISTS `sales_act` ( `id` int(11) NOT NULL auto_increment, `sale` decimal(10,2) NOT NULL default '0.00', `paymethod` smallint(2) NOT NULL default '0', `saledate` datetime NOT NULL default '0000-00-00 00:00:00', `status` smallint(2) NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ; INSERT INTO `sales_act` (`id`, `sale`, `paymethod`, `saledate`, `status`) VALUES (1, '150.00', 3, '2016-07-30 14:37:25', 2), (2, '50.00', 1, '2016-08-14 21:38:34', 1), (3, '150.00', 3, '2016-08-15 14:23:21', 2), (4, '100.00', 1, '2016-08-15 14:25:12', 1), (5, '50.00', 2, '2016-08-15 14:27:31', 3); I was reading here in stackoverflow some examples of this, but I cant seem to make it work, this is what I have so far, but doesnt work :( $result = $mysqli->query('SELECT DATE_FORMAT(saledate, "%m-%Y") AS Month, SUM(sale) AS `salessum` WHERE `status` < 3 GROUP BY DATE_FORMAT(saledate, "%m-%Y")'); while ($row = $result->fetch_assoc()) { echo '<pre>'; print_r($row); echo '</pre>'; } Can someone tell me what Im doing wrong? Thanks in advance!! :D A: You missed FROM clause should use MONTH (you have already saledate as datetime) 'SELECT MONTH(saledate) AS Month, SUM(sale) AS `salessum` FROM sales_act WHERE `status` < 3 GROUP BY MONTH(saledate)'
[ "stackoverflow", "0015654864.txt" ]
Q: Performance of MySQL "AS" and not "AS" Is there a performance difference between the following two queries? SELECT * FROM users AS u LEFT JOIN parents AS p ON u.id=p.user_id and SELECT * FROM users u LEFT JOIN parents p ON u.id=p.user_id (the second one doesn't have the AS) A: As with everything: to measure is to know. If you really want to know run a profiler and measure. Otherwise take it from us: it's not even worth the thought you have put in about it so far. If there's any difference (of considerable amount) at all that should a) be considered a flaw in MySQL, b) be a problem during the query parsing part, not the query execution part and thus be negligable anyway since execution rather than parsing will usually account for 99.99999% of the total "querytime" anyway (if not more). If there's any measurable difference, it will should be very, very, véry small and thus a) not be worth bothering about the difference since users don't usually notice speedups in increments of nanoseconds and b) only noticable when you run many, many thousands of queries in a tight loop. If MySQL's contributers didn't mess up then there's no difference at all since the AS keyword is just optional and exists for legibility. The only way to know for sure is to profile. It won't be the first time some strange bug or behaviour pops up in software. But it is (very) safe to assume the AS keyword doesn't make a difference at all since that would have been 'discovered' a long time ago by any of the millions of MySQL users that have preceeded you (or none of them ever bothered, you never know ). Spending any time profiling this "question" would, IMHO, be a waste of time. Read the rules of Optimization club. Only when there actually is a performance issue you start looking for places to optimize. And you only optimize "low hanging fruit" or stuff that accounts for considerable load (be it I/O, CPU, network, whatever). Optimizing queries removing AS keywords for performance is a microoptimization that will never, ever, return the investment of your time (barring bugs/issues). As a "thought experiment" though your question can (and should) be answered by establishing hard data using profiling rather than guesses, other people's opinions etc. I did leave out stuff like querycaches that could potentially suffer from queries being executed with/without AS keywords or AS keywords in different places each time a query is executed which would (or rather: could) cause query execution plans to be (unnecessarily) be recreated or query caches unable being unable to be reused etc. but now we're really talking edge-cases here and for this the saying, again, goes: to measure is to know.
[ "stackoverflow", "0054799265.txt" ]
Q: Deserialize json shows null in xamarin forms Hi I have a Login API which I am using to login though my xamarin.forms app. I will post my username and password and in return I am getting some data.Now Iam facing some issues at deserialization of json. Iam getting data at my resultJson but I cant deserialize it. Help me. My Json : [ { "Result":true, "ID":"fc938df0", "LoginName":"test", "UserName":"test", "ConnectionString":"MSSQLSERVER;Initial Catalog=Test1;User ID=db;Password=db@2018", "UserProfileID":"fc938df0" } ] My API Call class which have deserialization of Json. public T APICallResult<T>() { try { Device.BeginInvokeOnMainThread(() => { if (loadingIndicator != null) { loadingIndicator.IsRunning = true; loadingIndicator.IsVisible = true; } }); var client = new HttpClient { BaseAddress = baseAddress }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var req = new HttpRequestMessage(HttpMethod.Post, apiurl); req.Content = new StringContent(postdata, Encoding.UTF8, "application/json"); string stringObtained = ""; Task<string> task = Task.Run(async () => await Threading(client, req)); task.Wait(); stringObtained = task.Result; var jsonObtained = Regex.Unescape(stringObtained); int startIndex = jsonObtained.IndexOf('['); int endIndex = jsonObtained.LastIndexOf(']'); int length = endIndex - startIndex + 1; var resultJSON = jsonObtained.Substring(startIndex, length); T resultObject;//Generic type object try { //**Deserializing** resultObject = JsonConvert.DeserializeObject<T>(resultJSON);//, settings); removeLoadingAnimation(); return resultObject; } catch (Exception e) { List<ErrorMessageData> errorMessages = JsonConvert.DeserializeObject<List<ErrorMessageData>>(resultJSON); errorMessage = errorMessages[0]; removeLoadingAnimation(); return default(T); } } catch (Exception e) { errorMessage = new ErrorMessageData(); errorMessage.Flag = false; errorMessage.Message = e.Message; removeLoadingAnimation(); return default(T); } } My API call at login class string postdataForLogin = "{\"userName\":\"" + userName.Text + "\",\"password\":\"" + password.Text + "\",\"RequestURL\":\"" + CommonValues.RequestURL + "\"}"; APICall callForLogin = new APICall("/API/LoginMobile/HomeLogin", postdataForLogin, loadingIndicator); try { List<LoginData> resultObjForLogin = callForLogin.APICallResult <List<LoginData>>(); if (resultObjForLogin != null) { LoginData loginData = new LoginData(); loginData = resultObjForLogin[0]; Settings.userID = loginData.UserProfileID; Settings.connectionString = loginData.ConnectionString; if (loginData.Result) { Device.BeginInvokeOnMainThread(async () => { Navigation.InsertPageBefore(new MainPage(), this); await Navigation.PopAsync(); }); } My DataModel public class LoginData { public bool Result { get; set; } public string ID { get; set; } public string UserProfileID { get; set; } public string LoginName { get; set; } public string UserName { get; set; } public string ConnectionString { get; set; } } A: Its seems strange, My problem solved after downgrading my xamarin.forms from latest version to pre release 4.0.0.169046- pre5. I think its a xamarin forms bug
[ "stackoverflow", "0037803555.txt" ]
Q: Ajax html editor an issue with VS 2013 Ajax html editor issue with VS 2013 and calendar extender is coming from Ajax but getting an issue with the Ajax html editor not showing even design mode. Ajax html editor showing in the design mode message like: HtmlEditorExtender - Unnamed1 Below are my web config details: <pages> <namespaces> <add namespace="System.Web.Optimization" /> <add namespace="Microsoft.AspNet.Identity" /> </namespaces> <controls> <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" /> <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /> <add tagPrefix="asp" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /> <add tagPrefix="cc1" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /> </controls> </pages> Below is my Content Place Holder page: <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %> <ajaxToolkit:HtmlEditorExtender TargetControlID="txt_largedesc" runat="server" /> Below is my Master Page Script Manager: <asp:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <asp:ScriptReference Name="MsAjaxBundle" /> <asp:ScriptReference Name="jquery" /> <asp:ScriptReference Name="bootstrap" /> <asp:ScriptReference Name="respond" /> <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" /> <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" /> <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" /> <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" /> <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" /> <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" /> <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" /> <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" /> <asp:ScriptReference Name="WebFormsBundle" /> </Scripts> </asp:ScriptManager> Calender Extender is coming from an Ajax tool kit, but getting issues with Ajax html editor. A: Remove scriptmanager in master and add it to content page install AjaxControlToolkit.HtmlEditor.Sanitizer, use Html Editor together with Html Sanitizer code snippets <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <asp:TextBox ID="txtEditor" runat="server" Width="300" Height="200" /> <ajaxToolkit:HtmlEditorExtender ID="HtmlEditorExtender1" runat="server" TargetControlID="txtEditor"></ajaxToolkit:HtmlEditorExtender> <asp:Button Text="Submit" runat="server" OnClick="Submit" /> <br /> <asp:Label ID="lblContents" runat="server" /> Code behind protected void Submit(object sender, EventArgs e) { lblContents.Text = txtEditor.Text; } reference: ASP.Net AJAX Control Toolkit HtmlEditorExtender Example http://www.aspsnippets.com/Articles/ASPNet-AJAX-Control-Toolkit-HtmlEditorExtender-Example.aspx
[ "stackoverflow", "0015512033.txt" ]
Q: Some EKEvents doesn't match predicate I'm working on a calendar app. For a month I loop on all my day to get events of this day. I have to do this to handle recurent events and events longer than one day. It work great except for one case: the last day of a several day long event. I see the event for the other days of this event but not for the last one. (I'm in GMT+1 Time Zone, that's why I have this hours) SEARCH FOR THE LAST DAY OF EVENT Start: 2013-03-25 23:00:00 +0000 End: 2013-03-26 22:59:59 +0000 EVENT Start: 2013-03-24 21:00:06 +0000 End: 2013-03-26 21:00:06 +0000 No results! Here is the method returning events for the day: + (NSArray *)ekEventsWithStartDate:(NSDate*)startDate endDate:(NSDate*)endDate { NSLog(@"ekEventsWithStartDate:%@ endDate:%@",startDate,endDate); NSPredicate *predicate = [_eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:nil]; NSArray *events = [_eventStore eventsMatchingPredicate:predicate]; NSLog(@"events (%d):%@",[events count],events); return events; } Here is the event details: EKEvent <0xb0635e0> {EKEvent <0xb0635e0> {title = 24-26 Mars 10 PM; location = ; calendar = EKCalendar <0xb3c3c80> {title = Calendar; type = Local; allowsModify = YES; color = #0E61B9;}; alarms = (null); URL = (null); lastModified = 2013-03-19 22:11:10 +0000; timeZone = Europe/Paris (GMT+01:00) offset 3600}; location = ; startDate = 2013-03-24 21:00:06 +0000; endDate = 2013-03-26 21:00:06 +0000; allDay = 0; floating = 0; recurrence = (null); attendees = (null)} Here is the log for the 3 days of this event from ekEventsWithStartDate method: ekEventsWithStartDate:2013-03-23 23:00:00 +0000 endDate:2013-03-24 22:59:59 +0000 events (1):( "EKEvent <0x9b44c00> {EKEvent <0x9b44c00> {title = 24-26 Mars 10 PM; location = ; calendar = EKCalendar <0xb336870> {title = Calendar; type = Local; allowsModify = YES; color = #0E61B9;}; alarms = (null); URL = (null); lastModified = 2013-03-19 22:11:10 +0000; timeZone = Europe/Paris (GMT+01:00) offset 3600}; location = ; startDate = 2013-03-24 21:00:06 +0000; endDate = 2013-03-26 21:00:06 +0000; allDay = 0; floating = 0; recurrence = (null); attendees = (null)}" ) ekEventsWithStartDate:2013-03-24 23:00:00 +0000 endDate:2013-03-25 22:59:59 +0000 events (1):( "EKEvent <0xb28b970> {EKEvent <0xb28b970> {title = 24-26 Mars 10 PM; location = ; calendar = EKCalendar <0xb336870> {title = Calendar; type = Local; allowsModify = YES; color = #0E61B9;}; alarms = (null); URL = (null); lastModified = 2013-03-19 22:11:10 +0000; timeZone = Europe/Paris (GMT+01:00) offset 3600}; location = ; startDate = 2013-03-24 21:00:06 +0000; endDate = 2013-03-26 21:00:06 +0000; allDay = 0; floating = 0; recurrence = (null); attendees = (null)}" ) ekEventsWithStartDate:2013-03-25 23:00:00 +0000 endDate:2013-03-26 22:59:59 +0000 events (0):(null) Why the method return null array? Subsidiary question: is there a better way to get events for each days of a month? I'm looking for better performances. Thank you for your help! Edit 20/03/2013: I figure out thanks to Dhruvik that my code works perfectly for iOS 5.X but doesn't work for iOS 6.X (no test for 4.X). I check events and dates for 5.X and 6.X version and the only difference I saw is in event calendar timezone property: iOS 5.X timeZone = Europe/Paris (CET) iOS 6.X timeZone = Europe/Paris (UTC+01:00) This problem doesn't concern full day events. Do you have same problem with iOS 6.X? A: Here is the code to fecth Event, which i've implemented in my app.. in .h @property (nonatomic, retain) EKEventStore *eventStore; @property (nonatomic, retain) EKCalendar *defaultCalendar; @property (nonatomic, retain) NSMutableArray *eventsList; in .m //This code will fecth the events from one day Before the current date.. - (void) fetchevents { eventStore = [[EKEventStore alloc] init]; eventsList = [[NSMutableArray alloc] init]; EKEventStore *store = [[EKEventStore alloc] init]; [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { // handle access here }]; // Get the appropriate calendar NSCalendar *calendar = [NSCalendar currentCalendar]; // Create the start date components NSDateComponents *oneDayAgoComponents = [[NSDateComponents alloc] init]; oneDayAgoComponents.day = -1; // From which date you have to fetch Events from calander, as per your need subtract the days from current date NSDate *oneDayAgo = [calendar dateByAddingComponents:oneDayAgoComponents toDate:[NSDate date] options:0]; NSLog(@"%@", oneDayAgo); // Create the end date components NSDateComponents *oneYearFromNowComponents = [[NSDateComponents alloc] init]; oneYearFromNowComponents.year = 0; NSDate *oneYearFromNow = [calendar dateByAddingComponents:oneYearFromNowComponents toDate:[NSDate date] options:0]; NSLog(@"%@", oneYearFromNow); //Create the predicate from the event store's instance method NSPredicate *predicate = [store predicateForEventsWithStartDate:oneDayAgo endDate:oneYearFromNow calendars:nil]; NSArray *events_Array = [eventStore eventsMatchingPredicate: predicate]; for (EKEvent *eventToCheck in events_Array) { [eventsList addObject:eventToCheck.title ]; } } Hope it helps., Happy coding.. Thanks
[ "physics.stackexchange", "0000225003.txt" ]
Q: Why does this consider the center of mass instead of the end? (RIGID BODY MOTION) A uniform rod of length L and mass M is free to rotate on a frictionless pin passing through one end. The rod is released from rest in the horizontal position. What is its angular speed when it reaches its lowest position? I don't understand why we use the center of mass, since this object is constrained by the pivot, wouldn't it be correct to use L instead of 1/2 L? I got w = sqrt(6g/L) instead of w = sqrt(3g/L) A: The reason you use L/2 instead of L is because when you are using conservation of energy to convert the potential energy to kinetic energy, not all of the mass in the rod changes position by L. However, if you sum the energy contributions from each part of the rod, you will find that on average the decrease in height is L/2. For each part of the rod a distance $dl$ from the center of the rod that contributes slightly more energy, there is a piece at $-dl$ that contributes slightly less energy, the average of the two being equal to a contribution at L/2.
[ "stackoverflow", "0023550651.txt" ]
Q: Applying generic decorators conditionally in Autofac based on generic type constraints I have an application with an query/handler based architecture. I have the following interface: public interface IQueryHandler<TQuery, TResult> where TQuery : IQuery<TResult> { TResult Handle(TQuery query); } There are many non-generic implementations of this interface. Those implementations are wrapped by generic decorators for logging, profiling, authorization, etc. Sometimes however I want to apply a generic decorator conditionally based on the generic type constraints of the decorator. Take for instance this caching decorator that can only be applied to queries that return a ReadOnlyCollection<T> (simply because caching any collection that is mutable doesn't make much sense): public class CachingQueryHandlerDecorator<TQuery, TResult> : IQueryHandler<TQuery, ReadOnlyCollection<TResult>> where TQuery : IQuery<ReadOnlyCollection<TResult>> { private readonly IQueryHandler<TQuery, ReadOnlyCollection<TResult>> decoratee; private readonly IQueryCache cache; public CachingQueryHandlerDecorator( IQueryHandler<TQuery, ReadOnlyCollection<TResult>> decoratee, IQueryCache cache) { this.decoratee = decoratee; this.cache = cache; } public ReadOnlyCollection<TResult> Handle(TQuery query) { ReadOnlyCollection<TResult> result; if (!this.cache.TryGetResult(query, out result)) { this.cache.Store(query, result = this.decoratee.Handle(query)); } return result; } } What might make it more tricky is that those conditional decorators could be anywhere in the decorator chain. More than often they are one of the decorators in the middle. For instance, this CachingQueryHandlerDecorator wraps a non-conditional ProfilingQueryHandlerDecorator and should get wrapped by a conditional SecurityQueryHandlerDecorator. I found this answer that refers to applying non-generic decorators conditionally; not about applying generic decorators conditionally based on generic type constraints. How can we achieve this with generic decorators in Autofac? A: If I inherited a codebase that had decorator chains, this is what I would hope to see: // Think of this as the "master decorator" - all calling code comes through here. class QueryHandler<TQuery, TResult> where TQuery : IQuery<TResult> { private readonly IComponentContext context; public QueryHandler(IComponentContext context) { this.context = context; } public TResult Handle(TQuery query) { var handler = context.Resolve<IQueryHandler<TQuery, TResult>>(); if (typeof(TResult).IsClosedTypeOf(typeof(ReadOnlyCollection<>))) { // manual decoration: handler = new CachingQueryHandlerDecorator<TQuery, TResult>(handler); // or, container-assisted decoration: var decoratorFactory = context.Resolve<Func<IQueryHandler<TQuery, TResult>, CachingQueryHandlerDecorator<TQuery, TResult>>>(); handler = decoratorFactory(handler); } if (NeedsAuthorization(query)) { ... } return handler.Handle(query); } } Since the order of decoration is important, I want to be able to see it and easily change it and step through it if needed. Even if I'm new to DI, I can probably maintain this code. However, if you have a jumble of keys and callbacks and container-driven magic, it will be much harder for me to maintain. Just because you can use the container for something doesn't mean you should. Finally, notice that my QueryHandler class does not implement IQueryHandler - this is on purpose. I've come to think of the Decorator pattern as "mostly harmful" in that a lot of times it subverts the Liskov substitution principle. For example, if you use IQueryHandler everywhere then a misconfigured DI container could omit an Authorization decorator - the type system won't complain, but your app is definitely broken. For this reason, I like to separate the "call-site abstraction" from the "implementation-site abstraction" (see Event Handler vs Event Raiser on another of my answers) and make anything in-between as explicit as possible.
[ "stackoverflow", "0027716940.txt" ]
Q: Can I send Audio messages / notification in Android Auto? Can I just send only Android Text messages as notifications to Android Auto Messaging system/app or - Is it possible to send media files like a voice/audio/mp3 notification via Android Auto? A: As of now audio messages are not supported.(API level 21) Note that Android auto platform has feature to read out the text sent. And same way, for the reply, android auto can capture the user voice and return it as text.
[ "stackoverflow", "0033552608.txt" ]
Q: Currying for functions with n (3 or more) arguments? For functions with three or more arguments, how does currying work? I searched over SO and Google. Concrete examples given in e.g. What is 'Currying'? ; https://en.wikipedia.org/wiki/Currying are about binary functions f (x, y). In that case, g = curry f takes one parameter and produces a unary function (f x). My question is: How do we extend this consistently to a n-parameter function, e.g. f3 (x,y,z)? (f3: X->Y->Z->U) If the curry operation is treated as a higher order function, it can't directly apply to f3, because curry expects a function of type (X,Y) -> Z, and the argument of f3 is a triple, not a pair. The same issue arises with a function fn that takes an n-tuple. One solution might be to equate (x,y,z) and (x,(y,z)), then curry seems to apply. Then curry f3 = (f3 x) is of type (Y,Z) -> U. But is this how curry is supposed to be? A: If the curry operation is treated as a higher order function, it can't directly apply to f3, because curry expects a function of type (X,Y) -> Z, and the argument of f3 is a triple, not a pair. The same issue arises with a function fn that takes an n-tuple. There are aspects of your question that include much of the strong typing of Haskell that aren't present in most Lisps. For instance, an easy n-ary curry could be defined as: (defun curry (function first-argument) (lambda (&rest args) (apply function first-argument args))) CL-USER> (let ((f (curry (curry (lambda (x y z) (* x (+ y z))) 2) 3))) (mapcar f '(1 2 3 4 5))) ; (8 10 12 14 16)
[ "stackoverflow", "0008487673.txt" ]
Q: How would you make this Python Dictionary thread-safe? I have a Web Server running in Python. The server is private, so i only expect around 20 users to connect to it. The server is multi-threaded (8 cores at the moment, so 8 threads I guessed). When requests come in, I am able to identify the users. On some queries, I need to update a simple dictionary of the form username -> Boolean. How could I make this one thread safe ? A: You'll need to create a global lock object. lock = threading.Lock() Then around each access of the dictionary acquire and release the lock. The simplest way to do this is with the new(ish) with syntax. with lock: dict[key] = value A: If you need a lock (to avoid the race conditions Joonas described), and are stuck with Python 2.4, import threading lock = threading.Lock() shared_dict = {} def do_thing(user, value): lock.acquire() try: shared_dict[user] = value finally: # Always called, even if exception is raised in try block lock.release() A: You may or may not need to use a lock, depending on how the Boolean is updated. If the value of the Boolean doesn't depend on its previous value, then no lock is needed: writing and reading a Python dictionary is thread-safe by itself (except: writing while iterating is not allowed - but that's not allowed in single thread either). The memory visibility is similar to what would be achieved using volatile in some languages. What's inherently not thread-safe is the "read-modify-write" -sequence, resulting in a race condition. If the value of the Boolean does depend on its previous value, then you have to use a lock, because otherwise thread A could first read the value, then thread B could change it, and then A would change it again, based on outdated value to start with.
[ "stackoverflow", "0045286063.txt" ]
Q: Delphi XE3: [dcc32 Fatal Error] Unit5.pas(7): F1026 File not found: 'RzEdit.dcu' Delphi XE3 compiler cannot found Raize dcu files although the path is defined in Tools/Options/Delphi Options/Library/Library path! Checking the command line, there is only one path found in the -I option. All other Library paths are missing. Current command line -I option: "c:\program files\embarcadero\rad studio\10.0\lib\Win32\Debug" Expected command line -I option: "c:\program files\embarcadero\rad studio\10.0\Lib"; "c:\program files\embarcadero\rad studio\10.0\Imports";" "c:\program files\embarcadero\rad studio\10.0\include"; "C:\Users\Public\Documents\Embarcadero\rad studio\10.0\Dcp"; "C:\Users\Public\Documents\Embarcadero\rad studio\10.0\Bpl;" "C:\Program Files\embarcadero\rad studio\10.0\bin"; "c:\program files\embarcadero\rad studio\10.0\Lib\win32\release"; "c:\program files\embarcadero\rad studio\10.0\Lib\win32\debug"; "C:\Program Files\Raize\RC6\Lib\RS-XE3\Win32"; Why the other pathes are ignored? A: In March 2018, Microsoft seems to have shipped an update to the Windows Insider builds that introduces a PLATFORM environment variable, and doing this breaks the Delphi 10.x (seattle and up IDE). As a temporary workaround for win32 IDE targets users, create a user override PLATFORM environment variable and set the value to win32.
[ "gaming.stackexchange", "0000357751.txt" ]
Q: Installing Battlefield 3 from a Bluray disc without the game box I found a bluray disc of Battlefield 3 without the box. Will I be able to install it on a PS3 without a box/key or do I need a serial key that might have been on a box? A: I just looked at my box and there is no serial key on this game you should be fine to install it. There were several games with online codes in this era but this does not appear to be one. At most you might miss out on a promotional item that is no longer valid due to those having expiration dates on them.
[ "stackoverflow", "0041199367.txt" ]
Q: Nginx throwing 502 Bad Gateway on blog (subdomain) So, I was trying to setup mysite.com/blog initially, but got pretty fed up with it, so i setup blog.mysite.com instead. It successfully loads the index file: index.htm, but if i try to access a file info.php it fails saying: 502 bad gateway, i checked /var/log/nginx/error.log and it says: 2016/12/17 09:24:13 [error] 1042#0: *4 connect() failed (111: Connection refused) while connecting to upstream, client: x.xx.xx.xx, server: blog.mysite.com, request: "GET /info.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "blog.mysite.com" I installed php via: sudo apt-get install php5-fpm php5-mysql from this tutorial: link My nginx config in /etc/nginx/sites-enabled/myblog is: server { listen 80; root /home/www/flask-deploy/myblog; fastcgi_index index.php; index index.html index.htm index.nginx-debian.html; server_name blog.mysite.com www.blog.mysite.com; location / { try_files $uri $uri/ =404; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; #fastcgi_pass unix:/var/run/php-fpm.sock; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } } What am I doing wrong? Thank you so much! A: First of all, your nginx config has bad path to php-fpm.sock. (You error.log is right ;) ) 1) Which PHP version are you using? Use: php -v 2) Be sure php-fpm is installed it is very important for nginx sudo apt-get install php-fpm 3) Set correct path to php-fpm For example, I use PHP7.0 and my path is: fastcgi_pass unix:/run/php/php7.0-fpm.sock; Some my projects are running on PHP5.6 and path is: fastcgi_pass 127.0.0.1:9000; 4) Restart nginx and php-fpm (php5.6-fpm, php7.0-fpm...) sudo service nginx restart sudo service php5.6-fpm restart
[ "stackoverflow", "0035519204.txt" ]
Q: Where has json.org java library gone? So, I'm trying to learn JSON, for Java, but it appears to be a moving target - there are a number of libraries available, but I prefer to stick to either the JSON.ORG version or the Oracle Java javax version. However, it seems that JSON.ORG no longer provides docs or an 'official' library. None of the .org links I have found - apart from the landing page - work any longer. E.g. http://www.json.org/java The end result is that much of what I find and learn I can't apply because they reference the JSON.ORG library which does not seem to be available any longer. The landing page does provide a list of other libraries that can be used. One of these is generically named: JSON-lib on sourceforge. Is this the one that used to be on JSON.ORG? There's no reference that says that. Am I missing something? Is the JSON.ORG library available elsewhere, or shuld I just stick with Oracle's javax.json? Or, is Google's version a better option? A: I'm trying to learn JSON What is there to learn about JSON? There are objects, arrays, and values... I prefer to stick to either the JSON.ORG version or the Oracle Java javax version. Once you understand the structure of JSON, why does preference matter unless you are trying to maintain legacy code? Libraries become deprecated and developers often no longer maintain their projects when something else such as Gson or Jackson come along that outshine them. As long as you are familiar with the general concept of parsing JSON, library usage is a heavily opinionated answer. As you've discovered, the JSON.org library is non-existent, but at least there are a long list of alternatives. Gson and Jackson are the popular ones simply for their object marshaling capabilities as well as exception handling (such as getting a value from a JSONObject for a key that doesn't exist). If you just want a simple, minimal JSON parsing library, then either javax.json or json-simple are fine. I have used all 4 mentioned above on a variety of projects, but I am offering my unbiased opinion that you should just pick a library and hope it stays around and is maintained by its developers. A: The org.json library originally written by Douglas Crockford is alive and well, and can be found here: https://github.com/stleary/JSON-java Jar files are available from the Maven repository: https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.json%22%20AND%20a%3A%22json%22
[ "stackoverflow", "0060595453.txt" ]
Q: How to edit or provide data values in Outlook Webaddin Manifest XML file in runtime Im working on developing an Outlook Webadin. In the manifest XML file of the addin I need to provide some of the elements values in run time. For example I need to read a port number from registry and then assign this port number to SourceLocation in < SourceLocation DefaultValue="https://localhost:5005/" /> Is there a way to do it via code? or any other way in which I can provide these values in run time. Thanks. A: Currently the feature:dynamically update port number in manifest, you requested, is not a part of the product. We track Outlook add-in feature requests on our user-voice page (officespdev.uservoice.com/forums/224641-general/category/…). Please add your request there. Feature requests on user-voice are considered, when we go through our planning process.
[ "stackoverflow", "0011816829.txt" ]
Q: Can't call c-functions from NASM in VC++ except main, getting linking error Can anyone please tell me why I can't call any global functions from NASM, except main ? (Before you ask) Yes, I have read all the questions regarding this in stackoverflow and in internet for about 8 hours. C++ code. void main(); extern "C" void nasm_function(void); void c_function() { } void main() { nasm_function(); system("pause"); } NASM code, extern _c_function extern _main segment .text global _nasm_function _nasm_function: call _main call _c_function Output, 1>Linking... 1>my_asm.obj : error LNK2001: unresolved external symbol _c_function 1>F:\Projects\OSDev\assmebly_test\Debug\project.exe : fatal error LNK1120: 1 unresolved externals as you can see, we don't get linking error for main. I don't know why. :) Settings, building nasm using custom-build-rules with nasm.exe -f win32 Calling convention is __cdecl (/Gd) Visual Studio 2008 NASM version 2.05 Didn't include my_asm.obj as a input to linker Anyone please tell me what is the issue ? Thanks in advance. (note that this is a sample program, but still getting the issue) A: The issue is name mangling. The solution is extern "C".
[ "stackoverflow", "0019557118.txt" ]
Q: Internet Connection Status using MATLAB Is there a way to check if I'm connected to the internet using MATLAB? Is there a function that returns true if it's connected to the internet? A: A similar approach to the above: function tf = haveInet() tf = false; try address = java.net.InetAddress.getByName('www.google.de') tf = true; end end It does have the benefit of not spawning an additional process and being independent from the fact, whether a particular site may at the moment be unavailable (which might be a good or bad feature). A: How about using a ping to one of Google's DNSes? if ispc C = evalc('!ping -n 1 8.8.8.8'); elseif isunix C = evalc('!ping -c 1 8.8.8.8'); end loss = regexp(C, '([0-9]*)%.*loss', 'tokens'); connected = ~isempty(loss) && str2double(loss{1}{1})==0;
[ "stackoverflow", "0008396160.txt" ]
Q: How to Change Underlined Font Color in Android I have a problem with the Font Color for the Website link in an Android App. Please see the code below: Email.setText(Html.fromHtml("W : "+"<u>" +Email1+ "</u>")); Can i change the Font Color for Underlined Email1 Text without changing the W : Color? Is there any HTML Tags can be used inside "<u>" +Email1+ "</u>" to change the Font Color. Please help me with your ideas/code. Thanks in advance. A: You can use like this Email.setText(Html.fromHtml("W : "+"<u><FONT COLOR=\"#80776b\" >"+Email1+"</Font></u>")); Use color code what you want.
[ "unix.stackexchange", "0000303126.txt" ]
Q: what are gnome-session and gnome-settings-daemon? Can someone explain to me exactly what gnome-session and gnome-settings-daemon do and how they might be useful to me, as someone who doesn't use GNOME or any of its relatives as a DM (i use i3)? I've only known that one of the two can be used to automatically set media keybindings but am increasingly bothered that I know neither which one sets the keybindings nor what either of them is really for. A: gnome-session starts gnome-settings-daemon. The latter manages the data used in a session. The former tells it what to do. Based on the description, you'll be more interested in the settings daemon than the session manager. Further reading: Difference between gnome-session and gnome-shell? by default gnome.session starts gnome-shell and gnome-settings-daemon, gnome-settings-daemon-3.20.1 The GNOME Settings Daemon is responsible for setting various parameters of a GNOME Session and the applications that run under it. Package: gnome-settings-daemon The daemon sharing settings from GNOME to GTK+/KDE applications gnome-settings-daemon This package contains the daemon which is responsible for setting the various parameters of a gnome session and the applications that run under it. it handles the following kinds of settings: keyboard: layout, accessibility options, shortcuts, media keys clipboard management theming: background, icons, gtk+ applications cleanup of unused files mouse: cursors, speed, accessibility options startup of other daemons: screensaver, sound daemon it also sets various application settings through x resources and freedesktop.org xsettings. gnome-session-3.20.2
[ "stackoverflow", "0050753643.txt" ]
Q: How to redraw only the regions of an image that have changed using matplotlib I have an application where only one row of a 1024x2048 pixel image changes at a rate of 100 times per second. I would like to display and update this image in real time using minimal resources. However, matplotlib redraws the entire image every time I call the plt.draw() function. This is slow and processor intensive. Is there a way to redraw only one line at a time? A: I am not an expert on matplotlib internals, but I think it cannot be done in that way. Matplotlib was not designed for displaying large changing textures at a high frame rate, it is designed to offer a high level and be very easy to use API for displaying interactive plots. Internally it is implemented in both python and c++ (for low level and high performance operation), and it uses Tcl / Tk as graphical user interface and widget toolkit (what allows the great cross-platform portability among OSs). So, your 1024x2048 matrix has to be transformated several times before it is displayed. If you do not need the extra features matplotlib gives (as autoscaling, axes, interactive zoom...) and your main goal is speed, I recommend you to use a more focused in performance python library / module for displaying. There are lots of options: pyopencv, pySDL2...
[ "math.stackexchange", "0003758021.txt" ]
Q: How did Archimedes figure out that the area of ball is the same with the area of cylinder surrounding it? https://www.varsitytutors.com/hotmath/hotmath_help/topics/surface-area-of-a-sphere This one says the area of a ball is the same with the are of cylinder surrounding it. Why? A: Put the sphere inside the cylinder and let $\phi\in[0,\pi]$ be the oriented angle of a vector with the oriented axis of symmetry in the construction. Then take two parallel planes (perpendicular to the cylinder) cutting the sphere at angles $\phi$ and $\phi+\delta \phi$, respectively (with $\delta \phi$ being small). The slice on the sphere between the two cuts is comparable to a 'tilted' strip of width $r\delta \phi$ and of circumference $2\pi r \sin \phi$. Whence its area is of order: $$ \Delta A = ( r \ \delta\phi) \ (2 \pi r \cdot \sin(\phi))$$ Now the slice on the cylinder is a vertical strip of width $r \sin \phi \ \delta \phi$ (the factor $\sin \phi$ coming from projection) and circumference $2\pi r$. Whence of area: $$ \Delta A' = (r\ \sin (\phi) \ \delta \phi) \ (2\pi r),$$ i.e. the two slices have the same area. Applying some limiting argument we obtain the result as well as the following generalization: Take two parallel planes cutting the sphere at angles $\phi_1<\phi_2$ then the areas of the slice on the sphere and the cylinder are the same. This leads to Lamberts equal-area projection which provides maps of the earth respecting areas (but highly distorted near the poles).
[ "stackoverflow", "0025306235.txt" ]
Q: Eclipse- Workspace closed error I want to get the path of my workspace in Eclipse. I wrote the following code: IWorkspace myWorkspace = ResourcesPlugin.getWorkspace(); System.out.println(myWorkspace.getRoot().getFullPath()); The problem is that I get a workspace closed exception. How can I solve this ? A: First you must run this code in Eclipse plugin code. Using a main method will not work as the Eclipse/OSGi plugin infrastructure will not be initialized and nothing will work properly. Secondly getFullPath() returns the path relative to the workspace root so it will always be / for the root. To get the local file system path use getLocation()
[ "stackoverflow", "0003994464.txt" ]
Q: Open only one activity, without the main activity I have an application that has one service and 2 activities.One activity (the main one) is a preferences activity and the other one is a dialog themed activity. The service from time to time needs to open only the dialog themed activity (using FLAG_ACTIVITY_NEW_TASK). The problem is that when the preferences activity is opened in background (for example the user pressed HOME key instead of BACK, so the activity is OnPause) and the service tries to open the dialog themed activity, also the main activity is opened (comes in foreground). I don't want this. So, how can I open only the themed activity from the service, without the main activity pop up ? Android Manifest .xml <service android:name=".SimpleService"> </service> <activity android:name=".Preferences" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".popup_activity" android:theme="@android:style/Theme.Dialog" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.SAMPLE_CODE" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="screenon.popup.activity" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> And from the service : Intent intent = new Intent(Intent.ACTION_VIEW); intent.addCategory("screenon.popup.activity"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); A: Alex , I believe that all you want is to display preferences activity just once & then it must die(or lets say finish()) . In that case you can override onResume of the preferences activity to finish your preferences activity after it is resumed after pause @Override public void onResume() { //if activity is resumed after onPause then only run it this.finish(); //simply kill your activity if it is resumed after pause } EDIT-To know whether the activity was paused you need to override onPause().I think you can dig out the rest. Hope it helps!
[ "stackoverflow", "0062824381.txt" ]
Q: Cumulative sum of a numpy array and store each value into a new array I have a numpy array fs by reading from a *.csv file. It's size is (606,) and the data type is float64. Example a my raw data i M(i) dM(i) 1 0.0012 0.00013 2 0.00015 3 0.00016 4 0.00018 Now every element of my array should be calculated like this: M(i) = M(i-1) + dM(i-1)*t. t is a constant factor of 10. M(2) would be M(2) = M(1) + dM(1)*t = 0.0012 + 0.00013*10 = 0.0025 M(3) would be M(3) = M(2) + dM(2)*t = 0.0025 + 0.00015*10 = 0.004 I calculated some values manually. i M(i) dM(i) 1 0.0012 0.00013 2 0.0025 0.00015 3 0.004 0.00016 4 0.0056 0.00018 My idea was simply to write a for loop for every item in the array, but the calculations seem to be wrong. fs is the array and t is a certain time interval. t is constant and has a value of 10 # Ms(t) def mass(t, fs): M_st = 0 for i in fs M_st = M_st + i*t return M_st sum = mass(10,fs) A: Use the built in function cumsum for it (a is your array): a.cumsum() #[ 1 4 8 13 19 26] UPDATE: Based on OP's edit on post (t is scalar and M and dM are arrays. Note that python indexing is zero-based and NOT one-based): M(0) + (dM*t).cumsum()
[ "stackoverflow", "0046773118.txt" ]
Q: json string deserialization to custom object I am posting this question after reading the posts available. I have an ASP.NET web api controller with following methods. [DataContract] public class CustomPerson { [DataMember] public ulong LongId { get; set; } } [DataContract] public class Employee : CustomPerson { [DataMember] public string Name { get; set; } [DataMember] public string Address { get; set; } } Then in the controller public class CustomController : ApiController { [HttpPost] [ActionName("AddEmployee")] public bool AddEmployee(Employee empInfo) { bool bIsSuccess = false; // Code loginc here bIsSuccess = true; return bIsSuccess; } [HttpPost] [ActionName("AddEmployeeCustom")] public async Task<bool> AddEmployeeCustom() { string rawRequest = await Request.Content.ReadAsStringAsync(); bool bIsSuccess = false; // Code loginc here try { Employee emp = JsonConvert.DeserializeObject<Employee>(rawRequest); } catch (Exception ex) { } return bIsSuccess; } } When I call the following request to AddEmployee via soap ui the custom object is received without error i.e the empty value for LongId is ignored { "Name": "test1", "Address": "Street 1", "LongId": "" } When I call the AddEmployeeCustom method the runtime throws exception: Error converting value "" to type 'System.UInt64'. Path 'LongId', line 4, position 14. One option I read is to convert the incoming string to JObject and then create object of Employee class but I am trying to understand and mimic the behavior of default request handling mechanism when the incoming request is automatically handled by the controller and deserialized to Employee object A: The problem is that your JSON is not valid for your model. In the first method AddEmployee the process called Model Binding happens. MVC does the job of converting post content into the object. It seems its tolerant to type mismatch and forgives you the empty string. In the second case, you try to do it yourself, and try simply run deserialization without validating input data. Newtonsoft JSON does not understand empty string and crashes. If you still need to accept invalid JSON you may want to overwrite default deserialization process by implementing custom converter public class NumberConverter : JsonConverter { public override bool CanWrite => false; public override bool CanConvert(Type objectType) { return typeof(ulong) == objectType; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var value = reader.Value.ToString(); ulong result; if (string.IsNullOrEmpty(value) || !ulong.TryParse(value, out result)) { return default(ulong); } return result; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } And then specify your custom converter instance when calling deserialize return JsonConvert.DeserializeObject<Employee>(doc.ToJson(), new NumberConverter());
[ "stackoverflow", "0007528132.txt" ]
Q: Copy XValues from one TChartSeries to another Does anyone know how to copy the XValues from one TChartSeries to another in Delphi7 (and TeeChart 4.04)? TChartSeries.ReplaceList(CopySeries.XValues, OriginalSeries.XValues) does not work, since it seem to replace the reference, so when OriginalSeries is changed, so is CopySeries. The length of CopySeries is equal or greater than OriginalSeries. I want to preserve the CopySeries.YValues. My workaround has been to create a temporary list Dummy := TChartSeries.Create(nil); Dummy.AssignValues(OriginalSeries); CopySeries.ReplaceList(CopySeries.XValues, Dummy.XValues); Dummy.YValues.Destroy; but I get a memory leakage since I cannot Destroy the Dummy since that also removes the Dummy.XValues referenced by CopySeries.XValues. Any help is greatly appreciated. A: I can think of two options: Assigning ValueList arrays directly to the series as in the Real-time Charting article, for example: uses Series; procedure TForm1.FormCreate(Sender: TObject); begin Chart1.AddSeries(TLineSeries.Create(Self)).FillSampleValues; Chart1.AddSeries(TLineSeries.Create(Self)); { set our X array } Chart1[1].XValues.Value:=Chart1[0].XValues.Value; { <-- the array } Chart1[1].XValues.Count:=Chart1[0].Count; { <-- number of points } Chart1[1].XValues.Modified:=True; { <-- recalculate min and max } { set our Y array } Chart1[1].YValues.Value:=Chart1[0].YValues.Value; Chart1[1].YValues.Count:=Chart1[0].Count; Chart1[1].YValues.Modified:=True; { Show data } Chart1.Series[1].Repaint; end; Clone series: uses Series; procedure TForm1.FormCreate(Sender: TObject); begin Chart1.AddSeries(TLineSeries.Create(Self)).FillSampleValues; Chart1.AddSeries(CloneChartSeries(Chart1[0])); end; If you are using TeeChart 4.04 you'll probably have to address series like Chart1.Series[0] instead of Chart1[0] as in the Repaint call in the first example. Alternatively you could try something like this: uses Series, Math; procedure TForm1.FormCreate(Sender: TObject); var i, MinNumValues, MaxNumValues: Integer; begin Chart1.AddSeries(TLineSeries.Create(Self)).FillSampleValues(15); Chart1.AddSeries(TLineSeries.Create(Self)).FillSampleValues(25); MinNumValues:=Min(Chart1.Series[0].Count, Chart1.Series[1].Count); MaxNumValues:=Max(Chart1.Series[0].Count, Chart1.Series[1].Count); for i:=0 to MinNumValues -1 do Chart1.Series[1].XValue[i]:=Chart1.Series[0].XValue[i]; for i:=MinNumValues to MaxNumValues-1 do Chart1.Series[1].ValueColor[i] := clNone; end;
[ "stackoverflow", "0004542951.txt" ]
Q: WPF Datagrid items binding problem I get a problem while displaying a List in WPF-Datagrid. When I do this line ... DocumentList dt = new DocumentList(fileWordList, fileUriType, fileUri, cosineSimilarityRatio, diceSimilarityRatio, extendedJaccardSimilarityRatio); documentList.Add(dt); ... dataGrid1.Items.Add(dt); ... It creates an empty row into dataGrid1 and no text is shown there. my xaml implementation is this: <GroupBox Canvas.Left="-0.003" Canvas.Top="0" Header="Display Results" Height="427.5" Name="groupBox2" Width="645.56"> <toolkit:DataGrid Canvas.Left="137.5" Canvas.Top="240" Height="392" Name="dgrDocumentList" Width="627" ItemsSource="{Binding DocumentList }"> <toolkit:DataGrid.Columns> <toolkit:DataGridTextColumn Header="Type" Binding="{Binding type}" IsReadOnly="True"> </toolkit:DataGridTextColumn> <toolkit:DataGridHyperlinkColumn Header="Uri" Binding="{Binding path}" IsReadOnly="True"> </toolkit:DataGridHyperlinkColumn> <toolkit:DataGridTextColumn Header="Cosine" Binding="{Binding cos}" IsReadOnly="True"> </toolkit:DataGridTextColumn> <toolkit:DataGridTextColumn Header="Dice" Binding="{Binding dice}" IsReadOnly="True"> </toolkit:DataGridTextColumn> <toolkit:DataGridTextColumn Header="Jaccard" Binding="{Binding jaccard}" IsReadOnly="True"> </toolkit:DataGridTextColumn> </toolkit:DataGrid.Columns> </toolkit:DataGrid> </GroupBox> and my DocumentList class class DocumentList { public List<WordList> wordList; public string type; public string path; public double cos; public double dice; public double jaccard; //public static string title; public DocumentList(List<WordList> wordListt, string typee, string pathh, double sm11, double sm22, double sm33) { type = typee; wordList = wordListt; path = pathh; cos = sm11; dice = sm22; jaccard = sm33; } I would like to do that: When i add a new element into documentList instance, would like to see the results on data grid. Thank you in advance. A: You can only bind to properties, so change your DocumentList public fields to public properties instead.
[ "stackoverflow", "0043892289.txt" ]
Q: cookie value is undefined (react-cookie 2.0.6) I have a problem with implementing react cookies v^2. I use webpack-dev-server for testing. Here is a conlose log: Warning: Failed context type: The context cookies is marked as required in withCookies(App), but its value is undefined. in withCookies(App) in Provider /App.jsx: import React, { Component } from 'react'; import { CookiesProvider, withCookies, Cookies} from 'react-cookie' import {Route, Switch, BrowserRouter} from 'react-router-dom'; //import RequireAuth from './RequireAuth'; import NotFoundPage from './NotFoundPage'; import LandingPage from './LandindPage'; import WorkSpace from './WorkSpace'; import ActivationPage from './ActivationPage'; class App extends Component { render() { return ( <CookiesProvider> <BrowserRouter> <Switch> <Route exact={true} path="/" component={LandingPage}/> <Route path="/workspace" component={WorkSpace}/> <Route exact path="/activation" component={ActivationPage}/> <Route path="*" component={NotFoundPage}/> </Switch> </BrowserRouter> </CookiesProvider> ); } } export default withCookies(App); /index.js: import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware } from 'redux'; import reduxThunk from 'redux-thunk'; import reducers from './reducers'; import { Provider } from 'react-redux'; import App from './components/App'; const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore); const store = createStoreWithMiddleware(reducers); ReactDOM.render( <Provider store = {store}> <App/> </Provider> , document.getElementById('root')); A: It appears that the functionality previously present in the react-cookie npm package has been moved to universal-cookie. The relevant example from the universal-cookie repository now is: import Cookies from 'universal-cookie'; const cookies = new Cookies(); cookies.set('myCat', 'Pacman', { path: '/' }); console.log(cookies.get('myCat')); // Pacman Source (all credits to author of the orginal answer)
[ "stackoverflow", "0030998152.txt" ]
Q: How to use modport and What is the benefit to instanciate between interface and DUT in systemverilog? I'm verilog user and unfamiliar with systemverilog. I have found what to used modport and instanciate between DUT and interface in systemverilog. But I don't no why use the modport and how to use and interconnect between interface and DUT in systemverilog? A: Modport is short for module port. They allow for the definition of different views of the signals within the interface. In many cases, just two modports, or views, are needed - One for the source-side of the interface, and one for the sink-side. A simple example is below: interface simple_if (); wire we; wire wdata; wire full; // source-side view modport src ( output we, output wdata, input full ); // sink-side view modport snk ( input we, input wdata, output full ); endinterface The interface can be used to connect two module instances together, and which view, or modport to use can be specified at each module instance using the dot notation. Example below using the interface definition above: module top(); // first, instantiate the interface simple_if simple_if (); // source-side module instantiation src_side_module u_src_side_module ( .clk (clk), .rstl (rstl), .if(simple_if.src) // .src specifies the modport ); // sink-side module instantiation snk_side_module u_snk_side_module ( .clk (clk), .rstl (rstl), .if(simple_if.snk) // .snk specifies the modport ); endmodule Couple other notes: The clocks and resets can also be passed around inside the interface. Alternatively, the modport can be specified down in the module where you specify the IO, like this: module src_side_module ( input wire clk, input wire rstl, simple_if.src if ); .... Hope this helps.
[ "stackoverflow", "0045020046.txt" ]
Q: Long running file generation on Heroku + Django I have a Django app running on Heroku. The user can download various reports in either Excel/PDF format. Some of these reports can take a minute to generate, which means I need to create them on a background/worker process. I already have celery setup together with redis as the message broker. My question is what is the best way to deal with this? This is my idea so far. As soon as the user start the report, it shows 'Generating, please wait' on the page somewhere. The file then gets generation and saved in a temporary location. Probably on S3 or in some sort of cache. I then poll a specific location and once the file is ready it returns the url of where the file is stored. At this point the 'Please wait' turns into a link. Once a day I clear out the S3 bucket using lifecycle rules I'm sure this will work, but it just seems like a lot of effort and not the best user experience either. Currently the user just waits for the file once ready the download dialog appears. This works fine as long as the file is returned within 30 seconds, which isn't always the case. I've also thought about emailing the file to the user, but I don't think this is a great approach. Does anybody have any better suggestions? A: I would certainly not use e-mail. With that out of the way, I don't see what's wrong with your approach from a UX perspective. Waiting for a file to be generated certainly beats timing out or waiting for 30 seconds before download starts, for that matter. Depending on the use case, you could (a) provide an estimated time till the report is generated (may not be possible) and/or (b) have the user land on a different page with report details (possibly using the HTML5 history API to make it seamless).
[ "stackoverflow", "0034407808.txt" ]
Q: White space under nav bar, only goes away when border is added to header in next section I have a white space under the navigation bar of my webpage. The only way I can get it to go away is to add a border to the header section below. I've double checked my code so many times, please help me identify where I am going wrong. I'm a beginner, so let me know if I'm totally off base with my structure. In this snippet, you can see the result by simply un-commenting the on the header css. I really want to learn what I'm doing wrong here. Thanks. body { padding: 0; margin: 0; font-family: 'Josefin Sans', sans-serif; } .container { max-width: 940px; margin: 0 auto; padding: 0 10px; } /****************************** NAV ******************************/ nav { background-color: #393D44; margin: 0; padding: 10px 0; } nav ul li { list-style: none; display: inline-block; } nav ul li a { text-decoration: none; font-weight: 300; padding: 15px 10px; color: #fff; } nav ul li a:hover, .active { color: #4BAF70; } /****************************** HEADER ******************************/ header { margin: 0; background-image: url("http://easylivingmom.com/wp-content/uploads/2012/07/grocery-store-lg.jpg"); background-size: cover; background-repeat: no-repeat; height: 600px; /*border: 1px solid green;*/ <DOCTYPE html> <html> <head> <title>Grocery Shopping</title> <meta charset="UTF-8"> <link href='https://fonts.googleapis.com/css?family=Josefin+Sans:400,700,600,300' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <nav> <div class= "container"> <ul> <li><a href="#" class="active">Home</a></li> <li><a href="#">What</a></li> <li><a href="#">Where</a></li> <li><a href="#">When</a></li> <li><a href="#">How</a></li> </ul> </div> </nav> <header> <div class= "container"> <h1>Grocery Shopping</h1> <a href="#" class=btn>Get Involved</a> </div> </header> <section> <div class= "container"> <!- Need to figure this section out -> </div> </section> <footer> <div class= "container"> <p>&copy; Brianna Vay 2015</p> <p>Careers</p> </div> </footer> </body> </html> A: Your <h1>Grocery Shopping</h1> inside the header have a margin. try removing the margin. ie, header .container > h1{ margin-top: 0} This will solve the white space PS: add a class to the h1 tag and target only this element see this body { padding: 0; margin: 0; font-family: 'Josefin Sans', sans-serif; } .container { max-width: 940px; margin: 0 auto; padding: 0 10px; } /****************************** NAV ******************************/ nav { background-color: #393D44; margin: 0; padding: 10px 0; } nav ul li { list-style: none; display: inline-block; } nav ul li a { text-decoration: none; font-weight: 300; padding: 15px 10px; color: #fff; } nav ul li a:hover, .active { color: #4BAF70; } /****************************** HEADER ******************************/ header { margin: 0; background-image: url("http://easylivingmom.com/wp-content/uploads/2012/07/grocery-store-lg.jpg"); background-size: cover; background-repeat: no-repeat; height: 600px; /*border: 1px solid green;*/ <DOCTYPE html> <html> <head> <title>Grocery Shopping</title> <meta charset="UTF-8"> <link href='https://fonts.googleapis.com/css?family=Josefin+Sans:400,700,600,300' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <nav> <div class="container"> <ul> <li><a href="#" class="active">Home</a> </li> <li><a href="#">What</a> </li> <li><a href="#">Where</a> </li> <li><a href="#">When</a> </li> <li><a href="#">How</a> </li> </ul> </div> </nav> <header> <div class="container"> <h1 style="margin-top: 0">Grocery Shopping</h1> <a href="#" class=btn>Get Involved</a> </div> </header> <section> <div class="container"> <!- Need to figure this section out -> </div> </section> <footer> <div class="container"> <p>&copy; Brianna Vay 2015</p> <p>Careers</p> </div> </footer> </body> </html>
[ "diy.stackexchange", "0000068412.txt" ]
Q: How would I go about installing a prehung door in this opening? I've got an actual opening of 35.5" in an opening between my basement and garage. I'd like to install a prehung door (first time), and am a bit confused about the width necessary for framing. My door opening: From what I've read I want at least 2" between the prehung door width and my rough opening -- which I don't have yet. It sounds like this limits me to either a 32" prehung (actual 33.5") or a 30" (actual 31.5"). If I went the 30" route, that would leave me 2" on each side for framing the rough opening which seems like it would leave me with the most play and be able to do something like a 2x6 (1.5") on each side, leaving me with 1/2" gap for rough opening and making the door square. However, I'd prefer to use a wider 32" door (because why not?), but I'm not sure how to approach the framing: The opening minus the size of the prehung door would leave me with 2" for both sides with no framing. I'm pretty sure I need to frame at least the hinge side which would be possible with a 2x6 (1.5") leaving 1/2" for making square on either side. Is it okay to only frame one side? If not, would a 1x6 (3/4" width) be a thick enough board for framing and would the 1/4" gap rough opening be enough? A: Your idea about the 1X6 on either side is a good start. It would give you something to fasten to, in a simple fashion on both sides, although the fastening would be minimal. You may need to increase the number of nails in the jamb to keep it in place over the long haul. Same thing if you use screws. When the 1x6, for a 6" wall, or if it fits, 1X8 for an 8" wall, is set in place, use construction adhesive between the block and 1X and let it harden. Make sure your block are clean so the glue sticks. This will give a firm base to work to. Do not skimp on the glue. Use a 10 oz tube, a half tube at least, on each side before you set the 1X. Use concrete screws to fasten it in place, they are more reliable for a first time installer. You could use masonry nails but there are places they may not hold. The screws may fail in their holding, but that will be obvious. To increase the chances of holding, use the screws only in the block, not the joints. Keep the screws about an 1 1/4" to 1 1/2 from the edges of the block. The block is thicker there and is far enough from the edge to keep from cracking out (should be). Screws also only affect a small area when they fail, nails break out larger pieces. To answer the other part of your question, yes you could use framing only on one side, them shimming and fastening the other side is tricky. There are case hardened finish nails to do this, or even screws. For a first timer, what I mention above should do what you need.
[ "stackoverflow", "0014193009.txt" ]
Q: Android GCM service in another package than the main I implement GCM for my application. So I tried GCM sample code and made it work. But when I tried to inject the client side code in my app, I was suprised that I must put the GCMIntentService class in the main package otherwise it doesn't work (of course I changed the manifest file by adding <service android:name=".gcm.GCMIntentService" /> "my_main_package.gcm" is my new package where I put the service. For information, it works well when I put the service in the main package. Has anybody an idea? A: Here is the solution to put GCMIntentService in user defined package.
[ "stackoverflow", "0045564945.txt" ]
Q: How to implement a constructor so it only accepts input iterators using typeid? I want to implement a range constructor for a certain object, but I want to restrict it to only accept two input iterators. I've tried to compile this code with gcc 7.1.0. File test.cpp #include <vector> #include <type_traits> #include <typeinfo> template <typename Iterator> using traits = typename std::iterator_traits<Iterator>::iterator_category; template <typename T> class A{ private: std::vector<T> v; public: template <typename InputIterator, typename = std::enable_if_t< typeid(traits<InputIterator>) == typeid(std::input_iterator_tag)> > A(InputIterator first, InputIterator last) : v(first, last) {} }; int main(){ std::vector<double> v = {1, 2, 3, 4, 5}; A<double> a(v.begin(), v.end()); } I get this compilation error with g++ test.cpp -o test: test.cpp: In function ‘int main()’: test.cpp:27:34: error: no matching function for call to ‘A<double>::A(std::vector<double>::iterator, std::vector<double>::iterator)’ A<double> a(v.begin(), v.end()); ^ test.cpp:22:7: note: candidate: template<class InputIterator, class> A<T>::A(InputIterator, InputIterator) A(InputIterator first, InputIterator last) : v(first, last) {} ^ test.cpp:22:7: note: template argument deduction/substitution failed: test.cpp: In substitution of ‘template<bool _Cond, class _Tp> using enable_if_t = typename std::enable_if::type [with bool _Cond = ((const std::type_info*)(& _ZTISt26random_access_iterator_tag))->std::type_info::operator==(_ZTISt18input_iterator_tag); _Tp = void]’: test.cpp:18:16: required from here test.cpp:19:49: error: call to non-constexpr function ‘bool std::type_info::operator==(const std::type_info&) const’ typeid(traits<InputIterator>) == test.cpp:18:16: note: in template argument for type ‘bool’ typename = std::enable_if_t< ^~~~~~~~ test.cpp:10:7: note: candidate: A<double>::A(const A<double>&) class A{ ^ test.cpp:10:7: note: candidate expects 1 argument, 2 provided test.cpp:10:7: note: candidate: A<double>::A(A<double>&&) test.cpp:10:7: note: candidate expects 1 argument, 2 provided I decided to use default template parameter because is more suitable for constructors. The use of the operator typeid() is because I find it really easy to read when mantaining the code, but I can't get it to work in any way. Other solutions look very weird and are really obscure (like forcing the InputIterator parameter to have certain methods such as *it or ++it). If there's no way I can do this, I would appreciate a, more or less, easy-to-read solution. A: In order to do SFINAE you need to assure that evaluation of involving expressions happen at compile time. For typeid the following applies: When applied to an expression of polymorphic type, evaluation of a typeid expression may involve runtime overhead (a virtual table lookup), otherwise typeid expression is resolved at compile time. Thus, I wouldn't consider typeid a good option for static (compile time) polymorphism. One way you could solve your problem is by using tag dispatching in combination with a delegating costructor, as follows: template <typename T> class A{ std::vector<T> v; template <typename InputIterator> A(InputIterator first, InputIterator last, std::input_iterator_tag) : v(first, last) {} public: template<typename InputIterator> A(InputIterator first, InputIterator last) : A(first, last, typename std::iterator_traits<InputIterator>::iterator_category()) {} }; Live Demo
[ "stackoverflow", "0042065723.txt" ]
Q: Replacing one HTML table with another using the display method I have a series of tables to display, depending on the googlemaps api polygon that the user has clicked on. Code as follows: HTML <div id="adilaDIV" class="boxOne" style="display:none"> <table id="adilaTable" class="table" > <tr> <td>ADILABAD</td> </tr> <tr> <td>Population</td> <td>2,930,604</td> </tr> <tr> <td>Percent Adults</td> <td>81%</td> </tr> <tr> <td>Life Expectancy</td> <td>65</td> </tr> </table> </div> <div id="khamDIV" class="boxOne" style="display:none"> <table id="khamTable" class="table" > <tr> <td>KHAMMAM</td> </tr> <tr> <td>Population</td> <td>3,654,765</td> </tr> <tr> <td>Percent Adults</td> <td>81%</td> </tr> <tr> <td>Life Expectancy</td> <td>65</td> </tr> </table> </div> Javascript (with Googlemaps api) // Add a listener for the click event. adilabadBorder.addListener('click', showPanelAdila); //Show table with info function showPanelAdila() { document.getElementByClassName('boxOne').style.display="none"; document.getElementById('adilaDIV').style.display="block"; initialize(); } // Add a listener for the click event. khammamBorder.addListener('click', showPanelKham); //Show table with info function showPanelKham() { document.getElementByClassName('boxOne').style.display="none"; document.getElementById('khamDIV').style.display="block"; initialize(); } I require that when the user has clicked their second+ district, the old district table is hidden and the new district table displays. I have tried various other code but the above is the closest I've come to making it work: The toggle method generated no response from the browser: function myFunction() { var x = document.getElementById('myDIV'); if (x.style.display === 'none') { x.style.display = 'block'; } else { x.style.display = 'none'; } } As did the jQuery model solution: $("#hide").click(function(){ $("p").hide(); }); $("#show").click(function(){ $("p").show(); }); In my current 'solution' I am attempting to hide any of the boxOne Divs that might be displaying currently when the user selects a new district polygon (I have 29 districts). So hiding by class seems the right catch-all way to go about this but it doesn't work. However - if I use getElementById with just one district, instead of getElementByClassName, the code works. The previous table hides and the new one shows. A: Your problem is that there is no function getElementByClassName (I get a javascript error with your code Uncaught TypeError: document.getElementByClassName is not a function). The function that does what you want is getElementsByClassName, but as its name suggests, it returns an array of elements, so you need to iterate through that array to hide each element with that class, then you can show the div you are interested in. function hideAllBoxOne() { var elems = document.getElementsByClassName('boxOne'); for (i = 0; i < elems.length; i++) { elems[i].style.display = "none"; } } //Show table with info function showPanelAdila() { hideAllBoxOne(); document.getElementById('adilaDIV').style.display = "block"; } //Show table with info function showPanelKham() { hideAllBoxOne() document.getElementById('khamDIV').style.display = "block"; } proof of concept fiddle code snippet: var geocoder; var map; function initialize() { var map = new google.maps.Map( document.getElementById("map_canvas"), { center: new google.maps.LatLng(17, 80), zoom: 6, mapTypeId: google.maps.MapTypeId.ROADMAP }); var Khammam = { "formatted_address": "Khammam, Telangana 507001, India", "geometry": { "bounds": { "south": 17.1980713, "west": 80.09917259999997, "north": 17.2986392, "east": 80.20169729999998 }, "location": { "lat": 17.2472528, "lng": 80.15144469999996 } } }; // Define the LatLng coordinates for the polygon's path. var KhammamCoords = [{ lat: Khammam.geometry.bounds.south, lng: Khammam.geometry.bounds.west }, { lat: Khammam.geometry.bounds.south, lng: Khammam.geometry.bounds.east }, { lat: Khammam.geometry.bounds.north, lng: Khammam.geometry.bounds.east }, { lat: Khammam.geometry.bounds.north, lng: Khammam.geometry.bounds.west }]; // Construct the polygon. var khammamBorder = new google.maps.Polygon({ paths: KhammamCoords, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35 }); khammamBorder.setMap(map); var Adilabad = { "formatted_address": "Adilabad, Telangana 504001, India", "geometry": { "bounds": { "south": 19.6282789, "west": 78.50087639999992, "north": 19.696577, "east": 78.55979920000004 }, "location": { "lat": 19.6640624, "lng": 78.5320107 }, "location_type": "APPROXIMATE", "viewport": { "south": 19.6282789, "west": 78.50087639999992, "north": 19.696577, "east": 78.55979920000004 } } } // Define the LatLng coordinates for the polygon's path. var AdilabadCoords = [{ lat: Adilabad.geometry.bounds.south, lng: Adilabad.geometry.bounds.west }, { lat: Adilabad.geometry.bounds.south, lng: Adilabad.geometry.bounds.east }, { lat: Adilabad.geometry.bounds.north, lng: Adilabad.geometry.bounds.east }, { lat: Adilabad.geometry.bounds.north, lng: Adilabad.geometry.bounds.west }]; // Construct the polygon. var adilabadBorder = new google.maps.Polygon({ paths: AdilabadCoords, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35 }); adilabadBorder.setMap(map); // Add a listener for the click event. adilabadBorder.addListener('click', showPanelAdila); // Add a listener for the click event. khammamBorder.addListener('click', showPanelKham); } google.maps.event.addDomListener(window, "load", initialize); function hideAllBoxOne() { var elems = document.getElementsByClassName('boxOne'); for (i = 0; i < elems.length; i++) { elems[i].style.display = "none"; } } //Show table with info function showPanelAdila() { hideAllBoxOne(); document.getElementById('adilaDIV').style.display = "block"; } //Show table with info function showPanelKham() { hideAllBoxOne() document.getElementById('khamDIV').style.display = "block"; } html, body, #map_canvas { height: 100%; width: 100%; margin: 0px; padding: 0px } <script src="https://maps.googleapis.com/maps/api/js"></script> <div id="adilaDIV" class="boxOne" style="display:none"> <table id="adilaTable" class="table"> <tr> <td>ADILABAD</td> </tr> <tr> <td>Population</td> <td>2,930,604</td> </tr> <tr> <td>Percent Adults</td> <td>81%</td> </tr> <tr> <td>Life Expectancy</td> <td>65</td> </tr> </table> </div> <div id="khamDIV" class="boxOne" style="display:none"> <table id="khamTable" class="table"> <tr> <td>KHAMMAM</td> </tr> <tr> <td>Population</td> <td>3,654,765</td> </tr> <tr> <td>Percent Adults</td> <td>81%</td> </tr> <tr> <td>Life Expectancy</td> <td>65</td> </tr> </table> </div> <div id="map_canvas"></div>
[ "stackoverflow", "0017386077.txt" ]
Q: Update automatic ListBox items when alter List I have a ListBox, I populate it with ItemsSource with List<Control>. But when I delete or add new control for this List, I need every time reset my ListBox ItemsSource Have any method for ListBox sync List content? A: Instead of using a List<T>, use an ObservableCollection<T>. It is a list that supports change notifications for WPF: // if this isn't readonly, you need to implement INotifyPropertyChanged, and raise // PropertyChanged when you set the property to a new instance private readonly ObservableCollection<Control> items = new ObservableCollection<Control>(); public IList<Control> Items { get { return items; } }
[ "stackoverflow", "0048980395.txt" ]
Q: Chaining multiple for loops together into one I have two lists read from a file that look something along the lines of this: list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9, 0] I then have a for loop that needs to call both of those lists: res = [] for i in list1: for x in list2: if i + x * 2 == 10: res.append((i,x)) What I want to do is chain the for loops into one, so that it will only go through each number once, for example: res = [] for i in list1 and x in list2: if i + x * 2 == 10: res.append((i,x)) Doing the above now, will output an error that x is not defined: >>> list1 = [1, 2, 3, 4, 5] >>> list2 = [6, 7, 8, 9, 0] >>> res = [] >>> for i in list1 and x in list2: ... if i + x * 2 == 10: ... res.append((i,x)) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined >>> How can I go about doing this pythonically? A: Try zip itertools.product : import itertools ... for i, x in itertools.product(list1, list2): if i + x * 2 == 10: res.append((i, x))
[ "gamedev.stackexchange", "0000035246.txt" ]
Q: Fitting a rectangle into screen with XNA I am drawing a rectangle with primitives in XNA. The width is: width = GraphicsDevice.Viewport.Width and the height is height = GraphicsDevice.Viewport.Height I am trying to fit this rectangle in the screen (using different screens and devices) but I am not sure where to put the camera on the Z-axis. Sometimes the camera is too close and sometimes to far. This is what I am using to get the camera distance: //Height of piramid float alpha = 0; float beta = 0; float gamma = 0; alpha = (float)Math.Sqrt((width / 2 * width/2) + (height / 2 * height / 2)); beta = height / ((float)Math.Cos(MathHelper.ToRadians(67.5f)) * 2); gamma = (float)Math.Sqrt(beta*beta - alpha*alpha); position = new Vector3(0, 0, gamma); Any idea where to put the camera on the Z-axis? A: The trick to doing this is to draw the rectangle directly in raster space. This is the space that the GPU works in when actually rendering stuff. Normally your model starts in its own model space, you apply a world transform to get it into world space. You then apply a view transform to move the points in the world around the camera (to get the effect of the camera moving around the world). Then you apply a projection matrix to get all those points into the space that the GPU uses for drawing. It just so happens that this space is always - no matter the screen size - from (-1,-1) in the bottom left corner of the viewport, to (1,1) in the top right (and from 0 to 1 on the Z axis for depth). So the trick is to set all your matrices (world, view, project) to Matrix.Identity, and then draw a rectangle from (-1,-1,0) to (1,1,0). You probably also want to set DepthStencilState.None so that it doesn't affect the depth buffer. An alternative method is to just use SpriteBatch and draw to a rectangle that is the same size as the Viewport.
[ "stackoverflow", "0030772105.txt" ]
Q: Issue with tag in moqui <transition name="abc"> <actions> <if condition="update != null"> <service-call name="update#someEntity"/> </if> </actions> <default-response url="."/> </transition> Above code doesn't work. i.e. if I put log statements, it goes inside if block but update doesn't happen in DB entity. It is also verified that all params/values/p.keys etc are passed properly with proper values from FORM which invokes this transition on submitting. One other thing which was noticed is, it works perfectly when is changed as below (i.e. there is only a service call element inside transition and no any changes made to any other code anywhere in screen/other places): <transition name="abc"> <service-call name="update#someEntity"/> <default-response url="."/> </transition> Any guidance on this please? A: The Making Apps with Moqui explains the differences when service-call is used directly under the transition element as opposed to inside actions. With service-call directly under the transition element it assumes you want to use the "context" as the in-map and the out-map, unless you specify something different. Normally (i.e. within actions) the service-call element does not assume this, it wouldn't make sense not to specify what you want to do pass to the service (in-map) and it would be very confusing to have service outputs added to the context by default. To fix your first code example you need to add in-map and, if needed, out-map attributes, i.e.: <service-call name="update#someEntity" in-map="context" out-map="context"/> That should fix it.
[ "meta.stackexchange", "0000246865.txt" ]
Q: How do you delete your account at Area 51? It was quite simple to delete many accounts by clicking on 'help', but I cannot find such a possibility at Area51. Can someone tell me how to delete that account? A: This is actually a frequently asked question over at Meta.Stackexchange and has a specific question about Area51 accounts (which closed as duplicate of the previous). The process is simple: Change your name to delete Change your profile to say Please delete this account Go to the Contact Us page and fill out the form, stating you'd like your account deleted. That's pretty much it, network-wide.
[ "stackoverflow", "0007605508.txt" ]
Q: Interface with different parameter types and number I wanted to create a generic interface with a method I could use to convert objects ... Let me explain. In GWT, using GWT-Platform, the presenters have an inner interface that extends View. This interface is implemented by the class that builds the screen (the presenters have the button actions, etc.). So, assuming I have a presenter for user account, for example. It "represents" my User bean. I wish I could create a class implementing an interface, I could call a method passing the instance of the implementation of view, and he returned the bean populated ... I do not know if I could be clear enough .. OK. So far so good. I created an interface like this: public interface ViewBeanConverter<T, U extends View> { public T convert(U u); } It works for simple views, but the problem is that sometimes I need to pass parameters that are not in the interface view, but only in the presenter class, things that does not make sense being in view. For example, suppose the bean to build user, I need a list of belongings (the first thing that came to mind right now). And then, on another screen, a bean car for example, need an owner and a parts list for the concert... How I can handle that? I can not explain it right, sorry about that, but the real problem is I need different amounts of different types of parameters ... and was wondering if there is a elegant way to do this. thanks in advance. A: for different amounts of different types of parameters, use var args public interface ViewBeanConverter<T, V extends View> { public T convert(V v,Object... objects); } or simply a Map public T convert(V v, Map<Object, Object> objects);
[ "emacs.stackexchange", "0000028950.txt" ]
Q: Symbol's function definition is void: org-export--get-global-options I use a lot of embedded latex in my org files with drill mode. It worked fine with org 8, but recently I've upgraded to org 9, and now when I run C-c C-x C-l I'll get this error. My .emacs file contains the following code related with org and latex: (setq org-latex-create-formula-image-program 'dvipng) (setq org-format-latex-options (plist-put org-format-latex-options :scale 1.5)) I'm new to Emacs. What should I do to fix this? A: The problem is solved. I just added (require 'ox)
[ "stackoverflow", "0053855065.txt" ]
Q: Is there any way to save the trained data in Verilog? I wish to train a robot about the indoor environment with multiple obstacles. To save the trained data by this, is there anyway in verilog..!! This training data should be used by robot while deploying with dynamic data to move from one point to another in the trained indoor environment. What will be the best way of implementation in Verilog..!! A: Verilog is a Hardware Design Language. Thus you should think it terms of 'hardware'. There does not exist something like a "hardware database". The nearest and simplest I can think off, would be to make an SD-card interface and write raw data sectors to the SD-card. You will then need a special program to extract the data as computers like to see a FAT32-data structure. By the way: the option to read or write files only exists in a simulation environment. I don't know any synthesis tool which supports file I/O.
[ "stackoverflow", "0035454220.txt" ]
Q: Could not load file or assembly in COM visible class library C# I've created a class library project, and installed Newtonsoft.Json NuGet package. This operation added an app.config file, which contains: <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> </dependentAssembly> </assemblyBinding> Then I've made the class library COM visible: When I tried to use my class library in another C# WinForms project, I was getting error: System.IO.FileLoadException : Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) until I've added the same app.config lines in the WinForms project. Now I'm trying to use my assembly (referenced via COM) in Microsoft Word VBA developer, and I'm getting the same error, but I can't make an app.config file for Microsoft Word, can I? Is there any way, how this issue can be solved? Thanks in advance! A: Yes, this is a standard DLL Hell problem you'll have when you make a .NET assembly [ComVisible]. The CLR uses its normal way to look for dependent assemblies, those rules do not change in COM. It first looks in the GAC, it next looks in directory where the EXE is located. It does not look in the directory where your [ComVisible] assembly is located. Otherwise something that is easy to see with Fuslogvw.exe, be sure to practice it. There are multiple solutions to this problem, none are ideal so you'll have to pick the one that suits you best yourself. First thing you should strongly pursue is to get rid of the .config file. The <bindingRedirect> is always generated but is often unnecessary. It is only truly required when you reference multiple Nuget packages and they disagree about what version of Newtonsoft.Json.dll to use. If that's a problem then only deployment into the Office folder is practical, see the last bullet. Deploy everything to the GAC. This is normally the ideal solution for COM, it has a strong DLL Hell problem in general because registration is machine-wide. That makes deploying updates dangerous, you might fix a problem in one program but break another. Disadvantage is the install requirement. And the questionable practice of putting Newtonsoft.Json.dll in the GAC, an assembly that has a pretty opaque versioning history and is used by many other programs. Nonzero odds you'll break another app that uses it since it now loads the copy in the GAC instead of its local copy. The FUD is strong enough to avoid this. Use ILMerge so you'll only have a single DLL. Does not always work, it can't handle mixed-mode assemblies and cannot handle binding redirects. Try it and you'll quickly find out. Other than that, the only disadvantage is the extra build step. Subscribe the AppDomain.CurrentDomain.AssemblyResolve event and help the CLR to locate the dependency. Practical when you expose a limited number of classes or if only a few have a dependency. Best to subscribe the event in the static constructor of the class so it happens as early as possible. Be sure to do it only once. Be sure to test the Release build without a debugger, the jitter might require the dependency before any code starts running. Copy the dependencies into the Office install folder. That's where the CLR will look after it checked the GAC. If you need the bindingRedirect then the config file needs to be copied there as well, renamed to, say, Excel.exe.config to match the Office program name. Disadvantage is an admin that doesn't like you messing with that folder. And the problem of two programs doing this, the second overwriting your DLL or .config file, perhaps years after you finished your project. Not your problem, you'll get an ugly phone call anyway.
[ "superuser", "0000746768.txt" ]
Q: Show power icon in tray on desktop PC I have many power plans in my desktop PC - one is optimized for downloading (PC doesn't sleep but turns the display off), one for reading, one for games and so on. But the problem is that I have no power icon in tray (notification area), so I created a shortcut of Power Plans on my desktop, but it's really annoying. So how can I make Windows show power icon in tray? For moderators: this may seem duplicate of this and this, but they are about laptops. And their answers didn't work for this case. A: I have researched this myself for the same reason. I too had different power plans for different tasks. I found out that in windows 7 there is no real easy way to switch between powerplans and it will result in using a third party program. Laptops usually come with a power manager of the manufacturer to do the very same thing. Luckily there are a few free ones out there. But when you look into that, it is good to know that it is also possible to change the powerplan from the commandline directly. You could even create a scheduled task that changes the powerplan on certain occassions, such as, when you lock the pc and when you unlock the pc. I used this technique to go into a powersving mode everytime I lock the pc, and go out of it everytime I unlock the pc. To make one, do the following: Open a commandprompt window Type in: powercfg -l Rightclick in the window, and select mark. Use the mouse, to select the entire GUID number for the powerscheme you want to set. (It'll look like: 12345678-1234-1234-1234-1234567890abc) After the entire GUID is selected, right click. (this will copy the text to the clipboard.) Make a shortcut or task in the task schedular and give it the following program with parameters: {Guid} is that long number you copied: powercfg -setactive {Guid} You can even download a system-tray program launcher, and add these commands as programs.
[ "stackoverflow", "0037681231.txt" ]
Q: SQL Query: Remove duplicates in column that is not primary key I have a table with multiple columns, namely, Title, Url, Description and an integer Id which serves as the primary key. In the tables, there are multiple entries with the same title but different url, description and of course different Ids. What would be the SQL query to obtain the rows that have unique Titles. With rows with the same title, it doesnt matter which row is return. A: You can use a query like this: SELECT t1.Title, t1.Url, t1.Description, t1.id FROM mytable AS t1 JOIN ( SELECT MIN(id) AS min_id FROM mytable GROUP BY title ) AS t2 ON t1.id = t2.min_id This will pick the record having the minimum id for each distinct value of Title.