_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
21
37k
language
stringclasses
1 value
title
stringclasses
1 value
d18067
test
24 * (log(2) / log(10)) = 7.2247199 That's pretty representative for the problem. It makes no sense whatsoever to express the number of significant digits with an accuracy of 0.0000001 digits. You are converting numbers to text for the benefit of a human, not a machine. A human couldn't care less, and would much prefer, if you wrote 24 * (log(2) / log(10)) = 7 Trying to display 8 significant digits just generates random noise digits. With non-zero odds that 7 is already too much because floating point error accumulates in calculations. Above all, print numbers using a reasonable unit of measure. People are interested in millimeters, grams, pounds, inches, etcetera. No architect will care about the size of a window expressed more accurately than 1 mm. No window manufacturing plant will promise a window sized as accurate as that. Last but not least, you cannot ignore the accuracy of the numbers you feed into your program. Measuring the speed of an unladen European swallow down to 7 digits is not possible. It is roughly 11 meters per second, 2 digits at best. So performing calculations on that speed and printing a result that has more significant digits produces nonsensical results that promise accuracy that isn't there. A: If you have a C library that is conforming to C99 (and if your float types have a base that is a power of 2 :) the printf format character %a can print floating point values without lack of precision in hexadecimal form, and utilities as scanf and strod will be able to read them. A: If the program is meant to be read by a computer, I would do the simple trick of using char* aliasing. * *alias float* to char* *copy into an unsigned (or whatever unsigned type is sufficiently large) via char* aliasing *print the unsigned value Decoding is just reversing the process (and on most platform a direct reinterpret_cast can be used). A: In order to guarantee that a binary->decimal->binary roundtrip recovers the original binary value, IEEE 754 requires The original binary value will be preserved by converting to decimal and back again using:[10] 5 decimal digits for binary16 9 decimal digits for binary32 17 decimal digits for binary64 36 decimal digits for binary128 For other binary formats the required number of decimal digits is 1 + ceiling(p*log10(2)) where p is the number of significant bits in the binary format, e.g. 24 bits for binary32. In C, the functions you can use for these conversions are snprintf() and strtof/strtod/strtold(). Of course, in some cases even more digits can be useful (no, they are not always "noise", depending on the implementation of the decimal conversion routines such as snprintf() ). Consider e.g. printing dyadic fractions. A: The floating-point-to-decimal conversion used in Java is guaranteed to be produce the least number of decimal digits beyond the decimal point needed to distinguish the number from its neighbors (more or less). You can copy the algorithm from here: http://www.docjar.com/html/api/sun/misc/FloatingDecimal.java.html Pay attention to the FloatingDecimal(float) constructor and the toJavaFormatString() method. A: If you read these papers (see below), you'll find that there are some algorithm that print the minimum number of decimal digits such that the number can be re-interpreted unchanged (i.e. by scanf). Since there might be several such numbers, the algorithm also pick the nearest decimal fraction to the original binary fraction (I named float value). A pity that there's no such standard library in C. * *http://www.cs.indiana.edu/~burger/FP-Printing-PLDI96.pdf *http://grouper.ieee.org/groups/754/email/pdfq3pavhBfih.pdf A: You can use sprintf. I am not sure whether this answers your question exactly though, but anyways, here is the sample code #include <stdio.h> int main( void ) { float d_n = 123.45; char s_cp[13] = { '\0' }; char s_cnp[4] = { '\0' }; /* * with sprintf you need to make sure there's enough space * declared in the array */ sprintf( s_cp, "%.2f", d_n ); printf( "%s\n", s_cp ); /* * snprinft allows to control how much is read into array. * it might have portable issues if you are not using C99 */ snprintf( s_cnp, sizeof s_cnp - 1 , "%f", d_n ); printf( "%s\n", s_cnp ); getchar(); return 0; } /* output : * 123.45 * 123 */ A: With something like def f(a): b=0 while a != int(a): a*=2; b+=1 return a, b (which is Python) you should be able to get mantissa and exponent in a loss-free way. In C, this would probably be struct float_decomp { float mantissa; int exponent; } struct float_decomp decomp(float x) { struct float_decomp ret = { .mantissa = x, .exponent = 0}; while x != floor(x) { ret.mantissa *= 2; ret.exponent += 1; } return ret; } But be aware that still not all values can be represented in that way, it is just a quick shot which should give the idea, but probably needs improvement.
unknown
d18073
test
You can add a mapping for all requests with the * extension to the ASP.NET isapi dll (GET/POST) verbs. You will need to uncheck the "verify file is on disk" checkbox when mapping the extension in IIS. (In IIS7 integrated mode, you map the extension in the web.config as well). Note that this will caause everything to be served by asp.net, even images and script files, which can slow things down. Then create a handler mapping in your web.config to a http handler you create. From there, in the ProcessRequest() method of the handler, you have access to the HttpContext that spawned the request and can manipulate the URL from there. That is the easiest option, you could also create a HttpModule, or have the default page at root redirect to http://www.domain.com/default.aspx/this is my text, in the code-behind of default.aspx, you will be able to get the text following the page and slash.
unknown
d18075
test
Doubles are not objects, so referring to them as strong and weak does not make sense because they do not have reference counts. In practice, they obey the typical rules of variable scope. However, they should really not be a cause for significant memory usage, unless you are using very large arrays of them. My feeling is that something else is probably going on - probably to do with other data types present and how data is being passed between the functions.
unknown
d18077
test
This page covers the minimum recommended specification for running Couchbase Server. The minimum hardware specifications to install and effectively operate Couchbase Server are: Dual-core x86 CPU running at 2GHz. 4GB RAM (physical). It then goes on to say... The specification can be as low as 1GB of free RAM beyond operating system requirements and a single CPU core.
unknown
d18085
test
The error IndexError: index 37 is out of bounds for axis 0 with size 37 means that there is no element with index 37 in your object. In python, if you have an object like array or list, which has elements indexed numerically, if it has n elements, indexes will go from 0 to n-1 (this is the general case, with the exception of reindexing in dataframes). So, if you ahve 37 elements you can only retrieve elements from 0-36. A: This is a multi-class classifier with a huge Number of Classes (38 classes). It seems like GridSearchCV isn't spliting your dataset by stratified sampling, may be because you haven't enough data and/or your dataset isn't class-balanced. According to the documentation: For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. By using categorical_crossentropy, KerasClassifier will convert targets (a class vector (integers)) to binary class matrix using keras.utils.to_categorical. Since there are 38 classes, each target will be converted to a binary vector of dimension 38 (index from 0 to 37). I guess that in some splits, the validation set doesn't have samples from all the 38 classes, so targets are converted to vectors of dimension < 38, but since GridSearchCV is fitted with samples from all the 38 classes, it expects vectors of dimension = 38, which causes this error. A: Take a look at the shape of your y_train. It need to be a some sort of one hot with shape (,37)
unknown
d18087
test
I think you could. The language seems well suited for such situations, assuming you trust the compiler enough to use it in mission critical situation. Remember that in mission critical situations it is not only your code that is under scrutiny, but all other components too. That includes compiler (Haskell compiler is not among the easiest ones to code review), appropriate certified hardware that runs the software, appropriate hardware that compiles your code, hardware that bootstraps the compilation of the compiler that will compile your code, hell - even wires that connect that all to the power grid and frequency of voltage change in the socket. If you are interested in looking at mission critical software quality, I suggest looking at NASA software quality procedures. They are very strict and formal, but well these guys throw millions of dollars in space in hope it will survive pretty rough conditions and will make it to Mars or wherever and then autonomously operate and send some nice photos of Martians back to earth. So, there you go: Haskell is good for mission critical situations, but it'd be an expensive process to bootstrap its usage there.
unknown
d18089
test
Here's one way: $ sed 's/:/" "/g; s/.*/"&"/' example1.txt "1.2.3.4" "21" "172.16.1.2" "80" "192.168.5.4" "443" "192.168.10.1" "7007" The first s command replaces every colon with " " and the second just adds the leading and trailing double-quotes. Use the i flag if you need to save the changes to the original file. A: sed with a single s//: $ sed 's/\([^:]*\):\(.*\)/"\1" "\2"/' input.txt "1.2.3.4" "21" "172.16.1.2" "80" "192.168.5.4" "443" "192.168.10.1" "7007" A: This might work for you (GNU sed): sed 's/[^:]*/"&"/g;y/:/ /' file Surround fields delimited by :s by double quotes and replace :'s by spaces. A: Since there isn't an awk solution posted yet: $ awk -F':' -v OFS='" "' '{$1=$1; print "\"" $0 "\""}' file "1.2.3.4" "21" "172.16.1.2" "80" "192.168.5.4" "443" "192.168.10.1" "7007"
unknown
d18093
test
val MyCustomService = new MyService() with MyOtherTableName should work If you want to also inherit from the DefaultDBProvider and DefaultTableNames, you would have to either list them explicitly as well: val MyCustomService = new MyService() with MyOtherTableName with DefaultDBProvider with DefaultTableNames or create an intermediate trait in the common library: trait DefaultService extends MyService with DefaultDBProvider with DefaultTableNames A: You cannot override constructed type like that because MyService() is an object not a type anymore. So to reuse your code you might create a class like class ConfiguredMyService extends DefaultDBProvider with DefaultTableNames in the first app you can declare object MyService { def apply() = new ConfiguredMyService } and in the second val MyCustomService = new ConfiguredMyService with MyOtherTableName Note: Nowadays, Cake pattern is considered an anti-pattern, so I recommend you checkout Dependency Injection.
unknown
d18095
test
Use str_detect from stringr which is vectorized for both string and pattern library(stringr) library(dplyr) df %>% mutate(match = str_detect(b, a)) a b match 1 ABC XXC FALSE 2 ABB XCT ABB TRUE 3 ACC TTG WHO ACC TRUE 4 AAG AAG TRUE A: A base R option transform( df, match = mapply(grepl, a, b, USE.NAMES = FALSE) ) gives a b match 1 ABC XXC TTZ FALSE 2 ABB XCT ABB TRUE 3 ACC TTG WHO ACC TRUE 4 AAG AAG TRUE
unknown
d18097
test
The reason that you find these chips only in smart cards is that that is the best method of developing on them without hassle. There are also form factors for use in e.g. key fobs, which is probably what you're after. That means smaller antenna space and less chance of a good response. These chips and antenna's are tricky to get right so that all distances and orientations work well. Paper smart cards are commonly not smart cards but throw away memory cards like MiFare or MiFare ultra-light. Usually smart cards come in credit card form, like -uh- those in credit cards. And then they are in plastic (PVC) or polycarbonate for the higher end cards. Demo cards are usually plastic though. Manufacturers aren't shy of not putting any chips or antenna's in there at all when it comes to demo cards (they might be showing off their printing capabilities instead). The classic Java cards can be in any form factor. However, the more memory the larger the die may be. That can be an issue with some packaging, the small container that the IC is put in and to which the antenna's are connected. Although Java Card 3 is somewhat of a jump in functionality, most cards capable of version 2 would also be OK to run version 3 of Java Card. The failed web-based "connected" Java Card requires a lot of memory and if you can find it, it will probably be limited to specific form factors. Java Card 3.1 seems to be another jump in functionality for the common "classic" platform and I would expect for high end smart cards to lead the way. Generally we don't talk prices here. If you are interested in bulk pricing for specific form factors then you need to contact the resellers, not us. But I would first try and read into it. There are some great general purpose books out there on smart cards. That way you'd at least know a bit what you're talking about when contacting such vendor, and in that case you're more likely to be taken seriously.
unknown
d18107
test
Most RDBMS products will optimize both queries identically. In "SQL Performance Tuning" by Peter Gulutzan and Trudy Pelzer, they tested multiple brands of RDBMS and found no performance difference. I prefer to keep join conditions separate from query restriction conditions. If you're using OUTER JOIN sometimes it's necessary to put conditions in the join clause. A: I prefer the JOIN to join full tables/Views and then use the WHERE To introduce the predicate of the resulting set. It feels syntactically cleaner. A: I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time. I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times. A: Agree with 2nd most vote answer that it will make big difference when using LEFT JOIN or RIGHT JOIN. Actually, the two statements below are equivalent. So you can see that AND clause is doing a filter before JOIN while the WHERE clause is doing a filter after JOIN. SELECT * FROM dbo.Customers AS CUS LEFT JOIN dbo.Orders AS ORD ON CUS.CustomerID = ORD.CustomerID AND ORD.OrderDate >'20090515' SELECT * FROM dbo.Customers AS CUS LEFT JOIN (SELECT * FROM dbo.Orders WHERE OrderDate >'20090515') AS ORD ON CUS.CustomerID = ORD.CustomerID A: The relational algebra allows interchangeability of the predicates in the WHERE clause and the INNER JOIN, so even INNER JOIN queries with WHERE clauses can have the predicates rearrranged by the optimizer so that they may already be excluded during the JOIN process. I recommend you write the queries in the most readable way possible. Sometimes this includes making the INNER JOIN relatively "incomplete" and putting some of the criteria in the WHERE simply to make the lists of filtering criteria more easily maintainable. For example, instead of: SELECT * FROM Customers c INNER JOIN CustomerAccounts ca ON ca.CustomerID = c.CustomerID AND c.State = 'NY' INNER JOIN Accounts a ON ca.AccountID = a.AccountID AND a.Status = 1 Write: SELECT * FROM Customers c INNER JOIN CustomerAccounts ca ON ca.CustomerID = c.CustomerID INNER JOIN Accounts a ON ca.AccountID = a.AccountID WHERE c.State = 'NY' AND a.Status = 1 But it depends, of course. A: For inner joins I have not really noticed a difference (but as with all performance tuning, you need to check against your database under your conditions). However where you put the condition makes a huge difference if you are using left or right joins. For instance consider these two queries: SELECT * FROM dbo.Customers AS CUS LEFT JOIN dbo.Orders AS ORD ON CUS.CustomerID = ORD.CustomerID WHERE ORD.OrderDate >'20090515' SELECT * FROM dbo.Customers AS CUS LEFT JOIN dbo.Orders AS ORD ON CUS.CustomerID = ORD.CustomerID AND ORD.OrderDate >'20090515' The first will give you only those records that have an order dated later than May 15, 2009 thus converting the left join to an inner join. The second will give those records plus any customers with no orders. The results set is very different depending on where you put the condition. (Select * is for example purposes only, of course you should not use this in production code.) The exception to this is when you want to see only the records in one table but not the other. Then you use the where clause for the condition not the join. SELECT * FROM dbo.Customers AS CUS LEFT JOIN dbo.Orders AS ORD ON CUS.CustomerID = ORD.CustomerID WHERE ORD.OrderID is null A: WHERE will filter after the JOIN has occurred. Filter on the JOIN to prevent rows from being added during the JOIN process. A: Joins are quicker in my opinion when you have a larger table. It really isn't that much of a difference though especially if you are dealing with a rather smaller table. When I first learned about joins, i was told that conditions in joins are just like where clause conditions and that i could use them interchangeably if the where clause was specific about which table to do the condition on. A: It is better to add the condition in the Join. Performance is more important than readability. For large datasets, it matters. A: Putting the condition in the join seems "semantically wrong" to me, as that's not what JOINs are "for". But that's very qualitative. Additional problem: if you decide to switch from an inner join to, say, a right join, having the condition be inside the JOIN could lead to unexpected results.
unknown
d18109
test
Daniel - Dude there is an issue with the GCM documentation ! Use Browser key as the authorization key at the place of Server API key . It will work. A: OK, i am just shooting in the dark here. Take a look at this line: Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y"); Shouldn't it be: Request.Headers.Add(HttpRequestHeader.Authorization, "key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y"); Since you're telling it this is a Authorization header, there's no need to add 'Authorization: ' again, does it? Also, make sure the string constant 'HttpRequestHeader.Authorization' is 'Authorization'.
unknown
d18111
test
Sounds like this is a proxy issue, in order to isolate it, if possible and then host the application on the local box and then try to record it, it will work.!!
unknown
d18115
test
You can learn the meaning of OpenCL error codes by searching in cl.h. In this case, -11 is just what you'd expect, CL_BUILD_PROGRAM_FAILURE. It's certainly curious that the build log is empty. Two questions: 1.) What is the return value from clGetProgramBuildInfo? 2.) What platform are you on? If you are using Apple's OpenCL implementation, you could try setting CL_LOG_ERRORS=stdout in your environment. For example, from Terminal: $ CL_LOG_ERRORS=stdout ./myprog It's also pretty easy to set this in Xcode (Edit Scheme -> Arguments -> Environment Variables). Please find the original answer by @James A: This unhelpful error message indicates that there is bug in Apple's compiler. You can inform them of such bugs by using the Apple Bug Reporting System.
unknown
d18117
test
You are using __FUNCTION__ like a preprocessor macro, but it's a variable (please read http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html). Try printf("%s", __FUNCTION__) just for testing and it will print the function name. A: __FUNCTION__ is not standard. Use __func__. As the documentation says, it's as if: <ret-type> function_name( <args> ) { static const char __func__[] = "function-name"; ... A: In C/C++, the preprocessor will turn "my " "name " "is " "Bob" into the string literal "my name is Bob"; since __FILE__ and __LINE__ are preprocessor instructions, "We are on line " __LINE__ will pass "We are on line 27" to the compiler. __FUNCTION__ is normally a synonym for __func__. __func__ can be thought of as a pseudo-function that returns the name of the function in which it is called. This can only be done by the compiler and not by the preprocessor. Because __func__ is not evaluated by the preprocessor, you do not get automatic concatenation. So if you are using printf it must be done by printf("the function name is %s", __func__); A: Is there any way to force that replacement with a string to an earlier step so that the line is correct? No. __FUNCTION__ (and its standardized counterpart, __func__) are compiler constructs. __FILE__ and __LINE__ on the other hand, are preprocessor constructs. There is no way to make __FUNCTION__ a preprocessor construct because the preprocessor has no knowledge of the C++ language. When a source file is being preprocessed, the preprocessor has absolutely no idea about which function it is looking at because it doesn't even have a concept of functions. On the other hand, the preprocessor does know which file it is working on, and it also knows which line of the file it is looking at, so it is able to handle __FILE__ and __LINE__. This is why __func__ is defined as being equivalent to a static local variable (i.e. a compiler construct); only the compiler can provide this functionality. A: Is this what you want? #include <stdio.h> #define DBG_WHEREAMI(X) printf("%s %s(%d): %s\n",__func__,__FILE__,__LINE__,X) int main(int argc, char* argv) { DBG_WHEREAMI("Starting"); } Note: Since you marked this as C++ you should probably be using the iostreams to make sure it's type safe. A: printf("%s" __FILE__ __LINE__ "\n", __FUNCTION__); Yeah, I know that's not really the same. A: Note that if you create a class, you can build a message from any number of types as you'd like which means you have a similar effect to the << operator or the format in a printf(3C). Something like this: // make sure log remains copyable class log { public: log(const char *function, const char *filename, int line) { f_message << function << ":" << filename << ":" << line << ": "; } ~log() { //printf("%s\n", f_message.str().c_str()); -- printf?! std::cerr << f_message.str() << std::endl; } log& operator () (const char *value) { f_message << value; } log& operator () (int value) { f_message << value; } // repeat with all the types you want to support in the base class // (should be all the basic types at least) private: sstream f_message; }; // start the magic here log log_error(const char *func, const char *file, int line) { log l(func, file, line); return l; } // NOTE: No ';' at the end here! #define LOG_DEBUG log_error(__func__, __FILE__, __LINE__) // usage sample: LOG_DEBUG("found ")(count)(" items"); Note that you could declare the << operators instead of the (). In that case the resulting usage would be something like this: LOG_DEBUG << "found " << count << " items"; Depends which you prefer to use. I kind of like () because it protects your expressions automatically. i.e. if you want to output "count << 3" then you'd have to write: LOG_DEBUG << "found " << (count << 3) << " items";
unknown
d18131
test
Have you tried: $globaloptions = array( 'no-outline', 'encoding' => 'UTF-8', 'orientation' => 'Landscape', 'enable-javascript');
unknown
d18141
test
<form method="post"> <input type="text" name="numbers"/> <div><input type="submit" value="submit"></div> </form> <?php if(isset($_POST['numbers'])) { $arrayNums = explode(",", $_POST['numbers']); var_dump($arrayNums); } ?> Submitting a form will not pass a submit value in your html designed. Instead, you could check for the numbers that are posted. A: You must use $_POST[] superglobal if you are posting the form data to the server and not $_GET[].
unknown
d18143
test
Tough it isn't the most eloquent solution, you could try to create your own middleware that loads other middleware in a if/else or switch statement. That way you might be able to achieve the behaviour you'd want. Check the docs on the link below on how to program your own middleware: https://laravel.com/docs/5.3/middleware#defining-middleware
unknown
d18145
test
Not sure if this will exactly fit the bill, but check out the ASP.NET Scrollable Table Server Control Or were you asking for a slider pager control that will load more results for the user? A: For future reference, .FixedHeightContainer { float:left; height: 350px; width:100%; padding:3px; } .Content { height:224px; overflow:auto; } along with: <div class="FixedHeightContainer"> <h2>Results</h2> <div class="Content"> <asp:Table ID="Table1" runat="server" GridLines="Both" Height="350px" Width="80%"> <asp:TableHeaderRow> <asp:TableHeaderCell> </asp:TableHeaderCell> </asp:TableHeaderRow> </asp:Table> </div> </div> Is what I used to create a table with a slider Thanks for all the comments :) Nikita Silverstruk, your comment helped so much :) thanks
unknown
d18147
test
You can remove an element in javascript using var el = document.getElementById('id'); var remElement = (el.parentNode).removeChild(el); A: I'd suggest something akin to the following: function swapImageSrc(elem, nextElemId) { if (!elem) { return false; } if (!nextElemId || !document.getElementById(nextElemId)) { var id = elem.id.replace(/\d+/, ''), nextNum = parseInt(elem.id.match(/\d+/), 10) + 1, next = document.getElementById(id + nextNum).src; } else { var next = document.getElementById(nextElemId).src; } elem.src = next; } var images = document.getElementsByTagName('img'); for (var i = 0, len = images.length; i < len; i++) { images[i].onclick = function() { swapImageSrc(this,imgButton2); }; }​ JS Fiddle demo. Edited to add that, while it is possible to switch the src attribute of an image it seems needless, since both images are present in the DOM. The alternative approach is to simply hide the clicked image and show the next: function swapImageSrc(elem, nextElemId) { if (!elem) { return false; } if (!nextElemId || !document.getElementById(nextElemId)) { var id = elem.id.replace(/\d+/, ''), nextNum = parseInt(elem.id.match(/\d+/), 10) + 1, next = document.getElementById(id + nextNum); } else { var next = document.getElementById(nextElemId); } if (!next){ return false; } elem.style.display = 'none'; next.style.display = 'inline-block'; } var images = document.getElementsByTagName('img'); for (var i = 0, len = images.length; i < len; i++) { images[i].onclick = function() { swapImageSrc(this,imgButton2); }; }​ JS Fiddle demo. Edited to offer an alternate approach, which moves the next element to the same location as the clicked image element: function swapImageSrc(elem, nextElemId) { if (!elem) { return false; } if (!nextElemId || !document.getElementById(nextElemId)) { var id = elem.id.replace(/\d+/, ''), nextNum = parseInt(elem.id.match(/\d+/), 10) + 1, next = document.getElementById(id + nextNum); } else { var next = document.getElementById(nextElemId); } if (!next){ return false; } elem.parentNode.insertBefore(next,elem.nextSibling); elem.style.display = 'none'; next.style.display = 'inline-block'; } var images = document.getElementsByTagName('img'); for (var i = 0, len = images.length; i < len; i++) { images[i].onclick = function() { swapImageSrc(this,imgButton2); }; }​ JS Fiddle demo. A: You can hide the first button, not only change the image source. The code below shows one way of doing that. <img src="images/14.gif" id="ImageButton1" onClick="swapButtons(false)" style="visibility: visible;" /> <img src="images/getld.png" id="ImageButton2" alt="Get Last Digits" style="visibility: hidden;" onClick="swapButtons(true)" /> <script type="text/javascript" language="javascript"> function swapButtons(show1) { document.getElementById('ImageButton1').style.visibility = show1 ? 'visible' : 'hidden'; document.getElementById('ImageButton2').style.visibility = show1 ? 'hidden' : 'visible'; } </script>
unknown
d18157
test
(I hope I've understood your question correctly.) The relations in your database are always defined in database types, probably either an int or a uniqueidentifer in the case of foreign key columns. The database should know nothing of the data transfer objects NHibernate returns to your application code. When you map the foreign key columns in your data transfer objects using ManyToOne, etc., you specify the type of the object because NHibernate knows that the relation is always going to be between the foreign key column you specify in the attribute, and the Id (primary key) of the object type to be returned. This saves you the trouble of doing extra queries to return parent or child entities -- NHibernate just does a JOIN for you automatically and returns the relational information as an object hierarchy, instead of just a set of id values.
unknown
d18159
test
import re text = """System Id Interface Circuit Id State HoldTime Type PRI -------------------------------------------------------------------------------- rtr1.lab01.some GE0/0/1 0000000001 Up 22s L2 -- thing rtr2.lab01.some GE0/0/2 0000000002 Up 24s L2 -- thingelse rtr2.lab01.abcd GE0/0/4 0000000003 Up 24s L2 -- rtr2.lab01.none GE0/0/24 0000000004 Up 24s L2 -- sense rtr2.lab01.efgh GE0/0/5 0000000003 Up 24s L2 -- """ lines = text.rstrip().split('\n')[2:] n_lines = len(lines) current_line = -1 def get_next_line(): # Actual implementation would be reading from a file and yielding lines one line at a time global n_lines, current_line, lines current_line += 1 # return special sentinel if "end of file" return lines[current_line] if current_line < n_lines else '$' def get_system_id(): line = None while line != '$': # loop until end of file if line is None: # no current line line = get_next_line() if line == '$': # end of file return m = re.search(r'^([a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9])', line) id = m[1] line = get_next_line() # might be sentinel if line != '$' and re.match(r'^[a-zA-Z0-9]+$', line): # next line just single id? id += line line = None # will need new line yield id for id in get_system_id(): print(id) Prints: rtr1.lab01.something rtr2.lab01.somethingelse rtr2.lab01.abcd rtr2.lab01.nonesense rtr2.lab01.efgh See Python Demo
unknown
d18165
test
I don't think there is a more idiomatic way than using cond directly, binding "string argument" to a symbol and passing it to each predicate. Everything else looks confusing to people reading your code and involves extra function calls. Extra magic could be achieved with the following helper macro: (defmacro pcond "Translates clauses [pred result-expr] to a cond form: (cond (pred expr) result-expr ...) A single result-expr can follow the clauses, and it will be appended to the cond form under a generated test expression that returns logical true." [expr & clauses] (let [expr-sym (gensym "expr") else-kw (keyword (gensym "else")) step (fn [[pred-form clause-form]] (if (= else-kw clause-form) [else-kw pred-form] [(list pred-form expr-sym) clause-form])) body (->> clauses (partition 2 2 [else-kw]) (mapcat step))] `(let [~expr-sym ~expr] (cond ~@body)))) You can use it so (pcond "String argument" predicate1 "Result1" predicate2 "Result2" "Else") It macroexpands directly to cond: (clojure.core/let [expr13755 "String argument"] (clojure.core/cond (predicate1 expr13755) "Result1" (predicate2 expr13755) "Result2" :else13756 "Else")) A: You can use the anonymous function #(%1 %2) for what you are trying to do. IMO it's better than wrapping the condp expression in a vector, but either way works, neither is really straigthforward. (condp #(%1 %2) "string argument" string? "string" map? "map" vector? "vector" "something else") ;= Result1 EDIT (copied from the comments) I'm no expert on macros, but what I've heard over and over is that you shouldn't write a macro if a function will do and condp provides all the elements to use the power of Clojure functions. An approach that doesn't involve macros and improves readability could be defining a function (def apply-pred #(%1 %2)) and use it with condp.
unknown
d18167
test
There is a simple way to do that if you're using numpy: variance = tensors.var(axis=3)
unknown
d18171
test
The problem lies in that line because you are returning return ( {authenticated ? (...) : (...)}); Which means, that you're trying to return an object, and that's not what you actually want. So you should change it to this: return authenticated ? ( <Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions} trigger="click"> <Avatar src={require("assets/images/w-logo.png")} className="gx-avatar gx-pointer" alt="" /> </Popover> ) : ( <Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions} trigger="click"> <Avatar src={require("assets/images/w-logo.png")} className="gx-avatar gx-pointer" alt="" /> </Popover> );
unknown
d18175
test
Do something like this: @published_events = Event.select("events.*, dates.date AS date_of_event") .joins(:dates) # you join dates table to sort the events by date .where(:published => true) # here you take only published events .order("dates.date ASC") # here you order them In your views you'll do something like @published_events.each do |event| <p><%= event.id %></p> <p><%= event.name %></p> <p><%= event.date_of_event %></p> end Caution -> You did not specify the exact name of your columns so I'm guessing that you event has a name, or your dates table has a column call date. I hope this is useful! Edit: If you want to group them by date, after you retrieve them from the database (this is very important ), you could indeed use group_by ( group by is located in Enumerable/group_by ) like this @published_events.all.group_by(&:date_of_event) If you do like this you will end up with a hash where every key is a date, and the coresponding value for that key is an array of events
unknown
d18181
test
I would set up a parsing function that reacts to every change in any of the form elements, and "compiles" the string containing the bits of information. You could set this function to the "onchange" event of each element. How the parsing function will have to look like is really up to what you want to achieve. It could be something like this: (intentionally leaving out framework specific functions) function parse_form() { var age_string = "Your computer is" var age = document.getElementById("age").value; if (age == 1) age_string+= "one year old"; if (age > 1) age_string+= "more than one year old"; ... and so on. } A: A regular jQuery click listener will do. Making some assumptions about your HTML code (that you're using radio input buttons with label tags whose for attributes correspond to the IDs of the radio buttons): $("#options input").click(function(){ var optionID= $(this).attr(id); var outputText= $("label[for="+optionID+"]"); $("#output").text(outputText); }); This code will accomplish pretty much exactly what you want. If you want separate DIVs for each particular output message, just create divs each with class output with let's say a rel attribute corresponding to the ID of the input button, then: $("#options input").click(function(){ var optionID= $(this).attr(id); $("div.output[rel!="+optionID+"]").slideUp(function(){ var outputDiv= $("div[rel="+optionID+"]"); }); }); This code can be improved by better handling situations in which an already selected option is reclicked (try it... weird things may happen), or if clicks occur very quickly. Alternately, you can just use the regular onclick attribute for the input radio buttons if you just want to stick to native Javascript. If you're interested in the appropriate code for that, post a comment, and someone will surely be able to help you out. A: Here is an example with jQuery that will fit your needs. // no tricks here this function will run as soon as the document is ready. $(document).ready(function() { // select all three check boxes and subscribe to the click event. $("input[name=ComputerAge]").click(function(event) { var display = $("#ComputerAgeTextDisplay"); // # means the ID of the element switch (parseInt(this.value)) // 'this' is the checkbox they clicked. { case 1: display.html("Your computer is one year old."); break; case 2: display.html("Your computer is two years old."); break; case 3: display.html("Your computer is three years old."); break; default: display.html("Please select the age of your computer."); break; } }); }); A: <span id='#options'> Options: <input type='radio' name='options' value='one'>One Year</input> <input type='radio' name='options' value='two'>Two Years</input> <input type='radio' name='options' value='three'>Three Years</input> </span> Output: "<span id='#output'></span>" ... var labels = { one: "Your computer is One Year Old", two: "Your computer is Two Years Old", three: "Your computer is Three Years Old" }; $('#options :radio').click(function() { $('#output).html(labels[$(this).val()]); }); A: You'd need a way to associate each checkbox with the information you wanted to show. You could for example combine the name and value to get an ID to show, assuming the values are characters that are valid in an ID: <input type="radio" name="age" value="1" /> One year <input type="radio" name="age" value="2" /> Two years <input type="radio" name="age" value="3" /> Three years <div id="age-1"> Your computer is awesome!! </div> <div id="age-2"> Your computer is so-so </div> <div id="age-3"> Your computer sucks </div> Now you just need a bit of script to tie them together: function showElementsForInputs(inputs) { // Set the visibility of each element according to whether the corresponding // input is checked or not // function update() { for (var i= inputs.length; i-->0;) { var input= inputs[i]; var element= document.getElementById(inputs[i].name+'-'+inputs[i].value); element.style.display= input.checked? 'block' : 'none'; } } // Set the visibility at the beginning and also when any of the inputs are // clicked. (nb. use onclick not onchanged for better responsiveness in IE) // for (var i= inputs.length; i-->0;) inputs[i].onclick= update; update(); } showElementsForInputs(document.getElementById('formid').elements.age);
unknown
d18183
test
Is "dateString" supposed to be "dateCreated"? This code works: var dateCreated = new Date('2015-01-20'); var dd = dateCreated.getDate(); var mm = dateCreated.getMonth()+1; var yyyy = dateCreated.getFullYear(); if(dd<10) { dd='0'+dd } if(mm<10) { mm='0'+mm } dateCreated = yyyy + '-' + mm+'-'+dd; ; console.log(dateCreated, typeof(dateCreated)); 2015-01-20 string
unknown
d18185
test
This is what worked for me in the past. I'm not exactly sure of why it works and your solution doesn't, but I think it has something to do with not specifying the collection or the file in a certain way. mongoimport -u client -h production-db-b2.meteor.io:27017 -d myapp_meteor_com -p passwordthatexpiresreallyfast /pathtofile A: check your port. the local meteor mongodb uses 3001 not 27017... i'm using the following line successfully mongoimport --host localhost:3001 -d meteor -c TestCollection --type csv --file /home/ubuntu/meteorMongoImportTest/results1.txt --headerline
unknown
d18187
test
When you initialize the scroll on load make sure you have stored it in a variable called ias. Something like this var ias = jQuery.ias({ container: "#posts", item: ".post", pagination: "#pagination", next: ".next a" }); And in success method call just the ias.destroy(); and ias.bind(); methods as you have done before. Remove the initialization that is done again in your code i.e jQuery.ias({ container: "#posts", item: ".post", pagination: "#pagination", next: ".next a" });
unknown
d18189
test
Try following the instructions given in this link: http://jimneath.org/2011/10/19/ruby-ssl-certificate-verify-failed.html And you have to make this minor change in fix_ssl.rb at the end: self.ca_file = Rails.root.join('lib/ca-bundle.crt').to_s I hope this helps.
unknown
d18191
test
invalidate() just forces a repaint, it doesn't redo the whole layout, as you noticed. You can force a relayout by going up to the parent Screen object, and calling invalidateLayout(). Forcing the layout will almost certainly call setPositionChild() on the field you are trying to move, so you will want to make sure the new field position is preserved by the manager layout code. This may mean you need to write a custom manager.
unknown
d18195
test
The format you show you want cannot use smalldatetime because that is not the format of the data type you selected on your destination table. The destination date format would be like 2016-03-07 09:27:00, but if you want it as 2016-03-07-09-27:01 then you will have to store that as a string in your table. As well the input value is returning a NULL because SSIS cannot convert that format into a date. You would have to use an expression or Script Task of some sort in order to parse that value out to the end format you want it, before sending it to your destination.
unknown
d18197
test
You can use rhc app-tidy <yorApp> to delete the logs and contents of the /tmp directory on the gears (this is used primarily in order to free up some disk space). You can also ssh into your app rhc ssh <yourApp> and check individual logs in ~/app-root/logs/, which may bring some clarity if you are reading only the log that interests you. A: Configure logs To set * *maximum file size *maximum number of files The maximum file size and maximum number of files can be configured with the LOGSHIFTER__MAX_FILESIZE and LOGSHIFTER__MAX_FILES environment variables. $ rhc env set LOGSHIFTER_PHP_MAX_FILESIZE=5M LOGSHIFTER_PHP_MAX_FILES=5 -a myapp Setting environment variable(s) ... done $ rhc app stop RESULT: myapp stopped $ rhc app start RESULT: myapp started The exact variable names depend on the type of cartridge; the value of is DIY, JBOSSAS, JBOSSEAP, JBOSSEWS, JENKINS, MONGODB, MYSQL, NODEJS, PERL, PHP, POSTGRESQL, PYTHON, or RUBY as appropriate. copied from: https://developers.openshift.com/managing-your-applications/log-files.html https://developers.openshift.com/managing-your-applications/environment-variables.html
unknown
d18201
test
The question basically drill downs to when should I make a method static. The answer is simple- when your method has a very specific task and does not change the state of the object. Something like a utility method, say add(int a, int b) which simply returns a+b. If I need to store the value a+b for later use for the object, static method is strictly no-no (you will not be able to store a non static variable in a static method). But if we are dealing with some action which is independent of state of the object, static is the answer. Why are we giving preference to static if it is independent of state of object? * *Memory- static method will only have one copy, irrespective of the actual number of object. *Availability- Method is available even if you don't have single object Ofcourse the downside is that we are keeping a copy of method even if we do not use it at all (if it was non-static and no object was created, we would have saved this space). But this is of lower weight than the advantages mentioned above. As the method we are discussing here (makeText), does not need to maintain a state for later use, the best way to go is static method. --Edit-- The answer mentioned above is more generic as to when we should use static and when non-static, let me get specific to Toast class. Toast class gives us 2 ways to create a Toast object (Refer http://developer.android.com/reference/android/widget/Toast.html) * *makeText(Context context, CharSequence text, int duration) which returns a Toast object which the values assigned. *Normal way, use new Toast(context) to create an object, then set values as required. If you use method 1, you are saying something like Toast.makeText(context, text, duration).show(); and we are done. I use this method all the time. Method 2 is used only for a specific case, from http://developer.android.com/guide/topics/ui/notifiers/toasts.html Do not use the public constructor for a Toast unless you are going to define the layout with setView(View). If you do not have a custom layout to use, you must use makeText(Context, int, int) to create the Toast. @CFlex, If I got your question properly, I guess you just want to know why we have Toast.makeText(context, text, duration) returning a Toast object, when the same thing could have been done by a constructor. Whenever I look at something like ClassName.getObject returning object of class, I think about singleton pattern. Well, in this case we are not exactly talking about singleton, I would like to assume that makeText returns same object always (to save creation of N objects), otherwise it is just a fancy thing developed by Android team. A: One rule: Ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static. Remember that objects live in memory and they are created for certain jobs. Static methods are available for all the objects in a class and it is not necessary to create an object to use them. So there is no reason to create an object Toast to be able to access the method makeText, when you can access it as a static method (more elegant and compact) A: As far as I know: That's because we don't wish to hold an instance of the object toast, which would require an amount of memory persistently used until cleaned by the GarbageCollector. And that it always have access to being displayed, so it is not required by your application to have any set of permissions.
unknown
d18203
test
With your current code, you are trying to filter patterns with patterns. Using the WHERE Clause with variables would be the best approach. Match the pattern first and then filter on the desired property. You could use the following Query to match users based on their postcode: MATCH (p:Person)-[:HasPostcode]->(pc:Postcode) WHERE pc.value='LA2 0RN' RETURN p, pc If you want to use an OR condition and find matches for Postcode or Name: MATCH (f)<-[:HAS_FIRST_NAME]-(p:Person)-[:HasPostcode]->(pc) WHERE pc.value='LA2 0RN' OR f.value='Jerry' OR f.value='Tom' RETURN f, p, pc
unknown
d18209
test
Try with: $i = 0; // init $i $x = 'icon'.($i+1); If you want to regularly increment $i variable: $x = 'icon'.(++$i); A: try this : $temp = $i+1; $x = 'icon'.$temp; You are getting wrong answer because of "Operator Precedence", Ref this link : http://php.net/manual/en/language.operators.precedence.php Here see the line : left + - . arithmetic and string . has more Precedence than +, So your expression will be like : $x = ('icon'.$i)+1; To solve it either use the method i mentioned above or hsz answer ie : $x = 'icon'.($i+1); A: Operator Precedence explains why this is happening. You can use brackets: $x = 'icon'.($i+1); This should do the job. My test: $i = 18; $x = 'icon'.($i+1); var_dump($x); --> string(6) "icon19"
unknown
d18213
test
One way is to read a well known site content with URL connection. If you can read it, then it means you have an Internet connection. Other is to connect to your radio station site: this has double requirement: you have Internet connection AND the radio station site is up. Maybe both of them will block you, if you read too often! There is android buggy API to read the network state and suck, but if you connect to WIFI , then you will have the Connected state from API even if your WAN cable pulled out...
unknown
d18217
test
Agree this is a bug, which I see you've submitted. A temporary workaround is to specify the filename option: devtools::source_gist("524eade46135f6348140", filename = "ggplot_smooth_func.R")
unknown
d18219
test
Mark your superclass as abstract, because it clearly is supposed to be.
unknown
d18221
test
So, in that case does it make sense to have multiple methods with different signatures, or is that not a factory pattern at all? It doesn't make any sense to have a factory with specific methods. If your client code has to decide which specific method should it use, why wouldn't it call the specific car's constructor directly? In your example, factory methods would merely be wrappers over specific constructors. On the other hand having a single factory method that is called with an enum gives your client a chance to decide dynamically which car should it create, the decision could for example be based on a database query. There are some possible ways around your current approach. One option would be to have a hierarchy of classes that represent constructor parameters. You don't even need the enum then because the parameter type is enough to infer which specific car should be created: public abstract class CarCreationParams { } public class FordCreationParams : CarCreationParams { public Engine engine; } ... public class CarFactory { public Car GetCar( CarCreationParams parms ) { if ( parms is FordCreationParams ) return new Ford( ((FordCreationParams)parms).engine ); ... Another option would be to think whether you really need your Fords to be created with external engines (aggregation) or rather they own their engines (composition). In the latter case, you would expose parameterless constructors to your specific car types: public class Ford : Car { public Engine engine; // car is composed of multiple parts, including the engine public Ford() { this.engine = new FordEngine(); } which makes the implementation of the factory much easier. A: No that is not a good example of factor pattern. Rather if your Car class is dependent on different types of Components you can have factories for those too. E.G For Car and Engine you can have like: public interface ICar { IEngine Engine { get; set; } } public class Mustang : ICar { private IEngine _engine = EngineFactory.GetEngine(EngineType.Mustang); public IEngine Engine { get { return _engine; } set { _engine = value; } } } public class CarFactory { public ICar GetCar(CarType carType) { switch (carType) { case CarType.Ford: return new Mustang(); } } } Similarly for Engine public interface IEngine { } public class MustangEngine : IEngine { } public class EngineFactory { public static IEngine GetEngine(EngineType engine) { switch (engine) { case EngineType.Mustang: return new MustangEngine(); } } } A: In case you need different parameters for object creation(batteries for Tesla or Engine for Ford) you can choose between different solutions: - pass all of these parameters while creating a factory - it will be specific factory for all types of car with such available details; class SpecificCarFactory { public SpecificCarFactory(IList<Battery> batteries, IList<Engine> engines) { //save batteries etc into local properties } public Car GetCar(CarType carType) { switch(carType) { case CarType.Ford: return new Mustang(_engines.First()); } } } * *encapsulate parameters into class object and get them from factory method parameter; class CarFactory { public Car GetCar(CarDetail carDetail) //where CarDetails encapsulates all the possible car details { switch(carDetail.type) { case CarType.Ford: return new Mustang(carDetail.Engine);//just an example } } } A: Yes, It is factory pattern. factory pattern says to create factories of Object but let subclass decide the way to instantiate the object . This is true in your case your deciding based on type of Enum
unknown
d18223
test
Set the primarykey after you load from the database. I don't think dataadapters set the primarykey.
unknown
d18225
test
Sub SearchReport() Dim p As Integer p = 25 Report FileSystem.getFolder(HostFolder), p End Sub
unknown
d18231
test
str.replace(/(?<=\d),(?=\d)/g, '') (?<=\d): lookbehind - a digit (?=\d) : lookahead - a digit
unknown
d18235
test
Note that jstatd in CentOS 7 is now part of the package java-1.8.0-openjdk-devel. To install it: yum install java-1.8.0-openjdk-devel
unknown
d18237
test
If you need any price information you could use chainlink oracle. Here is official docs for evm data feeds; https://docs.chain.link/docs/using-chainlink-reference-contracts/ . For a simple implementation example you can take a look at freeCodeCamp.org 's 32-hour course/lesson4 on youtube. Also you can take a look at uniswap API ; https://docs.uniswap.org/protocol/V2/reference/API/entities A: If you want it to be compatible across multiple chains and multiple DEXs, the easiest way I could think of is to call the router by using the method getAmountsOut. router.methods.getAmountsOut(amountIn, [inAddress, outAddress]).call() amountIn would be 1 * Math.pow(10, inAddress token decimals) inAddress is WBTC address outAddress is USDC address The output will be: 100000000,22397189858 Output[0] is amount in. Output[1] is amount out. You then have to divide that by (1 * Math.pow(10, out address decimal), where you will get WBTCprice: 22397.189858 The only caveat of doing this method is that you need to know the stable pair that exist on that dex. Some dex may use WBTC/USDT, some may use WBTC/USDC.
unknown
d18239
test
Here's an answer addressing iterkeys vs. viewkeys here: https://stackoverflow.com/a/10190228/344143 Summary (with a little backstory): view* methods are a live view into the data (that will update as it updates), whereas iter* and just-plain * are more like snapshots. The linked answerer suggests that while the view*-flavored methods may have a minor performance edge as well, there may be compatibility issues with the backport, and recommends continuing to use iter*/* under Python 2. My take: if you want a live view and you're under Python 2, use view*; if you just want to whip through the set of keys/values/items once, use iter*; if you want to hang on to a snapshot of k/v/i for a bit (or iterate in some non-linear fashion), use *. Let the performance slide until you pick it up in an inner loop.
unknown
d18241
test
I just briefly looked at the Github project you referenced, and I wanted to throw in my $0.02, for whatever it's worth - Breeze.js is responsible for taking care of client side caching for you. The idea is to not have to worry about what the back-end is doing and simply make a logical decision on the client on whether to proceed and hit the server for data again. If you don't need to refresh the data, then never hit the server, just return from Breeze's cache. The project you are referencing seems to do both - server side and client-side caching. The decision of caching on the server is one not to be taken lightly, but this project seems to handle it pretty well. The problem is that you are trying to mix two libraries which, at best, conflict in the area of what their concerns are. There may be a way to marry the two up, but at what cost? Why would you need to cache on the server that which is already cached on the client? Why cache on the client if you plan to cache the exact same data on the server? The only reason I can think of is for paging of data (looking at a subset of the whole) and wanting to see the next data set without having to hit the server again. In that case, your query to the server should not match the original anyway and therefore one would expect that you need to customize the two solutions to do what you are asking for. In general that project seems to ignore queryString parameters, from what I can tell, to support JSONP so you should have no problem coming up with a custom solution, if you still think that is necessary.
unknown
d18245
test
This might be the complete solution as you are looking for. This code is from the udacity computer science course (CS101) It uses simulated webpages using method get_page(url): Run in your computer once and read the code It also try to remove duplicate urls def get_page(url): # This is a simulated get_page procedure so that you can test your # code on two pages "http://xkcd.com/353" and "http://xkcd.com/554". # A procedure which actually grabs a page from the web will be # introduced in unit 4. try: if url == "http://xkcd.com/353": return '<?xml version="1.0" encoding="utf-8" ?><?xml-stylesheet href="http://imgs.xkcd.com/s/c40a9f8.css" type="text/css" media="screen" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>xkcd: Python</title> <link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/c40a9f8.css" media="screen" title="Default" /> <!--[if IE]><link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/ecbbecc.css" media="screen" title="Default" /><![endif]--> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/atom.xml" /> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/rss.xml" /> <link rel="icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> <link rel="shortcut icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> </head> <body> <div id="container"> <div id="topContainer"> <div id="topLeft" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s">\t<ul> <li><a href="http://xkcd.com/554"">Archive</a><br /></li>\t <li><a href="http://blag.xkcd.com/">News/Blag</a><br /></li> <li><a href="http://store.xkcd.com/">Store</a><br /></li> <li><a href="/about/">About</a><br /></li> <li><a href="http://forums.xkcd.com/">Forums</a><br /></li> </ul> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="topRight" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <div id="topRightContainer"> <div id="logo"> <a href="/"><img src="http://imgs.xkcd.com/s/9be30a7.png" alt="xkcd.com logo" height="83" width="185"/></a> <h2><br />A webcomic of romance,<br/> sarcasm, math, and language.</h2> <div class="clearleft"></div> <br />XKCD updates every Monday, Wednesday, and Friday. </div> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> <div id="contentContainer"> <div id="middleContent" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"><h1>Python</h1><br/><br /><div class="menuCont"> <ul> <li><a href="/1/">|&lt;</a></li> <li><a href="/352/" accesskey="p">&lt; Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_t">Random</a></li> <li><a href="/354/" accesskey="n">Next &gt;</a></li> <li><a href="/">&gt;|</a></li> </ul></div><br/><br/><img src="http://imgs.xkcd.com/comics/python.png" title="I wrote 20 short programs in Python yesterday. It was wonderful. Perl, Im leaving you." alt="Python" /><br/><br/><div class="menuCont"> <ul> <li><a href="/1/">|&lt;</a></li> <li><a href="/352/" accesskey="p">&lt; Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_b">Random</a></li> <li><a href="/354/" accesskey="n">Next &gt;</a></li> <li><a href="/">&gt;|</a></li> </ul></div><h3>Permanent link to this comic: http://xkcd.com/353/</h3><h3>Image URL (for hotlinking/embedding): http://imgs.xkcd.com/comics/python.png</h3><div id="transcript" style="display: none">[[ Guy 1 is talking to Guy 2, who is floating in the sky ]]Guy 1: You39;re flying! How?Guy 2: Python!Guy 2: I learned it last night! Everything is so simple!Guy 2: Hello world is just 39;print &quot;Hello, World!&quot; 39;Guy 1: I dunno... Dynamic typing? Whitespace?Guy 2: Come join us! Programming is fun again! It39;s a whole new world up here!Guy 1: But how are you flying?Guy 2: I just typed 39;import antigravity39;Guy 1: That39;s it?Guy 2: ...I also sampled everything in the medicine cabinet for comparison.Guy 2: But i think this is the python.{{ I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I39;m leaving you. }}</div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="middleFooter" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <img src="http://imgs.xkcd.com/s/a899e84.jpg" width="520" height="100" alt="Selected Comics" usemap=" comicmap" /> <map name="comicmap"> <area shape="rect" coords="0,0,100,100" href="/150/" alt="Grownups" /> <area shape="rect" coords="104,0,204,100" href="/730/" alt="Circuit Diagram" /> <area shape="rect" coords="208,0,308,100" href="/162/" alt="Angular Momentum" /> <area shape="rect" coords="312,0,412,100" href="/688/" alt="Self-Description" /> <area shape="rect" coords="416,0,520,100" href="/556/" alt="Alternative Energy Revolution" /> </map><br/><br />Search comic titles and transcripts:<br /><script type="text/javascript" src="//www.google.com/jsapi"></script><script type="text/javascript"> google.load(\"search\", \"1\"); google.setOnLoadCallback(function() { google.search.CustomSearchControl.attachAutoCompletion( \"012652707207066138651:zudjtuwe28q\", document.getElementById(\"q\"), \"cse-search-box\"); });</script><form action="//www.google.com/cse" id="cse-search-box"> <div> <input type="hidden" name="cx" value="012652707207066138651:zudjtuwe28q" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" id="q" autocomplete="off" size="31" /> <input type="submit" name="sa" value="Search" /> </div></form><script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&lang=en"></script><a href="/rss.xml">RSS Feed</a> - <a href="/atom.xml">Atom Feed</a><br /> <br/> <div id="comicLinks"> Comics I enjoy:<br/> <a href="http://www.qwantz.com">Dinosaur Comics</a>, <a href="http://www.asofterworld.com">A Softer World</a>, <a href="http://pbfcomics.com/">Perry Bible Fellowship</a>, <a href="http://www.boltcity.com/copper/">Copper</a>, <a href="http://questionablecontent.net/">Questionable Content</a>, <a href="http://achewood.com/">Achewood</a>, <a href="http://wondermark.com/">Wondermark</a>, <a href="http://thisisindexed.com/">Indexed</a>, <a href="http://www.buttercupfestival.com/buttercupfestival.htm">Buttercup Festival</a> </div> <br/> Warning: this comic occasionally contains strong language (which may be unsuitable for children), unusual humor (which may be unsuitable for adults), and advanced mathematics (which may be unsuitable for liberal-arts majors).<br/> <br/> <h4>We did not invent the algorithm. The algorithm consistently finds Jesus. The algorithm killed Jeeves. <br />The algorithm is banned in China. The algorithm is from Jersey. The algorithm constantly finds Jesus.<br />This is not the algorithm. This is close.</h4><br/> <div class="line"></div> <br/> <div id="licenseText"> <!-- <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/"><img alt="Creative Commons License" style="border:none" src="http://imgs.xkcd.com/static/somerights20.png" /></a><br/> --> This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/">Creative Commons Attribution-NonCommercial 2.5 License</a>.<!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns "><Work rdf:about=""><dc:creator>Randall Munroe</dc:creator><dcterms:rightsHolder>Randall Munroe</dcterms:rightsHolder><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:source rdf:resource="http://www.xkcd.com/"/><license rdf:resource="http://creativecommons.org/licenses/by-nc/2.5/" /></Work><License rdf:about="http://creativecommons.org/licenses/by-nc/2.5/"><permits rdf:resource="http://web.resource.org/cc/Reproduction" /><permits rdf:resource="http://web.resource.org/cc/Distribution" /><requires rdf:resource="http://web.resource.org/cc/Notice" /><requires rdf:resource="http://web.resource.org/cc/Attribution" /><prohibits rdf:resource="http://web.resource.org/cc/CommercialUse" /><permits rdf:resource="http://web.resource.org/cc/DerivativeWorks" /></License></rdf:RDF> --> <br/> This means you\"re free to copy and share these comics (but not to sell them). <a href="/license.html">More details</a>.<br/> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> </div> </body></html> ' elif url == "http://xkcd.com/554": return '<?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet href="http://imgs.xkcd.com/s/c40a9f8.css" type="text/css" media="screen" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>xkcd: Not Enough Work</title> <link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/c40a9f8.css" media="screen" title="Default" /> <!--[if IE]><link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/ecbbecc.css" media="screen" title="Default" /><![endif]--> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/atom.xml" /> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/rss.xml" /> <link rel="icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> <link rel="shortcut icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> </head> <body> <div id="container"> <div id="topContainer"> <div id="topLeft" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <ul> <li><a href="/archive/">Archive</a><br /></li> <li><a href="http://blag.xkcd.com/">News/Blag</a><br /></li> <li><a href="http://store.xkcd.com/">Store</a><br /></li> <li><a href="/about/">About</a><br /></li> <li><a href="http://forums.xkcd.com/">Forums</a><br /></li> </ul> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="topRight" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <div id="topRightContainer"> <div id="logo"> <a href="/"><img src="http://imgs.xkcd.com/s/9be30a7.png" alt="xkcd.com logo" height="83" width="185"/></a> <h2><br />A webcomic of romance,<br/> sarcasm, math, and language.</h2> <div class="clearleft"></div> XKCD updates every Monday, Wednesday, and Friday. <br /> Blag: Remember geohashing? <a href="http://blog.xkcd.com/2012/02/27/geohashing-2/">Something pretty cool</a> happened Sunday. </div> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> <div id="contentContainer"> <div id="middleContent" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <h1>Not Enough Work</h1><br/> <br /> <div class="menuCont"> <ul> <li><a href="/1/">|&lt;</a></li> <li><a href="/553/" accesskey="p">&lt; Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_t">Random</a></li> <li><a href="/555/" accesskey="n">Next &gt;</a></li> <li><a href="/">&gt;|</a></li> </ul> </div> <br/> <br/> <img src="http://imgs.xkcd.com/comics/not_enough_work.png" title="It39;s even harder if you39;re an asshole who pronounces &lt;&gt; brackets." alt="Not Enough Work" /><br/> <br/> <div class="menuCont"> <ul> <li><a href="/1/">|&lt;</a></li> <li><a href="/553/" accesskey="p">&lt; Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_b">Random</a></li> <li><a href="/555/" accesskey="n">Next &gt;</a></li> <li><a href="/">&gt;|</a></li> </ul> </div> <h3>Permanent link to this comic: http://xkcd.com/554/</h3> <h3>Image URL (for hotlinking/embedding): http://imgs.xkcd.com/comics/not_enough_work.png</h3> <div id="transcript" style="display: none">Narration: Signs your coders don39;t have enough work to do: [[A man sitting at his workstation; a female co-worker behind him]] Man: I39;m almost up to my old typing speed in dvorak [[Two men standing by a server rack]] Man 1: Our servers now support gopher. Man 1: Just in case. [[A woman standing near her workstation speaking to a male co-worker]] Woman: Our pages are now HTML, XHTML-STRICT, and haiku-compliant Man: Haiku? Woman: &lt;div class=&quot;main&quot;&gt; Woman: &lt;span id=&quot;marquee&quot;&gt; Woman: Blog!&lt; span&gt;&lt; div&gt; [[A woman sitting at her workstation]] Woman: Hey! Have you guys seen this webcomic? {{title text: It39;s even harder if you39;re an asshole who pronounces &lt;&gt; brackets.}}</div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="middleFooter" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <img src="http://imgs.xkcd.com/s/a899e84.jpg" width="520" height="100" alt="Selected Comics" usemap=" comicmap" /> <map name="comicmap"> <area shape="rect" coords="0,0,100,100" href="/150/" alt="Grownups" /> <area shape="rect" coords="104,0,204,100" href="/730/" alt="Circuit Diagram" /> <area shape="rect" coords="208,0,308,100" href="/162/" alt="Angular Momentum" /> <area shape="rect" coords="312,0,412,100" href="/688/" alt="Self-Description" /> <area shape="rect" coords="416,0,520,100" href="/556/" alt="Alternative Energy Revolution" /> </map><br/><br /> Search comic titles and transcripts:<br /> <script type="text/javascript" src="//www.google.com/jsapi"></script> <script type="text/javascript"> google.load("search", "1"); google.search.CustomSearchControl.attachAutoCompletion( "012652707207066138651:zudjtuwe28q", document.getElementById("q"), "cse-search-box"); }); </script> <form action="//www.google.com/cse" id="cse-search-box"> <div> <input type="hidden" name="cx" value="012652707207066138651:zudjtuwe28q" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" id="q" autocomplete="off" size="31" /> <input type="submit" name="sa" value="Search" /> </div> </form> <script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&lang=en"></script> <a href="/rss.xml">RSS Feed</a> - <a href="/atom.xml">Atom Feed</a> <br /> <br/> <div id="comicLinks"> Comics I enjoy:<br/> <a href="http://threewordphrase.com/">Three Word Phrase</a>, <a href="http://oglaf.com/">Oglaf</a> (nsfw), <a href="http://www.smbc-comics.com/">SMBC</a>, <a href="http://www.qwantz.com">Dinosaur Comics</a>, <a href="http://www.asofterworld.com">A Softer World</a>, <a href="http://buttersafe.com/">Buttersafe</a>, <a href="http://pbfcomics.com/">Perry Bible Fellowship</a>, <a href="http://questionablecontent.net/">Questionable Content</a>, <a href="http://www.buttercupfestival.com/buttercupfestival.htm">Buttercup Festival</a> </div> <br/> Warning: this comic occasionally contains strong language (which may be unsuitable for children), unusual humor (which may be unsuitable for adults), and advanced mathematics (which may be unsuitable for liberal-arts majors).<br/> <br/> <h4>We did not invent the algorithm. The algorithm consistently finds Jesus. The algorithm killed Jeeves. <br />The algorithm is banned in China. The algorithm is from Jersey. The algorithm constantly finds Jesus.<br />This is not the algorithm. This is close.</h4><br/> <div class="line"></div> <br/> <div id="licenseText"> <!-- <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/"><img alt="Creative Commons License" style="border:none" src="http://imgs.xkcd.com/static/somerights20.png" /></a><br/> --> This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/">Creative Commons Attribution-NonCommercial 2.5 License</a>. <!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns "><Work rdf:about=""><dc:creator>Randall Munroe</dc:creator><dcterms:rightsHolder>Randall Munroe</dcterms:rightsHolder><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:source rdf:resource="http://www.xkcd.com/"/><license rdf:resource="http://creativecommons.org/licenses/by-nc/2.5/" /></Work><License rdf:about="http://creativecommons.org/licenses/by-nc/2.5/"><permits rdf:resource="http://web.resource.org/cc/Reproduction" /><permits rdf:resource="http://web.resource.org/cc/Distribution" /><requires rdf:resource="http://web.resource.org/cc/Notice" /><requires rdf:resource="http://web.resource.org/cc/Attribution" /><prohibits rdf:resource="http://web.resource.org/cc/CommercialUse" /><permits rdf:resource="http://web.resource.org/cc/DerivativeWorks" /></License></rdf:RDF> --> <br/> This means you"re free to copy and share these comics (but not to sell them). <a href="/license.html">More details</a>.<br/> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> </div> </body> </html> ' except: return "" return "" def get_next_target(page): start_link = page.find('<a href=') if start_link == -1: return None, 0 start_quote = page.find('"', start_link) end_quote = page.find('"', start_quote + 1) url = page[start_quote + 1:end_quote] return url, end_quote def union(p,q): for e in q: if e not in p: p.append(e) def get_all_links(page): links = [] while True: url,endpos = get_next_target(page) if url: links.append(url) page = page[endpos:] else: break return links def crawl_web(seed): tocrawl = [seed] crawled = [] while tocrawl: page = tocrawl.pop() if page not in crawled: union(tocrawl, get_all_links(get_page(page))) crawled.append(page) return crawled print crawl_web('http://xkcd.com/353') A: Do you want to extract urls from a html file? Then this is what you need: http://youtu.be/MagGZY7wHfU?t=1m54s Its a great course by the way. Maybe you are interested. A: To parse html file you should use XML parsing library. See: https://docs.python.org/2/library/xml.html
unknown
d18247
test
The problem is that u are using a version of the engines that don't use generics but using generics in the handler Try with this: var engine = new FileHelperEngine<MyClass>(); engine.Options.IgnoreFirstLines = 1; engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue; engine.AfterReadRecord += new FileHelpers.Events.AfterReadHandler<MyClass>(engine_AfterReadRecord);
unknown
d18249
test
Try File.seek and File.rawRead. They work like their C counterparts, but rawRead determines the read count from the size of the output buffer you hand it.
unknown
d18251
test
bower will download the entire package using Git. Your package must be publically available at a Git endpoint (e.g., GitHub). Remember to push your Git tags! This means that bower will actually download the entire repository/release for you to use in your ASP project. I've tested this with bootstrap and jQuery. These repositories can contain many many files so including them into the .csproj file will clutter your project file and may not be ideal. This can be compared to using nuget packages where we are only referencing external packages in the packages.config file but we do not include the dll and other assemblies into the project. This leads me to think that bower_components should indeed not be included in the project; this makes no difference to usage as you can still reference the packages and use the files.
unknown
d18253
test
css cant affect anything before it, it can only affect stuff after the targeted element change like below #menu-open + #logo { color: #ccc; font-style: italic; } #menu-open:checked + #logo { color: #f00; font-style: normal; } <input type="checkbox" id="menu-open"> <div id="logo" class="logoib"> my logo here </div> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label> A: You could use pure JS, JQuery or CSS. Here is a pure JS solution. If you want to set it also on load, you could call myFunction when the DOM is ready. function myFunction() { var cb = document.getElementById('menu-open'); var logo = document.getElementById('logo'); if (cb.checked) { logo.setAttribute("class", "newClass"); } else { logo.removeAttribute("class"); } } #menu-open:checked~.logoib { -webkit-filter: invert(100%); filter: invert(100%); } .newClass { color: red; } <div id="logo" class="logoib">Logo </div> <input type="checkbox" id="menu-open" onchange="myFunction()"> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label>
unknown
d18255
test
InstanceProfileCredentialsProvider retrieves credentials as needed; a client using it should never see a credentials timeout exception. This implies that either (1) you are explicitly setting instance profile credentials on the client that is timing out, or (2) there is something else in the provider chain that is providing limited-time credentials. Or, I suppose, you might be using an extremely old version of the SDK. I don't know at what point they added automatic refresh; according to git blame, the fetcher variable was last changed 13 months ago. But I've been using instance credentials with long-running processes for much longer than that. A: This article may help you. If you really need to get a new credentials, the following example shows pseudocode for how to use temporary security credentials if you're using an AWS SDK: assumeRoleResult = AssumeRole(role-arn); tempCredentials = new SessionAWSCredentials( assumeRoleResult.AccessKeyId, assumeRoleResult.SecretAccessKey, assumeRoleResult.SessionToken); s3Request = CreateAmazonS3Client(tempCredentials); Read further info about temporary credentials in this docs.
unknown
d18259
test
Just add .Where(i => i.Extension.Equals(".finfo", StringComparison.InvariantCultureIgnoreCase)) to the enumerable. Or better, use the other overload of EnumerateFiles: foreach (FileInfo filemove in finfo.Directory.EnumerateFiles("*.finfo")) { Also, note that MoveTo only works on the same logical drive. If that's not enough for you, you will need to add your own copy+delete method for moving files accross drives.
unknown
d18261
test
If you want it to fire after a click: $(".element").click(function(){ $("link[rel='stylesheet']").remove(); }); or at the beginning: $(document).ready(function(){ $("link[rel='stylesheet']").remove(); }); A: Try this: $('link[rel="stylesheet"]').remove(); This will remove all stylesheets (all the styles applies due to those stylesheets) from the page. A: Just spent few mintues to draft one (function(f,a,s,x){ x=$(a);x.map(function(i,o){o=$(o);o.data(s+s,o.attr(s));o.removeAttr(s)}); $(s+',link[rel='+s+'sheet]').appendTo(f); setTimeout(function(){ $(a,f).appendTo('head'); x.map(function(i,o){o=$(o);o.attr(s,o.data(s+s))}) },999); })($('<i>'),'*','style'); A: Disable all StyleSheetList.prototype.forEach=Array.prototype.forEach; // *Note document.styleSheets.forEach((ss)=>ss.disabled=true); or (Disable All) for(styleSheet of document.styleSheets){ styleSheet.disabled=true; } or (Remove all) StyleSheetList.prototype.forEach=Array.prototype.forEach; document.styleSheets.forEach((ss)=>ss.ownerNode.parentNode.removeChild(ss.ownerNode)); or (Remove all) for(styleSheet of document.styleSheets){ styleSheet.ownerNode.parentNode.removeChild(styleSheet.ownerNode); } *Note: If you don't want to change the prototype, you can invoke it like this: Array.prototype.forEach.apply(document.styleSheets,[(ss)=>ss.disabled=true]) A: Try this $('link[rel="stylesheet"]').remove(); A: Place this on document ready: $('link[rel=stylesheet]').remove(); Or bind it to a button. A: A rough, dirty and brute approach: document.querySelector("head").remove(); A bookmarklet version of the same code that you can paste as the URL of a bookmark. You can also paste it into the address bar (for security reasons, when you paste the text, chrome/firefox remove the javascript: bit at the beginning so you'll need to type that by hand): javascript:(function(){document.querySelector("head").remove();})() A: Use below code to remove all kinds of styles, inline, internal, external. let elements=document.querySelectorAll("*"); elements.forEach(el=>{ if(el.tagName==="LINK" || el.tagName==="STYLE") el.remove(); else el.removeAttribute("style"); }); Thank me later! ;)
unknown
d18263
test
Can a stack allocated buffer be accessed through C++? Yes. From the type-system perspective there is no difference between statically allocated, stack allocated, or heap allocated: the C signature only takes pointer and size, and cares little where that pointer points to. Is this safe? Most likely. As long as the C function is correctly written and respects the bounds of the buffer, this will be safe. If it doesn't, well, that's a bug. One could argue that it's better to have a heap-allocated buffer, but honestly once one starts writing out of bounds, overwriting arbitrary stack bytes or overwriting arbitrary heap bytes are both bad, and have undefined behavior. For extra security, you could use a heap allocated nested between 2 guard pages. Using OS specific facilities, you could allocate 3 contiguous OS pages (typically 4KB each on x86), then mark the first and last as read-only and put your buffer in the middle one. Then any (close) write before or after the buffer would be caught by the OS. Larger jumps, though, wouldn't... so it's a lot of effort for a mitigation. Is your code safe? You most likely need to know how many bytes were written, so using a null pointer is strange. I'd expect to see: let mut written: size_t = 0; let written_size = &mut written as *mut _; And yes, that's once again a pointer to a stack variable, just like you would in C. A note on style. Your Rust code is unusual in that you use fully typed variables and full paths, a more idiomatic style would be: // Result is implicitly in scope. pub fn receive(&mut self, f: &dyn Fn(&[u8])) -> Result<(), &str) { let mut buffer = [0u8; MAX_BYTES_TRANSPORT]; let mut written: size_t = 0; let written_size = &mut written as *mut _; // Safety: // <enumerate preconditions to safely call the function here, and why they are met> let result = unsafe { openvpn_client_receive_just( buffer.as_mut_ptr(), buffer.len(), written_size, self.openvpn_client) }; translate_openvpn_error(result)?; let buffer = &buffer[0..written]; f(buffer); Ok(()) } I did annotate the type for written, to help along inference, but strictly speaking it should not be necessary. Also, I like to preface every unsafe call I make with the list of pre-conditions that make it safe, and for each why they are met. It helps me audit my unsafe code later on.
unknown
d18265
test
Your code needs to run in a new thread. Look into the System.Threading namespace for instructions and examples of how to create a new thread. Essentially, you create the thread Here is an example from one of my old test programs. Thread thdOneOfTwo = new Thread(new ParameterizedThreadStart(TextLogsWorkout.DoThreadTask)); In the above example, TextLogsWorkout.DoThreadTask is a static method on class TextLogsWorkout, which happens also to contain the above statement. You have the option of giving each thread a name, and of using a WaitHandle that it can signal when it has completed its assignment. Both are optional, but you must execute the Start method on the instance. Be aware that you are entering the world of multi-threaded programming, where many hazards await the unwary. If you aren't already, I suggest you read up on mutexes, wait handles, and the intrinsic lock () block. Of the three, lock() is the simplest way that a single application can synchronize access to a property. Of the other two, WaitHandles and Mutexes are about equal in complexity. However, while a WaitHandle can synchronize activities within a process, a Mutex is a filesystem object, and, as such, can synchronize activities between multiple processes. In that regard, be aware that if a mutex has a name, as it must if it is to synchronize more than one process, that name must begin with "\?\GLOBALROOT", unless all of them run in the same session. Failure to do this bit me really hard a few years ago.
unknown
d18267
test
if (document.getElementById('name').value != "" && document.getElementById('company').value != "" && document.getElementById('email').value != ""){ document.getElementById('hiddenpdf').style.display = 'block'; }else{ document.getElementById('hiddenpdf').style.display = 'none'; } Hope this helps. You have a syntax error in your code. Above solution checks with "and" logic and will only execute 'block' statement if all three conditions are met otherwise it will move over to else statement.
unknown
d18271
test
this issue arise with mysql database setup. please follow below listed link to sorted out that issue.. https://docs.wso2.org/display/EMM100/General+Server+Configurations there are few mistakes on documentation. On step 6, type exit; and Step 9. add given config values within <datasources> </datasources> A: Please check using MySQL console whether the admin has permission to access EMM_DB. Meanwhile you can try WSO2 EMM 1.1.0 http://wso2.com/products/enterprise-mobility-manager/
unknown
d18275
test
>>> import json >>> data = ''' { ... "items":[ ... { ... "item":0 ... }, ... { ... "item":1 ... }, ... { ... "item":2 ... }, ... { ... "item":3 ... } ... ] ... }''' >>> print(json.dumps({a:[{b:1+c[b]for b in c}for c in d]for a,d in json.loads(data).items()},indent=4)) { "items": [ { "item": 1 }, { "item": 2 }, { "item": 3 }, { "item": 4 } ] }
unknown
d18277
test
You can use the error style class to mark the entry as having error. The following is a minimal example that checks if an entry has a valid hex digit and updates the entry style: /* main.c * * Compile: cc -ggdb main.c -o main $(pkg-config --cflags --libs gtk+-3.0) -o main * Run: ./main * * Author: Mohammed Sadiq <www.sadiqpk.org> * * SPDX-License-Identifier: LGPL-2.1-or-later OR CC0-1.0 */ #include <gtk/gtk.h> static void entry_changed_cb (GtkEntry *entry) { GtkStyleContext *style; const char *text; gboolean empty; g_assert (GTK_IS_ENTRY (entry)); style = gtk_widget_get_style_context (GTK_WIDGET (entry)); text = gtk_entry_get_text (entry); empty = !*text; /* Loop until we reach an invalid hex digit or the end of the string */ while (g_ascii_isxdigit (*text)) text++; if (empty || *text) gtk_style_context_add_class (style, "error"); else gtk_style_context_remove_class (style, "error"); } static void app_activated_cb (GtkApplication *app) { GtkWindow *window; GtkWidget *entry; window = GTK_WINDOW (gtk_application_window_new (app)); entry = gtk_entry_new (); gtk_widget_set_halign (entry, GTK_ALIGN_CENTER); gtk_widget_set_valign (entry, GTK_ALIGN_CENTER); gtk_widget_show (entry); gtk_container_add (GTK_CONTAINER (window), entry); g_signal_connect_object (entry, "changed", G_CALLBACK (entry_changed_cb), app, G_CONNECT_AFTER); entry_changed_cb (GTK_ENTRY (entry)); gtk_window_present (window); } int main (int argc, char *argv[]) { g_autoptr(GtkApplication) app = gtk_application_new (NULL, 0); g_signal_connect (app, "activate", G_CALLBACK (app_activated_cb), NULL); return g_application_run (G_APPLICATION (app), argc, argv); }
unknown
d18279
test
You can do this: private final List<Button> mButtons = new ArrayList<>(); // somewhere in your code mButtons.add(mButton1); mButtons.add(mButton2); mButtons.add(mButton3); mButton1.setOnClickListener(mClickListener); mButton2.setOnClickListener(mClickListener); mButton3.setOnClickListener(mClickListener); private final View.OnClickListener mClickListener = new View.OnClickListener() { @Override public void onClick(View v) { for (Button button : mButtons) { if (button == v) { // set selected background } else { // set not selected backround } } } }; If you define a stateful drawable for your buttons, then you can simply change the onclick to this: private final View.OnClickListener mClickListener = new View.OnClickListener() { @Override public void onClick(View v) { for (Button button : mButtons) { button.setSelected(v == button); } } }; A: For changing background color/image based on the particular event(focus, press, normal), you need to define a button selector file and implement it as background for button. For example button_selector.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/your_image1" /> <!-- pressed --> <item android:state_focused="true" android:drawable="@drawable/your_image2" /> <!-- focused --> android:drawable="@drawable/your_image3" <!-- default --> </selector> then just apply it as : <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawable="@drawable/button_selector.xml" /> A: "Pressed", "selected", "disabled" and such are View states. As such they're supposed to be handled automatically by Android and not by your click listeners. This is achieved using SateLists, which control the look your Views sould have depending on which state(s) they're in. So you can easily set subject_button as the unpressed state, clicked_subject as the pressed state, and let Android take care of actually switching between them. Full explanation: https://developer.android.com/guide/topics/resources/drawable-resource.html#StateList A: I solved it by instead of changing only the background color on clicking the button, I also change the textColor, then I can check the textColor with if (((Button) v).getCurrentTextColor() == Color.WHITE)
unknown
d18289
test
You can do it like so. * *use groupingBy and create a Map<String, List<String>> *if the string starts with "el" group using the els key *otherwise, use the others key List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el"); Map<String, List<String>> map = elements.stream().collect( Collectors.groupingBy(str -> str.startsWith("el") ? "els" : "others")); map.entrySet().forEach(System.out::println); prints els=[el2, el3] others=[e1, 4 el, 5 el] A: Since you have a threshold condition which determine if an item will go to group A, otherwise B, I suggest using partitioningBy for this. For example: List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el"); //create the partition map Map<Boolean,List<String>> partitionMap = elements.stream() .collect(Collectors.partitioningBy(s-> s.startsWith("el"))); //getting the partitions List<String> startsWithEl = partitionMap.get(true); List<String> notStartingWilEl = partitionMap.get(false); Now each list will hold its partition .
unknown
d18291
test
As I looked at your source code, I guess you should somehow add the .cbp-af-header-shrink class back to the header, when you click the green button.
unknown
d18293
test
I think is better like this: var mobileController = TextEditingController(); getMobile() async { Future notificatinstatus = SharedPrefrence().getUserMobile(); notificatinstatus.then((data) async { var mobile_no=data; setState(() { if(mobile_no.isNotEmpty){ mobileController.text = mobile_no; } }); }); } @override void initState() { super.initState(); getMobile(); }
unknown
d18295
test
db.Customers.aggregate({ $group: { "_id": { $toLower: "$city" }, "count": { $sum: "$Number_Days_booked" } } }, {$match:{_id:"tel_aviv"}}) matching at the end did the trick.
unknown
d18297
test
Using new Integer() will guarantee that you have a new Integer object reference. Using the value directly will not guarantee that, since auto boxing int to Integer may not do that object instantiation. I would say that you will only need new Integer(1) in really strange edge cases, so most of the time I would say you never need to do new Integer... Also please bear in mind that auto boxing / unboxing may produce some errors in some edge cases. Integer x = null; int y = x; // Null Pointer Exception Long iterations where auto(un)boxing is happening may have a performance cost that an untrained eye might not notice A: Use autoboxing as a default pattern - it's been about forever and makes life ever-so-slightly easier. Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, .. While there are slight difference with new Integer (see other answers/comments/links), I generally do not consider using new Integer a good approach and strictly avoid it.
unknown
d18299
test
If you're curious about this sort of stuff you should play around with Chrome Developer Tools, the Firefox Firebug Addon or the Safari's 'Developer' menu. They're really great at giving you an insight as to what is going on in a webpage As to "how did they build this" there's many, many different technologies being used up and down the web application stack. Keep in mind the servers storing, caching and fetching all this data are just as much a part of the web application as the frontend. But I imagine your question is asking how "how did they get this webpage to do all this interactive stuff". Basically it looks like it's all traditional HTML/CSS--no "HTML5" canvas shenanigans or Flash. The interactivity comes from their custom Javascript code. I tried to figure out if they're using some popular 3rd party Javascript Framework (like jQuery or Prototype) but they are importing so many scripts it's hard to follow. Interestingly enough jQuery and $ are not defined variables on the Evernote page, so it looks like they're not using jQuery at the least. They have clearly written a lot of Javascript to get this thing up and running so it's not that big of a stretch to imagine they they would just decide to keep all their code in-house. FYI: The three columns are just absolutely positioned and sized <div>s. <div style="position: absolute; overflow-x: hidden; overflow-y: hidden; left: 0px; top: 0px; bottom: 0px; width: 220px; ">...</div> <div style="position: absolute; overflow-x: hidden; overflow-y: hidden; left: 220px; top: 0px; bottom: 0px; width: 360px; ">...</div> <div style="position: absolute; overflow-x: hidden; overflow-y: hidden; left: 580px; top: 0px; right: 0px; bottom: 0px; ">...</div> The scrolling that you see in those columns is done in child <div>s. A: webapps like this are usually built with a javascript framework such as backbone, angularjs, ember, etc. here is a reference site which lists them: http://todomvc.com/ Its hard to see what js framework they are using if any but there are using jQuery 1.8 They are using http://icanhazjs.com/ which is a javascript client side template library. They are using http://requirejs.org/ A: Well, at the very basic evernote has accomplished its note app workflow using custom javascript, although there are lot of others frameworks they have used for backend work. One way is to see it using Chrome web Inspector nad if on Firefox ,then they have upgraded there web inspector and its much cooler now, but if you prefer the much popular firebug, it will do. For detailed info, on what are the resources they have used to build, on way is to track it using a web analyzer tool like www.buitwith.com here, is the link for the homepage of the evernote site , searched over Builtwith.com : http://builtwith.com/?https%3a%2f%2fwww.evernote.com However the app, that is built upon comprises a lot of custom code. Hard to specify the exact usage, but if we check the code, it doesn't show any of specific use of AngularJS , they do use requireJS for loading modules. As your question is front-end specific, it can be done using HTML5, with some javascript or if you prefer a framework to ease the process, then checkout this link from JQueryUI. https://jqueryui.com/resizable/ They are still the kings of UI development, if AngularJS and ReactJS are not mentioned to be overwhelmed. And also , if you try to do it using plain vanilla JavaScript, that will give you an edge to the learning curve a loads. A: They use Angular.js, HTML5, CSS3, custom Javascript, and JQuery (and lots of other stuff as others have noted). From: http://evernote.com/careers/job.php?job=om2qXfwv
unknown
d18301
test
You cannot do it atomically but you can use limit which reduces it. return mongoTemplate.find(myQuery.limit(1000), Document::class.java)
unknown
d18305
test
Here static variable will help you: function content_before_after($content) { // define variable as static static $content_shown; // if variable has __no__ value // it means we run function for the first time if (!$content_shown) { // change value and return required string $content_shown = true; return 'something goes here'; } // empty string will be returned in second and other function calls return ''; }
unknown
d18311
test
The problem was that I was not flushing stdout. Due to buffering, the printf succeeded, but the fflush failed.
unknown
d18315
test
The OpenCV DLL comes with the Computer Vision System Toolbox for MATLAB. It sounds like the Computer Vision System Toolbox is not correctly installed on your computer.
unknown
d18317
test
Without using an extra lib: const useDebounce = (value, delay, fn) => { //--> custom hook React.useEffect(() => { const timeout = setTimeout(() => { fn(); }, delay); return ()=> { clearTimeout(timeout); } }, [value]); }; SomeComponent.js const [someInputValue, setsomeInputValue] = useState(null); const fn = ()=> console.log(someInputValue); useDebounce(someInputValue, 2000, fn);
unknown
d18321
test
You would feed the data into chunks with a for loop. Cory Schafer's video demonstrates this in his video: https://www.youtube.com/watch?v=Uh2ebFW8OYM&t=607s
unknown
d18331
test
Perhaps your customer doesn't want people "guessing" incremental or string IDs in the URL, which is how a lot of insecure web applications get hacked (E.g. Sony) right? It's a slightly-uninformed demand, but well intentioned. I understand your pain. Would your customer know the difference between a hashed and encrypted ID? Maybe your life could be simpler if you just used salted+hashed IDs, which adds just as much obfuscation (not security!) to the URL, minus the need to URLEncode the encrypted value. Ideally, you could get this "encrypted ID" requirement punted in favor of a combination of SSL, an authentication system with page level rights-enforcement, and solid audit trail logging. This is standard web application security stuff.
unknown
d18333
test
Yes the above is possible. I still don't get it where is the problem statement. Did you try above? is it failing? if yes then what is the error? 1) Yes, You can have 2 @Test methods in one class using same data provider. 2) If in the same sheet if you are using same data for this tests then there is no problem at all. if there is different data for different test then in your data provider toggle between test data using method name. Let me know if you need further help.
unknown
d18335
test
You should be able to just do something like this... =Sum(Fields!myAmountField.Value) / CountDistinct(Fields!myMonthField.Value) if your report spans more than one year you may have to do something like =Sum(Fields!myAmountField.Value, "myYearGroupName") / CountDistinct(Fields!myMonthField.Value, "myYearGroupName")
unknown
d18339
test
Yes, that is possible with Amazon Pinpoint. Please see documentation regarding setting up and executing a scheduled campaign. https://docs.aws.amazon.com/pinpoint/latest/userguide/campaigns.html thanks
unknown
d18345
test
Here's one approach which should work for you. Setup assumed: Sheet1 data is in range A1:B8 Sheet2 data is in range A1:B3 Then formula that you should insert in Sheet2!C2 shall be: =SUM((FREQUENCY(IFERROR(MATCH(IF(Sheet1!$A$1:$A$8=Sheet2!A2,Sheet1!$B$1:$B$8,"z"),IF(Sheet1!$A$1:$A$8=Sheet2!B2,Sheet1!$B$1:$B$8,"a"),0),"a"),IFERROR(MATCH(IF(Sheet1!$A$1:$A$8=Sheet2!A2,Sheet1!$B$1:$B$8,"z"),IF(Sheet1!$A$1:$A$8=Sheet2!B2,Sheet1!$B$1:$B$8,"a"),0),"b"))>0)+0) NOTE: This is an array formula and shall be inserted by committing CTRL+SHIFT+ENTER and not just ENTER. If entered correctly, Excel put {} braces around it.
unknown
d18347
test
As an alternative to dynamic sql you can use a case expression. This will make the entirety of your procedure this simple. create procedure test_sp ( @metric varchar(50) = NULL ,@from_date date =NULL ,@to_date date =Null ) AS BEGIN SET NOCOUNT ON; select sum(case when @metric = 'Sales' then sales_value else revenue_value end) from <dataset> where metric = @metric END A: You need dynamic SQL here. You can't use a variable for an object (table name, column name, etc) without it. ... declare @sql varchar(max) --sum the value based on the metric set @sql = 'select sum(' + @column_name + ') from <dataset> where metric = ' + @metric print(@sql) --this is what will be executed in when you uncomment the command below --exec (@sql) end --execute the procedure exec test_sp @metric ='sales' But, you could eliminate it all together... and shorten your steps use testdb go create procedure test_sp ( @metric varchar(50) = NULL ,@from_date date =NULL ,@to_date date =Null ) AS BEGIN SET NOCOUNT ON; --specifying the column name based on the metric provided if @metric = 'Sales' begin select sum('sales_value') from yourTable where metric = @metric --is this really needed? end else begin select sum('revenue_value') from yourTable where metric = @metric --is this really needed? end Also, not sure what @from_date and @to_date are for since you don't use them in your procedure. I imagine they are going in the WHERE clause eventually.
unknown
d18349
test
You can to use the ResultTransformer to transform your results in a map form. Following the oficial documentation Like this: List<Map<String,Object>> mapaEntity = session .createQuery( "select e from Entity" ) .setResultTransformer(new AliasToEntityMapResultTransformer()) .list(); A: Please try with Query q1 = entityManager().query(nativeQuery); org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)q1) .getHibernateQuery(); hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);‌​
unknown
d18353
test
show me the created the Notification channel Details. Then don't test in Redmi or mi Phones. addListenersForNotifications = async () => { await PushNotifications.addListener('registration', 'registration Name'); await PushNotifications.addListener('registrationError', 'error'); await PushNotifications.createChannel({ id: 'fcm_default_channel', name: 'app name', description: 'Show the notification if the app is open on your device', importance: 5, visibility: 1, lights: true, vibration: true, }); await PushNotifications.addListener('pushNotificationReceived', this.pushNotificationReceived); await PushNotifications.addListener('pushNotificationActionPerformed', this.pushNotificationActionPerformed); };
unknown
d18357
test
There is, as you suggested, a Java API in the class path. (You can see the automatic imports in the "Imports" section of the Scala or Java tab in the Language Manager.) If you choose "Class Documentation" under "Help" you will see the documentation for these API classes. Bad news: there is no real documentation to speak of. There's method names and parameter types—basically what Javadoc will auto-generate for files that have no documentation. The tutorials have some examples using Groovy, which may help some if you can do the mental conversion to Java/Scala.
unknown
d18359
test
If you check your browser's devtools console, you will see a Javascript error thrown when you try to add the second select2: Uncaught query function not defined for Select2 undefined If you search for that error, you will find some other questions about this, for eg this one: "query function not defined for Select2 undefined error" And if you read through the answers and comments, you will find several which describe what you are doing: * *This comment: This problem usually happens if the select control has already been initialized by the .select2({}) method. A better solution would be calling the destroy method first. Ex: $("#mySelectControl").select2("destroy").select2({}); * *This answer: One of its other possible sources is that you're trying to call select2() method on already "select2ed" input. * *Also this answer: I also had this problem make sure that you don't initialize the select2 twice. ... and possibly more. These describe what you are doing - calling .select2() on elements which are already initialised as select2s. The second time $('.select2').select2() runs, as well as trying to initialise your new select2, it is re-initialising the first select2 as a select2 again. You have another problem in your code - every select has the same ID: id='cntType'. IDs must be unique on the page, so this is invalid HTML. We can solve both problems at once by keeping track of how many selects you have on the page, and giving each new one an ID including its number, like say cntType-1, cntType-2, etc. Then we can target just the new ID to initialise it as a select2. Here's a working example. $(document).ready(function () { // Track how many selects are on the page let selectCount = 0; $("#packages").on("click", function () { // New select! Increment our counter selectCount++; //. Add new HTML, using dynamically generated ID on the select $(this).before( "<div class='col-12 packageCard'>" + "<div class='col-4'>" + "<div class='form-group'>" + "<label>Container Type</label>" + "<select name='cntType' id='cntType-" + selectCount + "' class='form-control select2' data-dropdown-css-class='select2' style='width: 100%;'>" + "<option value='0' selected='selected' disabled>Select Container Type</option>" + "<option>20 feet</option>" + "<option>40 feet</option>" + "</select>" + "</div>" + "</div>" + "</div>"); // Initialise only our new select $('#cntType-' + selectCount).select2(); }); }) <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.0.0/select2.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/2.1.0/select2.min.js"></script> <button id="packages">Add</button>
unknown
d18365
test
I managed to get what I want by using [%hardbreaks] option to keeping line breaks and by using {nbsp} built-in attribute for non-breaking spaces. Here is the complete code: [%hardbreaks] Array( {nbsp}{nbsp}Element1, {nbsp}{nbsp}Element2, {nbsp}{nbsp}Element3 )
unknown
d18367
test
From what you wrote and the comments in your code I am guessing that you want the program to continue running and asking for input if you enter a non-positive number. In that case I would rewrite it as: print("Welcome to the number program") total_number = 0 entries = 0 while True: number = input("Please give me a number \n") number = int(number) if number == -999: break if number <= 0: print("Sorry, this value needs to be positive. Please enter a different number.") continue total_number = total_number + number entries += 1 print(total_number) print(total_number) print(entries) print(total_number / entries) Also, you can increment numbers with entries += 1 A: * *In most cases you should NOT create variables first, however this case you should. Create number = 0, tally = 0 and total_number = 0 first *Accept your first number inside your while loop and handle all of the logic in there as well. *Your while loop should continue to loop until the final condition is met which seems to be number == -999 *Should tally be incremented if you enter a negative number? I assume not. What about a 0? Wrap the increment for tally and the addition to total_number in an if number > -1: condition. Use an if else to check for number == -999, and an else for handling invalid entries. *Finally, move your print statements outside of your while loop. It also doesn't need a condition around it because now, if you've exited your while loop, that condition has been satisfied. Final note here, and this is just a nice to know/have and purely syntactic sugar, MOST languages support abbreviated incrementing. Theres a better word for it, but the gist is simply this. total_number += number # is exactly the same as total_number = total_number + number # but way nicer to read and write :) print("Welcome to the number program") number = 0 total_number = 0 entries = 0 while number != -999: number = input("Please enter a number! \n") number = int(number) if number >= 0 total_number += number entries += 1 print("Current sum: " + total_number) elif number == -999: break else print("Sorry, this value needs to be positive.") print("Sum of entries: "+str(total_number)) print("Number of entries: " + str(entries)) print("Average entry: " +str(total_number/entries)) A: I have rewritten your code. But I am not sure what the goal was. Anyways, if the value were ever to be under 0 the loop would have been exited and a new value would have never been accepted from an input. Also some things I have written more elegant. print("Welcome to the number program") number=int(input("Please give me a number \n")) total_number=0 entries=0 while number > 0: total_number += number print(total_number) number = int(input("Please give me another number! \n")) entries += 1 if number == -999: print(total_number) print(entries) print(total_number/entries) break elif number < 0: number = input("Sorry, this value needs to be positive. Please enter a different number!")
unknown
d18371
test
I made a little example of how to use a TestScheduler. I think it's very similar to the .NET implementation @Test public void should_test_the_test_schedulers() { TestScheduler scheduler = new TestScheduler(); final List<Long> result = new ArrayList<>(); Observable.interval(1, TimeUnit.SECONDS, scheduler) .take(5) .subscribe(result::add); assertTrue(result.isEmpty()); scheduler.advanceTimeBy(2, TimeUnit.SECONDS); assertEquals(2, result.size()); scheduler.advanceTimeBy(10, TimeUnit.SECONDS); assertEquals(5, result.size()); } https://github.com/bric3/demo-rxjava-humantalk/blob/master/src/test/java/demo/humantalk/rxjava/SchedulersTest.java EDIT According to your code : you should pass the scheduler to the Observable.interval operation, as this is what you want to control : TestScheduler scheduler = new TestScheduler(); Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler); Subscription toBeTested = Observable.from(Arrays.asList(1, 2, 3, 4, 5)) .buffer(3) .zipWith(tick, (i, t) -> i) .subscribe(System.out::println); scheduler.advanceTimeBy(2, TimeUnit.SECONDS); A: you have some class: public class SomeClass { public void someMethod() { Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS); contactsRepository.find(index) .buffer(MAX_CONTACTS_FETCH) .zipWith(tick, new Func2<List<ContactDto>, Long, List<ContactDto>>() { @Override public List<ContactDto> call(List<ContactDto> contactList, Long aLong) { return contactList; } }).subscribe() } } Look up [Observable.interval][1] in the docs and you will see it operates on the computation scheduler, so lets override that in our test. public class SomeClassTest { private TestScheduler testScheduler; @Before public void before() { testScheduler = new TestScheduler(); // set calls to Schedulers.computation() to use our test scheduler RxJavaPlugins.setComputationSchedulerHandler(ignore -> testScheduler); } @After public void after() { // reset it RxJavaPlugins.setComputationSchedulerHandler(null); } @Test public void test() { SomeClass someInstance = new SomeClass(); someInstance.someMethod(); // advance time manually testScheduler.advanceBy(1, TimeUnit.SECONDS); } This solution is an improvement to the accepted answer as the quality, integrity and simplicity of the production code is maintained.
unknown
d18373
test
If you take a look at the NSString reference you will get various methods to get the data from a string. An example is NSData *bytes = [yourString dataUsingEncoding:NSUTF8StringEncoding]; You can also make use of the method UTF8String
unknown
d18377
test
TableAID int, Col1 varchar(8) TableB: TableBID int Col1 char(8), Col2 varchar(40) When I run a SQL query on the 2 tables it returns the following number of rows SELECT * FROM tableA (7200 rows) select * FROM tableB (28030 rows) When joined on col1 and selects the data it returns the following number of rows select DISTINCT a.Col1,b.Col2 FROM tableA a join tableB b on a.Col1=b.Col1 (6578 rows) The above 2 tables on different databases so I created 2 EF models and retried the data separately and tried to join them in the code using linq with the following function. Surprisingly it returns 2886 records instead of 6578 records. Am I doing something wrong? The individual lists seems to return the correct data but when I join them SQL query and linq query differs in the number of records. Any help on this greatly appreciated. // This function is returning 2886 records public List<tableC_POCO_Object> Get_TableC() { IEnumerable<tableC_POCO_Object> result = null; List<TableA> tableA_POCO_Object = Get_TableA(); // Returns 7200 records List<TableB> tableB_POCO_Object = Get_TableB(); // Returns 28030 records result = from tbla in tableA_POCO_Object join tblb in tableB_POCO_Object on tbla.Col1 equals tblb.Col1 select new tableC_POCO_Object { Col1 = tblb.Col1, Col2 = tbla.Col2 }; return result.Distinct().ToList(); } A: The problem lies in the fact that in your POCO world, you're trying to compare two strings using a straight comparison (meaning it's case-sensitive). That might work in the SQL world (unless of course you've enabled case-sensitivity), but doesn't quite work so well when you have "stringA" == "StringA". What you should do is normalize the join columns to be all upper or lower case: join tblb in tableB_POCO_Object on tbla.Col1.ToUpper() equals tblb.Col1.ToUpper() Join operator creates a lookup using the specified keys (starts with second collection) and joins the original table/collection back by checking the generated lookup, so if the hashes ever differ they will not join. Point being, joining OBJECT collections on string data/properties is bad unless you normalize to the same cAsE. For LINQ to some DB provider, if the database is case-insensitive, then this won't matter, but it always matters in the CLR/L2O world. Edit: Ahh, didn't realize it was CHAR(8) instead of VARCHAR(8), meaning it pads to 8 characters no matter what. In that case, tblb.Col1.Trim() will fix your issue. However, still keep this in mind when dealing with LINQ to Objects queries. A: This might happen because you compare a VARCHAR and a CHAR column. In SQL, this depends on the settings of ANSI_PADDING on the sql server, while in C# the string values are read using the DataReader and compared using standard string functions. Try tblb.Col1.Trim() in your LINQ statement. A: As SPFiredrake correctly pointed out this can be caused by case sensitivity, but I also have to ask you why did you write your code in such a way, why not this way: // This function is returning 2886 records public List<tableC_POCO_Object> Get_TableC() { return from tbla in Get_TableA() join tblb in Get_TableB() on tbla.Col1 equals tblb.Col1 select new tableC_POCO_Object { Col1 = tblb.Col1, Col2 = tbla.Col2 }.Distinct().ToList(); } where Get_TableA() and Get_TableB() return IEnumerable instead of List. You have to watch out for that, because when you convert to list the query will be executed instantly. You want to send a single query to the database server.
unknown
d18379
test
On Android platform: MainThread == UiThread == "ApplicationThread" (it doesn't really exists), so in your case the new Activity will NOT start a new Service but Service's OnStartCommand() method will be raised. The Service will continue to run in the "ApplicationThread". A: According to the Android Developer Doc, A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. A: When you start an app by clicking on app's icon on launcher or home screen, Android will create a process for the app with a single thread (aka main or UI thread) of execution. This thread will exist even though there is no component started, such as Activity, Service, BroadcastReceiver, ContentProvider. Then, it will find and start the default or entry activity for the app (which defined in AndroidManifest.xml file). I have an Activity A that starts a service S via startService method. Now as per the documentation Service S will run on main thread or the UI thread Now my question is when activity A is destroyed will the UI thread still exist? Yes, UI thread still exist. What will happen if I reopen the Activity A through its launcher icon will there be two UI threads spawned in total? When you finish Activity A, Android does not destroy the process for the application at that time. It will keep the application in the memory for faster loading if you start the app later. So when you reopen the Activity A, if there is a process for that application exists already, then the Activity A is started within that process and uses the same thread of execution. Otherwise, Android will create a new process for the application. Which Thread will a Service run in? By default, all components (including Service) of the same application run in the same process and thread (called the main or UI thread). You can find more details in this link: https://developer.android.com/guide/components/processes-and-threads
unknown
d18387
test
regarding: if (i == 0) { printf("\nNo interfaces found! Make sure WinPcap is installed.\n"); return 0; } pcap_freealldevs(alldevs); since the variable i is initialized to 0 and never modified, this if() statement will always be true. One result is the call to: pcap_freealldev() will never be called. the scope of variables should be limited as much as reasonable. Code should never depend on the OS to clean up after itself. suggest #include <stdio.h> #include <stdlib.h> #include "pcap.h" int main( void ) { pcap_if_t *alldevs = NULL; char errbuf[PCAP_ERRBUF_SIZE]; /* Retrieve the device list from the local machine */ if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL /* auth is not needed */, &alldevs, errbuf) == -1) { fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf); exit(1); } /* Print the list */ for( pcap_if_t *d = alldevs; d != NULL; d= d->next) { printf("%d. %s", ++i, d->name); if (d->description) printf(" (%s)\n", d->description); else printf(" (No description available)\n"); } if ( ! alldevs ) { printf("\nNo interfaces found! Make sure WinPcap is installed.\n"); } /* We don't need any more the device list. Free it */ pcap_freealldevs(alldevs); }
unknown
d18395
test
Recursive directory traversal to rename a file can be based on this answer. All we are required to do is to replace the file name instead of the extension in the accepted answer. Here is one way - split the file name by _ and use the last index of the split list as the new name import os import sys directory = os.path.dirname(os.path.realpath("/path/to/parent/folder")) #get the directory of your script for subdir, dirs, files in os.walk(directory): for filename in files: subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory filePath = os.path.join(subdirectoryPath, filename) #get the path to your file newFilePath = filePath.split("_")[-1] #create the new name by splitting the old name by _ and grabbing last index os.rename(filePath, newFilePath) #rename your file Hope this helps. A: check below code example for the first filename1, replace path with the actual path of the file: import os os.rename(r'path\\sample_2_description.txt',r'path\\description.txt') print("File Renamed!")
unknown
d18401
test
1- Most trivial query, get all FileSystem Documents: const fileSystems = await FileSystem.find({ // Empty Object means no condition thus give me all your data }); 2- Using the $eq operator to match documents with a certain value const fileSystems = await FileSystem.find({ isDir: true, folderName: { $eq: 'root' } }); 3- Using the $in operator to match a specific field with an array of possible values. const fileSystems = await FileSystem.find({ isDir: true, folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] } }); 4- Using the $and operator to specify multiple conditions const fileSystems = await FileSystem.find({ $and: [ { isDir: true }, { folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] } } ] }); 5- Retrieve all documents that are directories and are not empty. const fileSystems = await FileSystem.find({ isDir: true, $or: [ { files: { $exists: true, $ne: [] } }, { folders: { $exists: true, $ne: [] } } ] }); 6- All directories that have a folder name that starts with the letter 'n' const fileSystems = await FileSystem.find({ isDir: true, folderName: { $regex: '^n' } }); Now the tougher queries: 1- count the total number of documents const count = await FileSystem.aggregate([ { $count: 'total' } ]); 2- count the total number of documents that are directories const count = await FileSystem.aggregate([ { $match: { isDir: true } }, { $count: 'total' } ]); 3- Get 'foldername' and 'filename; of all documents that are files. const fileSystems = await FileSystem.aggregate([ { $match: { isDir: false } }, { $project: { folderName: 1, fileName: 1 } } ]); 4- Retrieve the total number of files (isDir: false) in each directory (isDir: true) const fileCounts = await FileSystem.aggregate([ { $match: { isDir: true } }, { $project: { folderName: 1, fileCount: { $size: { $filter: { input: '$files', as: 'file', cond: { $eq: ['$$file.isDir', false] } } } } } } ]); 5- Recursive structure querying: The FileSystem interface is recursive, because it has both an array of files and an array of folders, which are both of type File[] and FileSystem[]. To query this recursive schema, you can use the $lookup operator in an aggregate pipeline, to make a left join between FileSystem and itself, based on some criteria. //Retrieve All Documents from FileSystem and their child documents const fileSystems = await FileSystem.aggregate([ { $lookup: { from: 'FileSystem', localField: '_id', foreignField: 'parentId', as: 'children' } } ]); //Use the match operator in the pipeline to filter the results: const fileSystems = await FileSystem.aggregate([ { $lookup: { from: 'FileSystem', localField: '_id', foreignField: 'parentId', as: 'children' } }, { $match: { isDir: true } } ]);
unknown
d18403
test
The problem is that you can't combine a SELECT which sets a variable with a SELECT which returns data on the screen. You set @OutputName to (case when (a.M_TRN_TYPE='XSW' .. ) but in the same SELECT you're also trying to display the results of: case when @OutputName='XSW' and (case when c.M_DATESKIP='+1OD' then b.M_DTE_SKIP_1 else b.M_DTE_SKIP_2 end)=a.M_TP_DTEFST then 0 else a.M_NB end as 'NBI' You can't have these two in the same SELECT, in the format you're using. My recommendation is to split them, one for assigning the variable: DECLARE @OutputName CHAR(50) SELECT @OutputName= (case when (a.M_TRN_TYPE='XSW' or a.M_TRN_TYPE='SWLEG') then 'FXSW' when (a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS='C') then 'DCS' when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)='+1' then (case when b.M_DTE_SKIP_1>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end) when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)<>'+1' then (case when b.M_DTE_SKIP_2>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end) end) from TP_COMPL_PL_REP b join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA) left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA) and one for returning the data: SELECT case when @OutputName='XSW' and (case when c.M_DATESKIP='+1OD' then b.M_DTE_SKIP_1 else b.M_DTE_SKIP_2 end)=a.M_TP_DTEFST then 0 else a.M_NB end as 'NBI' from TP_COMPL_PL_REP b join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA) left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA)
unknown
d18405
test
Use the default argument to set the default date. This should handle all the cases except the third one, which is somewhat ambiguous and probably needs some parser tweaking or a mindreader: In [15]: from datetime import datetime In [16]: from dateutil import parser In [17]: DEFAULT_DATE = datetime(2013,1,1) In [18]: dates=["Today is August 2012. Tomorrow isn't", ...: "Another day 12 August, another time", ...: "12/08 is another format", ...: "have another ? 08/12/12 could be", ...: "finally august 12 would be"] In [19]: for date in dates: ...: print parser.parse(date,fuzzy=True, default=DEFAULT_DATE) ...: 2012-08-01 00:00:00 2013-08-12 00:00:00 2013-12-08 00:00:00 # wrong 2012-08-12 00:00:00 2013-08-12 00:00:00
unknown
d18409
test
You can try with the following package of npm: Infinite Scrolling package
unknown
d18411
test
you can use the below code snippet. If you are writing logic within the step definition method then the below code would be handy as method nesting is not advisable. Boolean elementnotpresent; Try { IWebElement element = Driver.FindElement(By.XPath("Element XPath")); } catch (NoSuchElementException) { elementnotpresent=true; } if (elementnotpresent == true) { Console.WriteLine("Element not present"); } else { throw new Exception("Element is present"); } A: Here's a straightforward approach to the problem: if (Driver.Instance.FindElements(By.XPath(baseXPathSendKeys + "div[2]/textarea")).Count != 0) { // exists } else { // doesn't exist } You could create a method Exists(By) to test elements: public bool Exists(By by) { if (Driver.Instance.FindElements(by).Count != 0) { return true; } else { return false; } } Then call it when you want to test something: By by = By.XPath(baseXPathSendKeys + "div[2]/textarea") if (Exists(by)) { // success } A: I had a strange case, when selenium was not throwing a NoSuchElementException exception, but MakeHttpRequest timed out. So i had come up with idea, that i got the attribute innerHTML of parent HTML element, and assert that it doesnot contain not wanted element. Assert.IsTrue(!parent.GetAttribute("innerHTML").Contains("notWantedElement")); A: I know this was asked a while ago but you can try something like this var wait = new WebDriverWait(driver, Timespan.FromSeconds(10)); wait.Until(driver => driver.FindElements(By.WhateverYourLocatorIs("")).Count == 0);
unknown
d18417
test
Is your NAS running SAMBA? If so will the Samba log files or smbstatus command solve your need? See https://askubuntu.com/questions/89288/how-can-i-monitor-my-samba-traffic
unknown
d18419
test
It looks like you're trying to use the ContentType header to determine which type of response to return. That's not what it's for. You should be using the Accepts header instead, which tells the server which content types you accept. A: Try using $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", url: "/Vendor/Details/" + newid, beforeSend: function(xhr) { xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); }, data: "{}", dataType: "json", success: function(data) { alert(data); }, error: function(req, status, err) { ShowError("Sorry, an error occured (Vendor callback failed). Please try agian later."); } }); a la - http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/ A: The "content-type" header doesn't do anything when your method is "GET".
unknown