text
stringlengths
64
89.7k
meta
dict
Q: How to print tiff files automatically? I have a folder which will contain only one tiff file at a time, so the moment I receive one I should be able to print it to the default printer. I have a small Windows application which is looking for any tiff files in the particular folder. I just have to print it to the default printer the moment a tiff file is received. Does anyone have any idea how to do this using C#? A: As OP said in the question, this can be done with this piece of code: System.Diagnostics.Process printProcess = new System.Diagnostics.Process(); printProcess.StartInfo.FileName = strFileName; printProcess.StartInfo.Verb = "Print"; printProcess.StartInfo.CreateNoWindow = true; printProcess.Start();
{ "pile_set_name": "StackExchange" }
Q: Store SNS share value via function.php I am trying to store SNS share value + comment count on my postmeta, DB. I put code below to accomplish this task, function get_sns_share($post_ID=0) { $url1=get_permalink($post->ID); $src = json_decode(file_get_contents('http://graph.facebook.com/' . $url1)); $share_count = $src->shares; // facebook commnet + comment like + share + like $my_var = get_comments_number( $post_id ); // comment count $social_score = $share_count + $my_var + $tweet; // social score sum if ($social_score > 999) $social_socre = 999; return $social_score; update_post_meta($post_id, '_social_score', $social_score); } The problem is this code certainly do works every field other than update_post_meta. It seems it does not add add post meta field to my database, thus I cannot get any value from there. Your help would be much appreciated. A: Within a function or method, the return statement immediately stops the execution of the earlier. Hence the last line never gets interpreted. Switch the order of this: return $social_score; update_post_meta($post_id, '_social_score', $social_score); to this: update_post_meta($post_id, '_social_score', $social_score); return $social_score; Update: You are using three different variables for the post id, namely: $post_ID, $post_id and $post->ID. You should use the function argument: $post_ID.
{ "pile_set_name": "StackExchange" }
Q: Ruby or Ruby on Rails I am trying to build a browser based remote SSH using Ruby. I am not sure whether to use Ruby or Ruby on Rails. There won’t be any database involved. I just want to display the output of my commands neatly on the browser. Can this be achieved using Ruby alone or is it better to use Ruby on Rails? More Info: Basically, I will have an HTML page which will POST the SSH command. This command will be executed on the remote machine and then the result will be returned. It will be something like this: Net::SSH.start( HOST, USER, :password => PASS ) do|ssh| result = ssh.exec!('ls') puts result I don't know how to POST the command from HTML to ruby code. I also don't know how to return "result" back to the HTML page. I want to print what is present in 'result' on the HTML page. A: Ruby on Rails is a web framework that has been written in the Ruby programming language. If you don't take the time to learn the Ruby syntax, you will struggle with Rails. Not saying you must become an expert in all things Ruby, but you should at a minimum get comfortable with the basic object classes (arrays, strings, hashes, etc) and their corresponding methods. If you are just getting started, I would urge you to check out Chris Pine's site - http://pine.fm/LearnToProgram/ which covers the basics of the Ruby programming language, then you can start reading through the Rails Guides http://guides.rubyonrails.org/getting_started.html to learn more about the framework. This site will help you out the most: http://www.sinatrarb.com/ I really think that sinatra will be most beneficial for you. You don't need the extra stuff that Rails does.
{ "pile_set_name": "StackExchange" }
Q: Where to call an Action when user removes an uploaded image in GWTUpload? I am using GWTUpload , the library is in here https://code.google.com/p/gwtupload/ The Example code at client side found on that website has this structure: // Attach an image to the pictures viewer private OnLoadPreloadedImageHandler showImage = new OnLoadPreloadedImageHandler() { public void onLoad(PreloadedImage image) { //showImageFlowPanel code solution 1 image.setWidth("75px"); showImageFlowPanel.add(image); } }; private IUploader.OnFinishUploaderHandler onFinishUploaderHandler = new IUploader.OnFinishUploaderHandler() { public void onFinish(IUploader uploader) { if (uploader.getStatus() == Status.SUCCESS) { new PreloadedImage(uploader.fileUrl(), showImage); UploadedInfo info = uploader.getServerInfo(); String headShotImageUrl="http://"+Window.Location.getHost()+"/" +"images/uploaded/"+info.message; //headShotImage code solution 2 if(!"".equals(headShotImageUrl) && UriUtils.isSafeUri(headShotImageUrl)){ headShotImage.setUrl(UriUtils.fromString(headShotImageUrl)); } } } }; The example uses showImageFlowPanel (solution 1) to store the image but I want to store the image inside headShotImage which take the url after user uploaded image successfully, see the headShotImage (solution 2) code above. Ok, the headShotImage code work fine but I dont know how to remove it when users remove the image. If I use showImageFlowPanel as in the solution 1 then the program remove the image automatically for me and I do not need to do anything. So my question is "Where to call an Action when user removes an uploaded image in GWTUpload?" A: You have to use setOnCancelUploaderHandler. Take a look to this code took from the demo. // When the user clicks a cancel button we get an event uploader.addOnCancelUploadHandler ( new IUploader.OnCancelUploaderHandler() { public void onCancel(IUploader uploader) { for (String iname : uploader.getServerMessage().getUploadedFieldNames()) { // loadedImages is an temporary table where we are adding all uploaded files // indexed by field name Widget w = loadedImages.get(iname); if (w != null) { w.removeFromParent(); loadedImages.remove(uploader.getInputName()); } } } });
{ "pile_set_name": "StackExchange" }
Q: Stop refresh modaless popup on button click if already open up I have page where I'am opens a modaless popup on a button click Open Popup. Scenario: Initially when page opens up no popup is displaying, I click on button Open Popup, my modaless popup is opens up and I have filled some data on that popup and if I click again on "Open Popup" button of parent page then my popup gets refreshed. Expected: If my modaless popup is already open then on click on Open Popup button (of parent) instead of refresing the popup, focus should comes on already opened popup. I'm trying to achieve this using jQuery or JavaScript. What I have tried so far: On click on Open Popup, I'm trying to check if open popup has 'in' class then do not open popup like: if ($('#NewPopup').hasClass('in')) { return false; } But, this is not working. Any idea how can I achieve this? A: I have found one solution which checks if jQuery dialog is already open or not. Here I am checking if dialog is already opens up then do not open it again: if (!$('.ui-dialog-content').dialog("isOpen")) { $("#" + options.id).dialog("open"); }
{ "pile_set_name": "StackExchange" }
Q: Do we have a reference for reference requests? Context: There are now 43 questions tagged reference-request. The current tag wiki guidance is For questions asking for references from the literature or textbooks on specific topics. If possible, references should be accompanied by a hyperlink to the article for accessibility. Related OR Meta discussions like Avoid usage of non-permanent URLs to reference papers are very limited in scope. Our own Help Center even states to avoid asking subjective questions where every answer is equally valid. Also from OR Meta, Stack Exchange was not intended to be a list of links or a search engine telling users where to find their answers elsewhere. — Robert Cartaino ♦ (source) Peer Sites: CrossValidated (stats) has a related discussion on this issue including guidelines on using community wiki for certain reference requests. They refer to these guidelines officially. Mathematics has language to avoid "big lists" (source). Physics seems to have address this this topic by creating the specific-reference tag which has usage guidance that separates these "What is the canonical source for X?" or "What is the first paper on Y?" from general topical questions to use the resource-recommendation tag. The two tags are considered mutually exclusive. These topical resource recommendation tags must comply with the usage policy. Resource recommendations must ask for descriptive answers. It's not enough to ask for a list of books that cover topic X — a simple Amazon search can provide that. Instead, you should ask for recommendations, which specify: What the book covers How it covers it — is it rigorous? Intuitive? How is the writer's style? What are the prerequisites? and similar questions. (Source: Physics.SE FAQ) Discussion: I expect these kinds of questions will likely continue on the site and we should note these questions can be highly useful. Here are some examples of reference requests in reverse chronological order:[1] Categorization of optimization models Reference request for Evacuation Planning [2] Good textbook for queueing theory and performance modeling [2] Bridge the gap between theory and practice in Integer Programming PhD-level textbooks on linear programming Looking for books in the same style as Hans Kellerer 2004, Knapsack Problems references on the empirical study on the practice of OR References for "metric" network flow problems Good sources on developing mathematical models (closed) Classics in Operations Research from around WW II? [2] Recommended books/materials for practical applications of Operations Research in industry Single reference for Mixed Integer Programming formulations to linearize, handle logical constraints and disjunctive constraints, do Big M, etc? [2], also a fav of mine Some questions are of dubious quality but without the tag: What are good reference books for introduction to operations research? (closed) The amount of research or even detail provided by the asker varies greatly from question to question. The lack of guidance on reference-request questions currently leaves the site open to low quality generic questions that may have limited value for future visitors (similar to the gimme the codez questions on StackOverflow). While some users already attempt to improve these questions before answering, many (including myself) have rushed in to provide answers (see [2]). Perhaps the community should consider how these questions should be asked and how we should curate them on the site. A few questions for discussion: What research is expected of someone asking a reference-request question? What should be included in the question? How should the community moderate these questions? (and if needed, improve their quality to help askers) [1] Examples only include literature-specific requests (books, papers, references) and do not include benchmark problems, courses, etc. [2] Disclosure for questions that I have also answered. A: In my opinion, the things we expect of someone asking a reference-request question are pretty similar to the things we ask of someone asking any other question: do research, show your work, be specific, make it relevant to others, etc. I agree that some of the questions you link to do a better job than others of ticking those boxes, but that's true of non-reference-request questions too. By the way, I fully agree that these questions are welcome on OR.SE, even if other SE sites frown on them. What do others think?
{ "pile_set_name": "StackExchange" }
Q: Get Name of Range in Excel with Formula I've named a bunch of columns in Excel. Now I would like to be able to get the name of a column in a cell using a formula. So for example, if A:A was named Dates, I want to be able to put a formula in a cell such that =RangeName(A:A) returns the word Dates. I've found examples of how to do this for a single cell, but not for a range of cells. This is what I have found for a single cell. Public Function CellName(cel As Range) As Variant Dim nm As Name For Each nm In Names If nm.RefersTo = "=" & cel.Parent.Name & "!" & cel.Address Then CellName = nm.Name Exit Function End If Next CellName = CVErr(xlErrNA) End Function A: It sounds like a case for Intersect: Public Function CellName(cel As Range) As Variant Dim nm As Name For Each nm In Names If Not Intersect(cel, nm.RefersToRange) Is Nothing Then CellName = nm.Name Exit Function End If Next CellName = CVErr(xlErrNA) End Function
{ "pile_set_name": "StackExchange" }
Q: Alarm's notification only trigger in background I am creating an alarm application ,in that i have created notification that display message and play sound. But now its work only in background,i have to minimize my application to trigger my notification,if my app is open then notification does not show. code for notification are: - (void)viewDidLoad { [super viewDidLoad]; dateTimePiker.date = [NSDate date]; } - (void)scheduleLocalNotificationWithDate:(NSDate *)fireDate { UILocalNotification *notification = [[UILocalNotification alloc] init]; notification.fireDate = fireDate; notification.alertBody = @"Wake up"; notification.soundName = @"ma.mp3"; [[UIApplication sharedApplication] scheduleLocalNotification:notification]; } - (IBAction)SetAlarmBtnTapped:(id)sender { ..... ..... [self scheduleLocalNotificationWithDate:dateTimePiker.date]; } A: implement application:didReceiveLocalNotification: on your app delegate from the docs: If the application is running in the foreground, there is no alert, badging, or sound; instead, the application:didReceiveLocalNotification: method is called if the delegate implements it.
{ "pile_set_name": "StackExchange" }
Q: Firefox border rendering css arrow bug In Firefox, I'm having an issue where the css generated arrow renders the border properties with a cut-through outline at the center point. Is there a fix for this? It renders perfectly fine in all other modern browsers where the border outline isn't visible and shows a clear arrow. The bug is only visible in Firefox. All other browsers (Chrome, Edge, Opera, IE11): Firefox: .bx-prev, .bx-next { border-right: 15px solid green; border-bottom: 15px solid green; width: 35px; height: 35px; transition: .25s all; cursor: pointer; z-index: 10000; } .bx-prev { transform: rotate(135deg); position: absolute; top: 120px; left: 220px; } .bx-next { transform: rotate(-45deg); position: absolute; top: 120px; right: 420px; } <a class="bx-prev"></a> <a class="bx-next"></a> A: Use translateZ(1px) with rotate property value transform:translateZ(1px) rotate(-45deg)
{ "pile_set_name": "StackExchange" }
Q: Highscore table - How to highest score per user? Yep there are many similar questions, but I really couldn't solve my problem. Unfortunately I don't have enough knowladge to understand that similar question's answers to solve mine ^^. I have id, name, score , ip variables. I don't care about id or ip variables.. My query like this; $query = "SELECT * FROM highscores ORDER BY score + 0 DESC LIMIT 10"; $result = mysql_query($query); This gives higscore table but, there are same user's different scores. I want to show highest score per user. I don't even know why there is + 0 on my code. And why if I delete it table doesn't show as desc. A: The following query will give you the name of each player and his best score : SELECT name, MAX(score) FROM highscores GROUP BY name ORDER BY MAX(score) DESC LIMIT 10
{ "pile_set_name": "StackExchange" }
Q: What AI is best for learning an area I have a robot that I need to write an autonomous program for. The program is to play on this feild: http://www.vexforum.com/wiki/index.php/Gateway. and pick up the balls and barrels and put them in the cylinders(goals). I have sensors like light detection(best for following white line on ground or keeping track of location by noticing when you cross a white line), ultrasonic sonar, bump sensors, and encoders(count amount of wheel rotations). I want to make a program where the program learns the field and learns how to navigate best with the tasks at hand. I am thinking a neural net is my best choice but I can't think of what inputs I would use. The main thing is I don't want scripted paths. I know this is pretty vague but too much detail and no one would read this. Anyone ave any ideas? A: You need to use Simultaneous localization and mapping (SLAM) It is a pretty standard and successful technique for robot localization.
{ "pile_set_name": "StackExchange" }
Q: Show records only if a previous record has a certain value I'm trouble shooting a certain business proces and i'm able to follow the flow in a database. I've found the error message I want to look into, but only in case of a certain flow. My problem is how to achieve that in SQL. For example Source Statement -------- ------------ PORT Cannot create APP No active visit GIK OIK APP No active visit Now I only want to have the record with statement 'No active visit', if the previous record has a Source value "GIK". How do I achieve that in SQL? I'm working in SSMS btw. greets, Stoney A: You can use lag() : select t.* from (select t.*, lag(Source) over (order by ?) as prev_source from table t ) t where Statement = 'No active visit' and prev_source = 'GIK'; If lag() will not support then you can use apply : select t.* from table t cross apply (select top (1) t1.* from table t1 where t1.<identity_col> < t.<identity_col> order by t1.<identity_col> desc ) t1 where t.Statement = 'No active visit' and t1.source = 'GIK'; SQL tables represent unordered sets. If you want a specific ordering in the result set, you need one ordering column. So, use column name instead of ? that specify your column ordering.
{ "pile_set_name": "StackExchange" }
Q: ElasticSearch should/must clause not working as expected Below is my elastic query GET _search { "query": { "bool": { "must": { "match": { "marriages.marriage_year": "1630" } }, "should": { "match": { "first_name": { "query": "mary", "fuzziness": "2" } } }, "must": { "range": { "marriages.marriage_year": { "gt": "1620", "lte": "1740" } } } } } } It is returning data with marriages.marriage_year= "1630" with Mary as first_name as highest score.I also want to include marriages.marriage_year between 1620 - 1740 which are not shown in the results. It is showing data only for marriage_year 1630 A: That's because you have two bool/must clauses and the second one gets eliminated when the JSON query is parsed. Rewrite it like this instead and it will work: { "query": { "bool": { "must": [ { "match": { "marriages.marriage_year": "1630" } }, { "range": { "marriages.marriage_year": { "gt": "1620", "lte": "1740" } } } ], "should": { "match": { "first_name": { "query": "mary", "fuzziness": "2" } } } } } } UPDATE Then you need to do it differently and in the bool/must you need to have only the range query and move the match inside the bool/should section: { "query": { "bool": { "must": [ { "range": { "marriages.marriage_year": { "gt": "1620", "lte": "1740" } } } ], "should": [ { "match": { "first_name": { "query": "mary", "fuzziness": "2" } } }, { "match": { "marriages.marriage_year": "1630" } } ] } } }
{ "pile_set_name": "StackExchange" }
Q: Is it possible to declare user-defined statements in python (same syntax of assert)? For example, what assert does: assert <boolean assertion to check>, <error string/value outputted if that assertion False> What I would like to do: mycommand <boolean assertion to check>, <value that will get returned if assertion is False> It would be the same as doing: if not <boolean assertion to check>: return <value> but concisely, with a simple one-liner. I know I should just use this last one, but I am more interested on finding out how much you can override/customize python. A: You can not use any "user-defined" syntax, but you could just use assert itself and use a decorator to make the function return the value instead of raising an AssertionError: def assert_to_return(f): def _f(*args, **kwargs): try: return f(*args, **kwargs) except AssertionError as e: return e.args[0] if e.args else None return _f @assert_to_return def div(x, y): assert y != 0, float("nan") return x / y print(div(42, 5)) # 8.4 print(div(42, 0)) # nan This way, the assert <condition>, <value> line means "check whether <condition> holds, otherwise immediately return <value>", i.e. pretty much exactly what you wanted. If the <value> is omitted, the function will just return None in that case, as defined in the decorator. Also note that <value> is only evaluated if the assert is violated, i.e. it could also contain an expensive function call or side-effects that you do not want to occur otherwise. Of course, while other exceptions will work just fine, any AssertionError raised by assert statements in functions your function is calling will also bei caught and handled by the decorator. If this is a problem, you could either (a) wrap the <value> in some special wrapper object and only return those in _f, otherwise re-raise the AssertionError, or (b) wrap all the functions you call in your function that might also raise an AssertionError so that their AssertionErrors are wrapped in another exception.
{ "pile_set_name": "StackExchange" }
Q: Finding $\frac{I_1}{I_2}$ from recurrence relation Consider following recurrence relation: $$2(\sum_{i = 0}^k I_{n-i}) + I_{n-k} = I_{n-k-1}$$ $k = 0 , 1 , \dots , n-1$ Also $I_0 = \frac{V}{R}$. Assuming that $n \ge2$ is a fixed integer, I'm looking for $\frac{I_1}{I_2}$ in terms of $n$. After that I will take the limit as $n \to \infty$. This problem has come up when solving a circuit with infinite number of resistors. I don't know how to tackle this problem. Setting $S(k) =\sum_{i = 0}^k I_{n-i}$ isn't helpful. Also I tried to find a pattern in value of $\frac{I_1}{I_2}$ as $n$ increases but it was so complicated. The first terms are $3, \frac{11}{3} $ and $ \frac{41}{11}$. Using equivalent resistor we find that $\frac{I_1}{I_2} = \sqrt{3} + 2$. Edit: Here is the circuit: I added a voltage source between a-b, so we have $I_0 = \frac{V}{R}$. Assuming there are $n$ blocks, we calculate $\frac{I_1}{I_2}$ and then taking the limit yields the result. According to Cesareo's answer, the answer doesn't depend on $n$. How this is plausible? Increasing $n$ should change the value of $\frac{I_1}{I_2}$. A: Hint. Making $$ R_{n,k} = 2\sum_{i=0}^{i=k}I_{n-i}+I_{n-k}-I_{n-k-1}=0 $$ we have $$ R_{n,k}-R_{n,k-1} = I_{n-k+1}-4I_{n-k}+I_{n-k-1}=0 $$ In this recurrence calling $n-k=m$ or $$ I_{m+1}-4I_{m}+I_{m-1}=0 $$ and this recurrence has the general solution $$ I_{m} = (2-\sqrt{3})^m C_1+(2+\sqrt{3})^m C_2 $$ now depending on the initial/boundary conditions for the determination of $C_1, C_2$ we have $$ \frac{I_2}{I_1}=\frac{(2-\sqrt{3})^2 C_1+(2+\sqrt{3})^2 C_2}{(2-\sqrt{3}) C_1+(2+\sqrt{3}) C_2} $$ for instance: if $I_n$ is limited then necessarily $C_2=0$ but if $I_n$ is unlimited then we need $C_1, C_2$ NOTE Included a MATHEMATICA script for the calculus of $\frac{I_2}{I_1}$ in the ladder resistance circuit included in the OP. R[1, r] = 3 r; R[n_, r_] := R[n, r] = 2 r + r R[n - 1, r]/(r + R[n - 1, r]) n = 10; For[j = 1; rel = {}, j <= n, j++, equ1 = Table[i[k] - i0[k + 1] + i0[k], {k, 1, n}]; equ2 = Table[r i[k] - i0[k] R[k, r], {k, 1, n}]; vars = Union[Variables[equ1], Variables[equ2]]; equs = Join[Join[equ1, equ2], {i0[n + 1] - in}]; solIJ = Solve[Thread[equs == 0], Take[vars, {2, Length[vars]}]][[1]]; AppendTo[rel, i[n - 1]/i[n - 2] /. solIJ] ] gr1 = ListPlot[rel, PlotStyle -> Red]; gr2 = Plot[2 + Sqrt[3], {k, 0, n + 2}]; Show[gr1, gr2] tr = Table[R[k, r], {k, 1, n}] /. {r -> 1} gr3 = ListPlot[tr, PlotStyle -> Red]; gr4 = Plot[(1 + Sqrt[3]), {k, 0, n}]; Show[gr3, gr4, PlotRange -> All]
{ "pile_set_name": "StackExchange" }
Q: Unable to use DOMDocument in Symfony I have been unable to use DOMDocument in symfony. After digging around, I found the problem might be that I do not have the php xml extension, but I thought that it was absurd because, despite no being able to use DOMDocument, I can use Symfony's DOMCrawler, which obviously uses something similar to DOMDocument. Well, After looking through Crawler's source code, I found they uses something like $dom = new \DOMDocument('1.0', $charset); instead of the usual $dom = new DOMDocument('1.0', $charset); Does someone know the difference between the two, and why one works and the other doesn't in Symfony? A: Because in symfony we use namespace in each class. And because you have declared a namespace in your class then you need to inform PHP about the namespaces of each class you want to use. If you do not declare the namespace of a class you are using, PHP will think this class is in the same namespace than the current class. So the backslash "\" in this code: new \DOMDocument() is there to informe PHP that you want to use the DOMDocument class from the "global" namespace. If you want to use the Datetime object you will also need to use a backslash when instantiating the Datetime object. Another solution is to declare with the keyword Use. For exemple: use \DOMDocument; And then in your code you will instanciate without backslash: new DomDocument()
{ "pile_set_name": "StackExchange" }
Q: Get the corresponding value of 2nd selector jQuery each HTML is like: <div class="sltbsummry collection"> <div class="sltabsecondrow"> <div> <small>Schedule</small> </div> <div> <small>Amount</small> </div> </div> <div class="planContainer"> <div class="sltabsecondrow"> <div> <span> <input type="text" value="11-02-2019" class="schDate inputFld" readonly=""> </span> <span class="pull-right"> <i class="fa fa-calendar"></i> </span> </div> <div> <span> <input type="text" value="10000000" class="schAmt inputFld"> </span> <span> <a title="Remove Row" class="remRow" href="javascript:void(0);" style="display: inline;"> <i class="fas fa-times-circle"></i></a> </span> </div> </div> <div class="sltabsecondrow"> <div> <span> <input type="text" class="schDate" readonly=""> </span> <span class="pull-right"> <i class="fa fa-calendar"></i> </span> </div> <div> <span> <input type="text" class="schAmt"> </span> <span> <a title="Remove Row" class="remRowAdd" href="javascript:void(0);"> <i class="fas fa-times-circle"></i></a> </span> </div> </div> <div class="sltabsecondrow"> <div> <span> <input type="text" class="schDate" readonly=""> </span> <span class="pull-right"> <i class="fa fa-calendar"></i> </span> </div> <div> <span> <input type="text" class="schAmt"> </span> <span> <a title="Remove Row" class="remRowAdd" href="javascript:void(0);"> <i class="fas fa-times-circle"></i></a> </span> </div> </div> <div class="sltabsecondrow"> <div> <span> <input type="text" class="schDate" readonly=""> </span> <span class="pull-right"> <i class="fa fa-calendar"></i> </span> </div> <div> <span> <input type="text" class="schAmt"> </span> <span> <a title="Remove Row" class="remRowAdd" href="javascript:void(0);"> <i class="fas fa-times-circle"></i></a> </span> </div> </div> </div> </div> Above image shows a fieldset in which Schedule & Amount are interrelated to each other. A data set has to be formed with each row value like: [ {date:11/02/2019,amt:1000000}, {date:13-02-2019,amt:1111}, {date:21-02-2019,amt:222}... so on ] Following iteration was tried but I cant figure out how to get the corresponding value of the schAmt(.schDate is selector of date fields & .schAmt is of amount) jQuery('.schDate,.schAmt').each(function(){ //when loop is over .schDate how to get corresponding .schAmt value? }); This can be done by assigning corresponding index but I was wondering if looping like this would save that overkill & always produce corresponding value set correctly?. A: What you need to do is to iterate through a common parent of the input elements, e.g. .sltabsecondrow, using .map() You will want to check if the element actually contains the input elements you want. If they do exist, you simply return the object, which will in turn create an array of objects as you have intended. To access the correct input element in each iteration, you supply this as the second argument in the selector, which defines the context in which the element has to be found in, e.g. $('.schDate', this). This is equivalent to using $(this).find('.schDate'), just a bit less verbose. Finally, you want to chain .get() at the end so that you convert the jQuery object back into a native JS array. var data = jQuery('.sltabsecondrow').map(function() { var $date = $('.schDate', this); var $amt = $('.schAmt', this); // Check if both input elements exist // If not, return nothing if (!$date.length || !$amt.length) return; return { date: $date.val(), amt: $amt.val() }; }).get(); The advantage of using .map() over .each() is that you don't need to define another variable outside the loop to store your data. See proof-of-concept below: jQuery(document).ready(function() { var data = jQuery('.sltabsecondrow').map(function() { var $date = $('.schDate', this); var $amt = $('.schAmt', this); // Check if both input elements exist // If not, return nothing if (!$date.length || !$amt.length) return; return { date: $date.val(), amt: $amt.val() }; }).get(); console.log(data); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="sltbsummry collection"> <div class="sltabsecondrow"> <div> <small>Schedule</small> </div> <div> <small>Amount</small> </div> </div> <div class="planContainer"> <div class="sltabsecondrow"> <div> <span> <input type="text" value="11-02-2019" class="schDate inputFld" readonly=""> </span> <span class="pull-right"> <i class="fa fa-calendar"></i> </span> </div> <div> <span> <input type="text" value="10000000" class="schAmt inputFld"> </span> <span> <a title="Remove Row" class="remRow" href="javascript:void(0);" style="display: inline;"> <i class="fas fa-times-circle"></i></a> </span> </div> </div> <div class="sltabsecondrow"> <div> <span> <input type="text" class="schDate" readonly=""> </span> <span class="pull-right"> <i class="fa fa-calendar"></i> </span> </div> <div> <span> <input type="text" class="schAmt"> </span> <span> <a title="Remove Row" class="remRowAdd" href="javascript:void(0);"> <i class="fas fa-times-circle"></i></a> </span> </div> </div> <div class="sltabsecondrow"> <div> <span> <input type="text" class="schDate" readonly=""> </span> <span class="pull-right"> <i class="fa fa-calendar"></i> </span> </div> <div> <span> <input type="text" class="schAmt"> </span> <span> <a title="Remove Row" class="remRowAdd" href="javascript:void(0);"> <i class="fas fa-times-circle"></i></a> </span> </div> </div> <div class="sltabsecondrow"> <div> <span> <input type="text" class="schDate" readonly=""> </span> <span class="pull-right"> <i class="fa fa-calendar"></i> </span> </div> <div> <span> <input type="text" class="schAmt"> </span> <span> <a title="Remove Row" class="remRowAdd" href="javascript:void(0);"> <i class="fas fa-times-circle"></i></a> </span> </div> </div> </div> </div> Bonus You can also do the same logic above in vanilla JS ;) ES5 var rows = document.querySelectorAll('.sltabsecondrow'); var data = Array.prototype.map.call(rows, function(row) { var date = row.querySelector('.schDate'); var amt = row.querySelector('.schAmt'); if (!date || !amt) return; return { date: date.value, amt: amt.value }; }).filter(function(datum) { return !!datum; }); ES6 const rows = document.querySelectorAll('.sltabsecondrow'); const data = Array.from(rows).map(row => { const date = row.querySelector('.schDate'); const amt = row.querySelector('.schAmt'); if (!date || !amt) return; return { date: date.value, amt: amt.value }; }).filter(datum=> !!datum);
{ "pile_set_name": "StackExchange" }
Q: Submit iOS app to the AppStore - ITMS-9000 Error That might be a silly question. But I'm having problems when submiting my app to the AppStore. Did everything at developer.apple.com until the message "Waiting for upload appears" and then when trying to submit the app through Application Loader I get this message: Sorry about printing the image, couldnt copy and paste. Thanks in advance A: Turns out the problem wasn't with apple servers. The problem(as the screenshot suggest) was with provisioning profiles that was not set correctly.
{ "pile_set_name": "StackExchange" }
Q: How to archive a vertical-slider like in example? does someone know how this effect is even called and how is it done? already tried something like this - but it's buggy and not working properly like i want it to. also not really good in fullscreen mode. first two images are logo and a navigation <div style="position:relative;height:720px;"> <img src="http://placehold.it/95x85" width="95" height="85" style="position:absolute;left:14px;top:27px;z-index:1000;" /> <img src="http://placehold.it/120x465" width="120" height="465" style="position:absolute;left:0;top:145px;z-index:1001;" /> <div id="img1" style="width:1920px;height:1080px;background-image:url('https://unsplash.it/g/1920/1080?image=0');position:absolute;left:0px;"></div> <div id="img2" style="width:1920px;height:1080px;background-image:url('https://unsplash.it/1920/1080?image=0');position:absolute;left:0px;"></div> <img src="https://d30y9cdsu7xlg0.cloudfront.net/png/273339-200.png" width="200" height="200" style="position:absolute;background-color: rgba(255, 255, 255, 0.25); top: 50%;" id="border" /> </div> JS: var img1 = document.getElementById('img1'); var img2 = document.getElementById('img2'); var border = document.getElementById('border'); img1.onmousemove = redraw; img2.onmousemove = redraw; border.onmousemove = redraw; function redraw(e){ posx = e.pageX - findPosX(img1); if (posx!=null&&posx>0&&posx<1600){ img1.style.width=posx+"px"; img2.style.backgroundPosition=(-posx)+"px"; img2.style.left=posx+"px"; img2.style.width=(1600-posx)+"px"; border.style.left=(posx-100)+"px"; } } function findPosX(obj){ var curleft = 0; if(obj.offsetParent) while(1){ curleft += obj.offsetLeft; if(!obj.offsetParent) break; obj = obj.offsetParent; } else if(obj.x) curleft += obj.x; return curleft; } https://jsfiddle.net/y7nfzw6z/ the effect can be found here: http://www.e2save.com/if-only-it-was-4k/ i'll add a screenshot of the website so you can see which effect i mean. A: @Dustin: It called Comparison Slider. There are a lot of good resource out there. https://codyhouse.co/gem/css-jquery-image-comparison-slider/ https://medium.com/jotform-form-builder/making-a-responsive-image-comparison-slider-in-css-and-javascript-f3a691a9dd71#.d76grg41h
{ "pile_set_name": "StackExchange" }
Q: Bootstrap dropdown hidden by panel Let's say I have a bootstrap panel on a page. Is there a way to have the contents of a dropdown fully visible within the panel. I'm having issues with the panel's overflow cutting off parts of my dropdowns. I don't want the panels to resize for their content, but rather to behave as you would expect from something like: <div class="panel panel-default"> <select> <option>...</option> ... </select> </div> Except with Bootstrap style drop-down content. Any suggestions? A: If your panel is inside a panel-group you could overwrite de default overflow property. In Bootstrap core exists this rule: .panel-group .panel { overflow:hidden; } so you should overwrite it: .panel-group .panel { overflow:visible; }
{ "pile_set_name": "StackExchange" }
Q: How can I convert a Clojure namespace to a string? I'm trying to pretty print a list of namespaces: (doseq [x (all-ns)] (println x)) This prints each namespace as #<Namespace xxxxx>. I would like to get each namespace as xxxxx (that is without the #<Namespace>. I tried to (name x), (symbol x) but I get ClassCastException clojure.lang.Namespace cannnot be cast to java.lang.Named, etc. (doseq [x (all-ns)] (println (name x))) (doseq [x (all-ns)] (println (str x))) (doseq [x (all-ns)] (println (namespace x))) How can I get the namespace as a string? A: Use ns-name: (doseq [x (all-ns)] (println (ns-name x))) Note that ns-name gives you a symbol. So if you want a string just use (str (ns-name ns)).
{ "pile_set_name": "StackExchange" }
Q: Bilinear transform and higher order differential equation The bilinear transform as I understand corresponds to the trapezoid rule. However, I have not been able to find whether the correspondence holds for higher order ODEs, or what kind of estimate the bilinear transform corresponds to in that case. As an example I use the Butterworth filter. The ODE of the filter is given by $$y(t)=-\frac{r}{\omega^2}y'(t)-\frac{1}{\omega^2}y''(t)$$ with initial condition $y(0)=0,y'(0)=\omega^2$. First calculate the coefficients by using the bilinear transform. Butterworth filter has the following transfer function: $$H(s)=\frac{\omega^2}{s^2+s\cdot r+\omega^2}$$ The bilinear transform is given by $s\rightarrow \frac{2}{T}\frac{1-z^{-1}}{1+z^{-1}}$. Then $$H(z)=\frac{\omega^2}{(\frac{2}{T}\frac{1-z^{-1}}{1+z^{-1}})^2+\frac{2}{T}\frac{1-z^{-1}}{1+z^{-1}} r+\omega^2}= \frac{\omega^2(1+z^{-1})^2}{(\frac{2}{T}(1-z^{-1}))^2+\frac{2}{T}(1-z^{-1})(1+z^{-1}) r+\omega^2(1+z^{-1})^2} =\frac{\omega^2(1+2z^{-1}+z^{-2})}{\frac{4}{T^2}(1-2z^{-1}+z^{-2})+\frac{2}{T}(1-z^{-2}) r+\omega^2(1+2z^{-1}+z^{-2})} =\frac{\omega^2(1+2z^{-1}+z^{-2})}{(\frac{4}{T^2}+\frac{2}{T}r+\omega^2)+2(-\frac{4}{T^2}+\omega^2)z^{-1}+(\frac{4}{T^2}-\frac{2}{T}r+\omega^2)z^{-2}} =\frac{\omega^2(1+2z^{-1}+z^{-2})/D}{1+2(-\frac{4}{T^2}+\omega^2)z^{-1}/D+(\frac{4}{T^2}-\frac{2}{T}r+\omega^2)z^{-2}/D}$$ So the coefficients are: $$a_0=1,a_1=2(-\frac{4}{T^2}+\omega^2)/D,a_2=(\frac{4}{T^2}-\frac{2}{T}r+\omega^2)/D$$ $$b_0=\omega^2/D,b_1=2b_1,b_2=b_0$$ $$D=(\frac{4}{T^2}+\frac{2}{T}r+\omega^2)$$ Ok, now do the same using the trapezoid method. We have the differential equation as before and the estimates (the stepsize is $h=T$): $$y(t+h)=y(t)+\frac{h}{2}(y'(t+h)+y'(t))$$ $$y'(t+h)=y'(t)+\frac{h}{2}(y''(t+h)+y''(t))$$ So that $$y(t+h)=y(t)+\frac{h}{2}(2y'(t)+\frac{h}{2}(y''(t+h)+y''(t)))$$ $$=y(t)+\frac{h}{2}(2y'(t)+\frac{h}{2}(-\omega^2y(t+h)-ry'(t+h)+\omega^2y(t)-ry'(t)))$$ $$=y(t)+\frac{h}{2}(2y'(t)+\frac{h}{2}(-\omega^2(y(t+h)+y(t))-r(y'(t+h)+y'(t)))$$ $$=y(t)+\frac{h}{2}(2y'(t)+\frac{h}{2}(-\omega^2(y(t+h)+y(t)))-r(y(t+h)-y(t))$$ And $$y(t+h)(1+\frac{h^2}{4}\omega^2+\frac{h}{2}r)=y(t)(1-\frac{h^2}{4}\omega^2+\frac{h}{2}r)+hy'(t)$$ $$\Leftrightarrow y(t+h)(\frac{4}{h^2}+\frac{2}{h}r+\omega^2)=y(t)(\frac{4}{h^2}+\frac{2}{h}r-\omega^2)+\frac{4}{h}y'(t)$$ But the above is not the same difference equation as given by the bilinear transform. For one $y(0)=0$ was an initial condition, but the bilinear transform gives $y(0)=\omega^2/D$ (unless there was a mistake somewhere). So what happens in higher order ODEs? A: Take one step more, either using $y(x+2h)$ or here for symmetry $y(x-h)$, and consider that equality is only up to terms of size $O(h^3)$, \begin{align} &y(x+h)-2y(x)+y(x-h) \\ &=\frac{h}2(y'(x+h)-y'(x-h))=\frac{h^2}4(y''(x+h)+2y''(x)+y''(x-h)) \\ &=-\frac{h^2}4[ry'(x+h)+ω^2y(x+h)+2ry'(x)+2ω^2y(x)+ry'(x+h)+ω^2y(x+h)] \\ &=-\frac{ω^2h^2}4[y(x+h)+2y(x)+y(x-h)]-\frac{rh}2[y(x+h)-y(x-h)] \end{align} using $y(x+h)-y(x-h)=[y(x+h)-y(x)]+[y(x)-y(x-h)]=\frac{h}2[y'(x+h)+2y'(x)+y'(x-h)]$ in the last step. Collecting coefficients gets us $$ \left[1+\frac{rh}2+\frac{ω^2h^2}4\right]y(x+h)-2\left[1-\frac{ω^2h^2}4\right]y(x)+\left[1-\frac{rh}2+\frac{ω^2h^2}4\right]y(x-h)=0 $$ which has exactly the same coefficient structure as your first approach. Let's back-test what the actual order of this method is by inserting Taylor expansions for $y(x\pm h)$ and then reducing by the ODE and its derivatives. \begin{align} -2&\left[1-\frac{ω^2h^2}4\right]y(x)+\left[1+\frac{ω^2h^2}4\right](y(x+h)+y(x-h))+\frac{rh}2(y(x+h)-y(x-h)) \\ &=2\left[-1+\frac{ω^2h^2}4\right]y(x) +2\left[1+\frac{ω^2h^2}4\right]\left(y(x)+\frac{h^2}2y''(x)+\frac{h^4}{24}y^{(4)}(x)+O(h^6)\right) +rh\left(hy'(x)+\frac{h^3}6y'''(x)+\frac{h^5}{120}y^{(5)}(x)+O(h^7)\right) \\ &=h^2\left(ω^2y(x)+ry'(x)+y''(x)\right)+\frac{h^4}{12}\left(3ω^2y''(x)+2ry'''(x)+y^{(4)}(x)\right)+O(h^6) \\ &=\frac{h^4}{12}\left(2ω^2y''(x)+ry'''(x)\right)+O(h^6) \end{align} Thus as the truncation error is $O(h^4)$, the method is $O(h^2)$ if the first step is $O(h^3)$, that is, $y(h)=y_1+O(h^3)$, $y_1=y(0)+hy'(0)-\frac{h^2}2(ω^2y(0)+ry'(0))$. The Lagrange and $z$ transformation methods assume that everything (not explicitly mentioned otherwise) is zero for negative times. Thus at time $0$ the right side of the recursion has to contain the defects of applying the difference operator to the sequence $...,0,y_0,y_1,y_2$, $b_k=a_0y_{k+1}+a_1y_k+a_2y_{k-1}$. This gives $b_{-2}=0$, $b_{-1}=a_0y_0$, $b_0=a_0y_1+a_1y_0$, $b_1=a_0y_2+a_1y_1+a_2y_0=0$, everything else is zero. This does not give the same structure as the numerator of $H(z)$.
{ "pile_set_name": "StackExchange" }
Q: Excel, Cumulative Summing every Nth row but random lengths of N I am trying to do a cumulative sum every Nth row on Excel however I am not what N could be as it is random and depends on other factors. I will attach a photo to show a simple clear example of what I mean. Thanks A: In Q2: =IF(OR(P2="-",Q1="-"),P2,P2+Q1) then copy down the column.
{ "pile_set_name": "StackExchange" }
Q: Helper class in ABAP to convert to Odata primitive types Is there any helper class in ABAP which I could use to convert ABAP data type of Date time format to that of Odata type ? I am creating a JSON payload natively in ABAP to post to a http REST API and the service expects the date to be in edm.datetimeoffset format . I was wondering if there is way to convert a date time stamp to that format so I could convert and send it out as a string. A: It's likely all the OData code is part of SAP Netweaver Gateway, which may or may not be installed on your system. I don't think it should be a problem to construct the correct value. The format is defined in the OData spec here dateTimeOffsetValue = year "-" month "-" day "T" hour ":" minute [ ":" second [ "." fractionalSeconds ] ] ( "Z" / sign hour ":" minute ) Using this pattern you could create the following string template expression. date_time = |{ date DATE = ISO }T{ time TIME = ISO }Z|. There's an example in the JSON format page here.
{ "pile_set_name": "StackExchange" }
Q: window.onerror does not work I have some tricky AJAX code on a form, and sometimes it will fail (don't ask why, I can't get around it). When this happens, I need to trap the error, reset a hidden field indicator, and submit the form naturally so that the user does not have an unpleasant experience. I planned on using window.onerror to do this, but it is never firing! I am using IE8 and all I have to worry about is the IE browser. Is there some gotcha to getting this event to work? Here's my code... window.onerror = function() { alert("Error!"); document.getElementById("hidAjax").value = "0"; document.forms[0].submit(); } A: "A common problem that bites many developers occurs when their onerror handler is not called because they have script debugging enabled for Internet Explorer. This will be the case by default if you have installed the Microsoft Script Debugger or Microsoft Visual Studio 6.0® (specifically Visual InterDev 6.0™)—onerror handling is how these products launch their debugger. You can disable script debugging for a given instance of Internet Explorer on the Advanced tab of the Internet Options dialog box (note that checking the Disable script debugging setting will apply only to that instance of Internet Explorer):" http://msdn.microsoft.com/en-us/library/ms976144.aspx
{ "pile_set_name": "StackExchange" }
Q: How [dis]similar are Trump's and Warren's (proposed) trade policies? An AIER article says Today Congress is statutorily impeded from stopping a continued march toward autarky, lest there appears some bipartisan legislation structured to take it back. The problem is that the Republican president has received almost no pushback from the Democrats against his trade policies; indeed, the leading contender for the Democratic presidential nomination, Elizabeth Warren, holds to a doctrine of “economic patriotism” that is not different in substance from Trump’s own. This is probably too much of a "soft question" to ask on Skeptics, but to what extent do Warren's and Trump's economic protectionism look alike, in terms of actual proposals? (The AIER article doesn't get into any further details on this. Are there any more substantive comparisons published?) A: Vox published an explainer on Warren's trade policy when she released her plans: President Trump’s pitch to white working-class voters has involved plenty of culture war politics, but also a striking break with the free trade policies adhered to by most Republicans over the past generation. [...] Warren’s plan is a rejection of that legacy, but also a counterpoint to Trump, who sees trade negotiations primarily through the lens of helping American exporters. For Warren, the key issue isn’t American interests versus those of foreigners, but wages and environmental protections versus the shared interests of multinational companies in sloughing off regulation. A: Economic policy is a huge area. I don't know if you can get a succinct answer on the whole lot. This Marketwatch article for example, implies that there are significant differences, but doesn't provide any solid details on those differences. A potential 2020 election showdown between President Donald Trump and Democratic candidate Elizabeth Warren would undoubtedly be touted as a clash of ideological extremes, but when it comes to economic policy, there is one area where there’s little daylight between the candidates. This area where their policies are similar is apparently the belief that the US Dollar is too strong. But both Trump and Warren contend an overly strong dollar hurts U.S. competitiveness. The Washington Post contrasts the approach Trump and Warren take to international Trade Deals. In broad terms both are sceptical of traditional (republican style) free trade deals that focus on removing trade barriers. There used to be a standard way in which political debates about trade played out. Republican candidates listened to business interests and were broadly supportive of free trade. Democrats, in contrast, often sounded skeptical about free-trade arguments to attract voters but generally ended up supporting trade agreements after concessions. The Post characterises the differences in approach as Trump being supportive of tariffs to protect industry and Warren supportive of Labour and Environmental protections, for much the same end. Protection of jobs within the US, by lowering competitive advantages of cheap labour markets. Trump Appeal to voters who have been hurt by globalization by criticizing free-trade agreements and supporting trade barriers. But he appears more willing than most Democrats to actually impose tariffs and other trade barriers. Warren ...calling for stronger protections for labor and the environment in U.S. trade agreements with other countries. Our research suggests this approach is popular with the U.S. public. Americans like free-trade deals, but they want the deals to come with protections.
{ "pile_set_name": "StackExchange" }
Q: Correct wrong prices Data: DB1 <- data.frame(orderItemID = 1:10, price = c("12.90","8.90","Mrz 40","79.95","Dez 45", "7.99","Jun 90","129.90","Jul 90","49.95") Expected Outcome: DB1 <- data.frame(orderItemID = 1:10, price = c("12.90","8.90","3.40","79.95","12.45", "7.99","6.90","129.90","7.90","49.95") Hey guys, it´s me again ;) and unfortunately I have a pretty difficult problem in my data set I need to solve... As you can see above I have some correct an some incorrect prices. At the incorrect prices there are always letters instead of a numbers before the decimal point (and theres no decimal point at the wrong prices). The 3 letters are acronyms for months of the year. So for example Dez is 12. month of the year, so the correct number is 12. So that Dez 45 should become 12.45. 2.example: Jun is the 6.month of the year so the correct number is 6. So that Jun 90 should become 6.90. (Hope its clear what I mean) So thats what I want to transform Jan=1. Feb=2. Mrz=3. Apr=4. Mai=5. Jun=6. Jul=7. Aug=8. Sep=9. Okt=10. Nov=11. Dez=12. I really have no idea this time how to solve this problem... Hope somebody got an idea A: if you are using first three letters of each month library(qdap) # mgsub DB1$price<-mgsub(month.abb,1:12,DB1$price) #month.abb from baseR give abbreviated months if you are sticking to your own month abbreviations: month_abb <-c("Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez") DB1$price<-mgsub(month_abb,1:12,DB1$price) A: Here's one way using regular expressions. First, make sure the price column is a character vector and not a factor DB1$price<-as.character(DB1$price) Then define your desired replacements replacewith<-c("Jan"="1.", "Feb"="2.", "Mrz"="3.", "Apr"="4.", "Mai"="5.", "Jun"="6.", "Jul"="7.", "Aug"="8.", "Sep"="9.", "Okt"="10.", "Nov"="11.", "Dez"="12.") Now turn those into a regular erxpression and match against your price column re <- paste0("^(",paste(names(replacewith),collapse="|"), ") ") m <- regexpr(re,DB1$price, perl=T) mm <- regmatches(DB1$price, m) Now we do a look up for the replacement regmatches(DB1$price, m) <- replacewith[substr(mm, 1, nchar(mm)-1)] DB1$price # [1] "12.90" "8.90" "3.40" "79.95" "12.45" "7.99" "6.90" "129.90" "7.90" "49.95"
{ "pile_set_name": "StackExchange" }
Q: Execute a forEach like a waterfall in async I'm trying to retrieve longitude and latitude from a list of addresses with the Google API via a Node.js script. The call itself works fine but since I have around 100 addresses to submit. I use a async.forEach on an array, but the calls are made too fast and I get the error "You have exceeded your rate-limit for this API." I found that the number of calls is limited to 2500 every 24h and maximum 10 a second. While I'm OK for the 2500 a day, I make my calls way too fast for the rate limit. I now have to write a function who will delay the calls enough not to reach the limit. Here is a sample of my code : async.forEach(final_json, function(item, callback) { var path = '/maps/api/geocode/json?address='+encodeURIComponent(item.main_address)+'&sensor=false'; console.log(path); var options = { host: 'maps.googleapis.com', port: 80, path: path, method: 'GET', headers: { 'Content-Type': 'application/json' } } // a function I have who makes the http GET rest.getJSON(options, function(statusCode, res) { console.log(res); callback(); }); }, function() { // do something once all the calls have been made }); How would you proceed to achieve this? I tried putting my rest.getJSON inside a 100ms setTimeout but the forEach iterates through all the rows so fast that it starts all the setTimeout almost at the same time and therefore it doesn't change anything... The async.waterfall looks like it would do the trick, but the thing is I don't know exactly how many rows I will have, so I can't hardcode all the function calls. And to be honest, it would make my code really ugly A: The idea is that you can create a rateLimited function that acts much like a throttled or debounced function, except any calls that don't execute immediately get queued and run in order as the rate limit time period expires. Basically, it creates parallel 1 second intervals that self-manage via timer rescheduling, but only up to perSecondLimit intervals are allowed. function rateLimit(perSecondLimit, fn) { var callsInLastSecond = 0; var queue = []; return function limited() { if(callsInLastSecond >= perSecondLimit) { queue.push([this,arguments]); return; } callsInLastSecond++; setTimeout(function() { callsInLastSecond--; var parms; if(parms = queue.shift()) { limited.apply(parms[0], parms[1]); } }, 1010); fn.apply(this, arguments); }; } Usage: function thisFunctionWillBeCalledTooFast() {} var limitedVersion = rateLimit(10, thisFunctionWillBeCalledTooFast); // 10 calls will be launched immediately, then as the timer expires // for each of those calls a new call will be launched in it's place. for(var i = 0; i < 100; i++) { limitedVersion(); }
{ "pile_set_name": "StackExchange" }
Q: Are the mid-episode transitions in One Piece random? In OP episodes there is a small transition/break mid-episode that shows one of the main characters picking up their most recognized item/weapon (prior it was a hat floating away or something or there were two of these). I used to think this was done using the character who appears in the main scene(s) for that episode but I just chanced across a few that had had Brooke picking up his violin and Chopper his backpack and no appearance of them. So I ask is it completely random or does it relate at time? A: On One Piece Wiki there is this page about the Eyecatchers, which seems to confirm your guess: In One Piece, there are two eyecatchers in every episode, and each one shows one of the Straw Hat Pirates, usually the ones who had the most significance in the episode, accompanied by a short excerpt of their respective themes. Moreover there are a lot informations, as the number of appearance of each character in the transitions and some trivia about the criteria behind the choice of the character, e.g. The characters of One Piece get a personal eyecatcher only after they join the Straw Hat Pirates. For example, Brook, despite fighting alongside the Straw Hats for the entirety of the Thriller Bark Arc, had no eyecatcher until his official recruitment. Sanji is the exception, having an eyecatcher just two episodes after his initial appearance, long before joining the crew.
{ "pile_set_name": "StackExchange" }
Q: .htaccess подмена картинки Есть ссылка на картинку somesite.ru/skins/Vasya.png. Нужно в .htaccess отловить ссылку подобного вида, которая /skins/ и .png и получить к скрипту слово Vasya. (По идеи можно его вычленять уже в самом скрипте) Нужно мне это, для того, чтобы подобные ссылки отдавали в итоге файл на сервере в малом регистре — vasya.png, а не все картинки на сайте. (Возможны и другие манипуляции в моем скрипте.) Нужно именно через .htaccess. A: RewriteEngine on RewriteRule ^skins/(.+)$ image.php?img=$1 [L]
{ "pile_set_name": "StackExchange" }
Q: RxAndroidBle - RxBleDevice getName() always returns null Having the following code rxBleClient = RxBleClient.create(this); scanSubscription = rxBleClient.scanBleDevices( new ScanSettings.Builder() .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) .build()) .subscribe(new Observer<ScanResult>() { @Override public void onCompleted() { Log.d(TAG_BT, "Scan completed"); } @Override public void onError(Throwable e) { Log.d(TAG_BT, "Scan onError", e); } @Override public void onNext(ScanResult scanResult) { RxBleDevice device = scanResult.getBleDevice(); Log.d(TAG_BT, "Scan - " + device.getName()); if (device.getName() != null && device.getName().contains( SMParameters.SM_BLUETOOTH_SSID_PREFIX)) { connectToDevice(device); } } } ); The results I get on every onNext() event are the following: 07-05 13:06:24.065 24390-24390/com.example.app D/TAG_BT: Scan - null 07-05 13:06:24.416 24390-24390/com.example.app D/TAG_BT: Scan - null 07-05 13:06:25.670 24390-24390/com.example.app D/TAG_BT: Scan - null 07-05 13:06:25.706 24390-24390/com.example.app D/TAG_BT: Scan - null 07-05 13:06:26.930 24390-24390/com.example.app D/TAG_BT: Scan - null 07-05 13:08:18.339 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:19.567 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:24.810 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:25.981 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:26.024 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:26.027 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:26.029 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:26.042 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:26.098 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:26.101 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:26.123 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:26.130 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:27.246 26550-26550/com.example.app D/TAG_BT: Scan - null 07-05 13:08:28.508 26550-26550/com.example.app D/TAG_BT: Scan - null Do I miss any configuration parameter? No error is thrown so if anyone has any clue... Thanks! A: BluetoothDevice may have a null name if it is not broadcasted. You may alternatively check for a name from scanResult.getScanRecord().getDeviceName() though it also can be null. This question was answered already here or here.
{ "pile_set_name": "StackExchange" }
Q: How to add multiple items in Listview Android I'm working on an Android application of booking medicine offline. I have used ListView for Cart, but whenever I add a new item in cart, my previous item get replaced. L1 = imageacidity L2 = imagecough if(msg.toString().equals("L1")) { adapter = new ContactImageAdapter(this, R.layout.list, imageacidity); ListView dataList = (ListView) findViewById(R.id.list); dataList.setAdapter(adapter); adapter.notifyDataSetChanged(); } if(msg.toString().equals("L2")) { adapter = new ContactImageAdapter(this, R.layout.list, imagecough); ListView dataList = (ListView) findViewById(R.id.list); dataList.setAdapter(adapter); adapter.notifyDataSetChanged(); } Here I have 5 elements in imageacidity and Imagecough Array. Whenever I select 1 item, it gets added in cart, but when I try to select another item it get replaced with new one. A: You have to Add the element inside your adapter. I will post a custom Adapter and show you how to add elements properly. Adapter: public class YourAdapter extends BaseAdapter { List<String> itens; private Context mContext; private static LayoutInflater inflater = null; public YourAdapter(Context context, List<String> itens){ this.itens = itens; mContext = context; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return itens.size(); } public String getItem(int position) { return itens.get(position); } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { View vi = convertView; if (convertView == null) vi = inflater.inflate(R.layout.list_row, parent, false); String msg = itens.get(position); TextView tx = vi.findViewById(R.id.your_id); tx.setText(msg); return vi; } public void addItem(String item){ itens.add(item); } public void addItens(List<String> itens){ this.itens.addAll(itens); } } ListView: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); adapter = new CustomAdapter(this,yourListOfItens); listView = (ListView) findViewById(R.id.list_view); listView.setAdapter(adapter); } You can set initial data on constructor of adapter, or use methods addItem and addAll on a click button for example. A: The problem you are describing of the data being removed is happening because making a new ContactImageAdapter and calling setAdapter, which will completely remove the data that was already in the ListView. If you want to properly implement the code in the question, you need something like this. String msg = ""; // TODO: get this String value ListView dataList = (ListView) findViewById(R.id.list); // TODO: Define a single List to store the data and use that in *one* adapter List<Contact> contacts = new ArrayList<Contact>(); adapter = new ContactImageAdapter(this, R.layout.list, contacts); dataList.setAdapter(adapter); // TODO: Replace this with the object to add to the adapter Contact contact = null; if(msg.equals("L1")) { // TODO: Use whatever values you want for "L1" int img = R.drawable.bati_acidity_1; String name = "Amlapitta"; String price = "price 170"; contact = new Contact(img, name, price); } else if(msg.equals("L2")) { // TODO: Use whatever values you want for "L2" int img = R.drawable.bati_acidity_2; String name = "Amlapitta2"; String price = "price 270"; contact = new Contact(img, name, price); } if (contact != null) { contacts.add(contact); adapter.notifyDataSetChanged(); } Another problem is that you are calling notifyDataSetChanged without actually changing the datasets of imageacidity or imagecough.
{ "pile_set_name": "StackExchange" }
Q: How to preserve kint output upon form submit redirection? I've attached a custom submit handler to node add/edit form for the article content type: $form['actions']['publish']['#submit'][] = 'my_module_node_edit_submit'; In the handler, I am trying to inspect the form state values with kint (via the devel module): kint($form_state->getValues()); Upon submission of the form, I'm able to briefly see the kint output on the screen, but I am also presented with this message: Redirecting to http://localhost/example.com/node/123 The page then redirects back to view the node, and the kint output is gone. How can I preserve the kint output so it is available after the redirection? A: Use ksm() instead of kint(). I ran into the same issue when I want to inspect the entity after saving, using drupal's hook_entity_presave and kint I found this article on how to print variables using kint() which explains that ksm() prints the output inside the drupal page (not before as kint()) does. So this example prints the entity without redirecting: function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) { ksm($entity->toArray()); }
{ "pile_set_name": "StackExchange" }
Q: Can I become eligible to receive free Windows 10 upgrade? My PC was installed with Windows 7 Pro full licence, now windows 8.1 enterprise. Through a development programme, I then attained MSDN membership for a year and decided to upgrade to windows 8.1 enterprise for free. (Perhaps ultimate would have been a better choice at the time). Enterprise is not eligible for a free upgrade to Windows 10. Is there a way, a relatively painless way of becoming eligible for a Windows 10 upgrade? Will any of these choices work? If I succeed, will I then become eligible for the upgrade? Or have I missed the boat? Downgrade my windows 8 enterprise to windows 7 pro. (have not looked into the detail) Clear PC and install windows 7 pro. Timely to resetup. Last resort is to just buy the Windows 10 upgrade. Again, probably cannot upgrade from enterprise and would have to clear PC using windows 7 as the upgrade. A: The better option is to re-install Windows7 and Upgrade to Windows10 using USB pendrive or CD. You can Download windows10 iso and prepare bootable USB/CD using Media Creation tool. http://windows.microsoft.com/en-us/windows-10/media-creation-tool-install No need to wait until you get the upgrade notification.
{ "pile_set_name": "StackExchange" }
Q: Select next once you know the closest selector with javascript I am developing a website and I can't use jQuery (no discussion about this), so pure javascript and a custom javascript framework is used. Actually I have found a situation that I don't know how to handle: I've a group of selectors, that for each one I add a "onclick" event to display / hide a div. For example: <div id="menu"> <div class="menu-item"> <div class="arrow"> <a class="down">Open / Close</a> </div> Menu Item <div class="extramenu hidden"> Extra menu items </div> </div> <div class="menu-item"> <div class="arrow"> <a class="up">Open / Close</a> </div> Menu Item 2 <div class="extramenu"> Extra menu items </div> </div> <div class="menu-item"> <div class="arrow"> <a class="down">Open / Close</a> </div> Menu Item 3 <div class="extramenu hidden"> Extra menu items </div> </div> </div> I select all "div.menu-item .arrow a" items, so I've 3 items. For each item I add a onclick event (that actually works fine). What I need to archive is how to select the "closest" class .extramenu inside the div.menu-item. Then detect if the <a /> have a class .up or .down and if class == .up, add the class hidden; and if class == .down, remove the class hidden. This a concept of what have to do, it's not javascript code: var elements; // my list of elements each(elements, function(element) { // here element is pointing to the ANCHOR add_event(element, "onclick", function(e) { var submenu; // here I need to detect the submenu closest to my anchor var state; // here I need to know if the anchor has class up or down if (state == "up") { add_class(submenu, "hidden"); // hide the submenu div remove_class(element, "up"); // remove the class up add_class(element, "down"); // and add the class down } else if (state == "down") { remove_class(submenu, "hidden"); // remove the class to show the menu remove_class(element, "down"); // remove the class down add_class(element, "up"); // and add the class up } }); }); Thank you guys and sorry if it's not well explained, I did my best! A: element.querySelectorAll allows you to select elements by CSS selector. element.classList allows you to access the classes of an element add_event(element, "onclick", function(e) { var el = e.target, state; var parent = el.parentNode; while (!parent.classList.contains('menu-item')) { parent = parent.parentNode; } var submenu = parent.querySelector('extramenu'); if (el.classList.contains('up')) { state = 'up'; } else { state = 'down' } /* ... */ }); You can write the rest of the pseudo code yourself. I'm assuming your already using Modernizr for supporting legacy browsers like IE8. If your not, then do so.
{ "pile_set_name": "StackExchange" }
Q: How to get specific MR counters from Hadoop java API? In hadoop ui, we can see standard MR counters in separated columns: map-task, reduce-task and total. But I don't see such methods in hadoop java API. How can we get separated counters from java api, e.g. how to get CPU time spent (ms) values for Map and Reduce columns? A: If you want to get separated task counters, you need to use getTaskReports() method to your hadoop job. After that you can use getTaskCounter() and findCounter() methods to find counter that you need, for each task separately. For example, how to get your map gc-time-millis counter: Long result = 0L; TaskReport[] taskReports = job.getHadoopJob().getTaskReports(TaskType.MAP); for (TaskReport taskReport : taskReports) { try { result += taskReport.getTaskCounters().findCounter(TaskCounter.GC_TIME_MILLIS).getValue(); } catch (Exception ignored) {} }
{ "pile_set_name": "StackExchange" }
Q: How works laravel session storage I am using Session::put('name','value') method to set session in laravel. But when I go to browser developer tools and check session storage there is nothing. Why is that? where is that session data saved A: To see session data, you can use laravel-debugbar to debug sessions, cache, logs, routes, views etc. To install: $ composer require barryvdh/laravel-debugbar --dev $ php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider" You will get a debugbar.php in your config folder, open it and configure what you want to debug. Make sure APP_DEBUG is set to true in your .env file for it to work. View the website and you will see the debugbar at the bottom of your screen.
{ "pile_set_name": "StackExchange" }
Q: Applying machine learning algorithms on Google's Quickdraw dataset I'm trying to apply machine learning algorithms available in python's scikit-learn package to predict doodle names from set of doodle images. Since I'm a complete beginner in machine learning and I have no knowledge about how neural network work yet. I wanted to try with scikit-learn's algorithms. I've downloaded doodles ( of cats and guitars ) with the help of api named quickdraw. Then I load the images with the following code import numpy as np from PIL import Image import random #To hold image arrays images = [] #0-cat, 1-guitar target = [] #5000 images of cats and guitar each for i in range(5000): #cat images are named like cat0.png, cat1.png ... img = Image.open('data/cats/cat'+str(i)+'.png') img = np.array(img) img = img.flatten() images.append(img) target.append(0) #guitar images are named like guitar0.png, guitar1.png ... img = Image.open('data/guitars/guitar'+str(i)+'.png') img = np.array(img) img = img.flatten() images.append(img) target.append(1) random.shuffle(images) random.shuffle(target) Then I applied the algorithm : - from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(images,target,test_size=0.2, random_state=0) from sklearn.naive_bayes import GaussianNB GB = GaussianNB() GB.fit(X_train,y_train) print(GB.score(X_test,y_test)) Upon running the above code (with other algorithms like SVM,MLP too), My system just freezes. I've do a force shutdown to get back. I'm not sure why is this happening. I have tried lowering the number of images to load by changing for i in range(5000): to for i in range(1000): But I only get accuracy around 50% A: First of all, if I may say so: Since I'm a complete beginner in machine learning and I have no knowledge about >how neural network work yet. I wanted to try with scikit-learn's algorithms. This is not a good way to approach ML in general, I strongly suggest you start studying the basics at least, otherwise you won't be able to tell what's going on at all (it's not something you can figure out by trying it). Back to your problem, applying Naive Bayes methods to raw images it's not a good strategy: the problem is that each pixel of your image is a feature and with images you can get a very high number of dimensions easily (also assuming each pixel is independant of its neighbors it's not what you want). NB is commonly used with documents and looking at this example on wikipedia might help you understand a bit more the algorithm. In short, NB boils down to computing joint conditional probabilities, which boils down to counting co-occurences of features (words in wikipedia's example) being co-occurences of pixels in your case, which in turn boils down to computing a huge matrix of occurences that you need to formulate your NB model. Now, if your matrix is made of all the words in a set of documents, this can get pretty expensive in both time and space (O(n^2)/2), with n being the number of features; instead, imagine the matrix being composed of ALL the pixels in your training set, as you're doing in your example... this explodes really fast. That's why cutting your dataset to 1000 images allows your PC to not run out of memory. Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: Convert XML to object in PHP a update values of some node and again convert object to XML? I am dealing with multiple APIs. Please find some steps. Step1 I have got the first API's result as below. Let's say I have got the following response. $xml = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <Response xmlns="http://schemas.martin-group.com/test"> <Result> <![CDATA[ <AccountInfo><CusAccount Action="Add" AccountID="2046369" DesiredCycleID="0" Name="" Corporation="" Cycle=""><AccountType><CusAccountType AccountTypeID="100001" Version="1" AccountTypeCode="BUS " AccountType="Business" MonthlyBillingMethod="P" /></AccountType> <InvoiceFormat><ICInvoiceFormat InvoiceFormatID="1" UserID="10490655" AddressAdjustmentY="0" AddressWidth="3500"/></InvoiceFormat></CusAccount> </AccountInfo>]]> </Result> </Response> </soap:Body> </soap:Envelope>'; Step2 I have converted XML to XML Object. $soap = simplexml_load_string($xml); $soap->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/'); $object = $soap->xpath('//soap:Envelope/soap:Body')[0]->Response; $cdata = $object->Result; $cdata_as_xml = simplexml_load_string($cdata); Step3 I have updated some node's values as follows. 1. $cdata_as_xml->CusAccount['Action'] = 'Edit' 2. $cdata_as_xml->CusAccount['DesiredCycleID'] = '1' 3. $cdata_as_xml->CusAccount->AccountType->CusAccountType['AccountTypeID'] = '1000023' Step4 Now I need this updated XML to pass in another API as body as follows: $xml = '<CusAccount Action="Edit" AccountID="2046369" DesiredCycleID="1" Name="" Corporation="" Cycle=""><AccountType><CusAccountType AccountTypeID="1000023" Version="1" AccountTypeCode="BUS " AccountType="Business" MonthlyBillingMethod="P" /></AccountType> <InvoiceFormat><ICInvoiceFormat InvoiceFormatID="1" UserID="10490655" AddressAdjustmentY="0" AddressWidth="3500"/></InvoiceFormat></CusAccount>'; But $cdata_as_xml something look like as follows: SimpleXMLElement Object ( [CusAccount] => SimpleXMLElement Object ( [@attributes] => Array ( [Action] => Edit [AccountID] => 2046414 [DesiredCycleID] => 1 [Name] => [Corporation] => [Cycle] => ) [AccountType] => SimpleXMLElement Object ( [CusAccountType] => SimpleXMLElement Object ( [@attributes] => Array ( [AccountTypeID] => 1000023 [Version] => 1 [ModifyDate] => 5/21/2009 9:46:00 AM [UserID] => 10120452 [AccountTypeCode] => BUS [AccountType] => Business [MonthlyBillingMethod] => P ) ) ) [InvoiceFormat] => SimpleXMLElement Object ( [ICInvoiceFormat] => SimpleXMLElement Object ( [@attributes] => Array ( [InvoiceFormatID] => 1 [UserID] => 10490655 [AddressAdjustmentY] => 0 [AddressWidth] => 3500 ) ) ) ) ) How can I get pure XML, not XML Object? Any help on this would be appreciated. Thank you. A: Use asXML() to save XML into a file https://www.php.net/manual/en/simplexmlelement.asxml.php If you don't specify a filename, the method will return a string, containing the well-formed XML of the Element.
{ "pile_set_name": "StackExchange" }
Q: Check if m3u8 has a stream c# I'm building a desktop application to check if m3u8 files are valid and have a stream. I tried to include VLC Lib in my project but I had a run time error and I could not include it,then I tried flash object but it did not play m3u8 file.Please advice and thank you. A: You can try these projects for playing m3u8 files WPF-MediaKit and Vlc.DotNet. Now I'm using WPF-MediaKit, although it's redundant to just play m3u8 files.
{ "pile_set_name": "StackExchange" }
Q: Unremovable 0 byte file in data dir A working app of mine started throwing warnings to logcat all of a sudden on my 4.4.4 Kitkat device: W/ContextImpl﹕ Failed to ensure directory: /storage/emulated/0/Android/data/com.example.app/files/Pictures All the photos and other data are unaccessable to the app. After some digging it turns out that there's a seemingly 0 byte file in /storage/emulated/0/Android/data with the package name of my app: com.example.app. No wonder that Android can't create a directory with the same name. I have absolutely no idea how, when and this file got created. Or better to say, how, when and why the original directory got corrupted. The strange thing is, that even though it's listed when I call either list() or listFiles() on the data dir itself, calling exists(), isFile(), isDirectory() on the file itself will all return false. The file seems to have no uid or gid and no date/time associated with it. It can neither be renamed nor deleted. Trying to clear the data of the app will also not remove it, nor will uninstalling the app. What to do now? Changing the package name of the app so that a new directory can be created is obviously not an option here. A: Rebooting removed the file, solving the problem. Still no idea how and why this happened though.
{ "pile_set_name": "StackExchange" }
Q: Css display none not working on div and its contents Having a little trouble with css display:none. The problem is I want to hide a div that contains a repeater on large screens but the div and its contents are still there when testing in the browser. The div I would like to hide has the id imgList I am unsure where the problem lies. Any help would be greatly received. html <div class="row"> <div id="slideShowContainer" class="col-md-12"> <div id="slideShow" class="slideshow "> <div id="slideShowWindow"> <asp:Repeater ID="rptSlides" runat="server" ClientIDMode="Static"> <ItemTemplate> <div class="slide"> <img runat="server" src='<%#DataBinder.Eval(Container.DataItem,"Value") %>' width="650" height="450" /> </div> </ItemTemplate> </asp:Repeater> </div> </div> </div> <div id="imgList" class="col-xs-12"> <asp:Repeater id="rptShowPics" runat="server"> <ItemTemplate> <div class="col-sm-12"> <img src='<%#DataBinder.Eval(Container.DataItem,"Value") %>'/> </div></div> </ItemTemplate> </asp:Repeater> </div> my css: img { width: 100%; height: auto; } @media screen and (min-width: 800px) { #slideShowContainer { display: block; } #imgList { display:none; } #slideShow #slideShowWindow { width: 650px; height: 450px; margin: 0; padding: 0; position: relative; overflow: hidden; margin-left: auto; margin-right: auto; } #slideShow #slideShowWindow .slide { margin: 0; padding: 0; width: 650px; height: 450px; float: left; position: relative; } } @media screen and (max-width:800px) { #imgList { display:block; } #slideShowContainer { display: none; } } As I said I am unsure where the problem lies. the slideshow div display:none works fine and I cant see what is so different to cause such a problem EDIT: the rendered html: <div class="col-sm-12"> <span id="ContentPlaceHolder1_lblError"></span> <div class="row"> <div id="slideShowContainer" class="col-md-12"> <div id="slideShow" class="slideshow "> <div id="slideShowWindow"> <div class="slide"> <img src="Images/portfolioImages/shutterstock_10708540.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_1308456.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_15254098.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_1886302.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_2008768.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_2008770.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_2275868.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_2854978.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_77129413.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_77347582.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_80296861.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_80313958.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_8922649.jpg" width="650" height="450" /> </div> <div class="slide"> <img src="Images/portfolioImages/shutterstock_9754504.jpg" width="650" height="450" /> </div> </div> </div> </div> <div id="imgList" class="col-xs-12"> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_10708540.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_1308456.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_15254098.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_1886302.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_2008768.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_2008770.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_2275868.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_2854978.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_77129413.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_77347582.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_80296861.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_80313958.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_8922649.jpg'/> </div></div> <div class="col-sm-12"> <img src='Images/portfolioImages/shutterstock_9754504.jpg'/> </div></div> </div> Another Edit: Incase it is something to do with my code behind or javascript they are as follows. JavaScript: $(document).ready(function () { var currentPosition = 0; var slideWidth = 650; var slides = $('.slide'); var numberOfSlides = slides.length; var slideShowInterval; var speed = 2000; slideShowInterval = setInterval(changePosition, speed); slides.wrapAll('<div id="slidesHolder"></div>'); slides.css({ 'float': 'left' }); $('#slidesHolder').css('width', slideWidth * numberOfSlides); function changePosition() { if (currentPosition == numberOfSlides - 1) { currentPosition = 0; } else { currentPosition++; } moveSlide(); } function moveSlide() { $('#slidesHolder').animate({ 'marginLeft': slideWidth * (-currentPosition) }); } }); My code behind (c#) protected void Page_Load(object sender, EventArgs e) { string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/portfolioImages/")); List<ListItem> files = new List<ListItem>(); foreach (string filePath in filePaths) { string fileName = Path.GetFileName(filePath); files.Add(new ListItem(fileName, "Images/portfolioImages/" + fileName)); } rptSlides.DataSource = files; rptSlides.DataBind(); rptShowPics.DataSource = files; rptShowPics.DataBind(); } A: I copied your code into a simple html doc and ran it, it worked perfectly in Chrome. I inspected the element, and indeed, when the screen is big, it is hidden, but when small, it shows up. this means that somewhere else in your code there is a style that is overriding your media query. most likely, somewhere in your code (possibly your bootstraps) it is being displayed. to find out where this is doing it, go into chrome or firefox (i use chrome so it might be a tad different in firefox) and right click on the elements that should be hidden and choose inspect element. move up until you are located on the div with id="imgList" and you should be able to see every single CSS style affecting it. crossed out ones are overridden by others, usually ones higher on the list. i bet you will find a display:block that is not crossed out.
{ "pile_set_name": "StackExchange" }
Q: How to correctly store values in an object's instance? I am learning OOP (normally used to functional programming). This small script here runs, but I am not sure how to permanently save data values in the object (in this case the object's instance is named count, and I am trying to store self.count into the instance). #! /usr/bin/python3 class WordCounter: def __init__(self, count = 0): self.__count = count def set_count(self, path): try: nfile = open(path, "r") except: print("Could not open file") fileList = [] lowerCaseList = [] line = nfile.read() fileList.append(line.split()) nfile.close lowerCaseList = [word.lower() for word in fileList[0]] print(lowerCaseList) self.count = len(lowerCaseList) def get_word_count(self): return self.count def __str__(self): return "Total word count is: " + str(self.__count) if __name__ == "__main__": count = WordCounter() print(count) count.set_count("/home/swim/Desktop/word_counter.txt") print(count.get_word_count()) print(count) And here is the output: Total word count is: 0 ['here', 'is', 'a', 'bunch', 'of', 'text.', 'hopefully', 'all', 'of', 'this', 'gets', 'counted', 'correctly.', 'here', 'it', 'goes.'] 16 Total word count is: 0 I can see that my get and set methods are working correctly. But how do I get that self.count variable to be stored in the count object? print(count) evaluates to 0 before and after the get/set. I was hoping the str method would print 16 as well after the line count.set_count("/path/to/my/text/file") Any advice? Thank you A: #! /usr/bin/python3 class WordCounter: def __init__(self, count = 0): self.__count = count def set_count(self, path): try: nfile = open(path, "r") except: print("Could not open file") fileList = [] lowerCaseList = [] line = nfile.read() fileList.append(line.split()) nfile.close() lowerCaseList = [word.lower() for word in fileList[0]] print(lowerCaseList) self.__count = len(lowerCaseList) def get_word_count(self): return self.__count def __str__(self): return "Total word count is: " + str(self.__count) if __name__ == "__main__": count = WordCounter() print(count) count.set_count("/home/swim/Desktop/word_counter.txt") print(count.get_word_count()) print(count) Again thanks roganjosh for pointing out that self.count and self.__count are supposed to be the same property but were given different names.
{ "pile_set_name": "StackExchange" }
Q: Windows phone 7 consume from Controller I have been reading about adding a webservice to an MVC project and how this might conflict with the MVC structure. I added a webservice and it works with windows phone 7, it receives a number, (it's a simple application). I added the webservice by right clicking the Controller folder and selecting add new item->webservice. I am using the SOAP support already integrated in visual studio. I was wondering if there is a way that instead of adding a webservice that the windows phone 7 receives and sends data directly to the controller. The windows phone 7 communicates by right clicking on the solution explorer and adding a service reference. Thanks! i also read ASP.NET MVC & Web Services A: If you're wanting to use the "Add Service Reference" in your WP7 project then you'll most likely need to expose a WCF Web Service from your project. If you're prefer to create a simpler REST based as discussed in ASP.NET MVC & Web Services then you won't be able to use "Add Service Reference" but you can still use the service either through building your own client on top of WebClient, there are few libraries to help with this. I recommend Hammock.
{ "pile_set_name": "StackExchange" }
Q: Permutation P(N,R) of types in compile time I've written a working code for computing P(N,R) for packs when the pack has all different types, e.g. PermutationN<2, P<int, char, bool>> is to be P< P<int, char>, P<int, bool>, P<char, int>, P<char, bool>, P<bool, int>, P<bool, char> > But when there are repeat elements, I'm getting the wrong results. For example, PermutationN<2, P<int, int, char>> should be P< P<int, int>, P<int, char>, P<char, int> > Here is my working code for when all the types are different. I'm stuck on how to adapt it so that it gives correct results when there are repeated types in the pack. Any help would be appreciated. #include <iostream> #include <type_traits> template <typename, typename> struct Merge; template <template <typename...> class P, typename... Ts, typename... Us> struct Merge<P<Ts...>, P<Us...>> { using type = P<Ts..., Us...>; }; template <std::size_t N, typename Pack, typename Previous, typename... Output> struct PermutationNHelper; template <std::size_t N, template <typename...> class P, typename First, typename... Rest, typename... Prev, typename... Output> struct PermutationNHelper<N, P<First, Rest...>, P<Prev...>, Output...> : Merge< // P<Prev..., Rest...> are the remaining elements, thus ensuring that the next // element chosen will not be First. The new Prev... is empty since we now start // at the first element of P<Prev..., Rest...>. typename PermutationNHelper<N-1, P<Prev..., Rest...>, P<>, Output..., First>::type, // Using P<Rest...> ensures that the next set of permutations will begin with the // type after First, and thus the new Prev... is Prev..., First. typename PermutationNHelper<N, P<Rest...>, P<Prev..., First>, Output...>::type > {}; template <std::size_t N, template <typename...> class P, typename Previous, typename... Output> struct PermutationNHelper<N, P<>, Previous, Output...> { using type = P<>; }; template <template <typename...> class P, typename First, typename... Rest, typename... Prev, typename... Output> struct PermutationNHelper<0, P<First, Rest...>, P<Prev...>, Output...> { using type = P<P<Output...>>; }; template <template <typename...> class P, typename Previous, typename... Output> struct PermutationNHelper<0, P<>, Previous, Output...> { using type = P<P<Output...>>; }; template <typename Pack> struct EmptyPack; template <template <typename...> class P, typename... Ts> struct EmptyPack<P<Ts...>> { using type = P<>; }; template <std::size_t N, typename Pack> using PermutationN = typename PermutationNHelper<N, Pack, typename EmptyPack<Pack>::type>::type; // Testing template <typename...> struct P; int main() { std::cout << std::is_same< PermutationN<2, P<int, char, bool>>, P< P<int, char>, P<int, bool>, P<char, int>, P<char, bool>, P<bool, int>, P<bool, char> > >::value << '\n'; // true std::cout << std::is_same< PermutationN<2, P<int, int, int>>, P< P<int, int>, P<int, int>, P<int, int>, P<int, int>, P<int, int>, P<int, int> > >::value << '\n'; // true (but the answer should be P< P<int, int> >. } N.B. I'm looking for an elegant (and efficient) solution that does not simply carry out the above and then merely remove all repeat packs from the output (I can already do that but refuse to write up such an ugly, inefficient solution that does not tackle the heart of the problem), but rather get the correct output directly. That's where I'm stuck. A: The basic idea is to process the initial list of types into a list of (type, count) pairs, and work from there. First, some primitives: template<class, size_t> struct counted_type {}; template<class...> struct pack {}; Our representation is going to be a pack of counted_types. To build it, we need to be able to add a type to it: template<class T, class CT> struct do_push; template<class T, class...Ts, size_t... Is> struct do_push<T, pack<counted_type<Ts, Is>...>>{ using type = std::conditional_t<std::disjunction_v<std::is_same<Ts, T>...>, pack<counted_type<Ts, Is + (std::is_same_v<Ts, T>? 1 : 0)>...>, pack<counted_type<Ts, Is>..., counted_type<T, 1>> >; }; template<class T, class CT> using push = typename do_push<T, CT>::type; If the type is already there, we add 1 to the count; otherwise we append a counted_type<T, 1>. And to use it later, we'll need to be able to remove a type from it: template<class T, class CT> struct do_pop; template<class T, class...Ts, std::size_t... Is> struct do_pop<T, pack<counted_type<Ts, Is>...>>{ using type = remove<counted_type<T, 0>, pack<counted_type<Ts, Is - (std::is_same_v<Ts, T>? 1 : 0)>...>>; }; template<class T, class CT> using pop = typename do_pop<T, CT>::type; remove<T, pack<Ts...>> removes the first instance of T from Ts..., if it exists, and returns the resulting pack (if T doesn't exist, the pack is returned unchanged). The (rather boring) implementation is left as an exercise to the reader. With push we can easily build a pack of counted_types from a pack of types: template<class P, class CT = pack<> > struct count_types_imp { using type = CT; }; template<class CT, class T, class... Ts> struct count_types_imp<pack<T, Ts...>, CT> : count_types_imp<pack<Ts...>, push<T, CT>> {}; template<class P> using count_types = typename count_types_imp<P>::type; Now, the actual implementation is template<class T> struct identity { using type = T; }; template <std::size_t N, typename CT, typename = pack<> > struct PermutationNHelper; // Workaround for GCC's partial ordering failure template <std::size_t N, class CT, class> struct PermutationNHelper1; template <std::size_t N, class... Types, std::size_t... Counts, class... Current > struct PermutationNHelper1<N, pack<counted_type<Types, Counts>...>, pack<Current...>> { // The next item can be anything in Types... // We append it to Current... and pop it from the list of types, then // recursively generate the remaining items // Do this for every type in Types..., and concatenate the result. using type = concat< typename PermutationNHelper<N-1, pop<Types, pack<counted_type<Types, Counts>...>>, pack<Current..., Types>>::type... >; }; template <std::size_t N, class... Types, std::size_t... Counts, class... Current > struct PermutationNHelper<N, pack<counted_type<Types, Counts>...>, pack<Current...>> { using type = typename std::conditional_t< N == 0, identity<pack<pack<Current...>>>, PermutationNHelper1<N, pack<counted_type<Types, Counts>...>, pack<Current...>> >::type; // Note that we don't attempt to evaluate PermutationNHelper1<...>::type // until we are sure that N > 0 }; template <std::size_t N, typename Pack> using PermutationN = typename PermutationNHelper<N, count_types<Pack>>::type; Normally this can be done in one template with two partial specializations (one for N > 0 and one for N == 0), but GCC's partial ordering is buggy, so I dispatched explicitly with conditional. Actually evaluating the pack expansion in PermutationNHelper1 with N equal to 0 will explode horribly, so the unimaginatively named PermutationNHelper1 is introduced to provide an extra level of indirection and prevent the explosion. concat is just a variadic version of your Merge (well, typename Merge<...>::type). The implementation is left as an exercise to the reader.
{ "pile_set_name": "StackExchange" }
Q: multiple bitmaps drawn while rotating I have an activity that rotates png image by the SeekBar progress. And it draws me multiple needles. why it does that? The needle and the speedometer are not perfect, they are just for testings :) In onCreate: @Override public void onCreate(Bundle savedInstanceState) { ... iv = (ImageView)findViewById(R.id.imageView1); bMap = BitmapFactory.decodeResource(getResources(), R.drawable.rodykle); workingBitmap = Bitmap.createBitmap(bMap); mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true); yourCanvas = new Canvas(mutableBitmap); later i use this void public void drawneedle(){ yourCanvas.rotate(speed, mutableBitmap.getWidth()/2, mutableBitmap.getHeight()/2); yourCanvas.save(Canvas.MATRIX_SAVE_FLAG); yourCanvas.drawBitmap(mutableBitmap, 0,0, null); yourCanvas.restore(); iv.setImageBitmap(mutableBitmap); } Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:mtr="http://schemas.android.com/apk/res/com.mindtherobot.samples.thermometer" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="top" android:orientation="vertical" > <SeekBar android:id="@+id/seekBar1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="30dp" android:paddingRight="30dp" android:max="270" /> <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/spidometras" > <ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="fill_parent"/> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40sp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" /> </RelativeLayout> </LinearLayout> A: Do you clear the inner circle of the previously drawn content? You can do that with canvas.drawColor(0, Mode.CLEAR); Also, in my opinion, you need to add the configChanges flag to your activity's tag in the AndroidManifest.xml file, to prevent onCreate to run more than once when activity rotates. android:configChanges="orientation|screenLayout|screenSize|smallestScreenSize" To know that the activity rotated, you need to override the onConfigurationChanged(Config newConfig) method and check the new orientation of the newConfig variable
{ "pile_set_name": "StackExchange" }
Q: Convention for naming table in MySQL database Can I use symbols for the table names in a database? For instance, $tablename %tablename I tested with a select query and they seems OK but I haven't seen anyone done that before so just want to know if it is safe to do. SELECT * FROM $tablename // returns result. SELECT * FROM %tablename // returns result. A: Quick answer: Yes! You can use any symbols your database supports, but that does not mean its a good idea to do so! I would suggest following standard naming conventions for the sake of readability and usability. There are many standard naming conventions listed online and widely accepted and used. Keep in mind your database does not work alone, it interfaces with applications and addons you might want to add later that might not support special characters. A: See documentation on valid identifiers.. You can use these, however you will need to quote any table or column name containing % (at least according to the documentation). $ is valid in unquoted identifiers, but % is not. Permitted characters in unquoted identifiers: ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore) Extended: U+0080 .. U+FFFF Permitted characters in quoted identifiers include the full Unicode Basic Multilingual Plane (BMP), except U+0000: ASCII: U+0001 .. U+007F Extended: U+0080 .. U+FFFF So, it is generally safe to do so, but you'll need to be consistent with quoting identifiers like SELECT * FROM `%tablename`
{ "pile_set_name": "StackExchange" }
Q: Upgrading from 1.9 to 2 - What about the SOAP API? we're thinking of moving from 1.9 to magento 2 in the future. I'd like to estimate the mass of work necessary for the upgrade. I cannot though find any information on how much the SOAP API was changed? Do we need to rewrite everything that uses the API in 1.9 (product sync, order import etc)? And are there significant changes in the data structures: API operations (names, parameters?) have changed i guess Objects and fields changed? Object relations changed? If you have any hint where to look, would be greatly appreciated. Otherwise i would need to examine each API operation we're using, if its still (remotely) compatible. (at the moment we're using the SOAP API v2 in Magento 1.9) A: The entire API has changed in Magento 2. No integration code for 1.x will directly translate, though most of the high-level techniques should be largely the same. You can find the official SOAP documentation here: http://devdocs.magento.com/guides/v2.1/soap/bk-soap.html You may be interested to know Magento 2 has placed a much greater emphasis on the REST API. The API interfaces and functionality should be all but identical for REST vs. SOAP, but the REST documentation is far more extensive, and probably has a lower barrier to entry. http://devdocs.magento.com/guides/v2.1/rest/bk-rest.html To your direct questions: Yes, API operations (names and parameters) have all changed. Objects and fields should be mostly unchanged, at least equivalent. Object relations have not changed.
{ "pile_set_name": "StackExchange" }
Q: Assign a function to a change in QcomboBox I have tried to call a function when there has been a change in the QcomboBox. When the comboBox is changed it will update the xAxis on a graph. Is there a way to call a function when a different item is selected from the comboBox? def updateGraph(): print("update graph") proxy = QtGui.QGraphicsProxyWidget() xAxis = QtGui.QComboBox() proxy.setWidget(xAxis) xAxis.currentIndexChanged().connect(updateGraph) Error that is currently produced: TypeError: native Qt signal is not callable A: Change the line xAxis.currentIndexChanged().connect(updateGraph) to xAxis.currentIndexChanged.connect(updateGraph) With the parentheses in front of currentIndexChanged you are actually calling the signal, when you really want to access the signal's connect method.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to prevent "half-dots" on this border? I'm creating a "lightbulb chain" using the dotted border, but when I make the left and bottom border transparent, it leaves me with these "half-dots", which kills the illusion. Is there anyway to do this without the dots being cut in half? .chain { height: 300px; width: 50px; border: 5px dotted black; border-color: #000 #000 transparent transparent; } <div class="chain"></div> A: You are seeing half-dots because you have set border to all side(top, right, bottom, left). So the fix for this problem is to only set border-top and border-right instead of setting border to all side. .chain { height: 300px; width: 50px; border-top: 5px dotted black; border-right: 5px dotted black; } <div class="chain"></div>
{ "pile_set_name": "StackExchange" }
Q: Can't get JavaScript to check for null objects I really don't know what the issue is here. As far as I can see, the code is simple and should work fine. var Prices=""; for (var PriceCount = 1; PriceCount <= 120; PriceCount++) { var CurrentPrice = "Price" + PriceCount; if (prevDoc.getElementById(CurrentPrice).value != null) { if (Prices == "") { Prices = prevDoc.getElementById(CurrentPrice).value; } else { Prices += "," + prevDoc.getElementById(CurrentPrice).value; } } else { break; } } There could be up to 120 hidden inputs on the form. The moment we check for an input that doesn't exist the loop should break. My test page has two input elements that get pulled. On the third (the null) I get this error in firebug: prevDoc.getElementById(CurrentPrice) is null if (prevDoc.getElementById(CurrentPrice).value != null) { Yes it is null...that's what the check is for ಠ_ಠ Does any one know what I'm doing wrong? This seems like it should be really straight forward. EDIT: for clarity's sake, prevDoc=window.opener.document A: if (prevDoc.getElementById(CurrentPrice).value != null) { can be expanded to: var element = prevDoc.getElementById(CurrentPrice); var value = element.value; /* element is null, but you're accessing .value */ if (value != null) {
{ "pile_set_name": "StackExchange" }
Q: Migrating existing domain to a new domain controller and keeping the server name My current problem is the following migration scenario: Existing domain: Domain-Controller (Windows Server 2003 x86) named "W2003SRV" with domain DOMAIN.LOCAL Terminal-Server 1 (Windows Server 2008 R2 x64) Terminal-Server 2 (Windows Server 2008 R2 x64) Client computers Now we need to replace the Domain Controller with a new machine which will run Windows Server 2008 R2 x64 as well. Normally I would add the new DC to the domain, promote it to new DC, transfer Active Directory FSMO roles, demote the old one and be done with it. However, the proprietory software that we use prohibits any change of the computer name. Adding the new DC to the domain first would mean that I have to give it another name, as the old one is still in use by the existing DC. If I don't migrate the domain at all and create a new domain DOMAIN.LOCAL with the new server only (named W2003SRV like the old one) I would fullfil the criteria of keeping the name. As I would left with a completely new domain all my User SIDs would change, though, and even after recreating the Users and Computers in the Active Directory, a new profile would be forced on every user (with its new SID) and I would spend at least a day setting the new profiles up. What other possibility do I have? I thought about doing it that way and - after the new server has been promoted to DC - changing the name of the new DC to the one of the old DC. However changing the name of the (only) Domain-Controller in the domain doesn't seem that wise... Or am I worrying to much here? I am grateful for every piece of advice! Update: ADMT (Active Directory Migration Tool) from Microsoft (as suggested by TheCleaner) seems to be the way to do it. It keeps the old SIDs in the SID history and thus the profiles would be reusable. I've looked into it and have downloaded the documentation. My only problem with that would be that it transfer AD objects from one Domain to another. I do have 2 domains but as both the server name as well as the domain name would be the same I think that is going to be a problem. Has anybody experiences with ADMT in such a case? A: Add a second server that only runs the software in question. Think of the lifecycle of a domain controller - it will be replaced at some point. This is one of the many reasons why it's a worst practice to install any business software on a domain controller. Alternatively, you could add a new DC, and then dcpromo down the old DC and keep the application on it. A: I would consider two approaches here, with #2 being my first choice. You could always get the domain and forest level up to 2008 R2 and then look at renaming the domain at that point if needed. I would also recommend that if possible you go with a 2012 server, but that might not be possible in your environment. If you think there is good reason to create a new domain, then I would consider going that route and using something like Forensit Profile Wizard to move the profiles over from the old domain to the new one on the computers/TS. Look at using ADMT as well to swing the users over from the old domain. Keep the existing domain and use the advice I was given when I had to do something very similar. See here: Windows 2003 DC to Windows 2008 R2 DC with same name and same IP This worked well for me, and allowed me to keep the name and IP without any issues.
{ "pile_set_name": "StackExchange" }
Q: Converting from list comprehension back to for loops mins = X.min().values #array of min vals maxs = X.max().values #array of max vals test = [] test = { i: [np.random.randint(mins[t], maxs[t]) for t in range(len(mins))] for i in range(k) } or this for c in range(k): indices = [distances.index(row) for row in distances if row[-1] == c] test[c] = X.iloc[indices].mean().values Is it possible to convert this list comprehension back to for loops in python? I'm relatively new to python and am having issues with the syntax. A: You basically just work backwards, so to start with you have: code 1 {i: [np.random.randint(mins[t], maxs[t]) for t in range(len(mins))] for i in range(k)} So the first step is for i in range(k) to generate your keys, followed by something to do with generating a list, or: result = {} for i in range(k): temp = [] # something to do with making a list result[i] = temp Then working backwards again you have for t in range(len(mins)) leaving just the np.random.randint(mins[t], maxs[t]) bit So: result = {} for i in range(k): temp = [] for t in range(len(mins)): temp.append(np.random.randint(mins[t], maxs[t])) result[i] = temp In a full code example it would be import numpy as np mins = [1, 2, 3, 4] maxs = [5, 6, 7, 8] k = 3 test = [] test = { i: [np.random.randint(mins[t], maxs[t]) for t in range(len(mins))] for i in range(k) } print(test) result = {} for i in range(k): temp = [] for t in range(len(mins)): temp.append(np.random.randint(mins[t], maxs[t])) result[i] = temp print(result) Where the first is your comprehension and the second is in for loops. The results: {0: [3, 3, 3, 4], 1: [2, 4, 3, 6], 2: [3, 2, 3, 5]} {0: [4, 3, 4, 4], 1: [3, 3, 4, 4], 2: [3, 2, 6, 4]} You can see we have achieved the same results by deconstructing the comprehension from right to left! case 2 indices = [distances.index(row) for row in distances if row[-1] == c] Can be decomposed the same way. Starting at the back-most for we find: for row in distances if row[-1] == c Which equates to: for row in distances: if row[-1] == c #do something We know it is all wrapped in a list, so adding in a list and appending the "something" to it is pretty straightforward: indices = [] for row in distances: if row[-1] == c: indices.append(distances.index(row)) Note that I haven't tested this one though (and it's also impossible to do so with the information given) If we put this into the original code block of for c in range(k): indices = [distances.index(row) for row in distances if row[-1] == c] test[c] = X.iloc[indices].mean().values We now have for c in range(k): indices = [] for row in distances: if row[-1] == c: indices.append(distances.index(row)) test[c] = X.iloc[indices].mean().values
{ "pile_set_name": "StackExchange" }
Q: How to modify only via CSS a color already defined in HTML? I'm trying to modify a color in a text marked by the tag "U" with the color already defined in html. It is so in html: <u> <font color="#0000c0">somente no seu e-commerce</font> </u> I tried as follows in the css: u {color: rgb (20,20,20)! important; } but I do not accept the color, I believe that the fact is defined in the source code. the important detail, I do not have access to modify the html, as it is generated by web software. all layout modification gotta be done ONLY by CSS. A: Your code is successfully changing the colour of the <u> element, but you can't see any effect because the <font> element does not have color: inherit (and there is no text outside of the <font>). It has its own colour and does not use the <u>'s colour at all. To change that, you need to target the font element. font { color: rgb(20, 20, 20); } <u> <font color="#0000c0">somente no seu e-commerce</font> </u> There is no need for the rule to be !important. There's no CSS of a higher specificity to hammer.
{ "pile_set_name": "StackExchange" }
Q: Substituting password parameter value in bash I have a script running on a Linux box that reads commands and calls a program on certain events. We need to log these commands, but filter/substitute the password parameter when it is used by putting in five Xs in a row (XXXXX). Example of input The input received by the bash script has a command type followed by various parameters and looks like these examples: adduser --username="foo" --password="bar" remove --username="foo" listusers changepass --username="foo" --password="bar" The basic format is command parameter="" parameter=""... Example of logged value The above values would look like this in a log: adduser --username="foo" --password="XXXXX" remove --username="foo" listusers changepass --username="foo" --password="XXXXX" What I have tried I tried to use bash substitution but in the first case, we were not quoting the passwords (we later found out that this would be passed with quotes). It would cut off everything after the password. The second option just does not do the substitution at all. echo "${value%password=*}password=XXXXXX" >> somelog.log echo "${value/password=\"(.*?)\"/password=xxxxx }" >> somelog.log I feel like the second option is close, but I am missing something. If anybody can direct me on this it would be greatly appreciated. A: Is there a requirement to do this natively in bash? It would probably be easier to just pipe through sed. but if you want to use bash I'd suggest the following to change anything prefixed with --password= followed by anything non-space (so it catches quoted and unquoted passwords). I used // in case multiple instances of --password on one line are a requirement. extglob (extended pattern matching) needs to be turned on in your script for this to work. shopt -s extglob "${value//--password=+([! ])/--password=XXXXX }" References: http://wiki.bash-hackers.org/syntax/pattern http://wiki.bash-hackers.org/syntax/pe#search_and_replace Testdata: adduser --username="foo" --password="bar" adduser --username="foo" --password=bar remove --username="foo" listusers changepass --username="foo" --password="bar" --something="else" changepass --username="foo" --password="bar" --something="else" --password="again" Turns into: adduser --username="foo" --password=XXXXX adduser --username="foo" --password=XXXXX remove --username="foo" listusers changepass --username="foo" --password=XXXXX --something="else" changepass --username="foo" --password=XXXXX --something="else" --password=XXXXX Edit: I forgot to mention extglob needs to be activated for this.
{ "pile_set_name": "StackExchange" }
Q: Write a SQL delete based on a select statement How I can make the following query and delete in one query ? select krps.kpi_results_fk from report.kpi_results_per_scene krps inner join report.kpi_results kr on kr.session_uid = '0000c2af-1fc8-4729-bb2a-d4516a63107a' and kr.pk = krps.kpi_results_fk delete from report.kpi_results_per_scene where kpi_results_fk = 'answer from above query' A: I think for your case, NO need to use inner join. Following query could reduce the overhead of inner join DELETE FROM report.kpi_results_per_scene WHERE kpi_results_fk IN (SELECT kr.pk FROM report.kpi_results kr WHERE kr.session_uid = '0000c2af-1fc8-4729-bb2a-d4516a63107a')
{ "pile_set_name": "StackExchange" }
Q: How to append value to Multilevel Dictionary in Swift? I have dictionary in swift var data = ["GenInfo":Dictionary<String,String>(),"LangInfo":Array<String>(),"EduInfo":Array<Dictionary<String,String>>(),"JobInfo":Array<Dictionary<String,String>>(),"SkillInfo":Array<Dictionary<String,String>>()] Now I want to add values to this dictionary, How can I do that. Suppose if I want to add these "FirstName": "Varun", "Email": "[email protected]", "State": "Rajasthan", "Address": "Plot No. 00, Bhagwan Nagar 31,", "Zip": "21354", "Phone": "123456789", "LastName": "Sharma" value to the valueForKey "GenInfo" A: Your where making a Dictionary (i.e. NSDictionary) whose not mutable after it's declaration (unlike NSMutableDictionary). That said, you can either do like this : var data : NSMutableDictionary = ["GenInfo":Dictionary<String,String>(),"LangInfo":Array<String>(),"EduInfo":Array<Dictionary<String,String>>(),"JobInfo":Array<Dictionary<String,String>>(),"SkillInfo":Array<Dictionary<String,String>>()] data["GenInfo"] = ["FirstName": "Varun", "Email": "[email protected]", "State": "Rajasthan", "Address": "Plot No. 00, Bhagwan Nagar 31,", "Zip": "21354", "Phone": "123456789", "LastName": "Sharma" ] data["LangInfo"] = ["English", "French", "Italian"] data["EduInfo"] = [["Degree": "MCA", "School": "University of Kota", "Year": "2013"], ["Degree": "Another degree", "School": "University of London", "Year": "2015"]] // And so on... Or like this : var data = [String: AnyObject]() data["GenInfo"] = [String: String]() // Dictionary<String,String>() data["LangInfo"] = [String]() // Array<String>() data["EduInfo"] = [[String: String]]() // Array<Dictionary<String,String>>() data["JobInfo"] = [[String: String]]() // Array<Dictionary<String,String>>() data["SkillInfo"] = [[String: String]]() // Array<Dictionary<String,String>>() data["GenInfo"] = ["FirstName": "Varun", "Email": "[email protected]", "State": "Rajasthan", "Address": "Plot No. 00, Bhagwan Nagar 31,", "Zip": "21354", "Phone": "123456789", "LastName": "Sharma" ] data["LangInfo"] = ["English", "French", "Italian"] data["EduInfo"] = [["Degree": "MCA", "School": "University of Kota", "Year": "2013"], ["Degree": "Another degree", "School": "University of London", "Year": "2015"]] // And so on...
{ "pile_set_name": "StackExchange" }
Q: grab more results from DB as the user scrolls down the page...what's that called? I'm looking to implement something like Facebook's news feed, where when you load the page 'x' number of results are shown. As the user scrolls down, more results are brought back from the database. What is that called? ....are there any good tutorials out there on it? I'd prefer something in jquery but am open to other suggestions (I am using html, php, jquery, mysql) A: its called 'infinite scroll' here's a jquery library to do that http://www.infinite-scroll.com/
{ "pile_set_name": "StackExchange" }
Q: Umlaute im Fraktursatz Setzt man im Fraktursatz Umlaute auf Großbuchstaben, oder umschreibt man diese mit Ae o.ä.? Ich habe bei der Verwendung der yfonts in LaTeX festgestellt, dass diese fehlen. Wie ist hier die typographische Regel? A: Umlaute werden im Fraktursatz in der Regel mit nachgestelltem e wiedergegeben, wenn es sich bei dem Umlaut um Großbuchstaben (Majuskeln) handelt: Aepfel, Oeſe, Uebung Umlaute als Kleinbuchstaben werden, je nach Schrift, durch ein Trema (¨) oder durch ein übergestelltes kleines e gekennzeichnet. Historischer Nachsatz: Im Mittelalter wurde ein langer Umlaut durch die Ligatur (Æ), ein kurzer Umlaut mit Trema (Ä) oder übergestelltem e (Aͤ ) geschrieben. Mit Aufkommen des Buchdrucks wurden Trema und übergestelltes e bei den Großbuchstaben unüblich, weil die Schriftkegel (der rechteckige Block, der den einzelnen Buchstaben trägt) die Höhe der umlautlosen Großbuchstaben hatten und keinen Platz für Trema oder e boten. Ältere Drucke aus der Zeit des Barock (als die Großschreibung eingeführt wurde) verzichteten deshalb häufig auf die Umlaute und schrieben an ihrer Stelle die nicht umgelauteten Vokale A, O und U (so liest man bei Harsdöffer von den "Apfeln"). Später wurden als Behelf die Punkte oder das e teilweise in den Kreis des O, zwischen die Aufstriche des U oder neben die Spitze des A gestellt. Erst Anfang des 20. Jahrhunderts wurden die Schriftkegel aufgrund eines Beschlusses der Buchdruckerei- und Schriftgießereibesitzer von 1903 entsprechend vergrößert und die typografischen Notbehelfe verschwanden allmählich. A: Ursprünglich wurden statt der heutigen Großbuchstabenumlaute Ae, Oe und Ue genutzt. Die heutigen Umlaute kamen erst Anfang des 20. Jahrhunderts auf, setzten sich dann aber recht schnell durch – auch in der Fraktur. In Duden von 1926 (Fraktur) wird die alte Schreibung bereits gänzlich für falsch erklärt. Vereinzelt gab es auch Schriften, die die alte Form der Umlaute (mit kleinem e über dem Buchstaben) für die Umlaute der Großbuchstaben nutzten.
{ "pile_set_name": "StackExchange" }
Q: asp.net mvc application need access to users google drive account from "service" Im writing a web-app that gives our customers the possibility to SYNC their files on their personal Google Drive onto OUR bushiness application. (only limited file types). So - what works so far: Users signup to the app, (using OAuth2 and saves a refreshtoken in my end) the user/and my app, have now access to files on their Drive, and can manually invoke file transfers. Working fine. Users can afterwards login again and repeat this without having to authenticate the app again. Fine. In parallel, I need some kind "service" that loops thru our app's user-base and AUTOMATICALLY syncs files in a designated folder - say every 10 mins. Now im running into problems because of OAuth2 model, needs to redirect to authenticate every user. But I cannot make multiple redirects out of a single request to, say "/SyncAllUsers". Also, when testing with one user only, the user still have to be logged in into the browser session, or else google will redirect to the service-login page. (We use a chron-job to invoke these methods at a specified interval - and it is working well with dropbox-accounts, and these users also use OAuth) So basically 2 questions: How can I access my users Drive accounts, with my already authorized app, without having users to "be logged in" And how should I handle the sync-service to run without having to redirect at every user. I have spent days searching for answers on https://developers.google.com/drive/ and in here. I have impl. the OAuth code from here https://developers.google.com/drive/credentials#retrieve_oauth_20_credentials and I modified it so it is using my own user-database. For your infomation im using the Client ID for web applications, in Google APIs Console A: Once you have the refresh token, you can use it to perform synchronization without user intervention. This is the nature of offline access and the whole purpose of a refresh token. (Sorry if this doesn't answer your question, I am not exactly sure what you are asking, so please explain more and I will try to give you a different/better answer.)
{ "pile_set_name": "StackExchange" }
Q: How to perform actions on successful login via OAuth2 in jhipster I want to ask how to perform an action after a successful login via OAuth2 and how to veto a login based on some preconditions. I tried to search on Google and found some links but I'm not sure how to do that on this framework. There might be some filter etc I can add but wanted to know the right place to do this. Note: The AuditEvent will not work for me since successful audit is called with every API call. Ref: http://blog.jdriven.com/2015/01/stateless-spring-security-part-3-jwt-social-authentication/ What I need to do is: After successful login, record a few details in a table and send a notification to a queue. In addition to successful login, I also want to perform some action on successful logout which I know I can do here: AjaxLogoutSuccessHandler. However I'm not able to find a similar place for successful login. Before login via OAuth2 if a certain condition is not met, then I can throw an exception and not allow that user. For example, if the user is coming from a particular IP range. Where can I add this? Please guide me in right direction. Thanks A: Create TokenEndpointAuthenticationFilter implementation CustomTokenEndpointAuthenticationFilter.java public class CustomTokenEndpointAuthenticationFilter extends TokenEndpointAuthenticationFilter { public CustomTokenEndpointAuthenticationFilter(AuthenticationManager authenticationManager, OAuth2RequestFactory oAuth2RequestFactory) { super(authenticationManager, oAuth2RequestFactory); } @Override protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { /* on successful authentication do stuff here */ } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { /* before authentication check for condition if true then process to authenticate */ if (!condition) { throw new AuthenticationServiceException("condition not satisfied"); } super.doFilter(req, res, chain); } } Inside AuthorizationServerConfiguration make these changes @Configuration @EnableAuthorizationServer protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Inject private DataSource dataSource; @Inject private JHipsterProperties jHipsterProperties; @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); } /* create OAuth2RequestFactory instance */ private OAuth2RequestFactory oAuth2RequestFactory; @Inject @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { /* assign value in OAuth2RequestFactory instance */ oAuth2RequestFactory = endpoints.getOAuth2RequestFactory(); endpoints .tokenStore(tokenStore()) .authenticationManager(authenticationManager); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { /* register TokenEndpointAuthenticationFilter with oauthServer */ oauthServer .allowFormAuthenticationForClients() .addTokenEndpointAuthenticationFilter(new CustomTokenEndpointAuthenticationFilter(authenticationManager, oAuth2RequestFactory)); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .inMemory() .withClient(jHipsterProperties.getSecurity().getAuthentication().getOauth().getClientid()) .scopes("read", "write") .authorities(AuthoritiesConstants.ADMIN, AuthoritiesConstants.USER) .authorizedGrantTypes("password", "refresh_token", "authorization_code", "implicit") .secret(jHipsterProperties.getSecurity().getAuthentication().getOauth().getSecret()) .accessTokenValiditySeconds(jHipsterProperties.getSecurity().getAuthentication().getOauth().getTokenValidityInSeconds()); } }
{ "pile_set_name": "StackExchange" }
Q: Cual es la mejor forma de guardar el resultado de un inner join y llamar los resultados por un metodo Tengo dos tablas inventario y producto, en producto tengo unos datos y en inventario otros, están ligadas por el numero de producto. En mi código tengo dos objetos que tienen por atributos las columnas de cada tabla. Hasta ahí nada nuevo. Generalmente, cuando consulto una tabla de un solo tipo de objetos guardo los resultados en un ArrayList del tipo objeto (producto, inventario, etc), El asunto es que hare una consulta que me muestre datos de ambas tablas con un join, pero no se como guardar los resultados. En resumen seria una lista multdimensional que es la primera vez que realizo. Alguien que se apiade de mi!!!! Pd Creo que no tengo problemas con la consulta por que jala.. Mi objeto Producto public class Producto implements Serializable { private int Num_Producto; private String NombreProd; private String Clasificacion; private float Precio_Venta; private float Precio_Compra; Mi Objeto Inventario public class Inventario implements Serializable { private int Num_Inventario; private int Producto_Num; private int Cantidad; private int EmpleadoSrv; private String FechaCad; private String Lote; Mi intento de metodo public static ArrayList ***no se como va ****ConsultarProductobyInventario() { PreparedStatement st = null; try { String SQL = "SELECT producto.NombreProd, producto.Clasificacion, producto.Precio_Venta, inventario.Cantidad, inventario.Lote FROM producto join inventario on inventario.Producto_Num = producto.Num_Producto;"; st= conexion().prepareStatement(SQL); ResultSet res = st.executeQuery(); ArrayList<Producto> lista = new ArrayList<>(); Producto prod; while(res.next()){ //aqui menos!!!! prod=new Producto(); prod.setNum_Producto(res.getInt("num_producto")); prod.setNombreProd(res.getString("nombreprod")); prod.setClasificacion(res.getString("clasificacion")); prod.setPrecio_Venta(res.getInt("precio_venta")); prod.setPrecio_Compra(res.getInt("precio_compra")); lista.add(prod); } //st.close(); return lista; } catch (SQLException ex){ Logger.getLogger(EmpresaDAO.class.getName()).log(Level.SEVERE, null, ex); } return null; } A: Por lo que veo usas JDBC a pelo (sin usar Hibernates ni otro framework). Lo mas facil es que crees una clase , que herede, por ejemplo producto, a la que le puedes llamar InventarioProducto y luego le añades los campos de Inventario ;-) public class InventarioProducto extends Producto { ... private int Num_Inventario; private int Cantidad; private int EmpleadoSrv; private String FechaCad; private String Lote; } Y en esa clase metes los resultados de tu query.
{ "pile_set_name": "StackExchange" }
Q: SCSS: Fixed and fluid table-cells I'm building a div-list as a table with scss. I've converted it into css for the demonstartion. The first and the last column is fixed with 90px and 30px. The surrounded link is the table-row | 90px | fluid sdfsdfsdfsdfd sd... | 30px | | 90px | fluid asdasdasd (blank) | 30px | The Table width should be 100%. The width of the fluid part should get automatically 100% - 30px - 90px My plan is to get the fluid width automatically depending on the fixed widths without width: calc(100% - 30px - 90px) The table should not be stretched greater than 100% and the content of the fluid container should be get the nice ellipsis tag. Is there a mistake in my stylesheet? div.menu { display: table; border-collapse: collapse; width: 100%; } div.menu .head { display: table-row; height: 34px; line-height: 34px; } div.menu .head div { padding: 0 5px; display: table-cell; } div.menu .head div:first-of-type { width: 90px; } div.menu .head div:last-of-type { width: 30px; } div.menu a { height: 60px; line-height: 60px; display: table-row; border-top: 1px solid #f2f2f2; text-decoration: none !important; } div.menu a div { display: table-cell; padding: 0 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } div.menu a div:first-of-type { width: 90px; } div.menu a div:last-of-type { width: 30px; } div.menu a:last-of-type { border-bottom: 1px solid #f2f2f2; } <div class="menu"> <div class="head"> <div>Text</div> <div>Name</div> <div></div> </div> <a href="#"> <div>Info</div> <div>Name of the item</div> <div>icon</div> </a> <a href="#"> <div>Info</div> <div>Name of another item</div> <div>icon</div> </a> <a href="#"> <div>Info</div> <div>This is a very long name, and it should not be greater than the page, and i want to see the icon. But it's not working.</div> <div>icon</div> </a> </div> A: Using table-layout: fixed; solves the issue for me. div.menu { display: table; border-collapse: collapse; width: 100%; table-layout: fixed; } JSFiddle example: https://jsfiddle.net/jennifergoncalves/1tv3ygka/ table-layout Documentation: https://www.w3schools.com/cssref/pr_tab_table-layout.asp
{ "pile_set_name": "StackExchange" }
Q: Defining a struct in its own .cpp then using it in main So I tried to define a struct in its own .cpp file (for organization or whatever) and I forward declared it in a header, included the header in the .cpp file, then included the header in main.cpp and tried to create a vector of the struct, and it did not work. However I then took the definition of the struct and put it into main.cpp and it did work. Is this just a quirk of structs that I was unaware of, that they need to be defined in the file that they are used (for some reason)? Here was the code: //people.h struct People; //people.cpp #include people.h struct People { std::string name; int age; }; //main.cpp #include"people.h" #include<vector> std::vector<People> list; A: When compiling main.cpp, the compiler can only see the contents files that have been #included. This means that it can only see struct People; which is a forward declaration, not a full definition. The declaration std::vector<People> needs to know how big a People structure actually is, so the compiler need to see the whole definition. You will need to put the entire struct People { ... }; definition into people.h. (You could copy and paste the definition into main.cpp, but having multiple definitions of a structure is a really bad idea because it's hard to keep them all in sync.) Forward declarations of structures are useful if you only need to use that structure in the context of a pointer or reference to it.
{ "pile_set_name": "StackExchange" }
Q: Regex to matches a url with or without http in java I want to validate a url that is with or without http. i tried ^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]* But this is matches http://google.com but not www.google.com. i want a regex that matches www.google.com too. Thanks A: Try starting your regex with ^(https?://)? instead of ^http(s{0,1}):// A: ^(?:https?://)? ... the rest of your regex ?: means do not capture group ? quantifier minification (match if exists, if not - omit it) P.S. I'm not sure if quantifier minification makes sense to english native speakers, this is a rough translation from russian :) Hopefully, if I'm mistaken, somebody understands what I meant and could fix me.
{ "pile_set_name": "StackExchange" }
Q: How do you find these equations that explain a infectious disease? (SIR model) I have the following model for a infectious disease spread, but can't figure out why they chose the equations they chose. (I know it is closely related to the standard SIR model) Let $G$ be a network with $N$ nodes. Let $S_k(t), I_k(t), R_k(t)$ be the proportion of the population with $k$ connections that is respectively susceptible, infected and recovered by the virus at the time t. Let $\alpha$ be the probability that a susceptible node will be infected per unit time if it is connected to one or more infected nodes. Let $\beta$ be the probability that we detect the virus and remove it. Let$\theta (t)$ the proportion of edges in G that connect to infected nodes at time t. Then we model the problem by $$\frac{dS_k(t)}{dt} = -\alpha k S_k(t)\theta(t)$$ $$\frac{dI_k(t)}{dt} = -\beta I_k(t) + \alpha k S_k(t)\theta(t) $$ $$\frac{dR_k(t)}{dt}= \beta I_k(t)$$ How do you get this equations? I mean, why does it make sense to have (for instance) the equation $$\frac{dS_k(t)}{dt} = -\alpha k S_k(t)\theta(t)$$ such that it models the susceptible fraction of the population? In other words, how can I interpret this equations (geometrically, a priori)? A: Actually it's not quite right. For each connection of a susceptible and an infective, the rate at which infection occurs (on the average) is $\alpha$. When there are $S_k$ susceptibles having $k$ connections, and fraction $\theta$ of all connections of susceptibles are to infectives, that makes $k S_k \theta$ connections from susceptibles to infectives, the total rate is $\alpha k S_k \theta$ infections per unit time. Each of those infections decreases $S_k$ by one and increases $I_k$ by one, so that's where they get the $$ \dfrac{d S_k}{dt} = - \alpha k S_k(t) \theta(t)$$ and also the term $+\alpha k S_k(t) \theta(t)$ in $dI_k/dt$. The part that's wrong is that $\theta(t)$ is the fraction of all connections in the graph that are to infectives, not the fraction of connections of susceptibles. These are not likely to be the same. For example, we might imagine a scenario in which there are two distinct subpopulations which are not connected to each other at all, and you start out with some infectives in subpopulation 1 but none in subpopulation 2. After a while, nearly everybody in subpopulation 1 is infective, but everyone in subpopulation 2 is still susceptible and will remain so, despite that fact that $\theta$ (which measures connections to susceptibles in the population as a whole) is near $1/2$.
{ "pile_set_name": "StackExchange" }
Q: What is the safest way to pass strings around in C? I have a program in C using Solaris with VERY ancient compatibility it seems. Many examples, even here on SO, don't work, as well as lots of code I've written on Mac OS X. So when using very strict C, what is the safest way to pass strings? I'm currently using char pointers all over the place, due to what I thought was simplicity. So I have functions that return char*, I'm passing char* to them, etc. I'm already seeing strange behavior, like a char* I passed having its value right when I enter a function, and then the value being mysteriously gone OR corrupted/overwritten after something simple like one printf() or an malloc to some other pointer. One approach to the functions, which I'm sure is incorrect, could be: char *myfunction(char *somestr) { char localstr[MAX_STRLENGTH] = strcpy(localstr, somestr); free(somestr); /* ... some work ... */ char *returnstr = strdup(localstr); return returnstr; } This seems...sloppy. Can anyone point me in the right direction on a simple requirement? Update One example of a function where I am at a loss for what is happening. Not sure if this is enough to figure it out, but here goes:' char *get_fullpath(char *command, char *paths) { printf("paths inside function %s\n", paths); // Prints value of paths just fine char *fullpath = malloc(MAX_STRLENGTH*sizeof(char*)); printf("paths after malloc %s\n", paths); // paths is all of a sudden just blank } A: Well-written C code adheres to the following convention: All functions return a status code of type int, where a return value of 0 indicates success, and a -1 indicates failure. On failure, the function should set errno with an appropriate value (e.g. EINVAL). Values that are "reported" by a function should be reported via the use of "out parameters". In other words, one of the parameters should be a pointer to the destination object. Ownership of pointers should belong to the invoker; consequently, a function should not free any of its parameters, and should only free objects that it, itself, allocates with malloc/calloc. Strings should be passed either as const char* objects or as char* objects, depending on whether the string is to be overwritten. If the string is not to be modified, then const char* should be used. Whenever an array is passed that is not a NUL-terminated string, a parameter should be provided indicating the the number of elements in the array or the capacity of that array. When a modifiable string/buffer (i.e. char*) object is passed into a function, and that function is to overwrite, append, or otherwise modify the string, a parameter indicating the capacity of the string/buffer needs to be provided (so as to allow for dynamic buffer sizes and to avoid bufffer overflow). I should point out that in your example code, you are returning localstr and not returnstr. Consequently, you are returning an address of an object in the current function's stack frame. The current function's stack frame will disappear once the function has returned. Invoking another function immediately afterwards will likely alter the data in that location, leading to the corruption that you have observed. Returning the address of a local variable leads to "undefined behavior" and is incorrect. Edit Based on your updated code (get_fullpath), it is clear that the problem is not in your function get_fullpath, but rather in the function that is calling it. Most likely, the paths variable is being supplied by a function that returns the address of a local variable. Consequently, when you create a local variable within get_fullpath, it is using the same exact location on the stack that paths previously occupied. Since "paths" is aliasing "fullpaths", it is basically overwritten with the address of the buffer that you've malloced, which is blank. Edit 2 I have created a C Coding Conventions page on my website with more detailed recommendations, explanations, and examples for writing C code, in case you are interested. Also, the statement that localstr is being returned instead of returnstr is no longer true since the question has last been edited. A: You can't return a pointer to an array that's allocated locally within the function. As soon as the function returns, that array is going to be clobbered. Also, when you put char localstr[MAX_STRLENGTH] = strcpy(localstr, somestr); what happens is that strcpy() will copy the bytes into the localstr[] array, but then you have an unnecessary assignment thing going on. You could probably get the intended effect as two lines, thus .. char localstr[MAX_STRLENGTH]; strcpy(localstr, somestr); Also, it's bad form to embed a free() call inside a function like this. Ideally the free() should be visible at the same level of scope where the malloc() occurred. By the same logic it's a little dubious to allocate memory down in a function this way. If you want a function to modify a string, a common convention goes something like so // use a prototype like this to use the same buffer for both input and output int modifyMyString(char buffer[], int bufferSize) { // .. operate you find in buffer[], // leaving the result in buffer[] // and be sure not to exceed buffer length // depending how it went, return EXIT_FAILURE or maybe return EXIT_SUCCESS; // or separate input and outputs int workOnString(char inBuffer[], int inBufSize, char outBuffer[], int outBufSize) { // (notice, you could replace inBuffer with const char *) // leave result int outBuffer[], return pass fail status return EXIT_SUCCESS; Not embedding malloc() or free() inside will also help avoid memory leaks.
{ "pile_set_name": "StackExchange" }
Q: How to use electrum RPC to get address balance on windows $ ./electrum-3.2.3.exe --testnet setconfig rpcport 7777 true $ ./electrum-3.2.3.exe --testnet setconfig rpcuser blah true $ ./electrum-3.2.3.exe --testnet setconfig rpcpassword blah true $ ./electrum-3.2.3.exe --testnet daemon start Traceback (most recent call last): File "run_electrum", line 433, in <module> AttributeError: module 'os' has no attribute 'fork' I can't install on linux as centos 7.5 can't compile python3. I won't try any further since I have already wasted a day on compilation issues. $ ./electrum-3.2.3.exe --testnet starts up a gui client which is fine $ curl --data-binary '{"id":"curltext","method":"blockchain.scripthash.get_balance","params":["mveNDYcr9Bb1xjnNeCRumiDHKU3n3CJBuk"]}' http://blah:[email protected]:7777 {"result": null, "id": "curltext", "error": {"code": -32601, "message": "Method blockchain.scripthash.get_balance not supported."}} $ curl --data-binary '{"id":"curltext","method":"get_balance","params":["mveNDYcr9Bb1xjnNeCRumiDHKU3n3CJBuk"]}' http://blah:[email protected]:7777 {"result": null, "id": "curltext", "error": {"code": -32601, "message": "Method get_balance not supported."}} $ curl --data-binary '{"id":"curltext","method":"getbalance","params":["mveNDYcr9Bb1xjnNeCRumiDHKU3n3CJBuk"]}' http://blah:[email protected]:7777 {"result": null, "id": "curltext", "error": {"code": -32601, "message": "Method getbalance not supported."}} I also tried without specifying the bitcoin address with the same results. https://bitcointalk.org/index.php?topic=1894185.0 discusses the same issue and states isnt giving an error about the wallet being loaded, which is why I am getting the error above. Assuming the poster didn't mean "isn't" but rather "is", how would I "unload the wallet"? note: mveNDYcr9Bb1xjnNeCRumiDHKU3n3CJBuk is an address in electrum's wallet A: Turns out that electrum doesn't have to be in daemon mode to receive api requests, but it has to be in daemon mode before it supports them.
{ "pile_set_name": "StackExchange" }
Q: Does the Académie Française set out how to format currencies? I know Académie Française covers orthography beyond just how to spell words. I also know Académie Française encompasses differences between the various French-using countries. I'm interested to know if Académie Française clarifies how to format references to amounts of money, including: Whether the currency symbol is to the left or right of the price Whether using a symbol such as $, £, € means a different format to using USD, EUR, CHF Which symbol to use as thousands separator Which symbol to use as decimal point Whether different French-using countries differ on any of these points Whether the rules also cover the formatting of foreign currencies There is an article on Wikipedia which lists in a table: € Language Euro sign usage French 6,28 € But I want to know what the Academy has to say. A: Here are some answers: Whether the currency symbol is to the left or right of the price AFAIK, the currency symbol is to the right side of the price: 123 € Which symbol to use as thousands separator Use a thin space for number with more than 3 digit long (i.e. 1 000 €, 10 000 €) Which symbol to use as decimal point ALWAYS use a comma: 123,45 € Whether the rules also cover the formatting of foreign currencies This is valid for any currency and also for any unit: 12 345,67 kg Reference Académie Française (especially §3) A: To complete @M42 answer, I'll add that we should use 1,23 € but use a lot 1€23 in France, to write it like we say it. In particular, the latter is used on many price tags.
{ "pile_set_name": "StackExchange" }
Q: Program Crashes on Debugging I am new to C# this is kind of my first program. I am trying to integrate a SOAPI from OVH.IE (more info here: www.ovh.ie/products/soapi.xml), but whenever I launch the program and click the login button the program crashes (memory usage of VS2012 increases and then crashes). using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Web.Services; namespace Server_Manager { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { textBox1.Clear(); textBox2.Clear(); } void login(string uid, string pwd, string dc) { if (dc == "OVH") { managerService soapi = new managerService(); string session = soapi.login(uid, pwd, "ie", false); if (String.IsNullOrWhiteSpace(session)) { MessageBox.Show("Not Logged"); } else { MessageBox.Show("Logged In"); } } } private void button1_Click(object sender, EventArgs e) { if (String.IsNullOrWhiteSpace(textBox1.Text) || String.IsNullOrWhiteSpace(textBox1.Text)) { MessageBox.Show("Please Fill all the Details"); } else { string uid, pwd, dc; uid = textBox1.Text; pwd = textBox2.Text; dc = comboBox1.Text; login(uid,pwd,dc); } MessageBox.Show(comboBox1.Text); } } } A: These instructions are for diagnosing this in WinDBG, a command line based debugger from microsoft, but I have been told they can work in Visual Studio. Start up the application Start up WinDBG and attach to the application Type in ".loadby sos clr" (assuming >=4.0 framework) Type "dumpheap -stat" Look over the results, for suspicious objects type "dumpheap -mt {0}" where {0} is replaced by the objects MT address If you don't know why objects are alive, type "gcroot {0}" passing an object address from above
{ "pile_set_name": "StackExchange" }
Q: How to add variables to prefix path? Ansible 2.3 Below is the code: - name: List keys simple s3: bucket: mybucket mode: list prefix: "/{{a}}/{{b}}/tmp/" register: foo - name: when you need the result debug: msg: 'print this' when: "{{foo.s3_keys |length}} > 0" where variables a & b are used Can we avoid double quotes(" ") for prefix: & when:? A: If you consistently use double quotes for your strings you will avoid a number of common errors. For example, this: somestring: yes Will not actually set somestring to the string value yes (you actually get the boolean value true). And this: somestring: 12:34 Will not set somestring to the string value 12:34 (you actually get 754). In other words, you need double quotes in a number of situations you might not expect, so you're better off using them whenver you have a string value. With respect to your specific question: The value for prefix: does not require double quotes. This is fine: - name: List keys simple s3: bucket: mybucket mode: list prefix: /{{a}}/{{b}}/tmp/ register: foo This works because the value does not start with a character that has any special meeting to YAML. On the other hand, you need to use double quotes in your when: statement, because the value starts with a {, which in YAML indicates the start of a dictionary.
{ "pile_set_name": "StackExchange" }
Q: Write Unit Test In Different Package Calling Private/Protected Methods Using Intellij I realize this question has been asked before here -> How to create a test directory in Intellij 13? However, the answer is not working for me and I can't figure out why... Intellij Version: IntelliJ IDEA 2016.1.4 Build #IC-145.2070, built on August 2, 2016 JRE: 1.8.0_77-b03 x86 JVM: Java HotSpot(TM) Server VM by Oracle Corporation MyApp.java package main.java.com.simpleproject; public class MyApp { private int updNum; public MyApp(int givenNum){ this.updNum = givenNum; } private void updateNumPlusTwo(){ this.updNum += 2; } protected int getUpdatedNum(){ return this.updNum; } } MyAppTest.java package test.java.com.simpleproject; import main.java.com.simpleproject.MyApp; public class MyAppTest { public static void main(String[] args) { MyApp app = new MyApp(4); app.getUpdatedNum(); app.updateNumPlusTwo(); } } The package/directory tree: The Issue: What I have tried: Anyone have any idea how to get this to work? A: Your sources directories and packages are wrong. You have chosen the Maven default sources directories structure of src/main/java for production code, and src/test/java for test code. You should declare both directories as source folders in IntelliJ (Project Structure -> Modules -> select the folders and click on Sources for src/main/java and Tests for src/test/java) Your packages should be the same: com.simpleproject. The problem is that you have declared 2 different packages (main.java.com.simpleproject and test.java.com.simpleproject) that's why you cannot call a protected method. It is not possible to call a private method, from the same or different package. You have to use reflection for that. But preferably you should at least put your method protected or package default. Your test should use JUnit, not a main method. Something like : package com.simpleproject; import static org.assertj.core.api.Assertions.assertThat; public class Test { @Test public void shouldTestMyClass() { // Given int givenNum = 3; // When MyApp myApp = new MyApp(givenNum); myApp.updateNumPlusTwo(); // Then (use AssertJ library for example) assertThat(myApp.getUpdatedNum()).isEqualTo(5); } }
{ "pile_set_name": "StackExchange" }
Q: MySQL query: Updating foreign key with unique Id I need to link two tables 1-to-1, but the values that are to be compared and linked upon, are not unique. I cannot find a way. As an example, I added a very simple version. CREATE TABLE `T1` ( `id` int(6) unsigned NOT NULL, `cmp` int(3) NOT NULL, `uniqueT2Id` int(3) unsigned, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `T2` ( `id` int(6) unsigned NOT NULL, `cmp` int(3) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8; INSERT INTO `T1` (`id`, `cmp`, `uniqueT2Id`) VALUES ('1', '1', NULL), ('2', '1', NULL), ('3', '2', NULL), ('4', '3', NULL), ('5', '1', NULL); INSERT INTO `T2` (`id`, `cmp`) VALUES ('1', '1'), ('2', '1'), ('3', '1'), ('4', '2'), ('5', '3'); UPDATE T1 SET uniqueT2Id= (SELECT id FROM T2 WHERE T2.cmp=T1.cmp AND id NOT IN (SELECT * FROM (SELECT uniqueT2Id FROM T1 WHERE uniqueT2Id IS NOT NULL) X) ORDER BY id ASC LIMIT 1); SELECT * FROM T1; http://sqlfiddle.com/#!9/3bab7c/2/0 The result is id cmp uniqueT2Id 1 1 1 2 1 1 3 2 4 4 3 5 5 1 1 I want it to be id rev uniqueT2Id 1 1 1 2 1 2 3 2 4 4 3 5 5 1 3 In the UPDATE I try to pick an Id that is not already used, but this obviously does not work. Does anyone know a way to do this in MySQL, preferrably without PHP? A: I found an answer myself, with variables. It is horrible and requires a dummy field in the table, but it works. I am open for improvements. CREATE TABLE `T1` ( `id` int(6) unsigned NOT NULL, `cmp` int(3) NOT NULL, `uniqueT2Id` int(3) NULL, `dummy` varchar(200) NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `T2` ( `id` int(6) unsigned NOT NULL, `cmp` int(3) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8; INSERT INTO `T1` (`id`, `cmp`, `uniqueT2Id`) VALUES ('1', '1', NULL), ('2', '1', NULL), ('3', '2', NULL), ('4', '5', NULL), ('5', '3', NULL), ('6', '1', NULL); INSERT INTO `T2` (`id`, `cmp`) VALUES ('1', '1'), ('2', '1'), ('3', '1'), ('4', '2'), ('5', '3'); SET @taken = '/' ; UPDATE T1 SET uniqueT2Id= @new:= (SELECT id FROM T2 WHERE T2.cmp=T1.cmp AND INSTR(@taken, CONCAT('/',id,'/')) = 0 ORDER BY id ASC LIMIT 1), dummy=IF(@new IS NOT NULL,@taken:=CONCAT(@taken, @new, "/"),NULL); http://sqlfiddle.com/#!9/4a61d/1/0
{ "pile_set_name": "StackExchange" }
Q: Declaring List before for loop in java Below program gives output : 4 4 4 4 4 package HelloWorld; import java.util.List; import com.google.common.collect.Lists; public class HelloWorld { public static void main(String args[]) { List<Product> productList = Lists.newArrayList(); **Product product = new Product();** for (int i = 0; i < 5; i++) { product.setId("id:" + i); productList.add(product); } // Printing values for (int i = 0; i < productList.size(); i++) { System.out.println(productList.get(i).getId()); } } } This is because Product is declared outside the loop. But see another program : package HelloWorld; import java.util.List; import com.google.common.collect.Lists; public class HelloWorld { public static void main(String args[]) { **List<String> list = Lists.newArrayList();** for(int i=0;i<5;i++){ list.add(""+i); } for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } } This gives output : 0 1 2 3 4 May i know why is it printing 0 1 2 3 4 even if the list is declared out side the for loop? I expected it to print 4 4 4 4 4 A: product is defined outside the for loop, so each time you are doing product.setId("id:" + i); you are overriding the id of the same instance and adding it again to the list. Create the product instance inside the loop List<Product> productList = Lists.newArrayList(); for (int i = 0; i < 5; i++) { Product product = new Product(); product.setId("id:" + i); productList.add(product); }
{ "pile_set_name": "StackExchange" }
Q: LT3081 Precision Current Limit Programming I am trying to precisely control current limit of the LT3081 IC following this paper, page 12, schematic on page 14, but by using a microcontroller. I'm controlling the output voltage with a 10kOhm, 8 bit, digital potentiometer, which I feed with 1.2mA constant current to make it regulate the output voltage between 0 and 12 V. I'm trying to limit the output current from 1 mA to 1A, idealy with 1 mA step, without using more expensive 10 bit digital pots. By using a similar configuration as shown in the schematic for higher accuracy (pot + paralel res + series res), using one 10k, 8 bit, digital pot and considering the wiper resistance, I got to a point where I can control the current limit with a 7 mA step at lower values, and 2 mA steps as I get closer to 1 A limit. Spreadsheet for 10k 8b values: link Equation for current limit(from datasheet): RILIM = ILIMIT/360mA/kΩ + 450Ω Simplified equation: RILIM = ((ILIM*1000)/0.36) + 450 Simplified schematic: simulate this circuit – Schematic created using CircuitLab My question is: Is there any other way for a more precise current limit control without using a higher step count (bit) digital pot? A: An 8 bit pot gives you 2^8 possible taps (256) so at best you could manage slightly under 4mV steps. A 10 bit pot has 2^10 steps (1024) so in theory could give you your 1mA resolution in a suitable circuit. You are going to need a digipot that can handle 12V on the element, not a given as most of them are limited to within the logic supply voltage. Were it me, I would be thinking in terms of setting a fixed current limit with this mechanism, then doing the current limit by using the Imon pin and an opamp or such to pull the set pin down on overcurrent, this has the advantage that such things as foldback limiting become possible, and both your control signals are now ground referenced and can be trivially generated.
{ "pile_set_name": "StackExchange" }
Q: How can I search the disabled AD account in the people picker of Sharepoint 2016? I'm using Sharepoint 2016. How can I search the diabled AD accounts in the people picker control? Thanks. A: This behaviour is "by design". So theres only one workaround: create a custom claims provider for peoplepicker Refer: Plan for custom claims providers for People Picker in SharePoint 2013
{ "pile_set_name": "StackExchange" }
Q: zsh for loop exclusion This is somewhat of a simple question, but for the life of me, I cannot figure out how to exclude something from a zsh for loop. For instance, let's say we have this: for $package in /home/user/settings/* do # do stuff done Let's say that in /home/user/settings/, there is a particular directory ("os") that I want to ignore. Logically, I tried the following variations: for $package in /home/user/settings/^os (works w/ "ls", but not with a foor loop) for $package in /home/user/settings/*^os for $package in /home/user/settings/^os* ...but none of those seem to work. Could someone steer my syntax in the right direction? A: It looks to me that the extra $ may be what's causing your grief. Try this: for package in /home/user/settings/^os; do echo "Doing stuff with ${package}..." done If you want to limit ${package} to just directories, use /home/user/settings/^os(/). Also ensure that you have extendedglob set (which I think you do since ls works for you): > set -o | grep -i extendedglob extendedglob on
{ "pile_set_name": "StackExchange" }
Q: if fall through What's the Haskell equivalent pattern for if fall through in imperative languages, like: function f (arg, result) { if (arg % 2 == 0) { result += "a" } if (arg % 3 == 0) { result += "b" } if (arg % 5 == 0) { result += "c" } return result } A: Instead of using the State monad, you can also use the Writer monad and take advantage of String's Monoid instance (really [a]'s Monoid instance): import Control.Monad.Writer f :: Int -> String -> String f arg result = execWriter $ do tell result when (arg `mod` 2 == 0) $ tell "a" when (arg `mod` 3 == 0) $ tell "b" when (arg `mod` 5 == 0) $ tell "c" Which I think is pretty succinct, clean, and simple. One advantage this has over the State monad is that you can rearrange order in which concatenations happen by just rearranging the lines. So for example, if you wanted to run f 30 "test" and get out "atestbc", all you have to do is swap the first two lines of the do: f arg result = execWriter $ do when (arg `mod` 2 == 0) $ tell "a" tell result when (arg `mod` 3 == 0) $ tell "b" when (arg `mod` 5 == 0) $ tell "c" Whereas in the State monad you'd have to change the operation: f arg = execState $ do when (arg `mod` 2 == 0) $ modify ("a" ++) when (arg `mod` 3 == 0) $ modify (++ "b") when (arg `mod` 5 == 0) $ modify (++ "c") So instead of having a relationship between execution order and order in the output string, you have to examine the actual operations closely (there's a subtle difference between (++ "a") and ("a" ++)), while the Writer code is very clear at first glance in my opinion. As @JohnL has pointed out, this is not exactly an efficient solution since concatenation on Haskell Strings is not very fast, but you could pretty easily use Text and Builder to get around this: {-# LANGUAGE OverloadedStrings #-} import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.Builder as B import Control.Monad.Writer f :: Int -> Text -> Text f arg result = B.toLazyText . execWriter $ do tellText result when (arg `mod` 2 == 0) $ tellText "a" when (arg `mod` 3 == 0) $ tellText "b" when (arg `mod` 5 == 0) $ tellText "c" where tellText = tell . B.fromLazyText And so there's no real change to the algorithm other than conversion to more efficient types. A: The function can be written quite succinctly, provided that we're willing to somewhat obscure the logic of the original imperative version: f :: Int -> String -> String f arg = (++ [c | (c, n) <- zip "abc" [2, 3, 5], mod arg n == 0]) Monad comprehensions can reproduce the original logic nicely: {-# LANGUAGE MonadComprehensions #-} import Data.Maybe import Data.Monoid f :: Int -> String -> String f arg res = maybe res (res++) $ ["a" | mod arg 2 == 0] <> ["b" | mod arg 3 == 0] <> ["c" | mod arg 5 == 0] However, it isn't a very commonly used language extension. Luckily for us (hat tip to Ørjan Johansen in the comments), there is already built-in comprehension sugar for the list monad, which we can also use here: f :: Int -> String -> String f arg res = res ++ ['a' | mod arg 2 == 0] ++ ['b' | mod arg 3 == 0] ++ ['c' | mod arg 5 == 0] A: Using the State monad as Jan Dvorak's comment suggested: import Control.Monad.State f :: Int -> String -> String f arg = execState $ do when (arg `mod` 2 == 0) $ modify (++ "a") when (arg `mod` 3 == 0) $ modify (++ "b") when (arg `mod` 5 == 0) $ modify (++ "c")
{ "pile_set_name": "StackExchange" }
Q: How can I convert a input string into dictionary for each rows of a column in pyspark I have a column values of a dataframe where I am receiving a string input like below where startIndex is the index of beginning of each character, end index is the end of occurrence of that character in the string and flag is the character itself. +---+------------------+ | id| Values | +---+------------------+ |01 | AABBBAA | |02 | SSSAAAA | +---+------------------+ Now I want to convert the string into dictionary for each rows as depicted below: +---+--------------------+ | id| Values | +---+--------------------+ |01 | [{"startIndex":0, | | | "endIndex" : 1, | | | "flag" : A }, | | | {"startIndex":2, | | | "endIndex" : 4, | | | "flag" : B }, | | | {"startIndex":5, | | | "endIndex" : 6, | | | "flag" : A }] | |02 | [{"startIndex":0, | | | "endIndex" : 2, | | | "flag" : S }, | | | {"startIndex":3, | | | "endIndex" : 6, | | | "flag" : A }] | +---+--------------------+- I have the pseudo code to frame the dictionary but not sure how to apply it to all the rows at one go without using loops. Also the problem with such approach is only the last framed dictionary is getting overwritten in all the rows import re x = "aaabbbbccaa" xs = re.findall(r"((.)\2*)", x) print(xs) start = 0 output = '' for item in xs: end = start + (len(item[0])-1) startIndex = start endIndex = end qualityFlag = item[1] print(startIndex, endIndex, qualityFlag) start = end+ A: Using udf() to wrap up the code logic and to_json() to convert the array of structs into string: from pyspark.sql.functions import udf, to_json import re df = spark.createDataFrame([ ('01', 'AABBBAA') , ('02', 'SSSAAAA') ] , ['id', 'Values'] ) # argument `x` is a StringType() over the udf function # return `row` as a list of dicts @udf('array<struct<startIndex:long,endIndex:long,flag:string>>') def set_fields(x): row = [] for m in re.finditer(r'(.)\1*', x): row.append({ 'startIndex': m.start() , 'endIndex': m.end()-1 , 'flag': m.group(1) }) return row df.select('id', to_json(set_fields('Values')).alias('Values')).show(truncate=False) +---+----------------------------------------------------------------------------------------------------------------------------+ |id |Values | +---+----------------------------------------------------------------------------------------------------------------------------+ |01 |[{"startIndex":0,"endIndex":1,"flag":"A"},{"startIndex":2,"endIndex":4,"flag":"B"},{"startIndex":5,"endIndex":6,"flag":"A"}]| |02 |[{"startIndex":0,"endIndex":2,"flag":"S"},{"startIndex":3,"endIndex":6,"flag":"A"}] | +---+----------------------------------------------------------------------------------------------------------------------------+
{ "pile_set_name": "StackExchange" }
Q: Error when I send email of Marketing cloud in salesforce when I send a email of Marketing cloud in salesforce when I preview email I got a error 'Error retrieving subscriber data: [E131] We couldn't retrieve the Contact/Lead information for the Marketing Cloud. Make sure you have permission to access email opt out and try again' pls suggest me if there is any solution for that ? Thanks ! A: Make sure your user has the needed permission sets for Marketing Cloud Connect applied, as well as having the Sales/Service Cloud User integrated with a Marketing Cloud user with the correct permissions. Field level security settings on the Contact/Lead object's opt out field could also have an impact on the email send. If that doesn't help there may be a problem with the API user integration. Possible reasons summarized: Necessary permission sets not applied Sales/Service Cloud user not integrated with Marketing Cloud user Field level security not set correctly API user integration faulty Related information: Manage Users Troubleshooting Guide Troubleshoot Connected App Update Field Level Security
{ "pile_set_name": "StackExchange" }
Q: Creating multiple themes in a single ionic 2 app We are currently migrating a hybrid application from a selfmade framework to ionic 2. In the old app we had multiple sass files that compiled into a singe css file containing different themes that were applied to the app by switching a class on the body (like ".skin-red"). Is there a way to achieve that with the $varaiables map of ionic or will i have to create multiple style files with a custom written task and change the used css file at runtime with js code? (which i'd rather not do) A: Follow this User-Selected Style Themes in an Ionic 2 Application tutorial. Or you can set all colors using ts variable and update color hash code run time. HTML: <ion-header> <ion-toolbar color="primary" [style.background]="headerBackground"> <ion-title> </ion-title> </ion-toolbar> </ion-header> TS: public headerBackground = '#ddd'; Should be shared variable.
{ "pile_set_name": "StackExchange" }
Q: Android Architecture Components: bind to ViewModel I'm a bit confused about how data binding should work when using the new Architecture Components. let's say I have a simple Activity with a list, a ProgressBar and a TextView. the Activity should be responsible for controlling the state of all the views, but the ViewModel should hold the data and the logic. For example, my Activity now looks like this: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_main); listViewModel = ViewModelProviders.of(this).get(ListViewModel.class); binding.setViewModel(listViewModel); list = findViewById(R.id.games_list); listViewModel.getList().observeForever(new Observer<List<Game>>() { @Override public void onChanged(@Nullable List<Game> items) { setUpList(items); } }); listViewModel.loadGames(); } private void setUpList(List<Game> items){ list.setLayoutManager(new LinearLayoutManager(this)); GameAdapter adapter = new GameAdapter(); adapter.setList(items); list.setAdapter(adapter); } and the ViewModel it's only responsible for loading the data and notify the Activity when the list is ready so it can prepare the Adapter and show the data: public int progressVisibility = View.VISIBLE; private MutableLiveData<List<Game>> list; public void loadGames(){ Retrofit retrofit = GamesAPI.create(); GameService service = retrofit.create(GameService.class); Call<GamesResponse> call = service.fetchGames(); call.enqueue(this); } @Override public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) { if(response.body().response.equals("success")){ setList(response.body().data); } } @Override public void onFailure(Call<GamesResponse> call, Throwable t) { } public MutableLiveData<List<Game>> getList() { if(list == null) list = new MutableLiveData<>(); if(list.getValue() == null) list.setValue(new ArrayList<Game>()); return list; } public void setList(List<Game> list) { this.list.postValue(list); } My question is: which is the correct way to show/hide the list, progressbar and error text? should I add an Integer for each View in the ViewModel making it control the views and using it like: <TextView android:id="@+id/main_list_error" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{viewModel.error}" android:visibility="@{viewModel.errorVisibility}" /> or should the ViewModel instantiate a LiveData object for each property: private MutableLiveData<Integer> progressVisibility = new MutableLiveData<>(); private MutableLiveData<Integer> listVisibility = new MutableLiveData<>(); private MutableLiveData<Integer> errorVisibility = new MutableLiveData<>(); update their value when needed and make the Activity observe their value? viewModel.getProgressVisibility().observeForever(new Observer<Integer>() { @Override public void onChanged(@Nullable Integer visibility) { progress.setVisibility(visibility); } }); viewModel.getListVisibility().observeForever(new Observer<Integer>() { @Override public void onChanged(@Nullable Integer visibility) { list.setVisibility(visibility); } }); viewModel.getErrorVisibility().observeForever(new Observer<Integer>() { @Override public void onChanged(@Nullable Integer visibility) { error.setVisibility(visibility); } }); I'm really struggling to understand that. If someone can clarify that, it would be great. Thanks A: Here are simple steps: public class MainViewModel extends ViewModel { MutableLiveData<ArrayList<Game>> gamesLiveData = new MutableLiveData<>(); // ObservableBoolean or ObservableField are classes from // databinding library (android.databinding.ObservableBoolean) public ObservableBoolean progressVisibile = new ObservableBoolean(); public ObservableBoolean listVisibile = new ObservableBoolean(); public ObservableBoolean errorVisibile = new ObservableBoolean(); public ObservableField<String> error = new ObservableField<String>(); // ... // For example we want to change list and progress visibility // We should just change ObservableBoolean property // databinding knows how to bind view to changed of field public void loadGames(){ GamesAPI.create().create(GameService.class) .fetchGames().enqueue(this); listVisibile.set(false); progressVisibile.set(true); } @Override public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) { if(response.body().response.equals("success")){ gamesLiveData.setValue(response.body().data); listVisibile.set(true); progressVisibile.set(false); } } } And then <data> <import type="android.view.View"/> <variable name="viewModel" type="MainViewModel"/> </data> ... <ProgressBar android:layout_width="32dp" android:layout_height="32dp" android:visibility="@{viewModel.progressVisibile ? View.VISIBLE : View.GONE}"/> <ListView android:layout_width="32dp" android:layout_height="32dp" android:visibility="@{viewModel.listVisibile ? View.VISIBLE : View.GONE}"/> <TextView android:id="@+id/main_list_error" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{viewModel.error}" android:visibility="@{viewModel.errorVisibile ? View.VISIBLE : View.GONE}"/> Also notice that it's your choice to make view observe ObservableBoolean : false / true // or ObservableInt : View.VISIBLE / View.INVISIBLE / View.GONE but ObservableBoolean is better for ViewModel testing. Also you should observe LiveData considering lifecycle: @Override protected void onCreate(Bundle savedInstanceState) { ... listViewModel.getList().observe((LifecycleOwner) this, new Observer<List<Game>>() { @Override public void onChanged(@Nullable List<Game> items) { setUpList(items); } }); }
{ "pile_set_name": "StackExchange" }
Q: How can I prevent Gnome from showing two windows when doing alt-tab? (c++ qt app) (see edits) I'm developing a QT/c++ application under gnome. The application a main window and QListBox child window. Both of these windows show up as separate main windows when I alt-tab away from the application. How can I make it so that only one window is shown when I (or later the user) uses alt-tab? I am guessing this behavior comes because one main window doesn't clip the subwindow - the subwindow extends the boundary of the main window. Gnome has bad alt-tab behavior for a number of other applications too, showing modal dialog boxes separately from main windows. But in the case of my app, this is really annoying. I am thinking I could make a giant transparent window that includes both existing windows. But it would be nicer to find a "clean" solution. (the most logical guess is indeed that it has something to do with window flags. I've tried every reasonable combination of flags I could think of. The window types are described here) Edit: The app has a QWidget as its main window (Not QMainWindow), QListView is contained in the QWidget object and created by passing a point to the main window. is styled with Qt::Tool | Qt::FramelessWindowHint. Edit2: The Qt::X11BypassWindowManagerHint style does work to remove the window from the alt-tab list. The problem is that it also makes the window "unmanaged" so it cover the other windows. I could manaully hide whenever I lose focus - prize now for a better solution. A: When creating a window for your QListBox window set a Qt::Tool window flag in its constructor or later with setWindowFlags function call. Here is some code snippet(I omitted the headers): int main(int argc, char** argv) { QApplication app(argc, argv); QMainWindow mw; mw.show(); QWidget toolWindow(&mw, Qt::Window|Qt::Tool); QHBoxLayout layout(&toolWindow); toolWindow.setLayout(&layout); QListView lv(&toolWindow); layout.addWidget(&lv); toolWindow.show(); return app.exec(); } I've tested this on my Debian sid box (Gnome 2.30, metacity 2.30.1) with freshly created user: . If this is not what you wanted, then please name the software which works correctly or you may check it yourself. To do this run xprop in terminal window and click on the window you are interested in. The output will contain window flags. The one you are interested in is _NET_WM_WINDOW_TYPE(ATOM). For the tool window(i.e. not listed in alt-tab) this flag is: _NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_UTILITY, _NET_WM_WINDOW_TYPE_NORMAL If the window with these flags is not a toolbox window then something is wrong with your window manager or you have personally set such behavior.
{ "pile_set_name": "StackExchange" }
Q: VSTS msbuild: How to use parameters instead of profile? Error: Could not find __.dll I have a simple "Hello World" mvc web application that I am attempting to build in VSTS. My steps are: Get Sources Run msbuild on a single project Publish artifact (publish directory) Everything works fine whenever I use a profile for msbuild, but I would like to just pass the parameter commands in instead. When I do this I get the following error: Error : Copying file bin\WebApp01.dll to obj\Release\Package\PackageTmp\bin\WebApp01.dll failed. Could not find file 'bin\WebApp01.dll'. What mistake am I making with my msbuild parameters? How do I properly duplicate a simple file system profile? Parameters (error'ing): /p:DeployOnBuild=true /p:Configuration="Release" /p:Platform="Any CPU" /t:WebPublish /p:WebPublishMethod=FileSystem /p:publishUrl=PublishToOctopus Profile (works): <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <WebPublishMethod>FileSystem</WebPublishMethod> <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration> <LastUsedPlatform>Any CPU</LastUsedPlatform> <SiteUrlToLaunchAfterPublish /> <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish> <ExcludeApp_Data>False</ExcludeApp_Data> <publishUrl>PublishToOctopus</publishUrl> <DeleteExistingFiles>False</DeleteExistingFiles> </PropertyGroup> </Project> A: When using /p:DeployOnBuild=true, you can use the normal Build target. You directly called WebPublish (/t:WebPublish) which expects a build to already have happened but since it doesn't, the file is missing from the expected location.
{ "pile_set_name": "StackExchange" }
Q: Can I make iPhone/iPad broadcast as Eddystone Beacon? We can make iOS devices act as a iBeacon transmitter and We can locate nearby iBeacons if we know their Proximity UUID. With Google's Proximity Beacon API, It's possible to configure and register real Beacon hardware, and we can locate them with Nearby Messaging API. But is it possible to make iOS devices to broadcast as Eddystone Beacons ? And it needs to be discoverable by apps that scan Eddystone beacons. Thanks in advance. A: Unfortunately, this is not possible. While iOS devices can advertise Bluetooth LE service advertisements(which are the advertisement type used by Eddystone) using CoreBluetooth APIs, you cannot attach the necessary data. This is because the CBAdvertisementDataServiceDataKey that associates service data to an advertisement is read-only on iOS. You can't set the data. So while you want to make the iOS device advertise something like this to transmit Eddystone-UID: 0201060303aafe1516aafe00e72f234454f4911ba9ffa6000000000001 You end up advertising something like this: 0201060303aafe0316aafe This leaves off the Eddystone-UID type code (00), the calibrated power (e7), the namespace identifier (2f234454f4911ba9ffa6) and the instance identifier (000000000001). As a result, it won't be recognized as an Eddystone-UID frame.
{ "pile_set_name": "StackExchange" }
Q: What does a HTML filter need to do, to protect against SVG attacks? I recently learned that SVG (Scalable Vector Graphics) images introduce a number of opportunities for subtle attacks on the web. (See paper below.) While SVG images may look like an image, the file format can actually contain Javascript, and it can trigger loading or execution of HTML, Flash, or other content. Therefore, the SVG format introduces new potential ways to try to sneak malicious content onto a web page, or to bypass HTML filters. I'm writing a HTML filter to sanitize user-provided HTML. What do I need to do in my HTML filter to make sure that SVG images cannot be used to bypass my filter? What HTML tags and attributes do I need to block? Do I need to do anything when filtering CSS? If I want to simply block all SVG images, what are all the ways that SVG can be embedded into a HTML document? References: Crouching Tiger – Hidden Payload: Security Risks of Scalable Vectors Graphics, Mario Heiderich, Tilman Frosch, Meiko Jensen, Thorsten Holz. ACM CCS 2011. See also Exploits or other security risks with SVG upload? (a different, but related, question) and Mike Samuel's answer elsewhere. A: Good day! Edit: Sorry for the unlinked links - given that I just created my account to reply to this I have not enough "cred" to post more that 2 links per post... This post is not the freshest I reckon - but I am going to reply nevertheless. I am one of the authors of this paper you linked. And I noticed, that some of the advice given in this thread is well meant and well thought but not 100% correct. For example, Opera is not providing reliable safety when dealing with SVGs embedded via <img> or CSS backgrounds. Here's an example for that, just for the funzies we created a SVG embedded via <img> that would contain a PDF that would open a skype: URL that would then call you: http://heideri.ch/opera/ http://www.slideshare.net/x00mario/the-image-that-called-me We created the SVGPurifier - a set of rules that extend the HTMLPurifier to be able to deal with cleaning SVG. Back when we wrote those rules (you can have them if you want - let me know and I'll put 'em on Github), every browser we tested treated SVG differently. Also strongly dependent on the way it was embedded: inline, with <embed>/<object>, <applet>, <img>, SVG in SVG, CSS background, list-style and content... It turned out that it was possible, to find a harmless subset in SVG if you threat model mainly involved XSS and beyond. If your threat model nevertheless also includes for instance mitigation of UI overlaps, side-channels, history stealing attacks and what not it gets a bit harder. Here's for example a funny snippet showing, how we can cause XSS with very much obfuscated JavaScript URI handlers: http://jsbin.com/uxadon Then we have inline SVG. In my personal opinion, this was one of the worst ideas W3C/WHATWG ever had. Allowing XML documents inside HTML5 documents, forcing them to comply with HTML5 parsing rules and what not... security nightmare. Here's one gripping example of inline SVG and contained JavaScript that shows, what you'd be dealing with: http://pastebin.com/rmbiqZgd To not have this whole thing end up in a long lament on how terrible SVG might be in a security/XSS context, here's some advice. If you really and still want to / are working on this HTML filter, consider doing the following: Give us a public some-test where we can hammer that thing. Be flexible with your rule-set, expect new bypasses every day. Make sure to know what the implications of filtering inline SVG are. Try to see if the HTMLPurifier approach might be the best. White-list, don't black-list. Avoid reg-ex at all costs. This is not a place for regular expressions to be used. Make sure that your subset only allows those elements, that have been tested for security problems in all relevant browsers. Remember the SVG key-logger? http://html5sec.org/#132 Study the SVG-based attacks that were already published and be prepared to find more on a regular basis: http://html5sec.org/?svg I like the idea of someone attempting to build a properly maintained and maybe even working HTML+SVG filter and I'd be more than happy to test it - as many others as well I assume ;) But be aware: HTML filtering is damn hard already - and SVG just adds a whole new layer of difficulty to it. A: As far as I know the following ways can be used to refer to an svg. <img src="http://example.com/some-svg.svg"> Any tag with css styles. e.g. style="background-image:url(http://example.com/some-svg.svg) Filtering on extensions is not enough. HTTP headers determine the content type, not the extension. A .jpg file may be read as an SVG. Therefore, any remote image is dangerous. You can inline any XML format, including SVG, in a web page. Even if you check for all the items above, you cannot be sure that there is no SVG injection possible. You may want to go for white-listing instead of blacklisting.
{ "pile_set_name": "StackExchange" }
Q: retrieve common CSS patterns in websites code I have a collection of off-line web sites. Every website has a folder with the site name. (e.g. microspino.com). Those websites are somewhat similar (i.e. same doctype, same basic html structure). I would like to find a clever way to generate a file with all the recurring/common patterns for the CSS applied to their index pages. It could be whatever you think is better, write a script, use the shell etc. and the output could have, again, whatever format. The goal for me is to analyze and store somewhere the most useful/used CSS rules of the entire collection, updating my findings from time to time. Is it possible? How can I do that? UPDATE I don't need only the count but also to extract the most common rules. Ideally, but this is not a format constraint, I woud like to have: [count] [css rule] A: This sounds ugly but for a one- off time saver you could merge the CSS files into one and import the resulting file into a SQL table and analyse the results with basic TSQL counts?
{ "pile_set_name": "StackExchange" }
Q: ANR caused by Input dispatching timed out - while trying to get my public IP address I get the following complete error message: Input dispatching timed out (Waiting to send non-key event because the touched window has not finished processing certain input events that were delivered to it over 500.0ms ago. Wait queue length: 2. Wait queue head age: 9379.7ms.) See below the code + traces. It seems that the lock happens at GetIP_WAN.java:32 which is the line: BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream())); I call this function whenever I detect a network change wifi-3g/4g-no internet. and in a few other places. it happens on every occasion but much more from the network change detection obviously. I verify if the public IP has changed this way: ipwan = giw.getWanIpAddress(); and in getWanIpAddress: ipwan = new GetIP_WAN().execute().get(); ipwan being a String pointing to the public ip. I am not able to reproduce this ANR. My app uses several async task that might be intensive async task for several seconds. If I test it with a strong load and I switch off wifi I don't have problems. Input would be much appreciated!!! public class GetIP_WAN extends AsyncTask<Void, Integer, String> { @Override protected String doInBackground(Void... params) { URL url; String ipwan = null; try { // get URL content url = new URL("http://ipv4bot.whatismyipaddress.com/"); URLConnection conn = url.openConnection(); conn.setConnectTimeout(3000); // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream())); String inputLine; ipwan = br.readLine(); br.close(); } catch (java.net.SocketTimeoutException e) { return ("timeout"); } catch (MalformedURLException e) { e.printStackTrace(); return ("malformed"); } catch (IOException e) { e.printStackTrace(); return ("exception"); } return (ipwan); } } and here is the trace (my code where the lock happens is identified by >>>): "main" tid=1 Waiting "main" prio=5 tid=1 Waiting | group="main" sCount=1 dsCount=0 obj=0x7331b000 self=0xb81bb2c0 | sysTid=23053 nice=-4 cgrp=default sched=0/0 handle=0xb6f5cbec | state=S schedstat=( 26983505120 16031385654 42843 ) utm=2225 stm=473 core=0 HZ=100 | stack=0xbe5d4000-0xbe5d6000 stackSize=8MB | held mutexes= at java.lang.Object.wait! (Native method) - waiting on <0x0448108a> (a java.lang.Object) at java.lang.Thread.parkFor (Thread.java:1220) - locked <0x0448108a> (a java.lang.Object) at sun.misc.Unsafe.park (Unsafe.java:299) at java.util.concurrent.locks.LockSupport.park (LockSupport.java:157) at java.util.concurrent.FutureTask.awaitDone (FutureTask.java:400) at java.util.concurrent.FutureTask.get (FutureTask.java:162) at android.os.AsyncTask.get (AsyncTask.java:487) >>> at com.bernard_zelmans.checksecurity.Connectivity.GetInfoWan.getWanIpAddress (GetInfoWan.java:168) >>> at com.bernard_zelmans.checksecurity.Connectivity.ConnectivityFragment$2.onClick (ConnectivityFragment.java:155) at android.view.View.performClick (View.java:4781) at android.view.View$PerformClick.run (View.java:19874) at android.os.Handler.handleCallback (Handler.java:739) at android.os.Handler.dispatchMessage (Handler.java:95) at android.os.Looper.loop (Looper.java:135) at android.app.ActivityThread.main (ActivityThread.java:5254) at java.lang.reflect.Method.invoke! (Native method) at java.lang.reflect.Method.invoke (Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:902) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:697) "AsyncTask #5" tid=21 Native Performing network I/O "AsyncTask #5" prio=5 tid=21 Native | group="main" sCount=1 dsCount=0 obj=0x1372b0a0 self=0xb8537190 | sysTid=23175 nice=10 cgrp=bg_non_interactive sched=0/0 handle=0xb8536ee0 | state=S schedstat=( 9854319 53209536 49 ) utm=0 stm=0 core=0 HZ=100 | stack=0xa413d000-0xa413f000 stackSize=1036KB | held mutexes= native: pc 000000000003a180 /system/lib/libc.so (recvfrom+16) native: pc 0000000000020165 /system/lib/libjavacore.so (???) native: pc 00000000002d557d /data/dalvik-cache/arm/system@[email protected] (Java_libcore_io_Posix_recvfromBytes__Ljava_io_FileDescriptor_2Ljava_lang_Object_2IIILjava_net_InetSocketAddress_2+176) at libcore.io.Posix.recvfromBytes (Native method) at libcore.io.Posix.recvfrom (Posix.java:185) at libcore.io.BlockGuardOs.recvfrom (BlockGuardOs.java:250) at libcore.io.IoBridge.recvfrom (IoBridge.java:553) at java.net.PlainSocketImpl.read (PlainSocketImpl.java:485) at java.net.PlainSocketImpl.access$000 (PlainSocketImpl.java:37) at java.net.PlainSocketImpl$PlainSocketInputStream.read (PlainSocketImpl.java:237) at com.android.okio.Okio$2.read (Okio.java:113) at com.android.okio.RealBufferedSource.indexOf (RealBufferedSource.java:147) at com.android.okio.RealBufferedSource.readUtf8LineStrict (RealBufferedSource.java:94) at com.android.okhttp.internal.http.HttpConnection.readResponse (HttpConnection.java:179) at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders (HttpTransport.java:101) at com.android.okhttp.internal.http.HttpEngine.readResponse (HttpEngine.java:628) at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute (HttpURLConnectionImpl.java:388) at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse (HttpURLConnectionImpl.java:332) at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream (HttpURLConnectionImpl.java:199) >>> at com.bernard_zelmans.checksecurity.Connectivity.GetIP_WAN.doInBackground (GetIP_WAN.java:32) >>> at com.bernard_zelmans.checksecurity.Connectivity.GetIP_WAN.doInBackground (GetIP_WAN.java:16) at android.os.AsyncTask$2.call (AsyncTask.java:292) at java.util.concurrent.FutureTask.run (FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:587) at java.lang.Thread.run (Thread.java:818) "WifiManager" tid=22 Native "WifiManager" prio=5 tid=22 Native | group="main" sCount=1 dsCount=0 obj=0x137192e0 self=0xb85369a0 | sysTid=23176 nice=0 cgrp=default sched=0/0 handle=0xb84af978 | state=S schedstat=( 2818438 6808230 23 ) utm=0 stm=0 core=1 HZ=100 | stack=0xa4035000-0xa4037000 stackSize=1036KB | held mutexes= native: pc 000000000003a0ac /system/lib/libc.so (__epoll_pwait+20) native: pc 0000000000011483 /system/lib/libc.so (epoll_pwait+26) native: pc 0000000000011491 /system/lib/libc.so (epoll_wait+6) native: pc 0000000000010edf /system/lib/libutils.so (_ZN7android6Looper9pollInnerEi+98) native: pc 0000000000011109 /system/lib/libutils.so (_ZN7android6Looper8pollOnceEiPiS1_PPv+92) native: pc 000000000007e371 /system/lib/libandroid_runtime.so (_ZN7android18NativeMessageQueue8pollOnceEP7_JNIEnvi+22) native: pc 000000000010e76b /data/dalvik-cache/arm/system@[email protected] (Java_android_os_MessageQueue_nativePollOnce__JI+102) at android.os.MessageQueue.nativePollOnce (Native method) at android.os.MessageQueue.next (MessageQueue.java:143) at android.os.Looper.loop (Looper.java:122) at android.os.HandlerThread.run (HandlerThread.java:61) "Heap thread pool worker thread 1" tid=2 Native "Heap thread pool worker thread 1" prio=5 tid=2 Native (still starting up) | group="" sCount=1 dsCount=0 obj=0x0 self=0xb8337008 | sysTid=23060 nice=0 cgrp=default sched=0/0 handle=0xb81c1910 | state=S schedstat=( 2796719 5468959 19 ) utm=0 stm=0 core=0 HZ=100 | stack=0xb49ce000-0xb49d0000 stackSize=1020KB | held mutexes= native: pc 000000000000f9b0 /system/lib/libc.so (syscall+28) native: pc 00000000000a8c4b /system/lib/libart.so (_ZN3art17ConditionVariable4WaitEPNS_6ThreadE+82) native: pc 000000000022f877 /system/lib/libart.so (_ZN3art10ThreadPool7GetTaskEPNS_6ThreadE+50) native: pc 000000000022f81f /system/lib/libart.so (_ZN3art16ThreadPoolWorker3RunEv+54) native: pc 000000000023005d /system/lib/libart.so (_ZN3art16ThreadPoolWorker8CallbackEPv+52) native: pc 00000000000132bb /system/lib/libc.so (_ZL15__pthread_startPv+30) native: pc 00000000000111e7 /system/lib/libc.so (__start_thread+6) "Heap thread pool worker thread 2" tid=3 Native "Heap thread pool worker thread 2" prio=5 tid=3 Native (still starting up) | group="" sCount=1 dsCount=0 obj=0x0 self=0xb81c0ea0 | sysTid=23061 nice=0 cgrp=default sched=0/0 handle=0xb833a0b0 | state=S schedstat=( 5997967 2723698 18 ) utm=0 stm=0 core=0 HZ=100 | stack=0xb48ce000-0xb48d0000 stackSize=1020KB | held mutexes= native: pc 000000000000f9b0 /system/lib/libc.so (syscall+28) native: pc 00000000000a8c4b /system/lib/libart.so (_ZN3art17ConditionVariable4WaitEPNS_6ThreadE+82) native: pc 000000000022f877 /system/lib/libart.so (_ZN3art10ThreadPool7GetTaskEPNS_6ThreadE+50) native: pc 000000000022f81f /system/lib/libart.so (_ZN3art16ThreadPoolWorker3RunEv+54) native: pc 000000000023005d /system/lib/libart.so (_ZN3art16ThreadPoolWorker8CallbackEPv+52) native: pc 00000000000132bb /system/lib/libc.so (_ZL15__pthread_startPv+30) native: pc 00000000000111e7 /system/lib/libc.so (__start_thread+6) "Heap thread pool worker thread 0" tid=4 Native "Heap thread pool worker thread 0" prio=5 tid=4 Native (still starting up) | group="" sCount=1 dsCount=0 obj=0x0 self=0xb83390c0 | sysTid=23059 nice=0 cgrp=default sched=0/0 handle=0xb82a4b58 | state=S schedstat=( 3379426 4137085 15 ) utm=0 stm=0 core=1 HZ=100 | stack=0xb4ace000-0xb4ad0000 stackSize=1020KB | held mutexes= native: pc 000000000000f9b0 /system/lib/libc.so (syscall+28) native: pc 00000000000a8c4b /system/lib/libart.so (_ZN3art17ConditionVariable4WaitEPNS_6ThreadE+82) native: pc 000000000022f877 /system/lib/libart.so (_ZN3art10ThreadPool7GetTaskEPNS_6ThreadE+50) native: pc 000000000022f81f /system/lib/libart.so (_ZN3art16ThreadPoolWorker3RunEv+54) native: pc 000000000023005d /system/lib/libart.so (_ZN3art16ThreadPoolWorker8CallbackEPv+52) native: pc 00000000000132bb /system/lib/libc.so (_ZL15__pthread_startPv+30) native: pc 00000000000111e7 /system/lib/libc.so (__start_thread+6) "HeapTrimmerDaemon" tid=6 Waiting "HeapTrimmerDaemon" daemon prio=5 tid=6 Waiting | group="system" sCount=1 dsCount=0 obj=0x12c061c0 self=0xb833c230 | sysTid=23066 nice=0 cgrp=default sched=0/0 handle=0xb833ca20 | state=S schedstat=( 16039218 18453438 23 ) utm=1 stm=0 core=3 HZ=100 | stack=0xa6f4e000-0xa6f50000 stackSize=1036KB | held mutexes= at java.lang.Object.wait! (Native method) - waiting on <0x1c7546fb> (a java.lang.Daemons$HeapTrimmerDaemon) at java.lang.Daemons$HeapTrimmerDaemon.run (Daemons.java:311) - locked <0x1c7546fb> (a java.lang.Daemons$HeapTrimmerDaemon) at java.lang.Thread.run (Thread.java:818) "GCDaemon" tid=7 Waiting "FinalizerWatchdogDaemon" tid=8 Waiting "Binder_1" tid=9 Native "FinalizerDaemon" tid=10 Waiting "ReferenceQueueDaemon" tid=11 Waiting "Binder_2" tid=12 Native "AsyncTask #1" tid=13 Waiting "Timer-0" tid=14 Waiting "RenderThread" tid=15 Native "AsyncTask #2" tid=18 Waiting "AsyncTask #3" tid=19 Waiting "AsyncTask #4" tid=20 Waiting "Binder_3" tid=23 Native "AdWorker(Default) #1" tid=24 TimedWaiting "java.lang.ProcessManager" tid=25 Waiting "AdWorker(Default) #2" tid=26 TimedWaiting "AdWorker(Default) #3" tid=27 TimedWaiting "AdWorker(Default) #4" tid=28 TimedWaiting "AdWorker(Default) #5" tid=29 TimedWaiting "Binder_6" tid=30 Native "Binder_4" tid=40 Native "Binder_7" tid=45 Native "Binder_5" tid=49 Native "Signal Catcher" tid=5 Runnable "Signal Catcher" daemon prio=5 tid=5 Runnable | group="system" sCount=0 dsCount=0 obj=0x12c000a0 self=0xb833abf8 | sysTid=23062 nice=0 cgrp=default sched=0/0 handle=0xb8339498 | state=R schedstat=( 166092660 21972502 124 ) utm=8 stm=8 core=0 HZ=100 | stack=0xb47c4000-0xb47c6000 stackSize=1012KB | held mutexes= "thread list lock" "mutator lock"(exclusive held) native: pc 0000000000004758 /system/lib/libbacktrace_libc++.so (_ZN13UnwindCurrent6UnwindEjP8ucontext+23) native: pc 0000000000002f8d /system/lib/libbacktrace_libc++.so (_ZN9Backtrace6UnwindEjP8ucontext+8) native: pc 00000000002411c9 /system/lib/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiPKcPNS_6mirror9ArtMethodE+68) native: pc 0000000000225591 /system/lib/libart.so (_ZNK3art6Thread4DumpERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEE+148) native: pc 000000000022e8bb /system/lib/libart.so (_ZN3art10ThreadList14DumpForSigQuitERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEE+142) native: pc 0000000000215ca5 /system/lib/libart.so (_ZN3art7Runtime14DumpForSigQuitERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEE+68) native: pc 000000000021a431 /system/lib/libart.so (_ZN3art13SignalCatcher13HandleSigQuitEv+752) native: pc 000000000021aadb /system/lib/libart.so (_ZN3art13SignalCatcher3RunEPv+318) native: pc 00000000000132bb /system/lib/libc.so (_ZL15__pthread_startPv+30) native: pc 00000000000111e7 /system/lib/libc.so (__start_thread+6) A: I think your problem is that you're calling AsyncTask.get() right after you call GetIP_WAN().execute(). I assume that you're calling GetIP_WAN().execute() on the UI thread. If it's in an onClick callback or a BroadcastReceiver it most certainly is. So what I believe is happening is your GetIP_WAN task is correctly executing on a background thread completing but the get() call is attempting to retrieve the data that will get returned from doInBackground(). But that call (get()) will NEVER return before doInBackground and maybe onPostExecute(...) returns, thus causing blocking on the UI thread. If you read the documentation for get inside of the AsyncTask class it says /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */ Ironically, you are negating the purpose of you AsnycTask. Even though the work is taking place on the background thread, you are forcing the UI thread to wait for the work to complete before any additional processing on the UI thread can complete. The Android OS handles creating a ANR dialog when it detects the UI/Main thread has been blocking for 5 seconds. I assume you are calling get so you can get your data from GetIP_WAN, so you can manipulate/display it on the UI thread. What I recommend is you pass some form of reference to the owning activity or fragment into the GetIP_WAN and when the task completes and fires onPostExecute(...) which will be fired on the UI/Main thread, you act upon the activity or fragment to update it's UI with the data you downloaded in doInBackground(...). One pattern I'd recommend is passing a Handler reference that's wrapped inside of a WeakReference into GetIP_WAN and in onPostExecute(...), send an empty message indicating that the work was completed and it's safe to call GetIP_WAN.get().
{ "pile_set_name": "StackExchange" }
Q: Convergence of an improper integral $I=\int_0^\infty \frac{\sin{x}-x\cos{x}}{x^\alpha}dx$ Problem: Analyze convergence of an improper integral $I=\int_0^\infty \frac{\sin{x}-x\cos{x}}{x^\alpha}dx$. My work: Problematic points are $0$ and $\infty$. Therefore, we will write integral as a sum of two integrals : $$I=\int_0^1 \frac{\sin{x}-x\cos{x}}{x^\alpha}dx+\int_1^\infty \frac{\sin{x}-x\cos{x}}{x^\alpha}dx=I_1+I_2.$$ Second integral converges absolutely for $\alpha>3$. First integral converges for $\alpha<2$ by comparison test ($I_1\leq \int_0^1 \frac{dx}{x^{\alpha-1}}$). Now I'm stuck at this point of problem. Any hint or help is welcome. Thanks in advance. A: We have that $\sin(x)-x\cos(x)$ behaves like $x^3$ in a right neighbourhood of the origin, hence integrability over there is ensured by $\color{red}{\alpha < 4}$. By Dirichlet's test, $$ \int_{1}^{+\infty}\frac{\sin x}{x^\beta}\,dx,\qquad \int_{1}^{+\infty}\frac{\cos x}{x^\beta}\,dx $$ are convergent as soon as $\color{red}{\beta>0}$, hence the original integral is convergent as soon as $\color{red}{\alpha\in(1,4)}$. If you are allowed to use Laplace transforms, you may also compute the value of the integral, since $$ \mathcal{L}\left(\sin x-x\cos x\right) = \frac{2}{(1+s^2)^2}, \tag{1}$$ $$ \mathcal{L}^{-1}\!\!\left(x^{-\alpha}\right) = \frac{s^{\alpha-1}}{\Gamma(\alpha)} \tag{2}$$ and the equivalent integral $$ I(\alpha)=\frac{1}{\Gamma(\alpha)}\int_{0}^{+\infty}\frac{s^{\alpha-1}}{(1+s^2)^2}\,ds \tag{3}$$ is convergent iff ${\alpha >0}$ (that is needed to grant integrability in a right neighbourhood of the origin) and ${\alpha < 4}$ (that is needed to grant integrability in a left neighbourhood of $+\infty$). In such a case, through the substitution $\frac{1}{1+s^2}=u$, Euler's beta function and the $\Gamma$ reflection formula we have: $$ I(\alpha)= \color{red}{\frac{\pi\,(2-\alpha)}{2\,\Gamma(\alpha)\,\sin\left(\frac{\pi\alpha}{2}\right)}}.\tag{4}$$
{ "pile_set_name": "StackExchange" }
Q: So, "Some advice" or "some advices"? Which is correct? "Some advice" or "some advices" as in "I got some advice / advices for you"? So, Which is correct? In Oxford Learner's Dictionaries, "advice" is uncountable noun, so "Some advice" is the correct one. However, googling "some advices" returns 400K results and in fact many formal English articles / news use "some advices" as in this article on Yahoo News: "Real World 101: What Every Graduate Should Know". Although graduating from college is a great accomplishment which should be recognized, it is not the end. In fact, it is just the beginning of a totally new phase in life which the graduates are unfamiliar with. Below are some advices for the new graduates that are not thought in schools. So, I think "some advices" could be accepted as an alternative to "some advice" though it is not 100% accurate. A: As noted, advice is uncountable so it takes no plural form. In the following extract from "Oxford dictionaries", however, they hint at a legal/business usage of advice as a countable noun. Taking and giving advice The central difference between advice and advise is that the spelling advice, with -ice at the end, is the standard English spelling for the noun, but never for the verb. Advice has two meanings: guidance or recommendations offered to someone about the best course of action to take in a particular situation: she gave good advice about treating everyone with respect; her help surprised him, but he took her advice. (in business and legal use) a formal record of a financial agreement or other transaction: cheques and remittance advices were raised in alphabetical order. Advice is mainly used with the first meaning, and in this meaning it is a mass noun (that is, it has no plural). The business/legal meaning, however, is a count noun: it has a plural form, advices. Tip 1: there are just two possible forms for the noun: advice and advices. Tip 2: when you pronounce advice, the ending rhymes with ice. A: "Some advices" is archaic, having passed out of use about 100 years ago. See Ngram. Likely it is true that this usage still persists in India, as parts of the English language as used there were "frozen" about that long ago. It is not, however, considered to be modern, idiomatic usage in the US or, to my knowledge, in the British Isles, and its use would generally cause a reader to suspect that the author was not a "native English speaker". A: "Advice" is uncountable and all those "advices" you're seeing are just mistakes.
{ "pile_set_name": "StackExchange" }
Q: Why isn't my query outputting the expected results? CREATE TABLE IF NOT EXISTS `Channels` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(30) NOT NULL, `commercial` tinyint(1) NOT NULL DEFAULT '0', `usrid` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; INSERT INTO `Channels` (`id`, `name`, `commercial`, `usrid`) VALUES (2, 'ORF 1', 0, 0); PHP: <?php if (isset($_POST['name'])){ mysql_connect("localhost", "test", "test") or die(mysql_error()); mysql_select_db("test") or die(mysql_error()); $tmp = mysql_query("SELECT commercial FROM Channels WHERE name='".mysql_real_escape_string($_POST['name'])."'"); $row = mysql_fetch_row($tmp); echo $row['commercial']; } else { ?> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> <input name="name" type="text"> <input type="submit" name="submit" value="submit" > </form> <?php } ?> There is no output when I submit "ORF 1". A: It's vital that you learn to employ basic debugging techniques: Instead of this: $tmp = mysql_query("SELECT commercial FROM Channels WHERE name='".mysql_real_escape_string($_POST['name'])."'"); $row = mysql_fetch_row($tmp); echo $row['commercial']; do this: $tmp = mysql_query("SELECT commercial FROM Channels WHERE name='".mysql_real_escape_string($_POST['name'])."'"); // Make sure the query was successful if (false === $tmp) { die("Query failed: " . mysql_error()); } $row = mysql_fetch_row($tmp); // Don't assume a row was returned var_dump($row);
{ "pile_set_name": "StackExchange" }
Q: How to define a field type for field that contains both chinese and english I am now using Solr to index on a field. This field will contain both Chinese and English. At the same time, I need to use tokenizer NGramTokenizerFactory for searching. Below is the current field type I defined for the field: <fieldType name="text_general2" class="solr.TextField" positionIncrementGap="100"> <analyzer type="index"> <tokenizer class="solr.NGramTokenizerFactory" minGramSize="1" maxGramSize="15"/> <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" /> <filter class="solr.LowerCaseFilterFactory"/> </analyzer> <analyzer type="query"> <tokenizer class="solr.NGramTokenizerFactory" minGramSize="1" maxGramSize="15"/> <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" /> <filter class="solr.LowerCaseFilterFactory"/> </analyzer> </fieldType> I have to set minGramSize="1" to allow searching a single Chinese character. However, this is totally improper for searching an English word. e.g. If I search "see", it returns "s", "se", "ee", "see", "e" Therefore, could anyone please tell what is the best way to index a field that contains both Chinese and English? A: I'm sure that this isn't the answer you were hoping for, but it's the answer that will actually solve it: Don't use a single field to contain both chinese and english. Have one field for english and one field for chinese, indexing to the field matching the language of your input content. You can use the Language Detection feature in an update processor to let Solr decide which field to put the content into during indexing if you don't know the language when indexing. Searching is then done across both fields (depending on your query handler, possibly using qf), allowing for separate processing of tokens in each language against each field (so that english words doesn't get ngram-ed). If you have both english and chinese in the same document, process the document to decide the chinese and english parts (for example, iterate over each paragraph and detect language, before indexing to different fields).
{ "pile_set_name": "StackExchange" }
Q: Use half-duplex or full-duplex RS-485? I have a master microcontroller that can control 4 slave microcontrollers. Each slave microcontroller is connected to 3 sensors. The master microcontroller asks to retrieve the value of a specific sensor on a specific slave, and the slave sends the value to the master. And so on... Can I use the full duplex protocol ? Like this (where RO = RX and DI = TX) : Is it better to use half-duplex ? When is it necessary to use half-duplex ? It implies enabling receive and driver at a specific timing which can be annoying compared to the full duplex method. I have never used an RS-485 before so I am a beginner :) A: Is it better to use half-duplex ? When is it necessary to use half-duplex ? It implies enabling receive and driver at a specific timing which can be annoying compared to the full duplex method. It is necessary to use full-duplex when you want to transmit and receive simultaneously. It has nothing to do with the number of slave nodes, which requires either moderation/collision avoidance mechanism on one bus or individual peer-to-peer connections between master and each slave. It is never "necessary" to use half-duplex. The "better" part is defined mostly by the number of wires you are willing to run between the nodes. The "annoying" part is highly exaggerated. Since in your code ... master microcontroller asks to retrieve the value of a specific sensor on a specific slave, and the slave sends the value to the master ... you already have these two separate transmit/receive states. Adding one GPIO switch in between is trivial. Another consequence of the method of operation quoted above is that you also have moderation mechanism defined. If slave can only respond after being prompted and only one can be prompted at a time then there is no risk of collision (unless you mess up slave address assignment, that is). If you sum up all of the above you'd see that half-duplex communication with all the nodes on a same bus is quite sufficient for your needs. You just have to make sure that you use RS-485 compatible transceivers, like ADM3485.
{ "pile_set_name": "StackExchange" }
Q: Store class instance in the dom? Is it possible to store initialized class in the DOM for later use? let lion1 = new Animal("lion","5","100lb"); let lion2 = new Animal("lion","7","80lb"); document.getElementById("lion1").append(lion1); document.getElementById("lion2").append(lion2); then later lion1 = document.getElementById("lion1").getFirst(); lion1.roar() lion2 = document.getElementById("lion2").getFirst(); lion2.roar() A: For such a task I would suggest using IndexedDB_API or localStorage, also you can use data attribute
{ "pile_set_name": "StackExchange" }
Q: Расчетное поле после группировки Нужно сгруппировать данные и вывести расчетное поле 'price_u'. Знаю, что можно сделать через доп столбец: pandas_df['price_u'] = df['price']/df['quantity'] pandas_df.groupby('good')['price_u'].max().drop_duplicates() pandas_df.drop('price_u', axis=1, inplace=True) но хотелось бы сделать по-человечески. A: воспользуйтесь методом .eval(): In [348]: (df.eval("price_u = price / quantity") .groupby('good') ['price_u'] .max() .drop_duplicates()) Out[348]: good aaa 7.575 bbb 0.825 Name: price_u, dtype: float64 или .assign(): In [349]: (df.assign(price_u=df['price']/df['quantity']) .groupby('good') ['price_u'] .max() .drop_duplicates()) Out[349]: good aaa 7.575 bbb 0.825 Name: price_u, dtype: float64 Исходный DataFrame: In [347]: df Out[347]: good price quantity 0 aaa 10.1 2 1 aaa 20.2 5 2 aaa 30.3 4 3 bbb 1.1 2 4 bbb 2.2 5 5 bbb 3.3 4
{ "pile_set_name": "StackExchange" }
Q: Comparing Elements of a Generic List I have a TestClass<T> that will evolve to a heap-based priority queue. The heap is List<T> type. I was working on reordering code and I needed to compare the elements of the List<T>. As you can guess I received error CS0019: Operator < cannot be applied to operands of type T and T. I KNOW this is not surprising and C# generics are not C++ templates. So, I tried to constrain the Type T with an IComparable. But it did not help as well. The suggestions I found (in order to solve this problem) were mostly creating a dummy class that defines such operators and constrain the T with this class. However, I did not find this solution very convenient. So, are there any other ways to solve this? Here's the related piece of code: using System; using System.Collections.Generic; public class TestClass<T> where T : IComparable { private List<T> heap; public TestClass(int maxSize) { this.heap = new List<T>(maxSize + 1); } private void ReorderUpwards(int nodeIndex) { while (nodeIndex > 1 && this.heap[nodeIndex / 2] < this.heap[nodeIndex]) { nodeIndex /= 2; } } } A: Use IComparable and instead of using > and < use CompareTo method value.CompareTo(value2) <= 0
{ "pile_set_name": "StackExchange" }
Q: How do i get alert if someone tries to access my system? I am using ubuntu 10.04.I want to get an alert when someone tries to access my sytem.For example if someone access my system as an ssh user i want to get an alert in my system.How to get this type of alerts? A: fail2ban is probably the one tool you'll want for this. It works by parsing the logs of popular services (ssh, apache, etc) and looking for login failures. When it finds a certain number of failures (ie if it sees somebody trying to brute-force their way in over SSH) it can update iptables to block the attacking IP. It can also send out emails to notify you (as you ask). You can read more about setting it up from here: https://help.ubuntu.com/community/Fail2ban but there are lots of pages on the internet telling you how to do more with it. It's not a simple tool. Other than that, for any service, if you move it off to an unpredictable port, people will be much less likely to just stumble upon it and be able to start brute forcing it. I run my all my SSH servers in the 40000-50000 port range. I have fail2ban installed too but I've never had anybody find the SSH server yet. Of course this isn't useful for any service (http will always be expected on p80 for example) so if you're maintaining other users, you have to consider how much extra effort changing the port will cause them.
{ "pile_set_name": "StackExchange" }
Q: Geometry, Circles and Chords Two circles intersect at points $A$ and $B$. Chords $AC$ and $AD$ are drawn through the point $A$. Prove that $AC^2\cdot BD=AD^2\cdot BC$. So, most probably, we'll use Power of point on $A$ and $B$, giving $AC^2=AB \cdot BC$ and $AD^2=AB \cdot BD$. So, finally, we get the desired result. Is this solution proper? Thanks!!! A: If chords $AC$ and $AD$ are tangents to another circles, so $$\Delta ABC\sim \Delta DBA, $$ which gives $$\frac{AB}{DB}=\frac{AC}{DA}=\frac{BC}{BA}$$ and from here we obtain: $$AB^2=BC\cdot BD,$$ $$\frac{\sqrt{BC\cdot BD}}{BD}=\frac{AC}{AD},$$ which is $$AC^2\cdot BD=AD^2\cdot BC,$$ which is exactly that you want to get.
{ "pile_set_name": "StackExchange" }
Q: JSON: Jackson stream parser - is it really worth it? I'm making pretty heavy use of JSON parsing in an app I'm writing. Most of what I have done is already implemented using Android's built in JSONObject library (is it json-lib?). JSONObject appears to create instances of absolutely everything in the JSON string... even if I don't end up using all of them. My app currently runs pretty well, even on a G1. My question is this: are the speed and memory benefits from using a stream parser like Jackson worth all the trouble? By trouble, I mean this: As far as I can tell, there are three downsides to using Jackson instead of the built in library: Dependency on an external library. This makes your .apk bigger in the end. Not a huge deal. Your app is more fragile. Since the parsing is not done automatically, it is more vulnerable to changes in the JSON text that it's parsing (perhaps I'm wrong about this). Writing code to parse JSON via a stream parser is ugly and tedious. A: I am also using the build-in JSON parser in most cases, but recently stepped into a scenario where it doesn't fit: For some web service requests I receive JSON documents of more than 1 MB. Loading these with the build-in JSON parser requires tremendous amounts of main memory and resulted in OutOfMemoryException several times. For these scenarios a streaming parser is the better choice (even though it is more inconvenient in use) and the built-in JSON parser does not provide streaming, but only the DOM-like style. For anyone looking for a streaming JSON parser for Android I can strongly recommend to use Google's GSON. I've tried Jackson JSON at first and it worked fine until I tried to build the release version of my app: ProGuard reported several issues and the running app crashed with mysterious NullPointerException in the constructor of Jackson's ObjectMapper (though everything worked fine in the debug version). Even after a few hours of trying around I wasn't able to fix this. I then switched to GSON then and everything worked like a charm. BTW: The GSON streaming-only jar has a size of only 14kB -- so nothing to really worry about. A: Guess you've pretty much answered your own question. :) Using the built-in JSON parser myself and have never looked for an alternative. EDIT: Now I'm using a thin annotation-based wrapper from DroidParts.
{ "pile_set_name": "StackExchange" }
Q: Entity framework - to use to not in this scenario Here is my problem: I have 10 database (D1, D2, ....D10 ) with same schema but data is different in the tables. I do not have any control over these database as these belong to different companies. Now I have to develop a website which will run on any of these database. example I can run www.site.com/D1 or www.site.com/d2....like this..and the page will bring data from the respective database and render on page. Can I use entity framework in this case? Is EF would be recommended here or normal stored procedure based approach will be fine? Can I reset the entity framework connection string pragmatically and load the information from respective database dynamically, will it have performance issues...? A: Yeah you can do this with EF if you want. There is really only going to be one main difference that you encounter. Which db to use? When you have a mechanism for determining which database will be accessed then 90% of your problem will be solved. The other 10% is simply using that mechanism to point to a DbContext which will be using that company's connection string. So basically, in your web.config, you are going to have 10 unique connection strings defined with each name matched to the company. Then, using your determining mechanism, you will instantiate the matching DbContext and use that for your querying. web.config <configuration> ... <connectionStrings> <add name="PepsiDbContext" connectionString="conn string here" providerName="System.Data.SqlClient" /> <add name="ColaDbContext" connectionString="conn string here" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> DAL.cs public class EntityStructure : DbContext { public DbSet<Table1> TableName1s { get; set; } public DbSet<Table2> TableName2s { get; set; } } public class PepsiDbContext : EntityStructure {} public class ColaDbContext : EntityStructure {} querying if( company.Name == "Pepsi" ) { using( var db = new PepsiDbContext() ) { //query } }else { using( var db = new ColaDbContext() ) { //query } } The querying part here is over simplified on purpose. It is where 90% of your implementation is going to take place. Actually instantiating the different database contexts is what this demo shows, and it should be rather trivial.
{ "pile_set_name": "StackExchange" }