text
stringlengths
64
81.1k
meta
dict
Q: How does the Flaming Sphere spell's area of effect work? The description of the flaming sphere in the PHB reads: Any creature that ends its turn within 5 feet of the sphere must [...] Does this mean flaming sphere affects a sphere with a diameter of 15 feet (5 feet from itself, 10 feet towards either direction)? Also, does ramming the sphere require placing the sphere at the location of the enemy directly, or will it still do damage as long as the creature is in the affected range of the spell? A: The sphere of fire from the flaming sphere spell is only 5 feet wide. So on a grid with 5-foot squares, it would affect a 3×3 area, with the sphere in the middle square. For ramming, the spell specifically says: If you ram the sphere into a creature, that creature must make the saving throw against the sphere’s damage, and the sphere stops moving this turn. This means you use your command of the sphere to move it directly into a creature's space (thereby hitting it) and they have to make a normal Dex save, and if the sphere hits the target before moving its full 30 feet you lose the rest of the move distance.
{ "pile_set_name": "StackExchange" }
Q: How do I avoid Source Formatter from Unfolding XML Documentations? Just a tiny question, every time I fold an XML document, I then click Ctrl-D (Format Source) and then it Unfolds them. How can I disable that? (I don't think there's an option for this, is there?) Thanks all. A: There's no option for doing so. It's a known issue that formatting does not respect the folded sections of code (it doesn't restore them to the folded state after doing it's work). The solution appears to be to format the code yourself. :-) It's been discussed previously in the Embarcadero IDE forums since the formatter was added to the IDE.
{ "pile_set_name": "StackExchange" }
Q: Calculate percentage ratio from sum amount in mysql database in php I have a total_amount ($total_amount_column) which is the total sum of the Amount column down there. In the database, I have multiple entry called by name and they all have an amount associated to them. So it looks like this in table called "envelope_sub" name |amount |percentage House |1550.00 | Electricity |400.00 | Internet |50.00 | What I need is to calculate automatically the percentage column based on the total amount sum column. So In other words, I need the percentage ratio for each entry and insert them automatically in their respective percentage field in database. How I can achieve that please. A: Here's how I finally did it <?php $query = "SELECT * from stats where user_id='".$nameID."' $where order by week desc"; $result = mysql_query($query) or die(mysql_error()); $worked_week = mysql_num_rows($result); if(mysql_num_rows($result)) { $k = 1; while ($row_stats = mysql_fetch_array($result)) { // Total Section // $total_worked_hours=$total_worked_hours+$row_stats['worked_hours']; $total_sales=$total_sales+$row_stats['sales']; $total_sales=number_format($total_sales,2,'.',''); $total_facials=$total_facials+$row_stats['facials']; $total_double_facials=$total_double_facials+$row_stats['double_facials']; $total_classes=$total_classes+$row_stats['classes']; $total_faces_viewed=$total_faces_viewed+$row_stats['faces_viewed']; $total_interviews=$total_interviews+$row_stats['interviews']; $total_recruits=$total_recruits+$row_stats['recruits']; /// $k++; } // Percentage Section // $perc_worked_hours = $total_worked_hours / $worked_week; $perc_sales = $total_sales / $worked_week; $perc_facials = $total_facials / $worked_week; $perc_double_facials = $total_double_facials / $worked_week; $perc_classes = $total_classes / $worked_week; $perc_faces_viewed = $total_faces_viewed / $worked_week; $perc_interviews = $total_interviews / $worked_week; $perc_recruits = $total_recruits / $worked_week; // round up $perc_worked_hours=number_format($perc_worked_hours,0,'.',''); $perc_sales=number_format($perc_sales,2,'.',''); $perc_facials=number_format($perc_facials,0,'.',''); $perc_double_facials=number_format($perc_double_facials,0,'.',''); $perc_classes=number_format($perc_classes,0,'.',''); $perc_faces_viewed=number_format($perc_faces_viewed,0,'.',''); $perc_interviews=number_format($perc_interviews,0,'.',''); $perc_recruits=number_format($perc_recruits,0,'.',''); // END
{ "pile_set_name": "StackExchange" }
Q: Reading a value from a session variable into a local variable in Coldfusion I really hope you can help me. I usually read my session variables into a local variable, so that I don't have to create endless read locks. But I came across some interesting behavior. Note that I have not applied any write locks for brevity's sake: Consider the following: EXAMPLE 1: <cfset session.testvalue = 1 /> <cfset lcktestvalue = session.testvalue /> <cfoutput>#lcktestvalue#</cfoutput><br /> <cfset session.testvalue = 2 /> <cfoutput>#lcktestvalue#</cfoutput> OUTPUT: 1 1 EXAMPLE 2: <cfset session.testvalue1.item = 1 /> <cfset lcktestvalue1 = session.testvalue1 /> <cfoutput>#lcktestvalue1.item#</cfoutput><br /> <cfset session.testvalue1.item = 2 /> <cfoutput>#lcktestvalue1.item#</cfoutput> OUTPUT: 1 2 I am trying to work out why the second example, updates the 'lcktestvalue1.item', when the value was only read once? I would have expected example 1 & 2 to produce the same output, and the following to produce the second example's output: EXAMPLE 3: <cfset session.testvalue1.item = 1 /> <cfset lcktestvalue1 = session.testvalue1 /> <cfoutput>#lcktestvalue1.item#</cfoutput><br /> <cfset session.testvalue1.item = 2 /> <cfset lcktestvalue1 = session.testvalue1 /> <cfoutput>#lcktestvalue1.item#</cfoutput> OUTPUT: 1 2 The only reason for this behavior, I can think of, is that the second example, uses a structure inside a structure. But,I cannot expand on this concept. Can you? I really need to understand this, because I am creating a shopping cart, which makes extensive use of the methodology in example 2. It actually works fine, but I am not sure why, and I am afraid under load, it may fail? Thank you for any help you can give me on this. A: Because your second example is making a pointer, or a reference, from the original value to the new value. You can think of it is an imaginary string between the two such that when one is changed - the other is as well. This happens with structures. You can get around this by using duplicate. But NOTE! The need to obsessively cflock session/app/server variables has NOT been necessary for nearly ten years. You still have to worry about race conditions, but for 99% of the time this is not your concern. A: Charles, This is is expected behavior. Structures and objects are passed by reference - meaning you are actually just setting a pointer to a memory location to get at the underlying object. When the set statement is dealing with a primitive (a string, number, date etc) it copies the data into your new variable - so this: <Cfset session.testvalue = 1/> <cfset testvalue = session.testvalue/> ...actually creates 2 locations each containing a "1" When you are dealing with an object however (a structure, component, function, query etc. - anything not primitive), like this: <cfset session.testvalue.item1 = 1/> <cfset testvalue = session.testvalue/> The variables.testvalue variable is actually a pointer to the structure you created in the set statement (session.testvalue.item1 implicitely creates a structure). This is important fundamental stuff - especially when dealing with CFCs, functions, application scopes etc. This post on Primitive vs complex variables explains it in more detail. It has nothing to do with locking by the way. Unless you have some demonstratable race condition you need not go overbord with locking. I would note that your practice here is probably not a great idea - you should probably be scoping your local vars as variables.varName any way in which case pushing session variables to that scope is not saving you any effort. NOTE: While I was writing this Ray chimed in with a short concise answer exactly to the point (while I was being verbose). NOTE 2: In ColdFusion there is one nuance that some find unexpected - arrays are passed by value (as a copy) and not by reference. This can throw you sometimes - and if you ever do an array of objects
{ "pile_set_name": "StackExchange" }
Q: Button clicks in API level 3? I've written a relatively simple app, and I've been testing it out on the various different API levels created through the SDK and AVD manager in Eclipse. It works great in all API levels except for level 3. I have a few spinners on the front page which work just fine, but my four buttons don't seem to be working. I've tried adding a breakpoint in one of the 'onClick' methods that I specified in my xml layout file, but the breakpoint never seems to get reached. I'm kind of at a loss here. Does anyone have any idea what could be going on here? A: Level 3 does not support the onClick attribute in XML. Unfortunately, you'll have to wire up OnClickListeners in code. ... or drop support for 1.5. It's a small and shrinking part of the market.
{ "pile_set_name": "StackExchange" }
Q: Équivalent to $\sum_{k=0}^n \binom{2n}{k} $ Hollo Let $u_n = \sum_{k=0}^n \binom{2n}{k} $ then after change indice and pascal relation we have u_0=1 and. $u_n = 4u_n -\frac{1}{n+1} \binom{2n}{n}$. We remark. u_n équivalent (2/pi)*4^n A: Note that $2u_n=4^n+{2n\choose n}$. And ${2n\choose n}\sim\dfrac{4^n}{\sqrt{n\pi}}$ (easy to prove with Wallis' integrals or Stirling's formula), hence $u_n\sim 2^{2n-1}$.
{ "pile_set_name": "StackExchange" }
Q: How can I manage a rapidly changing copy deck with a fixed deadline? One of the projects I am managing is the creation of a large website for a very sensitive client. I am in a position where it's crunch time and I am being asked to promise on delivery dates for sections of the site. While we are delivering sections for review I am receiving back lists of issues to resolve. These are a mix of copy errors and new copy. The new copy is mostly small but it is quickly building up, and each change requires extensive testing to ensure the site works well in mobile/tablet/desktop layouts. What process can I implement to show the customer that their copy changes have an impact that needs to move the delivery date? Keeping in mind that I don't want to offend the client since some of these are small changes, it's just the volume of changes that is causing the issue. Each time they submit something like "add this section to the site with this sentence" should I be having them go through a formal process? A: A simple burn down chart might do the trick. We'll side step estimating and the value of it right now, that's a longer term thing that will help in the long run. Instead we'll go with fixed time as it sounds like you have a really solid grasp of the work you have to do. Step 1: Determine the number of workable hours remaining in your project. This is your Capacity. Step 2: Determine the total amount of work to be done. This is three sub-tasks. 2A- New Copy: For this, use hours as best as you can manage. The key is to well understand the "New Copy" effort. For example say you know that roughly 500 words of new copy takes an hour to implement, divide all the new copy by 500 and that's the number of hours for New Copy. Now divide the amount of done work by the new copy work. This gives you a percentage of change. This can be used to project how many hours of new copy you can expect to come from the undone work. 2B- Estimate your upcoming copy edits. Look at the work you have already done, determine how much copy you have put in and how much copy edit has been asked for. This is a percentage of change. Apply that to your undone work. Then figure out how long it takes to fix X amount of copy. For example 1000 words per hour. 2C- Determine how much time is left for new functionality/ pages. Step 3: Add up all of Step 2 and determine how many hours of work there is right now. Then add in the projected work for copy edits and new copy. This is your projected work. Do a simple graph with the vertical axis showing two values, total work to do and total work to be done. The horizontal is a date line. Now chart your progress based on the number of working hours per day. Say you can do six hours of work a day, each day the to do is reduced by six hours. Project this line out and see if you will be done on the due date. Do the same for project work to be done. Step 4: I'm going to assume you're already not going to make your date, much less be able to take new copy. Put all the remaining new development, current copy edit, current new copy into a single list. If you can meet with the client face to face use 3x5 cards if not use a spreadsheet. Step 5: Show the customer the burn down. Show them how the date won't be made (or won't be made if new work is added). Ask them what they want to do. When they say "What should we do?" pull out the list of work to be done and have them prioritize it in rank order (nothing can be equal). Feel free to ping me direct if you have more questions.
{ "pile_set_name": "StackExchange" }
Q: .htaccess 301 Redirect with HTTPS I recently had a client site change a page name, for SEO purposes, and we needed to do a redirect on the old link to the new one, but for some reason its not working correctly. The .htaccess looks like this: AddHandler php5-script .php RewriteEngine On # Turn on the rewriting engine RewriteCond %{SERVER_PORT} !^443$ RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] RewriteRule ^([^\.]+)$ $1.php [NC,L] Redirect 301 /oldpage1 /newpage1 Redirect 301 /oldpage2 /newpage2 But the page gets redirected to be: http://examplesite.com:443/newpage1 I've even tried doing the 301's like this: Redirect 301 /oldpage1 https://examplesite.com/newpage1 Both ways produce the same result. Any ideas? A: You should not mix mod_rewrite rules with mod_alias ones and also you need to keep external redirect rules before internal rewrite ones. Try this: AddHandler php5-script .php RewriteEngine On RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE] RewriteRule ^oldpage1/?$ /newpage1 [L,NC,R=301] RewriteRule ^oldpage2/?$ /newpage2 [L,NC,R=301] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC] RewriteRule ^(.+?)/?$ /$1.php [L]
{ "pile_set_name": "StackExchange" }
Q: Knockout js disable button if parent hasClass Is it possible to disable a button inside of a child div if $("#parent").hasClass("bar"); without putting a data-bind... attribute on the actual button? Below is my code. I sense this is possible but I am not sure I am approaching it right: The HTML: <div id="parent" class=""> <div class='active'> <button>Button 1</button> </div> <div> The JS function foo(){ var self = this; self.parent = ko.pureComputed(function(){ return $('#parent').hasClass('bar'); }); if(self.parent){ $('.active button').attr("disabled",true); } }; ko.applyBindings(foo); The reason for this approach is that there are going to be many, many child divs but only one with the active class and I am concerned about binding all of them if I don't have to. Many thanks, A: how about just using a subscription and stealing monkey_dev1300 jquery. run snippet below. and change the class from foo to bar. function viewModel(){ var self = this; this.parentCss = ko.observable('foo'); } var vm = new viewModel() ko.applyBindings(vm); vm.parentCss.subscribe(function(newValue) { if(newValue === 'bar') { $('.active button').attr("disabled",true); } else {{ $('.active button').attr("disabled",false); }} }); <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> change class: <input data-bind="value: parentCss"/> </p> <div id="parent" data-bind="css: parentCss" <div class='active'> <button >Button 1</button> </div> <div class='active'> <button >Button 2</button> </div> <div class='active'> <button >Button 3</button> </div> <div>
{ "pile_set_name": "StackExchange" }
Q: Looping through array doesnt seem to work This program supposed to go through the file and when character matches one of the given patterns assign either 0 or 1 to its array cell. And later display hidden message from spaces and stars. But it assigns either 0 or 1 to all cells in the array based on the last character in the file. EXAMPLE FILE TO LOOP THROUGH(30A.dat): ZuVbJJgFyMuVaXsRkgPuHJmNgiNPFJmHDVRFmPcNLgDykaFugooidgyBhgNEsVdXCcsaYyaYQEGsNhpIxOJHyFjluiNvoFJLSTRVlEPPHGNowGeavuRnNySivmuQXXLgxDKRXPutaBOgNYiZvtPwoYHXEFcrVVOJwirHoOwmxDqFILoHfygqNcBfXLsDMXtNymytqEgCeoMoIosuctXbsmDUsmfBwzJqBMyTHjaunrlTWjzxMuBhvUGIxRAqcrFheCGUzlhLKeLHAcsvaZCaNyzuwiMgkVBbLzBHPUiXlXDXTIwjqTHvIeWFTXLdDYccceSQBfIXDagvZPesYQdjeeUVZVqdyxPcFwxaWJywgWXviFkyKoz int tab_a[a][c]; int i = 0; int j = 0; while((znak = fgetc(plik2)) != EOF){ for(int i = 0; i < a; i++){ for(int j = 0; j < c; j++){ if((znak == 'a') || (znak == 'B') || (znak == 'c') || (znak == 'D') || (znak == 'e') || (znak == 'F') || (znak == 'g') || (znak == 'H') || (znak == 'i') || (znak == 'J') || (znak == 'k') || (znak == 'L') || (znak == 'm') || (znak == 'N') || (znak == 'o') || (znak == 'P') || (znak == 'q') || (znak == 'R') || (znak == 's') || (znak == 'T') || (znak == 'u') || (znak == 'V') || (znak == 'w') || (znak == 'X') || (znak == 'y') || (znak == 'Z')) { tab_a[i][j] = 0; } else if((znak == 'A') || (znak == 'b') || (znak == 'C') || (znak == 'd') || (znak == 'E') || (znak == 'f') || (znak == 'G') || (znak == 'h') || (znak == 'I') || (znak == 'j') || (znak == 'K') || (znak == 'l') || (znak == 'M') || (znak == 'n') || (znak == 'O') || (znak == 'p') || (znak == 'Q') || (znak == 'r') || (znak == 'S') || (znak == 't') || (znak == 'U') || (znak == 'v') || (znak == 'W') || (znak == 'x') || (znak == 'Y') || (znak == 'z')) { tab_a[i][j] = 1; } } } } for(int i = 0; i < a; i++){ for(int j = 0; j < c; j++){ if(tab_a[i][j] == 1){ printf("*"); } else{ printf(" "); } } printf("\n"); } fclose(plik); A: Something like this might work. Create an array of valid characters. Read a character from the file into znak. strchr will check to see if znak is one of the valid characters. If so, set a zero. If not, set a one. Increment j. If j is equal to c, reset j to zero and increment i. Read another character. When i is equal to a, the array is full. Break out of the loop. char valid[] = "aBcDeFgHiJkLmNoPqRsTuVwXyZ"; while ( (znak = fgetc(plik2)) != EOF) { if ( strchr ( valid, znak)) { tab_a[i][j] = 0; } else { tab_a[i][j] = 1; } j++; if ( j >= c) { j = 0; i++; if ( i >= a) { break; } } }
{ "pile_set_name": "StackExchange" }
Q: Cannot pass Global Variables to Multiple Functions inside a Module in Python After going through every possible resources I came to conclusion that I need an urgent help to pass global variables from a function to others inside a Module in Python. Actually I am writing a small UI in Autodesk Maya2010, here is a brief about the problem. In the following code I have got two Module Level Global Variables, I am assigning values to them inside a function. Now if I pass these variables directly(i.e. without converting the function call and assigning it as a string) then the code works fine, however since the Command Flag of the Button Function only allows a string or a function name hence I am stuck with this way of calling the function. The result which I get is : temp_var=None a_Window=None which I have got no idea about. Can anyone point down what exactly is happening when I use the string value as function call? **The sample code**: import maya.cmds; temp_var=None; a_Window=None; def im_PrimaryFunc(): imSecondary_func(); def imSecondary_func(): global a_Window; global temp_var; a_Window=maya.cmds.window(title="Something"); a_layout=maya.cmds.columnLayout(adj=1,rs=10); temp_var=maya.cmds.createNode("polySphere"); func_call="a_calledFunc(a_Window,temp_var)"; maya.cmds.button(label="call_aFunc",align="center",command=func_call); maya.cmds.showWindow(a_Window); def a_calledFunc(arg00,arg01): print(arg00); print(arg01); A: Try this code import maya.cmds from functools import partial temp_var=None a_Window=None def im_PrimaryFunc(): imSecondary_func() def imSecondary_func(): global a_Window global temp_var a_Window=maya.cmds.window(title="Something") a_layout=maya.cmds.columnLayout(adj=1,rs=10) temp_var=maya.cmds.createNode("polySphere") maya.cmds.button(label="call_aFunc",align="center",command = partial(a_calledFunc,temp_var, a_Window)) maya.cmds.showWindow(a_Window) def a_calledFunc(arg00,arg01, part): print(arg00) print(arg01) im_PrimaryFunc() Remember that you are writing python code so there is no need to add ; in your code :)
{ "pile_set_name": "StackExchange" }
Q: how can i generate Javascript and with PHP and put it into a .js file I want to generate javascript dinamically with php, but i want the code to appear in a different file, and call it from my index file in order to have a better structured code. Do you know a good way to do so? A: You can name a file anything you want as long as the file name ends with .php (or whatever extension is run by PHP). In the past I have used a file name like script.js.php so that I know it's JavaScript built by PHP. At the beginning of the file make sure you change the mime type. This has to be at the very beginning of the file with no white space before it. <?php header("Content-type: text/javascript"); ?> In your index file you would reference it like common JavaScript. <script src="script.js.php"></script> After your header you would have code like this: var data = <?php echo json_encode($data); ?>;
{ "pile_set_name": "StackExchange" }
Q: Binding data to html5 DataList in asp.net I'm trying my hands with HTML5. Is it possible to bind data to datalist in html5 as we bind data from a datatable to asp.net dropdown control. Where i can find this details. any pointers is much appreciated. :) Thanks A: 1) Assign runat="server" to the datalist so that it can be accessed from code behind: Enter your favorite browser name:<br /> <input id="browserName" list="browsers" /> <datalist id="browsers" runat="server" /> 2) Loop through the DataTable, construct and concatenate a list of options using a StringBuilder and add the result to the InnerHtml property of the datalist protected void Page_Load(object sender, EventArgs e) { DataTable table = new DataTable(); table.Columns.Add("BrowserName"); table.Rows.Add("IE"); table.Rows.Add("Chrome"); table.Rows.Add("Firefox"); table.Rows.Add("Opera"); table.Rows.Add("Safari"); var builder = new System.Text.StringBuilder(); for (int i = 0; i < table.Rows.Count; i++) builder.Append(String.Format("<option value='{0}'>",table.Rows[i][0])); browsers.InnerHtml = builder.ToString(); } If you're going to need this functionality in multiple places in your site, you can either create a WCF service and call it via jQuery where you can populate the datalist or create an HTTP handler like this: 1)Add a Generic Handler to your project and call it AutoCompleteHandler.ashx 2)Inside AutoCompleteHandler.ashx put: public class AutoCompleteHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Clear(); var options = new System.Text.StringBuilder(); options.Append("<option value='IE'>"); options.Append("<option value='Chrome'>"); options.Append("<option value='Firefox'>"); options.Append("<option value='Safari'>"); options.Append("<option value='Opera'>"); context.Response.Write(options.ToString()); context.Response.End(); } public bool IsReusable { get{return false;} } } 3)Call the handler via jQuery when the page loads and populate the datalist with the returned result: <script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $.post('AutoCompleteHandler.ashx', function (data) { $('#browsers').html(data); }); }); </script>
{ "pile_set_name": "StackExchange" }
Q: Why are there so many "Is it appropriate to..." questions on Academia.SE? I am not an academic, I am however a regular SE user. I see several Academia.SE questions in the "hot questions" sidebar. It seems that many of these questions go something like: "Is it appropriate to... ?" "Is it polite to... ?" "Is it normal to... ?" Why are there so many etiquette and protocol type questions at Academia.SE? Is this unique to Academia.SE or are there radically different standards for civility in real life academia? Some numbers from the SE API. There are 4614 total questions, a search for "appropriate" returns 665 results. Roughly 14%. A: Your 14% figure is quite misleading—it includes all questions and answers containing a variant of the term "appropriate," regardless of the topic of the question. Actually, the number of questions with "appropriate" in the title is less than 1% of the total, which I think is entirely reasonable. As I've stated elsewhere, though, academia is about interpersonal interactions—what you might think is reasonable (and what might pass for so in everyday life) might not be so well received in the academic world (for "diplomatic" as well as legal reasons). Asking about etiquette situations is therefore an appropriate use of this board. A: Compared to the world of business, academia has a much less well defined hierarchy. For example, I am line managed by one person, academically managed by another but the actual money for my paycheck comes from a third, fourth and fifth. At any one time I can be collaborating with a bunch of other people answerable to completely different (but equally complex) management structures. And I don't even have many teaching responsibilities to factor in at the moment! But the question of who takes credit/blame for outcomes (publications/funding) will have a major impact on my career. This is no bad thing, indeed it's part of why academics are regarded as independent thinkers (hopefully). Bearing all this in mind, though, sometimes you have to know the boundaries of what is considered acceptable behaviour. It's a bit different to business where you just do what your boss says. (Admittedly that's a slightly simplistic portrayal of the business world but I have worked there as well and the difference is certainly tangible to me).
{ "pile_set_name": "StackExchange" }
Q: Can a human be made with ovum but without sperm? This article says that scientists were successful in making a mouse using only a sperm and no egg (ovum). The article also states that this procedure could be applicable to humans. However, I want to know why didn't they try with only an ovum? Can a human be made only with an ovum, i.e. without sperm? A: Nice question! It is actually very difficult to do so because humans, obviously, are far more complex than some animal species which naturally show parthenogenesis. Just to mention, there are female-only animals also present in nature, such as New Mexico whiptail, which reproduce only by parthenogenesis, meaning that it is not as impractical as one might think. There have been many parthenogenesis tests on mice and monkeys, but they usually result in abnormal development. This is because mammals have imprinted genetic regions, where either the maternal or the paternal chromosome is inactivated in the offspring in order for development to proceed normally. A mammal created by parthenogenesis would have double doses of maternally imprinted genes and lack paternally imprinted genes, leading to developmental abnormalities. It has been suggested that defects in placental folding or interdigitation are one cause of swine parthenote abortive development. During oocyte development, high metaphase promoting factor (MPF) activity causes it to arrest at the metaphase II stage until a sperm fertilizes it. The fertilization event causes intracellular calcium oscillations, and targeted degradation of cyclin B, a regulatory subunit of MPF, thus permitting the oocyte to proceed through meiosis. The most precise and exact mechanism is not known yet. But this does not mean that it is not possible. Actually, it has been done quite a few times; once on June 26, 2007 by International Stem Cell Corporation (ISCC), and once (controversially) on August 2, 2007 by Hwang Woo-Suk. Even the procedure for parthenogenesis (in swine though) in lab is available. To initiate parthenogenesis of swine oocytes, various methods exist to induce an artificial activation that mimics sperm entry, such as calcium ionophore treatment, microinjection of calcium ions, or electrical stimulation. Treatment with cycloheximide, a non-specific protein synthesis inhibitor, enhances parthenote development in swine presumably by continual inhibition of MPF/cyclin B As meiosis proceeds, extrusion of the second polar is blocked by exposure to cytochalasin B. This treatment results in a diploid (2 maternal genomes) parthenote Parthenotes can be surgically transferred to a recipient oviduct for further development, but will succumb to developmental failure after ≈30 days of gestation. The major problem with parthenogenesis in humans is the abnormal development of embryo. This has been accounted by a phenomenon known as genomic imprinting. Genomic imprinting is the epigenetic phenomenon by which certain genes are expressed in a parent-of-origin-specific manner. For example, if the allele inherited from the father is imprinted, it is thereby silenced, and only the allele from the mother is expressed. The death of diploid parthenogenetic or androgenetic mammalian embryos is determined by the absence of expression of the genes of imprinted loci of the maternal or paternal genome, which leads to significant defects in development of tissues and organs. How this exactly works is not known yet, but it is supposed that it evolved to prevent parthenogenesis. Bi-parental reproduction is necessary due to parent-specific epigenetic modification of the genome during gametogenesis, which leads to non-equivalent expression of imprinted genes from the maternal and paternal alleles. Thus, genomic imprinting seems to be ineffective during normal reproduction. As a side note, in the article you refer to, the researchers did not just mix two sperms and produce diploid zygote or something like that. In the procedure, they injected a normal sperm to the above explained abnormal embryo, which later on proved to be viable. They, thus, showed that these kind of embryos can also become viable if they get fertilized by a sperm within time. References: Abnormal development of embryonic and extraembryonic cell lineages in parthenogenetic mouse embryos; Karin S. Sturm, Margaret L. Flannery, Roger A. Pedersen Parthenogenesis - Wikipedia Patient-Specific Stem Cell Lines Derived from Human Parthenogenetic Blastocysts; E.S. Revazova, N.A. Turovets, O.D. Kochetkova, L.B. Kindarova, L.N. Kuzmichev, J.D. Janus, and M.V. Pryzhkova Genomic imprinting is a barrier to parthenogenesis in mammals; Kono T. Genomic Imprinting and Problem of Parthenogenesis in Mammals; E. S. Platonov Mice produced by mitotic reprogramming of sperm injected into haploid parthenogenotes; Toru Suzuki, Maki Asami, Martin Hoffmann, Xin Lu, Miodrag Gužvić, Christoph A. Klein & Anthony C. F. Perry Stem cell fraudster made 'virgin birth' breakthrough; Silver lining for Korean science scandal; 3 Aug 2007, Christopher Williams
{ "pile_set_name": "StackExchange" }
Q: React Hooks in combination with Firebase data not showing on page load I want to use the React Hooks functionality in combination with Firebase. But now when the data is set, the result is only visible when the DOM is being updated. My current code is: import React, { useState, useEffect } from 'react'; import firebase, { getPivotFunction } from '../../firebase'; /** * Return a styled component */ const ListCards = () => { const [data, setData] = useState([]); const userListsRef = firebase .database() .ref('userLists') .child('1234d343f'); useEffect(() => { (async function() { try { const response = await getPivotFunction(userListsRef, 'lists'); setData(response); } catch (e) { console.error(e); } })(); }, []); /** * Return all list cards */ return ( <ul> {data.map(item => ( <li key={item.time}>dummy text</li> ))} </ul> ); }; When the page is beeing rendered for the first time the 'dummy text' is not displayed, only when there is an update beeing triggered. My goal is to let 'dummy text' apear when the page is done loading and data not having a length of 0. In this case getPivotFunction contains: /** Get FireBase data based on a pivot table */ const getPivotFunction = (ref, target) => { let dataArray = []; ref.once('value', userInfo => { userInfo.forEach(function(result) { firebase .database() .ref(target) .child(result.key) .on('value', snapshot => { dataArray.push(snapshot.val()); }); }); }); return dataArray; }; Please let me know A: Your getPivotFunction is an asynchronous function which relies on callback and this using async await on isn't the right approach. You instead need to have a callback /** Get FireBase data based on a pivot table */ const getPivotFunction = (ref, target, callback) => { const dataArray= []; ref.once('value', userChats => { var i = 0; userChats.forEach(function(result) { firebase .database() .ref(target) .child(result.key) .on('value', snapshot => { i++; dataArray.push(snapshot.val()); if(i === userChats.length) { callback(dataArray) } }); }); }); }; and use it like /** * Return a styled component */ const ListCards = () => { const [data, setData] = useState([]); const userListsRef = firebase .database() .ref('userLists') .child('1234d343f'); useEffect(() => { getPivotFunction(userListsRef, 'lists', (response) => { setData(response); }); }, []); /** * Return all list cards */ return ( <ul> {data.map(item => ( <li key={item.time}>dummy text</li> ))} </ul> ); };
{ "pile_set_name": "StackExchange" }
Q: Waterlock, Sails, Angular JWT token gives 403 from browser backend: Sails app w/ Waterlock, Waterlock-local-auth frontend: An angular app I'm running into a issue where postman works fine, gets JWT from /user/jwt all good and dandy but whenever I login through the browser and then attempt to hit /user/jwt it gives 403 forbidden. Any clues? I have CORs enabled for all origins on all routes. Any help would be appriciated! A: To save some time for novices like me: $http won't be passing the session data with the request, so Sails/express server doesn't know which 'session' the /user/jwt request is being made from and hence giving 403, as it should. I guess Postman handles this for you automagically. Added this to my angular config: config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.withCredentials = true; }]).
{ "pile_set_name": "StackExchange" }
Q: Detectng which page the current page in php has been forwarded from? First of all i am very very new to php. I have a page in php named CurrentPage.php. CurrentPage.php is forwarded from a page named PreviousPage.php using the method header('Location:CurrentPage.php'). Now after being forwarded to the page named CurrentPage.php is it possible to find out that this page has been forwarded from PreviousPage.php?(without using sessions). A: You can use the Referer header1 when it is available, but it is not guaranteed to be available (or correct; it can be modified by a malicious user): echo $_SERVER["HTTP_REFERER"]; 1 Yes, it really is misspelled.
{ "pile_set_name": "StackExchange" }
Q: Always stop in App delegate after enabling All exceptions break point When i enable all exceptions breakpoint my app always stops in AppDelegate, but im able to continue the program execution, but its very annoying cause always takes me to the appdelegate. Any ideas why? A: Only enable Objective-C breakpoints. To see the actual statement that is causing the error add an exception breakpoint: From the Main Menu Debug:Breakpoints:Create Exception Breakpoint. Right-click the breakpoint and set the exception to Objective-C. This will ignore other types of exceptions such as from C++. There are parts of the APIs that use exceptions such as Core Data (Apple is Special). Add an action: "po $arg1". Run the app to get the breakpoint and you will be at the line that causes the exception and the error message will be in the debugger console. Breakpoint example: A: If you're using Swift, or you want to have all the exceptions captured, you can change an option on All Exceptions to automatically continue after evaluating actions. Just find it in the Breakpoint Navigator and right/ctrl click the all Exceptions Breakpoint to edit it: Then check the Options box: A: Exceptions in C++ code common and normal. The exception breakpoint catches every raised exception even when they are being handled correctly. So if you don't specify Obj-C only you will notice that execution stops in a lot of seemingly random places. I run into this all the time with AVAudioPlayer especially. Another thing to look out for are missing assets. I came across this question from another asker who seems to have also run into the same issue. Xcode throws an exception in Main() in iOS 8 with 'all exceptions' breakpoint
{ "pile_set_name": "StackExchange" }
Q: Secure, simple php faq creating/editing script to base further development off of? I'm looking to build a simple site centered around a simple faq system in php. The faq concept is simple, but I want to have an administrative-access backend for editing and creating the entries, and securing a login seems more complex and time-consuming, so I'm looking for suggestions for code to start me off. Does anyone know of any open source php scripts or snippets that would work as base code for administrative login to some php scripts that could be used as a simple faq system? Or base code for both, the faq php code + web administrative access code? A: You could take a look at a script repository like Hot Scripts.
{ "pile_set_name": "StackExchange" }
Q: django.request logger not propagated to root? Using Django 1.5.1: DEBUG = False LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { # root logger '': { 'handlers': ['console'], }, #'django.request': { # 'handlers': ['console'], # 'level': 'DEBUG', # 'propagate': False, #}, } } If I uncomment the commented lines and call a view which has 1/0, the traceback is printed to the console: ERROR 2013-11-29 13:33:23,102 base Internal Server Error: /comment/*******/ Traceback (most recent call last): ... File "*****/comments/views.py", line 10, in post 1/0 ZeroDivisionError: integer division or modulo by zero WARNING 2013-11-29 13:33:23,103 csrf Forbidden (CSRF cookie not set.): /comment/******/ [29/Nov/2013 13:33:23] "POST /comment/******/ HTTP/1.0" 500 27 But if the lines stay commented, no traceback is printed to the console, just: [29/Nov/2013 13:33:23] "POST /comment/******/ HTTP/1.0" 500 27 I thought if django.request logger is not configured, it would propagate to the root logger, which prints everything to console. I didn't find any information that django.request is special. Why it doesn't work? Here I read: Prior to Django 1.5, the LOGGING setting always overwrote the default Django logging configuration. From Django 1.5 forward, it is possible to get the project’s logging configuration merged with Django’s defaults, hence you can decide if you want to add to, or replace the existing configuration. If the disable_existing_loggers key in the LOGGING dictConfig is set to True (which is the default) the default configuration is completely overridden. Alternatively you can redefine some or all of the loggers by setting disable_existing_loggers to False. In django/utils/log.py: # Default logging for Django. This sends an email to the site admins on every # HTTP 500 error. Depending on DEBUG, all other log records are either sent to # the console (DEBUG=True) or discarded by mean of the NullHandler (DEBUG=False). DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console':{ 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'null': { 'class': 'django.utils.log.NullHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['console'], }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'py.warnings': { 'handlers': ['console'], }, } } So by default django.request has propagate = False. But In my case I have 'disable_existing_loggers': True. A: The solution is to prevent Django from configuring logging and handle it ourselves. Fortunately this is easy. In settings.py: LOGGING_CONFIG = None LOGGING = {...} # whatever you want, as you already have import logging.config logging.config.dictConfig(LOGGING) UPDATE ~March 2015: Django has clarified their documentation: If the disable_existing_loggers key in the LOGGING dictConfig is set to True then all loggers from the default configuration will be disabled. Disabled loggers are not the same as removed; the logger will still exist, but will silently discard anything logged to it, not even propagating entries to a parent logger. Thus you should be very careful using 'disable_existing_loggers': True; it’s probably not what you want. Instead, you can set disable_existing_loggers to False and redefine some or all of the default loggers; or you can set LOGGING_CONFIG to None and handle logging config yourself. For posterity and detail: The explanation? Most of the confusion I think comes down to Django's poor explanation of disable_existing_loggers, which says that when True, "the default configuration is completely overridden". In your own answer you discovered that is not correct; what's happening is that the existing loggers, which Django already configures, are disabled not replaced. The Python logging documentation explains it better (emphasis added): disable_existing_loggers – If specified as False, loggers which exist when this call is made are left alone. The default is True because this enables old behaviour in a backward-compatible way. This behaviour is to disable any existing loggers unless they or their ancestors are explicitly named in the logging configuration. Based on Django docs we think, "override the defaults with my own LOGGING configuration and anything I don't specify will bubble up". I've tripped over this expectation as well. The behavior we expect is along the lines of replace_existing_loggers (which isn't a real thing). Instead the Django loggers are shut up not bubbled up. We need to prevent the setup of these Django loggers in the first place and here the Django docs are more helpful: If you don’t want to configure logging at all (or you want to manually configure logging using your own approach), you can set LOGGING_CONFIG to None. This will disable the configuration process. Note: Setting LOGGING_CONFIG to None only means that the configuration process is disabled, not logging itself. If you disable the configuration process, Django will still make logging calls, falling back to whatever default logging behavior is defined. Django will still use its loggers but since they are not handled (and then disabled) by the configuration, those loggers will bubble up as expected. A simple test with the above settings: manage.py shell >>> import logging >>> logging.warning('root logger') WARNING 2014-03-11 13:35:08,832 root root logger >>> l = logging.getLogger('django.request') >>> l.warning('request logger') WARNING 2014-03-11 13:38:22,000 django.request request logger >>> l.propagate, l.disabled (1, 0)
{ "pile_set_name": "StackExchange" }
Q: How to clean an image's text before reading with tesseract? I am using tesseract to read text from an image. As my BinaryImage input would not be a simple text over a plain white background, I am getting only 50 % as a correct output. is there any way to preprocess an image so that I can get proper output from tesseract? I have already tried grey scaling and binarizing the image using Otsu's method, but there was no improvement. As I am doing all this using java, it would be helpful if someone can share details of any java lib or steps to get the better results from tesseract. I am not getting proper ImageMagick docs to use it in my Java code as well. Any help on this is appreciated. sample image ( any wireless bill of AT & T) A: I tried to optimize my output by grey scaling and binarizing the image, but it wasn't helpful. Then I tried boofcv to sharpen my image and I got 90% optimized output. before sharpening the image, we can rescale the image if the resolutions are not big enough, using below code: public static BufferedImage scale(BufferedImage img, int imageType, int dWidth, int dHeight, double fWidth, double fHeight) { BufferedImage img = null; if(img != null) { img = new BufferedImage(dWidth, dHeight, imageType); Graphics2D g = img.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight); g.drawRenderedImage(img, at); } return img; } in case, anyone gets stuck in same situation.
{ "pile_set_name": "StackExchange" }
Q: php error using wordpress function get_terms I'm setting a variable in my site this way: $args = array('parent' => 2818,'hide_empty' => false); $best_of_cat_child_terms = get_terms( $args ); -> (functions.php:26) $best_of_cat = $best_of_cat_child_terms; The problem is that I'm also getting this php error: Warning: Invalid argument supplied for foreach() Location: wp-includes/class-wp-term-query.php:373 Call Stack: WP_Term_Query->get_terms() wp-includes/class-wp-term-query.php:287 WP_Term_Query->query() wp-includes/taxonomy.php:1217 get_terms() wp-content/themes/theme-child/functions.php:26 (-> functions.php line 26 marked above) Am I setting this the right way? A: You can check for the error with is_wp_error(), $terms = get_terms( array( 'taxonomy'=> 'category', 'parent' => 2818, 'hide_empty' => 0) ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ echo '<ul>'; foreach ( $terms as $term ) { echo '<li>' . $term->name . '</li>'; } echo '</ul>'; } else{ $error_string = $terms->get_error_message(); echo '<div id="message" class="error"><p>' . $error_string .'</p></div>'; } About the error you told in comment, it's look like you don't run with a WordPress version under 4.5 ? Prior to 4.5.0, the first parameter of get_terms() was a taxonomy or list of taxonomies: $terms = get_terms( 'post_tag', array( 'hide_empty' => false, ) ); Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the $args array: $terms = get_terms( array( 'taxonomy' => 'post_tag', 'hide_empty' => false, ) ); About get_terms() In your case, remove taxonomy from $args and $terms = get_terms('category', $args);
{ "pile_set_name": "StackExchange" }
Q: Composite component folder structure JSF spec 2.2 (2013-03-20) says in item 10.3.3.1 (Declaring a composite component library for use in a Facelet page): If a facelet taglibrary is declared in an XHTML page with a namespace starting with the string “http://java.sun.com/jsf/composite/” (without the quotes), the remainder of the namespace declaration is taken as the name of a resource library [...] If the substring following “http://java.sun.com/jsf/composite/” contains a “/” character, or any characters not legal for a library name the following action must be taken. If application.getProjectStage() is Development an informative error message must be placed in the page and also logged. Otherwise the message must be logged only. So that means it's illegal to have the following folder structure: resources components system something_specific something_even_more_specific and refer to the library name “http://java.sun.com/jsf/composite/components/something_specific”? Is this correct? That seems like a weird restriction. I want my sources structured, not mushed together in an enormous lump. Such hierarchical library actually works in Wildfly 8.0.0.CR1, but I'm not sure if it's wise to rely on this behavior. A "best practices" kind of answers are welcome. A: I'll summarize my findings. Sources: JSF spec issue 740, discussion preceding issue 740, another discussion, JSF spec issue 1141, discussion preceding issue 1141. Slash in a library name is disallowed. Slash in a resource name is allowed. In practice on Mojarra 2.2.5 composite component library just works both in a XHTML namespace declaration, and in taglib's <composite-library-name>components/system</composite-library-name>. I expect that could still break in future Mojarra and/or JSF spec versions. If you use this, you're at JSF spec/impl developers' mercy. Linked issues and discussions have shown them to be willing to preserve backwards compatibility even for unintended features. In MyFaces there is a special setting, org.apache.myfaces.STRICT_JSF_2_ALLOW_SLASH_LIBRARY_NAME (MyFaces issue 3454). I expect that relying on a resource library with slashes in its name, using this setting, could break some functionality such as JSF resource versioning (how can it know what part is a library name and what part belongs to resource name?). I think composite component library hierarchy may be implemented by importing components in a taglib one by one: <tag> <tag-name>test</tag-name> <component> <resource-id> components/system/test.xhtml </resource-id> </component> </tag> Thus the library name effectively becomes "components" and the resource name becomes "system/test.xhtml".
{ "pile_set_name": "StackExchange" }
Q: strcmp wrong usage? I am using the following method in order to compare two versions of a same file. fprintf(stdout, "ref_ptr %s\n", str); fprintf(stdout, "cur_ptr %s\n", cur); if (strcmp(cur, str) < 0) { fprintf(stderr,"Error: bad version!\n"); return -1; } Output : ref_ptr 01.100 01.020.21 cur_ptr 01.100 01.000.46 Error: bad version! In this specific case cur is not greater than str, why ? It works fine when ref_ptr 01.100 01.000.42 However, in the first case I would consider 46 > 21 A: strcmp finds the first mismatch between the strings (if it exists) and reports which string has greater value at the point of mismatch. In your case the first mismatch is here 01.020.21 <- str 01.000.46 <- cur ^ Clearly 2>0 which means cur appears before str in the lexicographical order so the function call strcmp(cur, str) should return negative number. int strcmp( const char *lhs, const char *rhs ); Return value Negative value if lhs appears before rhs in lexicographical order. Zero if lhs and rhs compare equal. Positive value if lhs appears after rhs in lexicographical order.
{ "pile_set_name": "StackExchange" }
Q: simplification of if equals (==) statement How can i simplify the following if statement to remove the repetition? if user.name == "john" && user.age > 10 or user.name == "wendy" && user.age > 10 or user.name == "mary" && user.age > 10 Thanks! A: Use Array#include? if ['john', 'wendy', 'mary'].include?(user.name) && user.age > 10
{ "pile_set_name": "StackExchange" }
Q: Enable button click only after the page is loaded I have a page which contains a listview alone. Upon clicking a row in the list, the next page is loaded. This next page contains a set of buttons. Upon clicking a row in the list, the loading of the next page may take sometime. So if someone is continuously clicking the row then at some point of time, the second page comes and the buttons inside that gets clicked, which I dont require. How can I prevent this clicking of buttons? Can someone help me out. Thanks in advance. A: Use AsyncTask concept to load data for next activity, do as follow: set setEnabled(false) to all buttons inside the onPreExecute() method. do all the background task inside the doInBackground() method. and now again setEnabled(true) to all the buttons so that it become enabled and user can click on the buttons.
{ "pile_set_name": "StackExchange" }
Q: Glide, possible to get image file size (not dimensions)? I am using ACTION_GET_CONTENT and load selected images using Glide. I would like to display the image file size in bytes, but does Glide support a way to get this data? I could find ways to get file size when using ACTION_GET_CONTENT, but I am afraid that if I use those methods, it may unnecessarily read the same file twice. (I read it once for the size, and Glide reads it once more to get the image). This would be particularly bad if the image is a remote image (users could select images from Google Drive). A: You can get the bitmap using SimpleTarget and then you can calculate the size in kb,mb by fetching bytes using getByteCount or getAllocationByteCount Glide .with(context) .load("https://www.somelink.com/image.png") .asBitmap() .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) { int byteCount = Integer.MIN_VALUE; if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT){ byteCount = resource.getByteCount(); }else{ byteCount = resource.getAllocationByteCount(); } int sizeInKB = byteCount / 1024; int sizeInMB = sizeInKB / 1024; image.setImageBitmap(resource); } });
{ "pile_set_name": "StackExchange" }
Q: Querying multiple joined inherited tables filtered by a many-to-many relationship I have an SQLAlchemy scheme that looks roughly like this: participation = db.Table('participation', db.Column('artist_id', db.Integer, db.ForeignKey('artist.id'), primary_key=True), db.Column('song_id', db.Integer, db.ForeignKey('song.id'), primary_key=True), ) class Streamable(db.Model): id = db.Column(db.Integer, primary_key=True) kind = db.Column(db.String(10), nullable=False) score = db.Column(db.Integer, nullable=False) __mapper_args__ = {'polymorphic_on': kind} class Artist(Streamable): id = db.Column(db.Integer, db.ForeignKey('streamable.id'), primary_key=True) name = db.Column(db.Unicode(128), nullable=False) __mapper_args__ = {'polymorphic_identity': 'artist'} class Song(Streamable): id = db.Column(db.Integer, db.ForeignKey('streamable.id'), primary_key=True) name = db.Column(db.Unicode(128), nullable=False) artists = db.relationship("Artist", secondary=participation, backref=db.backref('songs')) __mapper_args__ = {'polymorphic_identity': 'song'} class Video(Streamable): id = db.Column(db.Integer, db.ForeignKey('streamable.id'), primary_key=True) song_id = db.Column(db.Integer, db.ForeignKey('song.id'), nullable=False) song = db.relationship('Song', backref=db.backref('videos', lazy='dynamic'), primaryjoin="Song.id==Video.song_id") __mapper_args__ = {'polymorphic_identity': 'video'} I'd like to do a single query for Songs or Videos that have a particular artist; i.e., these two queries in one query (all queries should be .order_by(Streamable.score)): q1=Streamable.query.with_polymorphic(Video) q1.join(Video.song, participation, Artist).filter(Artist.id==1) q2=Streamable.query.with_polymorphic(Song) q2.join(participation, Artist).filter(Artist.id==1) Here's the best I reached; it emits monstrous SQL and always yields empty results (not sure why): p1=db.aliased(participation) p2=db.aliased(participation) a1=db.aliased(Artist) a2=db.aliased(Artist) q=Streamable.query.with_polymorphic((Video, Song)) q=q.join(p1, a1).join(Video.song, p2, a2) q.filter(db.or_((a1.id==1), (a2.id==1))).order_by('score') What's the right way to do this query, if at all (maybe a relational datastore is not the right tool for my job...)? A: Your queries are basically right. I think the change from join to outerjoin should solve the problem: q=q.outerjoin(p1, a1).outerjoin(Video.song, p2, a2) I would also replace the order_by with: q = q.order_by(Streamable.score)
{ "pile_set_name": "StackExchange" }
Q: SELECT min date for a varchar column The date column of my table is VARCHAR not datetime. Eg entry '03/01/2011' '03/22/2011' '05/22/2010' when I do a SELECT min(entry) FROM table I will get '03/01/2011' as it is the min in alphabetical order. I want to retrieve '05/22/2010' instead which is the min date. How do I convert the column to datetime and get the min. Thanks A: Assuming all entries are 'castable' as datetime: SELECT MIN(CAST(entry as datetime)) FROM table Assuming there might be some cases where entry isnt a datetime: SELECT MIN(CAST(ISNULL(NULLIF(ISDATE([entry]),0),'31/12/9999') as datetime)) FROM table If all records are a date column, as @Steve Wellens recommended, I would change the datetype to a datetime field to save future problems A: I would fix your database schema. Change the column type to a datetime. Otherwise you'll have problems forever.
{ "pile_set_name": "StackExchange" }
Q: From Option to iterator I have a function which consumes an iterator: fn func<T: iter::Iterator<Item = char>>(i: T) { //... } I need to write a function whose input is an Option<char> (type char is not important here, just for illustrative purpose), and depends on the value of input, it should create an empty or an once iterator. My solution is: use std::iter; fn option_iter(input: Option<char>) { let i: Box<iter::Iterator<Item = char>> = if let Some(input) = input { Box::new(iter::once(input)) } else { Box::new(iter::empty()) }; } I find this ugly because of type erasure by Box. I cannot use: let i = if let Some(input) = input { iter::once(input) } else { iter::empty() }; func(i); because the compiler complains the types of two branches are different. Is there any method which does not use Box for this situation? A: Option has an iter method that does what you want.
{ "pile_set_name": "StackExchange" }
Q: Closing .aspx as a fancybox popup with a button I have a javascript function that makes a popup and loads an .aspx page inside the popup. Here is my code: function moveEvent(doTheMove) { var selectedNotesList = getSelectedNoteIDs(); if (doTheMove) { $.fancybox({ 'autoScale': false, 'type': 'iframe', 'height': 225, 'width': 800, 'href': 'Utilities/MoveFileTemplate.aspx?eventID=' + selectedNotesList + '&oldEventCaseFile=' + $('#hidCaseFile').val(), onComplete: function () { $('#fancybox-overlay').unbind(); }, onClosed: function () { $("#viewNotesGrid").flexReload(); } }); } else showMessage("No expenses are selected."); } In my .aspx page I have 3 radio buttons, a DropDownList and 2 buttons. What I am trying to do is close the popup when the user clicks on the "cancel" button instead of having to press the "X" button in the top corner. (When the cancel button is pressed it has to mimic the "X" button so that the "onClosed:" can fire and reload my flexigrid) Any suggestions? A: you can try var theBox; ... function moveEvent(doTheMove) { ... theBox = $.fancybox({ 'autoScale': false, 'type': 'iframe', 'height': 225, 'width': 800, 'href': 'Utilities/MoveFileTemplate.aspx?eventID=' + selectedNotesList + '&oldEventCaseFile=' + $('#hidCaseFile').val(), onComplete: function () { $('#fancybox-overlay').unbind(); }, onClosed: function () { $("#viewNotesGrid").flexReload(); } }); ... } //close the moveEvent function then on the onclick of your cancel button call window.parent.theBox.close(); EDIT(OP): it is actually: parent.$.fancybox.close();
{ "pile_set_name": "StackExchange" }
Q: Multiplying a string with a number in python I need a string consisting of a repetition of a particular character. At the Python console, if I type : n = '0'*8 then n gets assigned a string consisting of 8 zeroes, which is what I expect. But, if I have the same in a Python program (.py file), then the program aborts with an error saying can't multiply sequence by non-int of type 'str' Any way to fix this ? A: You get that error because - in your program - the 8 is actually a string, too. >>> '0'*8 '00000000' >>> '0'*'8' # note the ' around 8 (I spare you the traceback) TypeError: can't multiply sequence by non-int of type 'str' A: I could bet you're using raw_input() to read the value which multiplies the string. You should use input() instead to read the value as an integer, not a string.
{ "pile_set_name": "StackExchange" }
Q: Differenze tra "circa" e "quasi" Ci sono differenze di uso o diverse sfumature di significato tra "circa", nel senso di approssimativamente, e l'avverbio "quasi"? Ad esempio, posso dire Dopo circa un'ora di attesa, ... Dopo quasi un'ora di attesa, ... ma non so se questi avverbi sono sempre interscambiabili. A: Circa significa approssimativamente, mentre quasi significa non del tutto. Quindi una quantità circa uguale ad un'altra può essere di poco minore, uguale, o di poco maggiore, mentre una quantità quasi uguale ad un'altra è solitamente di poco minore, anche se in alcuni rari casi, se l'avvicinamento avviene dalle quantità maggiori a quelle minori, può essere di poco maggiore. Quindi, in questo caso: Circa un'ora = un'ora precisa o un'ora più o meno un numero di minuti o secondi il cui massimo dipende dal contesto Quasi un'ora = un'ora meno un numero di minuti o secondi il cui massimo dipende dal contesto A: È spesso conveniente guardare l'origine latina delle parole: circa è, in latino, una forma alternativa di circum che, a sua volta è l'accusativo di circus, ciò che circonda qualcosa e, per estensione, le immediate vicinanze; quasi è “come se”. Se dico ho aspettato circa un'ora sto dando una misura approssimata del tempo di attesa, senza giudizi. Se dico ho aspettato quasi un'ora intendo che l'attesa è stata più lunga del previsto. L'esempio non tragga in inganno, perché quasi può avere anche un'accezione positiva: ho quasi finito i compiti (cioè mi manca poco a finirli). Non vedo la possibilità di usare circa. Si può dire quasi sempre/quasi tutti ma non circa sempre/circa tutti. Un uso come L'aspetto del tuo nato, Iperione, quivi sostenni, e vidi com'si move circa e vicino a lui Maia e Dione. nel Canto XXII del Paradiso è desueto.
{ "pile_set_name": "StackExchange" }
Q: Exceptions versus guard clauses I'm trying to get my head around Python exceptions. I've read quite a bit on the topic but can't get clear answers to some questions. In particular, I'm still not sure whether to use exceptions or guard clauses for dealing with invalid arguments. I know that this topic is, in general, a big debate with no clear answer. But I'm interested in whether Python in particular, as a language or as a community, has adopted a clear "best practice" answer. It seems that Python is more lax with exceptions and in fact encourages them to be used for control flow. E.g., the StopIterationError. Does this extend to using exceptions to handle argument validation? Here is a sample function I'm looking at: def add_document(data: dict, country: str): """Writes document to the database. """ # Guard clauses if data.get('Name', None) is None: log.warn("Name is none. Returning"); return if data.get('url', None) is None: log.warn("URL is none. Returning"); return <do write> To me, getting an invalid argument is not "exceptional". It is actually expected to happen about 10% of the time. And yet, I still seem to want to warn the user/programmer about it (I wrote this function a year ago and am looking at it again now). Should it therefore fail more loudly? Does Python Zen "Errors should never pass silently." apply here? Or should exceptions still be reserved for cases where either they have to be handled, or the software must be made to terminate? A: Does this extend to using exceptions to handle argument validation? Even more so. Consider C#, which discourages exceptions for control flow, but encourages enforcing function preconditions with exceptions. Should it therefore fail more loudly? Does Python Zen "Errors should never pass silently." apply here? Yes. As it stands the caller has no indication of the success or failure of add_document. Or should exceptions still be reserved for cases where either they have to be handled, or the software must be made to terminate? Every result always "has to be handled". Failure states are no exception. A: I'm still not sure whether to use exceptions or guard clauses for dealing with invalid arguments. Guard clauses and exceptions aren't mutually-exclusive. Failing the condition in a guard clause is often grounds for throwing an exception. In a lot of ways, something like guard_against_none(value) is a shorthand for "throw something if value is None." It seems that Python is more lax with exceptions and in fact encourages them to be used for control flow. E.g., the StopIterationError. Does this extend to using exceptions to handle argument validation? Don't get laxity and a different paradigm confused. A number of languages people tend to learn early these days impose a significant penalty for using exceptions. That fosters a general "exceptions considered harmful," mentality that sticks because there's no context for it. Nobody bothers to tell noobs that it's a limitation in the language and not with exceptions in general. Python is not one of those languages. Exceptions are cheap and efficient enough that using them for control flow is just fine and can make for easier-to-read code. To me, getting an invalid argument is not "exceptional". This code would beg to disagree: def divide(dividend, divisor): """Do a division. The divisor shouldn't be zero.""" return dividend / divisor print divide(12345, 0) Even if you don't check divisor, the divide operation in the returned expression is going to raise a ZeroDivisionError for you. That says that a division by zero happened, but it doesn't give the caller any hint whether it was because of a bug in the function or because the divisor passed into it wasn't valid according to its documentation. It is actually expected to happen about 10% of the time. ... Should it therefore fail more loudly? Yes. No. Maybe. That's a decision you have to make based on your circumstances. This specific case turns the invalid into the valid. The guard clauses as you wrote them don't really guard against anything. They codify an undocumented semantic that says the function will return silently without doing anything if given invalid input. This needs to be part of the function documentation so anyone calling the function understands the potential pitfall. If your program contains a mix of cases, you need different functions that provide different behaviors: def add_document(data, country): """Add a document.""" if <invalid-argument-condition(s)>: raise ValueError("Invalid argument(s).") # Add the document def quietly_add_document(data, country): """Add a document, ignoring invalid input by doing nothing.""" try: add_document(data, country) except ValueError: pass # Don't care if arguments were bogus. Does Python Zen "Errors should never pass silently." apply here? I'm not one for "never x"-type dicta; in this case I'd say it does apply in an "errors should never pass silently except where they should" sort of way. Or should exceptions still be reserved for cases where either they have to be handled, or the software must be made to terminate? Handling and termination are the only possible outcomes of an exception. Termination is there for cases where you know something wrong and none of the callers all the way up to the main program knows how to deal with it.
{ "pile_set_name": "StackExchange" }
Q: LINQ to SQL - Updating Data Context Objects in Partial Classes I have created an extensibility method for deleting one of my Linq To Sql objects called Reservation. Well, in this partial method I created, I want to update some other objects. I can't seem to get the update to be persisted in the database. Here is my partial method for deleting the reservation. public partial class LawEnforcementDataContext { partial void DeleteReservation(Reservation instance) { // Get ID's of those seated in course var roster = new Roster(this, instance.CourseID); var seated = from r in roster.All where r.WaitingList == false select r.ID; // delete the reservation this.ExecuteDynamicDelete(instance); // get seated id's not in original seated ids var newlySeated = from r in roster.All where r.WaitingList == false && !seated.Contains(r.ID) select r.ID; var reservations = this.Reservations.Where(r => newlySeated.Contains(r.ID)); foreach (var r in reservations) { r.Confirmed = false; // Have tried doing nothing, thinking calling code's db.SubmitChanges() would do the trick //this.ExecuteDynamicUpdate(r); HAVE TRIED THIS } //this.SubmitChanges(); HAVE TRIED THIS } } The delete is taking place but the update is not. Commented in the last few lines are some of the things I have tried. Any ideas? Thanks! EDIT Here is what I have done to solve this: public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode) { ChangeSet delta = GetChangeSet(); foreach (var res in delta.Deletes.OfType<Reservation>()) { // Get ID's of those seated in course var roster = new Roster(this, res.CourseID); var seated = from r in roster.All where r.WaitingList == false select r.ID; base.SubmitChanges(failureMode); // get seated id's not in original seated ids var newlySeated = from r in roster.All where r.WaitingList == false && !seated.Contains(r.ID) select r.ID; var reservations = this.Reservations.Where(r => newlySeated.Contains(r.ID)); foreach (var r in reservations) { r.Confirmed = false; } } base.SubmitChanges(failureMode); } A: I expect the problem here is that it has already called GetChangeSet(). I suggest you override SubmitChanges() at the data-context, and apply this logic there instead... partial class LawEnforcementDataContext { public override void SubmitChanges( System.Data.Linq.ConflictMode failureMode) { ChangeSet delta = GetChangeSet(); foreach (var reservation in delta.Deletes.OfType<Reservation>()) { // etc } base.SubmitChanges(failureMode); } }
{ "pile_set_name": "StackExchange" }
Q: Resource intensive multithreading killing other processes I have a very resource intensive code, that I made, so I can split the workload over multiple pthreads. While everything works, the computation is done faster, etc. What I'm guessing happens is that other processes on that processor core get so slow, that they crash after a few seconds of runtime. I already managed to kill random processes like Chrome tabs, the Cinnamon DE or even the entire OS (Kernel?). Code: (It's late, and I'm too tired to make a pseudo code, or even comments..) -- But it's a brute force code, not so much for cracking, but for testing passwords and or CPU IPS. Any ideas how to fix this, while still keeping as much performance as possible? static unsigned int NTHREADS = std::thread::hardware_concurrency(); static int THREAD_COMPLETE = -1; static std::string PASSWORD = ""; static std::string CHARS; static std::mutex MUTEX; void *find_seq(void *arg_0) { unsigned int _arg_0 = *((unsigned int *) arg_0); std::string *str_CURRENT = new std::string(" "); while (true) { for (unsigned int loop_0 = _arg_0; loop_0 < CHARS.length() - 1; loop_0 += NTHREADS) { str_CURRENT->back() = CHARS[loop_0]; if (*str_CURRENT == PASSWORD) { THREAD_COMPLETE = _arg_0; return (void *) str_CURRENT; } } str_CURRENT->back() = CHARS.back(); for (int loop_1 = (str_CURRENT->length() - 1); loop_1 >= 0; loop_1--) { if (str_CURRENT->at(loop_1) == CHARS.back()) { if (loop_1 == 0) str_CURRENT->assign(str_CURRENT->length() + 1, CHARS.front()); else { str_CURRENT->at(loop_1) = CHARS.front(); str_CURRENT->at(loop_1 - 1) = CHARS[CHARS.find(str_CURRENT->at(loop_1 - 1)) + 1]; } } } }; } A: Thank you for your answers and especially Matthew Fisher for his suggestion to try it on another system. After some trial and error I decided to pull back my CPU overclock that I thought was stable (I had it for over a year) and that solved this weird behaviour. I guess that I've never ran such a CPU intensive and (I'm guessing) efficient (In regards to not throttling the full CPU by yielding) script to see this happen. As Matthew suggested I need to come up with a better way than to just constantly check the THREAD_COMPLETE variable with a while true loop, but I hope to resolve that in the comments. Full and updated code for future visitors is here: pastebin.com/jbiYyKBu
{ "pile_set_name": "StackExchange" }
Q: resource fork, Finder information, or similar detritus not allowed on Flutter Ios This is a Flutter project. I used Flavor and two different main file for dev and prod. I got this error message when running on the Actual device. I didn't check on the simulator. How do I fix this issue? I tried to fix this using this way. But not working. I don't I do it correct way. I am beginning for ios development. https://stackoverflow.com/a/39667628/8822337 I tried this way too, I am in the ios folder xattr -lr pwd and then xattr -cr pwd Error CodeSign /Users/myName/Library/Developer/Xcode/DerivedData/Runner-eqlnuvcbgrvptadbnflmaqpmnpuk/Build/Products/Debug-dev-iphoneos/Demo\ app\ Dev.app (in target 'Runner' from project 'Runner') cd /Users/myName/AndroidStudioProjects/demo_app/ios export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate Signing Identity: "Apple Development: My Name (3YT9RVYQUA)" Provisioning Profile: "iOS Team Provisioning Profile: com.demo.demo" (f510aq0c-122c-3d99-c947-c2440s4bd06d) /usr/bin/codesign --force --sign F342223C2F11B79BD9B0B991D9E324B2A3F41B37 --entitlements /Users/myName/Library/Developer/Xcode/DerivedData/Runner-eqlnuvcbgrvptadbnflmaqpmnpuk/Build/Intermediates.noindex/Runner.build/Debug-dev-iphoneos/Runner.build/demo\ app\ Dev.app.xcent --timestamp=none /Users/myName/Library/Developer/Xcode/DerivedData/Runner-eqlnuvcbgrvptadbnflmaqpmnpuk/Build/Products/Debug-dev-iphoneos/demo\ app\ Dev.app /Users/myName/Library/Developer/Xcode/DerivedData/Runner-eqlnuvcbgrvptadbnflmaqpmnpuk/Build/Products/Debug-dev-iphoneos/demo app Dev.app: resource fork, Finder information, or similar detritus not allowed Command CodeSign failed with a nonzero exit code Prod Team is my company mail, Prod bundle identifier is com.demo.demo.prod, Dev Team is my company mail, Dev bundle identifier is com.demo.demo Is it right? A: I know you said you tried this already but just to double check did you try the solution with the path to your project directory this worked for me. After looking at your error closer I believe this is your problem. Your Error: Xcode - resource fork, Finder information, or similar detritus not allowed. According to what I can determine can be fixed like this. Solution Open terminal and execute this command where project_dir would be your flutter project xattr -cr <path_to_project_dir> Or Navigate to your projects root directory from within your terminal then execute this command xattr -cr .
{ "pile_set_name": "StackExchange" }
Q: Is it possible to change the clock frequency of Wifi chip? Is it possible under Linux to change the frequency of Wifi chips e.g. using Intel driver iwlwifi like we do for CPUs? A: A network adapter does not process tasks, queues, or priorities. All it does is convert the message received on one interface to a format compatible with the other one. There is also no way for the adapter to predict the processing that will be required in the next instant (let alone second). Even if there was any logical justification to implement this, which there isn't, it would probably require more processing to manage it than what would be saved. The only way to make such an adapter use less energy is to put it to sleep, if it supports it. Of course it won't be able to handle any communication during sleep.
{ "pile_set_name": "StackExchange" }
Q: How to get machine specific Microsoft.SqlServer.Smo.dll I need to use Server class which is stored in Microsoft.SqlServer.Smo.dll I don't see this assembly in usual References dialog. I have found it at C:/Program Files/Microsoft SQL Server/100/SDK/Assemblies and try to reference from there but Visual Studio throws an error A reference 'C:/Program Files/Microsoft SQL Server/100/SDK/Assemblies/Microsoft.SqlServer.Smo.dll' could not be added. Please make sure that file is accessible, and that it is a valid assembly or COM component. What am I doing wrong? A: C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies is the correct folder location. You need to add references to: Microsoft.SqlServer.ConnectionInfo.dll Microsoft.SqlServer.Smo.dll Microsoft.SqlServer.Management.Sdk.Sfc.dll Microsoft.SqlServer.SqlEnum.dll (These are the minimum files that are required to build an SMO application) Ref.: How to: Create a Visual C# SMO Project in Visual Studio .NET
{ "pile_set_name": "StackExchange" }
Q: How to find the reminder when $982^{40167}$ is divided by 15? I probably have to use Euler's function but I'm not sure how. A: $$\phi(15) = 8$$ which means $$a^8 \equiv 1\pmod {15}$$ $$ 40167 = 7 + 5020 \times 8$$ And $$982 = 65 \times 15 + 7$$ $$982^{40167} \equiv 7^{7} \equiv 13 \pmod {15}$$ EDIT: one may figure out how to calculate $7^{7}$ The story is really simple: $$7^2 \equiv 49 \equiv 4 \pmod{15} $$ Therefore, $$7^4 \equiv 4\times4 \equiv 1 \pmod{15} $$ $$7^7 \equiv 7^4 7^2 7 \equiv 1\times 4 \times 7 \equiv 13 \pmod {15}$$ A: One of the standard approaches is to find the remainder when divided by $3$ and $5$ respectively, then use Chinese Remainder Theorem. $982^{40167}\equiv1^{40167}\equiv1(\text{mod }3)$ $982^{40167}\equiv2^{40167}\equiv2^3\equiv3(\text{mod }5)$ (by the cyclic property $2^4\equiv1(\text{mod }5)$) Now by Chinese Remainder Theorem or simply some trial and error, $982^{40167}\equiv13(\text{mod }15)$
{ "pile_set_name": "StackExchange" }
Q: Is an implied "I know" considered correct English in this type of phrasing I often read or hear statements like "Joe robbed the bank because I saw him running away with the money." Clearly, the literal interpretation is not the intended meaning and there is an understood "I know/state/believe this" before the "because." Today I came across similar wording in a new ad campaign: "If you have seen AT&T's recent advertising campaign, someone is obviously worried." My first thought is, "well what if I haven't seen it?" Here, "then you (should) know" is apparently implied. I don't recall this topic coming up in school, but then I wasn't the best English student. Is this implied phrasing (in formal terms) correct? Is there a specific word to describe it? A: You are questioning the logical validity of the statements. Logical arguments (even if they have one premise and one conclusion) should be precisely worded or their validity can easily be questioned. Take your first example, about Joe robbing a bank. The explicit meaning is that Joe did something because you did something. This is not a logical argument with a premise and conclusion at all. (It's the same form as "I used cream because you used all of the milk." There is no premise-conclusion formulation.) If you want to infer a missing "I know that" or (equivalently) "I conclude that" to the front of the statement, it becomes a logical argument. This doesn't mean its a valid argument, though. If it's not a valid argument, then it's known as a logical fallacy. Interestingly, logical fallacies can be categorized based on interpretation of language and how it's used. The site Logical Fallicies has a lot of information on this, and it's worth reading. Your example of Joe robbing the bank might be considered a logical fallacy of equivocation. (I'm not a logician, so there might be a better category for this.) Equating "running away with" to "stealing" assumes there is no other explanation for Joe to be running away with the money. Making business decisions depend on good reasoning, based on sound (valid) arguments, but decisions are sometimes based on business intuition (a combination of risk taking and experience). You second example might be inferred be identical to: "If you have seen AT&T's recent advertising campaign, then you know that someone (at At&T) is obviously worried." Even though this, by itself, is a logical fallacy (there might be some other explanation for the campaign), it wouldn't necessarily be a meaningless statement. There may be enough context that a logically valid argument could be made. Hearing it at a business meeting, a manager may choose to react a certain way based on this information coupled with his own knowledge of the situation at AT&T. Does it matter, and should you just ignore it? It's good to understand that in some circumstances, knowing how to spot a logical fallacy can be important. In legal matters, precise language is always important, and a logical fallacy can be the basis for a case being dropped "due to a technicality". The answer to the question in your title is that it depends on the circumstances. But inferring meaning runs the risk that is is inferred incorrectly. If you're just reading an advertisement, then is doesn't matter. If you're reading your own bill of indictment, you need to understand words and the concept of logical fallacy.
{ "pile_set_name": "StackExchange" }
Q: MOSFETs leaks current between two water sensors Goal: I've got a set of EC and pH water sensors that need to sit in the same batch of water / capture values real-time for a Arduino project. However my sensors cancel each other out when both are submerged cause it's creating a circuit in said water. So I've been trying to utilize these MOSFETs (JEDEC TO-220AB - RFP30N06LEs) to turn power on and off (sequentially) between both sensors and capture their values. Issue As a test, I've setup two MOSFETs (one for positive, one for ground lines of sensor) and have turned off one sensor, while leaving the other sensor turned on. However even though one sensor is off, I'm still getting a circuit between sensors while both are submerged. If I remove the ground and positive from said MOSFETs, indeed the circuit in the water goes away and my on sensor begins reading correctly. As results of the above test, I think its safe to assume there is a small current leak from the MOSFETs that is only really apparent when measuring a highly conductive medium such as water. I've created a video to outline the issue a little quicker: MOSFET help video question! Question Does anyone have any advice on the best approach to completely kill a current to a sensor within in a conductive medium like water? Are MOSFETs indeed the correct way to go? Any advice would be greatly appreciated! Thank you. A: Needed power isolators is all. https://core-electronics.com.au/gravity-analog-signal-isolator.html allows water probes to be truly power isolated from one another, thus function correctly within the same water source. Thanks!
{ "pile_set_name": "StackExchange" }
Q: Variable inside double qoutes in onclick function Hi guys i have gone through many questions discussing about variable inside double qoutes.But i don't know why those are not workin for me.. My situation is this onclick="cBack(this.form,{$pageurl},{$token})" I have this kind of code inside my page..when clicking the button it calls a function.but in my case it is not working.it shows a reference error in my console.. my callback function function cBack(frm,pageurl,token) { pageurl=pageurl.trim(); frm.method="post"; frm.action=pageurl+'?gtoken='+token; frm.submit(); } Help me solving this.. A: $pageurl and $token are strings and need quotes like this: onclick="cBack(this.form,'{$pageurl}','{$token}')" With plain PHP and no templating engine: onclick='cBack(this.form,<?php echo json_encode($pageurl) ?>, <?php echo json_encode($token) ?>)' Notice I switched to single quotes, because json_encode will use double quotes. This produces save (means encoded) JavaScript parameters regardless of the content of your variables.
{ "pile_set_name": "StackExchange" }
Q: replaceWith not working for option to optgroup I can not replace option tag to optgroup tag using Jquery replaceWith. The code i tried so far, <select id="SelectboxId"> <option value="India">India</option> <option value="Bombae">Bombae</option> <option value="Chennai">Chennai</option> <option value="US">US</option> <option value="California">California</option> <option value="Delaware">Delaware</option> </select> var oSrc = document.getElementById('SelectboxId') for (var i = 0; i < oSrc.options.length; i++) { if (oSrc.options[i].text=="India" | oSrc.options[i].text=="US") { $("#SelectboxId").find('option[value="India"]').replaceWith('<optgroup> India <optgroup/>'); $("#SelectboxId").find('option[value="US"]').replaceWith('<optgroup> US <optgroup/>'); } } Note : There is a way <optgroup value="India">India</optgroup> but i want to do using replaceWith dynamically. Tell me where i am wrong in my code? A: You are actually looking for the wrap() method. For example: $("#SelectboxId option[value='India']").wrap("<optgroup/>)"); From the looks of it, what you actually want to do is to group the states from same country in an <optgroup>. For that first you need a way to indicate to which country an option belongs to. You can use a class or a data attribute for that purpose. Then you can use wrapAll() method as follows: $("#SelectboxId [data-group='india']").wrapAll("<optgroup label='India'/>"); $("#SelectboxId [data-group='US']").wrapAll("<optgroup label='US'/>"); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="SelectboxId"> <option value="Bombae" data-group="india">Bombae</option> <option value="Chennai" data-group="india">Chennai</option> <option value="California" data-group="US">California</option> <option value="Delaware" data-group="US">Delaware</option> </select>
{ "pile_set_name": "StackExchange" }
Q: ADO recordset fails on "memo" datatype during import into Excel I am trying retrieve data from a SQL server, for use in some Excel 2003 macros. I would like to avoid the use of QueryTables, as I don't want this intermediate step of writing and reading from actual sheets. It seems time-consuming and pointless. I have managed to get the recordset, but it contains empty data where the datatype is "memo", on the server. Further, the program crashes where it tries to store the data into a Range. It appears to make it to the first "empty" field and then it gives me a 1004 Error Code. Clearly the memo field is giving me grief. Can anyone make a suggestion as to how to get around this, or what I should be doing differently? objMyConn.connectionString = "ODBC;" _ & "Provider=SQLOLEDB;DRIVER={SQL Server};SERVER=VANDB;" _ & "APP=Microsoft Office 2003;DATABASE=WPDB_BE;Trusted_Connection=Yes;" objMyConn.Open I've been searching online for ages, but this Access / ADO / Excel stuff is exceedingly painful. Please help. Edit 1: I later modified the SQL query with "TOP 1" (SQL version of "LIMIT 1") and found that with that recordset, the memo fields were returned correctly. Similarly, I could SELECT a single problematic field, and get more rows, e.g. "SELECT TOP 52 bad_field FROM ..." So I suspect that the issue is an ADO connection data size limit of some sort? It seems the Access "memo" type is simply like a "MEDIUMTEXT" MySQL type, so how would I get around such a limit? It's a separate question then, but what alternatives are there to the ADO connections? A: You can use your ADO Connection object (objMyConn) to discover the data type (among other attributes) as ADO interprets it: With objMyConn.OpenSchema(adSchemaColumns, Array(Empty, Empty, "your_table_name_here")) .Filter = "COLUMN_NAME = 'your_column_name_here'" MsgBox .Fields("DATA_TYPE").Value End With This will return the integer value of its respective SchemaEnum enum value, use the object browser to discover the enum value. Posting the results here could give a further clue to your problem.
{ "pile_set_name": "StackExchange" }
Q: How can i update my custom listView display? I'm working on a message application and wanna update my custom listView when new message arrive. I have tried several ways to do that but was unsuccessful ...please help with complete description cause m new to android. Here my code public class SMSBroadcastReceiver extends BroadcastReceiver { Messages message1; MessageDbHelper db; Context context=null; SmsInboxList smsInboxList; BroadcastReceiver br; // ADapter adap; private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED"; IntentFilter intentFilter=new IntentFilter(ACTION); @SuppressLint("SimpleDateFormat") @Override public void onReceive(Context context, Intent intent) { // Retrieves a map of extended data from the intent. Bundle bundle = intent.getExtras(); message1 = new Messages(); this.context=context; // context = context.getApplicationContext(); smsInboxList = new SmsInboxList(); // adap=new ADapter(context, R.id.listView_Conversation); MessageDbHelper dbMessagedbHelper = new MessageDbHelper(context, null,null, 0); db = dbMessagedbHelper; try { if (bundle != null) { Object[] pdusObj = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdusObj.length; i++) { SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); String phoneNumber = currentMessage.getDisplayOriginatingAddress(); String senderNum = phoneNumber; String message = currentMessage.getDisplayMessageBody(); Long localLong = Long.valueOf(currentMessage.getTimestampMillis()); String datae = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(localLong.longValue())); /***************** ** @here we getting data for notification ** **/ try { message1.body(message); message1.number(senderNum); message1.date(datae); message1.type("1"); Log.i("" , "body++++++++++++++++" + message1.body); Log.i("" , "num+++++++++++" + message1.number); Log.i("" , "date+++++++++++" + message1.date); Log.i("" , "typeeee++++++++++++" + message1.type); db.insertDataInMsgTable(message1); createNotification(context, message1); } catch (Exception e) { Log.i("", "except" + e); } Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message); } } } } public void createNotification(Context context, Messages message1) { Log.i("", "get body====" + message1.body + "---" + message1.number); Intent intent = new Intent(context, SmsInboxList.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0); Notification notification = new NotificationCompat.Builder(context) .setContentTitle("From: " + message1.number) .setContentText(message1.body).setContentIntent(pendingIntent) .setSmallIcon(R.drawable.app_icon).build(); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notification.flags |= Notification.DEFAULT_LIGHTS; notification.flags |= Notification.FLAG_AUTO_CANCEL; manager.notify(0, notification); try { smsInboxList.adap.notifyDataSetChanged(); } catch(Exception e) { Log.i("", "error in addd==="+e); e.printStackTrace(); } } } And main activity class is public class SmsInboxList extends Activity { public ListView listView; public SmsInboxListAdapter adap ; Contact con; MessageDbHelper dbhelper; ProgressBar prob; LinearLayout rell; public static TextView newMsg; ImageView imgv; ImageView imgv1; ProgressBar pd; Dialog dialog; ArrayList<Messages> arrList = new ArrayList<Messages>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_sms_inbox_list); pd = new ProgressBar(SmsInboxList.this); pd = (ProgressBar) findViewById(R.id.progressBar_Inbox); dbhelper = new MessageDbHelper(this, null, null, 0); dbhelper.cleartable(); Log.i("", "qwertyu==" + dbhelper.getAllreceive().size()); listView = (ListView) findViewById(R.id.listView_Conversation); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) { // TextView number=(TextView)findViewById(R.id.textViewName); String addr = arrList.get(position).number; // number.getText().toString(); Log.i("" + position, "intent no==" + addr); Intent intent = new Intent(getApplicationContext(),ConversationChat.class); try { String key_num = "numbrr"; intent.putExtra(key_num, addr); Log.i("", "in intent put===" + addr); } catch (Exception e) { Log.i("", "putExtra==" + e); } startActivity(intent); } }); // prob=(ProgressBar)findViewById(R.id.progressBarInbox); rell = (LinearLayout) findViewById(R.id.relativeLayout_sent); imgv = (ImageView) findViewById(R.id.imageView_Setting); imgv1 = (ImageView) findViewById(R.id.imageView_Compose); newMsg = (TextView) findViewById(R.id.textView_Compose_new_message); imgv1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), SendMessage.class); startActivity(intent); } }); newMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), SendMessage.class); startActivity(intent); } }); // //////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////// imgv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Intent intent = new Intent(getApplicationContext(),FilterAct.class); // startActivity(intent); dialog=new Dialog(SmsInboxList.this); dialog.setContentView(R.layout.activity_chat_theme); dialog.setTitle("List"); ListView listView=(ListView)dialog.findViewById(R.id.listView_chatTheme); ArrayList<Messagesss> arr=new ArrayList<Messagesss>(); ArrayList<Messagesss> arr_sent=new ArrayList<Messagesss>(); final int image_rec[]={R.drawable.recieve,R.drawable.receive_rec,R.drawable.rec_recei}; final int image_sent[]={R.drawable.sentbubble,R.drawable.sent_rec,R.drawable.rec_sent}; for(int j=0;j<image_sent.length;j++) { Messagesss msg1=new Messagesss(); msg1.resid=image_sent[j]; arr_sent.add(msg1); } for(int i=0;i<image_rec.length;i++) { Messagesss msg=new Messagesss(); msg.resid=image_rec[i]; arr.add(msg); } final CategoryListAdapter1 adapter=new CategoryListAdapter1(SmsInboxList.this, R.id.listView_chatTheme,arr); try{ listView.setAdapter(adapter); } catch(Exception e){ Log.i("", "error in adapter call"+e); } dialog.show(); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { int val=adapter.getItem(position).resid; Log.i("", ""+val); Log.i("", "adapter value======"+adapter.getItem(position).resid); SharedPreferences mPrefs; SharedPreferences.Editor editor; mPrefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); editor = mPrefs.edit(); editor.putInt("hell_receive", image_rec[position]); editor.putInt("hell_sent", image_sent[position]); editor.commit(); dialog.dismiss(); } }); } }); // ///////////////////////////////////////////////////// // ////////////////////////////////////////////// // try { // new ProgressTas().execute(""); // } catch (Exception e) { // Log.i("", "error Progress Task==" + e); // } try{ getSMSInbox(); } catch(Exception e) { Log.i("","getSMSInboxttry"+e); } ArrayList<Messages> mymsg = new ArrayList<Messages>( dbhelper.getAllreceive()); dbhelper.insertDataInMsgTablePrimaryKey(mymsg); dbhelper.getAllreceiveCommon(); for (int i = 0; i < mymsg.size(); i++) { Log.i("" + i, "my dataaaa mymsg=====" + mymsg.get(i).number + "---" + mymsg.get(i).body + "---" + mymsg.get(i).type); } try{ addItem(listView); } catch(Exception e) { Log.i("", "error in call of addItem in smsInbox"+e); } /* * Log.i("", "size my msg =="+mymsg.size()); ArrayList<Messages> * testArr=new ArrayList<Messages>(dbhelper.getAllreceiveCommon()); * * for(int i=0;i<testArr.size();i++) { Log.i(""+i, * "my dataaaa mymsg test=====" * +testArr.get(i).number+"---"+testArr.get(i * ).body+"---"+testArr.get(i).type); * * } */ // setup(); // updateUi(mymsg); } public void chatTheme(){ } @SuppressWarnings({ "deprecation" }) public List<String> getSMSInbox() { List<String> sms2 = new ArrayList<String>(); Uri uri = Uri.parse("content://sms"); Cursor c = getContentResolver().query(uri, null, null, null, null); startManagingCursor(c); arrList.clear(); // Read the msg data and store it in the list if (c.moveToFirst()) { for (int i = 0; i < c.getCount(); i++) { Messages mssg = new Messages(); mssg.set_type("" + c.getString(c.getColumnIndexOrThrow("type"))); mssg.set_person("" + c.getString(c.getColumnIndexOrThrow("person"))); mssg.set_number("" + c.getString(c.getColumnIndexOrThrow("address"))); mssg.set_body("" + c.getString(c.getColumnIndexOrThrow("body"))); mssg.set_date("" + Functions.getTimefromMS(c.getString(c .getColumnIndexOrThrow("date")))); // Log.i(""+c.getString(c.getColumnIndexOrThrow("type")), // "message==="+c.getString(c.getColumnIndexOrThrow("body"))); // Log.i(""+c.getString(c.getColumnIndexOrThrow("_id")), // "reply path==="+c.getString(c.getColumnIndexOrThrow("reply_path_present"))); Log.i("SmsInboxList method part ", "type===="+ c.getString(c.getColumnIndexOrThrow("type")) + "name===="+ c.getString(c.getColumnIndexOrThrow("person")) + "number=="+ c.getString(c.getColumnIndexOrThrow("address")) + "body===="+ c.getString(c.getColumnIndexOrThrow("body")) + "date===="+ c.getString(4)); dbhelper.insertDataInMsgTable(mssg); c.moveToNext(); } } /* * this is very important to dont close cursor if u dont wanna perform * next activity and backtrack to previous activity */ // c.close(); // Set smsList in the arrList adap = new SmsInboxListAdapter(getApplicationContext(), R.id.listView_Conversation); dbhelper.insertDataInMsgTablePrimaryKey(dbhelper.getAllreceive()); arrList=new ArrayList<Messages>(dbhelper.getAllreceiveCommon()); Log.i("", "size cmn=="+arrList.size()); // listView.removeAllViews(); try { try{ adap.notifyDataSetChanged(); } catch(Exception e) { Log.i("", "error in notify dataset"+e); } listView.setAdapter(adap); } catch (Exception e) { Log.i("", "listView" + e); } for (int i = 0; i < arrList.size(); i++) { adap.add(arrList.get(i)); Log.i("", "oyee!!!"); try{ adap.notifyDataSetChanged(); } catch(Exception e) { Log.i("", "error in notify in smsInboxList=="+e); } } Button button=(Button)findViewById(R.id.btn_notify); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try{ getSMSInbox(); Log.i("", "getSmsInbox size of array list=="+arrList.size()); }catch(Exception e) { Log.i("", "error in notify click"); e.printStackTrace(); } } }); return sms2; // } } A: Use listView.invalidate(); after you have made changes to the list Eg. you have added/removed/updated data in listView.
{ "pile_set_name": "StackExchange" }
Q: Sending Text Cross Domain By Bookmarklet I need a user to navigate to a certain page that has a certain div full of useful text. Then click my bookmarklet and send the text in that div back to my server, which is different from the current domain. I have successfully inserted jQuery on the bookmarklet click and selected the text. Now I need to figure out a way to send that text cross domain to my server. I tried JSONP with jQuery and my text is too long for the url. My second idea was to open up a new window and load a page from my domain, and then somehow insert the selected text into the new window, after which the user could click submit and POST that data to my server. This didn't work for javascript cross-site reasons. Anyone have any experience with this or ideas for doing this? Thanks. A: Generate a form (with DOM) and POST the data (you might want to target an iframe, but it will be fire and forget). A: Here is an example to post text to a remote server. And you can print javascript in the remote server if you want to change the page you have the Iframe on to say something like success. Or a popup saying it finished. On the remote server you can print this to make a popup: <script> parent.document.getElementById('postmessage').style.display='block'; parent.alert('Successfully posted');</script> On the webpage you want to send information from make a form and Iframe like this. <span id="postmessage" style="display:none">Success Message</span> <form action="http://www.remoteserver.com/upload_test.php" method="post" target="post_to_iframe"> <input type="hidden" value="the text to send to remote server" /> <input type="submit" value="Submit" /> </form> <!-- When you submit the form it will submit to this iFrame without refreshing the page and it will make the popup and display the message. --> <iframe name="post_to_iframe" style="width: 600px; height: 500px;"></iframe>
{ "pile_set_name": "StackExchange" }
Q: Weird Array Creation in PHP? I was reading the PHP manual for mysqli_stmt_bind_result and saw this code in the comments: while ( $field = $meta->fetch_field() ) { $parameters[] = &$row[$field->name]; } given that neither $params nor $row existed before that line, why/how does that line work? A: PHP doesn't actually have variable declaration. That means in some cases you can reference variables without actually having them declared beforehand. I say some cases because: foreach($undefinedArray as $key=>$value){ // will give a notice and a warning // notice: undefined variable // warning: invalid argument to foreach } But this doesn't mean you can't do something like so: for($i=0;$i<5;$i++){ $undefinedArray[]=$i; } // will create an array with 5 indexes, each holding the numbers 0 through 4 This works because $undefinedArray is not found and created on the fly. Now, regarding your own case. I'm gonna assume you mean this post. And I have to admit, that's a very interesting solution, I'm gonna try to restrain myself from commenting on any kind of bad practice there, but let's get on to explaining it! $params[] = &$row[$field->name]; This is where the magic happens and it's actually due to the &. Because &$row['unknown_index'], actually creates the index! This means that above statement does 2 things. First it creates an array with each column name saved as an index in $row ($row[$field->name]). Then it saves a pointer to each of the elements from $row in $params. call_user_func_array(array($stmt, 'bind_result'), $params); This does $stmt->bind_result(). But passes each of the elements in $params as parameters to bind_result. And since they're passed by reference, each index of $row will hold each of the selected fields. The rest should be easy to figure out now. If you got any questions. Feel free to ask! A: From the first comment. $variables = array(); $data = array(); $meta = $result->result_metadata(); while($field = $meta->fetch_field()) $variables[] = &$data[$field->name]; // pass by reference call_user_func_array(array($result, 'bind_result'), $variables); So what's the problem?
{ "pile_set_name": "StackExchange" }
Q: HTML/CSS Horizontal navigation submenu hover wrong displayed I am creating an HTML page with a horizontal navigation and vertical submenu. Everything is working fine, except the fact, that the hover on the submenu is displayed to the left of the actual menu item. See my jsfiddle: https://jsfiddle.net/qmcte349/ /* Navigation */ nav ul { list-style: none; background-color: #444; text-align: center; padding: 0; margin: 0; } nav li { line-height: 40px; text-align: left; width: 13%; border-bottom: none; height: 50px; display: inline-block; margin-right: -4px; } nav a { font-size: .8em; text-decoration: none; color: #fff; display: block; padding-left: 15px; border-bottom: none; } nav a:hover { background-color: #8e2323; } nav a.active { background-color: #aaa; color: #444; cursor: default; } nav > ul > li { text-align: center; } nav > ul > li > a { padding-left: 0; } /* Sub Menus */ nav li ul { position: absolute; display: none; width: inherit; } nav li:hover ul { display: block; } nav li ul li { display: block; } <nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="#">Verein</a></li> <li><a href="#">Chronik</a></li> <li><a href="#">Termine</a> <ul> <li><a href="#">Veranstaltungen</a></li> <li><a href="#">Übungen</a></li> </ul> </li> <li><a href="#">Bilder und Videos</a></li> <li><a href="#">Links</a></li> </ul> </nav> Thank you for your suggestions! A: Your problem goes from setting width to 13%. This way the li in the submenu also is 13% of its parrent width. Another issue you will see with margin-right: -4px; I suggest this code: nav li { line-height: 40px; text-align: left; border-bottom: none; height: 50px; display: inline-block; } nav > ul > li { width: 13%; margin-right: -4px; } Set the things that are importaint for main menu (menu bar) only to it and not to its children.
{ "pile_set_name": "StackExchange" }
Q: php file exist not finding file I'm having some trouble with deleting a file from a website using PHP. I have some code which uploads a file, (which works) it then resizes, renames, changes image format and saves the uploaded image twice. (Once as the full size image, once as a thumbnail.) This part works fine, no worries. However, I'm writing some error checking code that will delete these uploaded images if the image formats do not match the files extension. (For example, create a bmp file in mspaint and save it. close paint, reopen the bmp file in paint then click file, save as, then save it as a png. What happens is paint will just change the extension and not the file format. Try opening that png with my php script and it will fail with an 'image not a valid png' error. I have written a custom error function to inform the user that the image format is bad. (Because informing users why they have an issue is better than just telling them they have an issue.) The below code will display the name of the file, which does exist, but will not pass the 'file_exists' check. print( $imagename . ".jpg<br/>\n" ); // Displays 'images/filename.jpg' if ( file_exists( $imagename.".jpg" ) ) { unlink( $imagename.".jpg" ); print( "Image deleted<br/>\n" ); } I've tried pre-pending a "/", with no luck, and I'm not really sure why the file isn't being found? Any hints? (And apologies for the huge block of text!) A: Thanks everyone for your help. Using getcwd() confirmed that it was looking in the correct location for the file, however the issue was on my part. My code created the new blank image, then copies the source image to it, (which is the part it would fail at) then if there was a failure, it would then copy the blank images to the final location. At the point of failure, the files do not in fact exist for file_exists to find them" I've now checked for failure and will not copy the file if there was an issue. Again, thanks for your help but once again, PEBCAK!
{ "pile_set_name": "StackExchange" }
Q: jQuery mobile: why fixed header/footer are not really css fixed? jQuery mobile: can I do header/footer really css fixed (like css position:fixed)? To fix header and footer i tried to use jquery-mobile's data-position="fixed" But it looks like ugly on the phone: when I scroll, it appears, disappears and blinks, hm.. that is not what fixed mean to be in css if set header style to: style="position:fixed;z-index:1000" it looks much better - it just fixed and that is all Is there a way to do it out of the box? A: All your questions why this happens and how to fix it: http://jquerymobile.com/test/docs/toolbars/bars-fixed.html For archiving: Known limitations jQuery Mobile uses dynamically re-positioned toolbars for the fixed header effect because very few mobile browsers support the position:fixed CSS property True fixed toolbars: touchOverflowEnabled In order to achieve true fixed toolbars, a browser needs to either support position:fixed or overflow:auto. Fortunately, this support is coming to mobile platforms so we can achieve this with web standards. In jQuery Mobile, we have added a global feature called touchOverflowEnabled that leverages the overflow:auto CSS property on supported platforms like iOS5. When enabled, the framework wraps each page in a container with it's own internal scrolling
{ "pile_set_name": "StackExchange" }
Q: Fix inability of a ComboBox to bind an observalbe collection I have a ComboBox withing a GridView column: ... <GridView AllowsColumnReorder="True" ColumnHeaderToolTip="Info test"> <GridViewColumn Header="Number" Width="120"> <GridViewColumn.CellTemplate> <DataTemplate> <ComboBox ItemsSource="{Binding Path=extensions}" Width="105" IsEditable="True" HorizontalAlignment="Center" Margin="0,0,0,0" BorderThickness="0"> <ComboBox.Resources> <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">15</sys:Double> </ComboBox.Resources> </ComboBox> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> ... In the code behind, "extensions" is an ObserverableCollection<string> that is 100% getting initialized and populated (this is in the class constructor): public partial class MyForm : Window { ... public ObservableCollection<string> extensions; ... public MyForm() { ... Initialize(); } private Initialize() { extensions = new ObservableCollection<string>(); extensions.Add("x100"); extensions.Add("x101"); } } But when the application runs while the comboboxes appear, the binding never happens. What additional step(s) are required for this to be complete/correct? A: First do not use public field, use properties instead. As far as I know public fields doesn't work with binding. public ObservableCollection<string> extensions {get; private set;} Second, probably the datacontext of the combobox is not set to the MyForm instance. Try this <ComboBox ItemsSource="{Binding Path=extensions, RelativeSource={RelativeSource AncestorType={x:Type MyForm}}}" ... >
{ "pile_set_name": "StackExchange" }
Q: Find the density function of $Z=X+Y$ when $X$ and $Y$ are standard normal Two independent random variables $X$ and $Y$ have standard normal distributions. Find the density function of random variable $Z=X+Y$ using the convolution method. This shows this problem on page 4 but it seems to use some tricks that are, well, pretty tricky. In particular getting behind their third line is beyond me. Is there an alternate way to show this that is more straightforward perhaps even with more (unskipped) steps? A: $$f_{Z}(z) = \int_{-\infty}^{\infty} f_X(z - y)f_Y(y)dy \\= \frac{1}{2 \pi}\int_{-\infty}^{\infty} e^{-\frac{(z - y)^2}{2}}e^{-\frac{y^2}{2}}dy \\= \frac{1}{2 \pi}\int_{-\infty}^{\infty} exp\left(-\frac{z^2 - 2zy + 2y^2}{2}\right)dy \\= \frac{1}{2 \pi}\int_{-\infty}^{\infty} exp\left(-\frac{\frac{z^2}{2} - 2zy + 2y^2 + \frac{z^2}{2}}{2}\right)dy \\= \frac{1}{2 \pi}\int_{-\infty}^{\infty} exp\left(-\frac{(\frac{z}{\sqrt{2}} - \sqrt{2}y)^2 + \frac{z^2}{2}}{2}\right)dy \\= \frac{e^{-\frac{z^2}{4}}}{2 \pi}\int_{-\infty}^{\infty} exp\left(-(\frac{z}{\sqrt{2}} - \sqrt{2}y)^2 / 2\right)dy \\= \frac{e^{-\frac{z^2}{4}}}{2\pi} \times \sqrt{\pi} \\= \frac{e^{\frac{-z^2}{4}}}{\sqrt{4 \pi}}$$ So, $Z \sim N(0, 2)$ A: A very simple way of finding the density of Z is to recognize that the sum of Gaussians is still Gaussian. Then you can identify the distribution by finding the mean and variance of Z. $${\mu _Z} = {E_Z}\left[ Z \right] = {E_X}\left[ X \right] + {E_Y}\left[ Y \right] = {\mu _X} + {\mu _Y} = 0$$ and $$\begin{array}{l} \sigma _Z^2 = {E_Z}\left[ {{Z^2}} \right] - \mu _Z^2 = {E_X}\left[ {{X^2}} \right] + 2{E_X}\left[ X \right]{E_Y}\left[ Y \right] + {E_Y}\left[ {{Y^2}} \right] - \mu _Z^2\\ = \left( {\sigma _X^2 + \mu _X^2} \right) + 2{\mu _X}{\mu _Y} + \left( {\sigma _Y^2 + \mu _Y^2} \right) - \left( {\mu _X^2 + 2{\mu _X}{\mu _Y} + \mu _Y^2} \right) = \sigma _X^2 + \sigma _Y^2 = 2 \end{array}$$
{ "pile_set_name": "StackExchange" }
Q: Python - WindowsError: [Error 2] The system cannot find the file specified I have a folder full of pdf files. I'm trying to remove all the spaces from files name and replace them with underscores. Here's what I have so far: import os, sys folder = path to folder FileList = os.listdir(folder) for files in FileList: if ' ' in files: NewName = files.replace(" ", "_") os.rename(files, NewName) When I run this script I get the following error: WindowsError: [Error 2] The system cannot find the file specified I'm guessing there is a pretty simple fix, but I've look all over and cannot find a solution for the life of me. Thanks for the help! A: ... os.rename(os.path.join(folder, files), os.path.join(folder, NewName))
{ "pile_set_name": "StackExchange" }
Q: RestTemplate URI template syntax for collections? I have a Spring Boot 2 service with a method @RequestMapping(path = "/usable/search") public List<Provider> findUsable( @RequestParam(name = "country-id", required = false) Integer countryId, @RequestParam(name = "network-ids[]", required = false) List<Integer> networkIds, @RequestParam(name = "usages[]") Set<Usage> usages) I want to call that service from another Spring Boot service. For this I do HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); val response = restTemplate.exchange( "http://castor-v2/providers/usable/search?network-ids[]={0}&usages[]={1}", HttpMethod.GET, new HttpEntity<Long>(httpHeaders), new ParameterizedTypeReference<List<Provider>>() {}, Collections.singletonList(networkId), Collections.singleton(Usage.MESSAGE_DELIVERY)); This generates a http request like search?network-ids[]=[428]&usages[]=[MESSAGE_DELIVERY] which is wrong (the server bombs with org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.List'; nested exception is java.lang.NumberFormatException: For input string: "[573]"); correct would be search?network-ids[]=77371&usages[]=MESSAGE_DELIVERY. Most likely the URI template is wrong. How should it be to use with Java collections? Update: I created a new api endpoint without the brackets and used UriComponentsBuilder as suggested by @vatsal. A: To easily manipulate URLs / path / params / etc., you can use Spring's UriComponentsBuilder class. It's cleaner that manually concatenating strings and it takes care of the URL encoding for you: Simple code to do this using RestTemplate will be as follows: HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); String url = "http://castor-v2/providers/usable/search"; UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParam("country-id", countryId) .queryParam("network-ids[]", networkId) .queryParam("usages[]", Usage.MESSAGE_DELIVERY); HttpEntity<?> entity = new HttpEntity<>(httpHeaders); HttpEntity<String> response = restTemplate.exchange( builder.toUriString(), HttpMethod.GET, entity, String.class); This should resolve your query. Also, make sure you pass Usage as a String. If you still want to continue using Usage as an Object then instead of RequestParam you can use RequestBody and pass it as Body to the POST call.
{ "pile_set_name": "StackExchange" }
Q: issues with tr:odd in jquery I'm trying to write this function where it will take users input from #rc and create a checker board of that size. It works fine when n is an even number like 8, but if n is an odd number ,like 9, every "tr:2n+1" is colored wrong. what is the reason for this ? what should I do with it? Thank you in advance! function setUpCheckBoard() { var n = $("#rc").val(); var stn= Number(n)+1; var col = new Array(stn).join('<td></td>'); var row = new Array(stn).join('<tr>' + col + '</tr>'); $('tbody').append(row); $("tr:odd td:odd").css("background-color", "black"); $("tr:odd td:even").css("background-color", "white"); $("tr:even td:odd").css("background-color", "white"); $("tr:even td:even").css("background-color", "black"); } A: You want this: $("tr:odd td:nth-child(2n+1)").css("background-color", "black"); $("tr:odd td:nth-child(2n)").css("background-color", "white"); $("tr:even td:nth-child(2n+1)").css("background-color", "white"); $("tr:even td:nth-child(2n)").css("background-color", "black"); The :odd and :even selectors don't care about the parent/child relationships of the selected elements; they select every other element out of all the matching elements. So, you take tr:odd td and get a bunch of td elements from various rows of the table. When you do the :odd ones of those, jQuery just counts through every other matching td — some of which will be in the first column, and some of which will be in the second. Using :nth-child(2n) and :nth-child(2n+1) specifically selects elements based on where they're positioned within their parent row.
{ "pile_set_name": "StackExchange" }
Q: scheduleOnce not working on my CCLayer class, when set in onEnter I have a CCLayer class that is a child of a base class I created that is, itself, a child of CCLayer. After creating this type of class hierarchy, I can not get the onEnter method of my child class to successfully schedule a method call. How can I fix this? I am trying to get started on a gaming project but I've hit a bit of a brick wall. This seems to be a common problem, however, I can't find a scenario similar to mine and, thus, can't derive a solution. I have a child CCLayer class that I've created, and it is essentially the exact same thing as the IntroLayer in the Cocos2D, starter iPhone template. In fact, my class is the exact same class with one major exception-- I created a base class that I derived from CCLayer, and that is used as my parent of my IntroLayer. My problem is that in the onEnter method of my child layer, I see that my transition method is being set in my scheduleOnce assignment. The problem, though, is that my transition method is never being called? I'm not sure what I am doing incorrectly. The code posted below is my .m file for a my IntroLayer. IntroLayer.m @implementation IntroLayer //Child of "MyBaseCCLayer" +(CCScene *) scene { CCScene *scene = [CCScene node]; IntroLayer *layer = [IntroLayer node]; [scene addChild: layer]; return scene; } -(void) onEnter { //This is calling an overridden onEnter of my base CCLayer. // See snippet below. [super onEnter]; CGSize size = [[CCDirector sharedDirector] winSize]; CCSprite *background; background = [CCSprite spriteWithFile:@"Default.png"]; [background setPosition:ccp(size.width/2, size.height/2)]; [background setZOrder: Z_BACKGROUND]; [self addChild: background]; //In one second transition to the new scene // I can put a break point here, and this being set. // It never gets called, though. [self scheduleOnce:@selector(makeTransition:) delay:1.0]; } -(void) makeTransition:(ccTime)delay { //Here is where I would transition to my menu. // This is a fresh project, so it's going to a test screen. // The problem is this method never fires. [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:0.5 scene:[TestLayer scene] withColor:ccBLACK]]; } -(void) dealloc { [super dealloc]; } @end MyBaseCCLayer.m //^boilerplate snip^ -(void) onEnter { //Setup overlay CGSize size = [[CCDirector sharedDirector] winSize]; ccTexParams tp = {GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT}; //overlay is a class variable, CCSprite object. overlay = [CCSprite spriteWithFile:@"tile_overlay.png" rect:CGRectMake(0, 0, size.width, size.height)]; [overlay retain]; [overlay setPosition: ccp(size.width/2, size.height/2)]; [overlay.texture setTexParameters:&tp]; //Always on top! [overlay setZOrder:Z_OVERLAY]; } -(void) dealloc { [overlay release]; [super dealloc]; } As you can see, there is nothing ground breaking going on here. I created this base class because I want to apply the overlay sprite to ever CCLayer in my application. This is why it made sense to create my own base, CCLayer. However, now that I've created my own base class, my IntroLayer won't call my scheduled method that I'm setting in onEnter. How can I get this to work? A: Your custom class MyBaseCCLayer is overriding the onEnter method, but you omitted the call to [super onEnter]. It's easy to forget sometimes, but calling [super onEnter] is critical to the custom class. Here is the description of the method from the Cocos2D documentation: Event that is called every time the CCNode enters the 'stage'. If the CCNode enters the 'stage' with a transition, this event is called when the transition starts. During onEnter you can't access a sibling node. If you override onEnter, you shall call [super onEnter]. If you take a look inside CCNode.m, you will see what happens inside onEnter: -(void) onEnter { [children_ makeObjectsPerformSelector:@selector(onEnter)]; [self resumeSchedulerAndActions]; isRunning_ = YES; } So you can see that if you override the onEnter method in your custom class, and you don't call [super onEnter], you miss out on this functionality. Essentially your custom node will remain in a 'paused' state.
{ "pile_set_name": "StackExchange" }
Q: What ports are open on xbox? Will it respond to pings/TCP connection? I'm trying to write an application to shut down my pc when I shutdown my xbox. The issue I'm having is my xbox dosent seem to respond to pings. I downloaded a port scanning tool and that didn't find any open ports on it. So I put up wireshark and ran a trace while streaming media to it. I can see TCP traffic travelling initially on 6453 then as "complex-link" on various other ports. I cant connect on telnet to 6453 or the other few I tried. Any advice on how to progress? I'm not sure if the xbox even listens on any ports or how I find out if it does. Possibly there is a more elegant way of doing what I want? (I'm intending to use C# for the actual application) A: It's fairly common security practice to not listen to pings. It can be considered a security risk. I don't think there's a reliable way to do what you want. The Xbox is going to only open ports when it wants to go out and contact other boxes. It's probably not going to sit there and leave ports open.
{ "pile_set_name": "StackExchange" }
Q: Active Directory CSV QUERIES NOT ADMIN My situation: I work at a help desk and have access to the server active directory is on. I do not have edit privileges. I am in control of inventory and need to have a way to get employee information more efficiently then navigating through the AD GUI. I am here asking because I may or may not be able to utilize the information in the manner that I want. I do not want to waste my system admins time asking him to do queries or csv exports for me. I want to use the csv to create an "employee table" in sql so that I only have to put in an employee name when issuing equipment and the name can be linked to this table with information from active directory. This would save a lot of trouble manually putting in information like office codes, addresses , ect. My question: Could I use queries in power shell in a read only capacity to get the information I need in my database? Is there any risk of actually altering the data without admin privileges? Am I free to experiment and learn how to do queries against the data without fear of messing up with the wrong command? Am I explicitly protected against messing up since I don't have elevated privileges or is there any way I could mess something up? A: One of the neat things about PowerShell is the standardization of verbs. The verb "Get" only retrieves information, and "Set" is used to make changes. This holds true in the ActiveDirectory module. As long as you stick with the "Get-" commands, you should be fine. For a list, run this from a PowerShell prompt: Import-Module -Name ActiveDirectory Get-Command -Module ActiveDirectory -Verb Get All the "Set-" commands have "-Confirm" and "-WhatIf" parameters to help protect you as well; use them if you're trying to make changes to check before actually running them. And as HBruijn says, importing the data into SQL might not be the best way, depending on where you're going with all this. It may be better to query both AD and your SQL inventory and match them up on the fly, rather than relying on copies of data that's pretty easily gotten directly from AD.
{ "pile_set_name": "StackExchange" }
Q: why do{ }while() loop doesn't work in body of a button_Click( ) method This code works correctly in a console application, but when I use it in a windows forms application it doesn't work correctly. It never stops and it also produces no output. I use it in a console aplication like this and it works : static void Main(string[] args) { Console.WriteLine("Enter your boolean query"); do{ string query = Console.ReadLine(); List<int> lst = ProcessQuery(query); count = 0; if (lst!=null) { foreach (int a in lst) { if (a == 1) { Console.WriteLine(documentContentList[count]); } count++; } } else { Console.WriteLine("No search result found"); } } while(1==1); } I try to use above code on a button_click method in a windows forms application, but it doesn't work. I think something is wrong with while(1==1) - is there any equivalent? Here is the method I wrote for the button: private void button6_Click(object sender, EventArgs e) { if (t == null) { MessageBox.Show("Click on LoadFile Button,Please."); return; } if (textBox4.Text == "") { MessageBox.Show("Enter your Boolean Query"); return; } listBox1.Items.Clear(); DateTime dt = DateTime.Now; do{ List<int> lst = t.ProcessQuery(textBox4.Text); count = 0; if (lst != null) { foreach (int a in lst) { listBox1.Items.Add(t.documentContentList[count]); } count++; } else { listBox1.Items.Add("No Search Result Found"); } label1.Text = "Search = " + listBox1.Items.Count + " items, " + DateTime.Now.Subtract(dt).TotalSeconds + " s"; } while (1==1); } A: I believe removing the do while loop from the button_click event handler will do the job for you. private void button6_Click(object sender, EventArgs e) { if (t == null) { MessageBox.Show("Click on LoadFile Button,Please."); return; } if (textBox4.Text == "") { MessageBox.Show("Enter your Boolean Query"); return; } listBox1.Items.Clear(); DateTime dt = DateTime.Now; //do{ List<int> lst = t.ProcessQuery(textBox4.Text); count = 0; if (lst != null) { foreach (int a in lst) { listBox1.Items.Add(t.documentContentList[count]); } count++; } else { listBox1.Items.Add("No Search Result Found"); } label1.Text = "Search = " + listBox1.Items.Count + " items, " + DateTime.Now.Subtract(dt).TotalSeconds + " s"; // } while (1==1); } The console application pauses execution when it waits synchronously to get user input with string query = Console.ReadLine(); and when it gets the input it does the necessary computation and prints whatever is to be printed and waits at the same line again for the next input. A winform application does not work this way, it already has an event loop that processes UI activity (KeyPressed etc.) In short, you do not need a loop in the handler method.
{ "pile_set_name": "StackExchange" }
Q: How to intersect two Selects with Joins? SQL I have a table with Artists and another with Prints. I want to get everything from the table Artist and just the print_id from the table Prints. Imagine if I have 3 Artists A, B and C. Imagine if artist A and B participated in print 1 and also 2. Artist C participated on print 2 and 3. What I want is the info about artist A and B because they participated on print 1 but also what other prints they participated (in this case, print 2). Table Artist : Artist A - Brazil. Artist B - USA. Artist C - Belgium. Table Print: 1 - Wave. 2 - Map. 3 - Night. Result Expected: Artist A - Brazil - 1. Artist A - Brazil - 2. Artist B - USA - 1. Artist B - USA - 2. I'm trying like this but I'm getting some errors... SELECT * FROM (SELECT DISTINCT artist.* ,print.print_id FROM artist JOIN print ON artist.artist_id = print.artist_id WHERE print.print_id = 1 INTERSECT SELECT DISTINCT artist.* ,print.print_id FROM artist JOIN print ON artist.artist_id = print.artist_id ) A: You can try using join for the table (select) you have SELECT * FROM ( SELECT DISTINCT Artist.*, Print.print_id FROM Artist JOIN Print ON Artist.artist_id = Print.artist_id WHERE Print.print_id=1 ) as T1 JOIN ( SELECT DISTINCT Artist.*, Print.print_id FROM Artist JOIN Print ON Artist.artist_id = Print.artist_id ) as T2 ON T1.artist_id = T2.artist_id essentially the selects are at tables while a INTERSESCT corresponds to a INNER JOIN with the bond of union keys of the two tables/select
{ "pile_set_name": "StackExchange" }
Q: Applying dataframe-returning function to every row of base dataframe Toy example Suppose that base_df is the tiny dataframe shown below: In [221]: base_df Out[221]: seed I S 0 a 0 b 1 1 a 2 b 3 Note that base_df has a 2-level multi-index for the rows. (Part of the problem here involves "propagating" this multi-index's values in a derived dataframe.) Now, the function fn (definition given at the end of this post) takes an integer seed as argument and returns a 1-column dataframe indexed by string keys1. For example: In [222]: fn(0) Out[222]: F key 01011 0.592845 10100 0.844266 In [223]: fn(1) Out[223]: F key 11110 0.997185 01000 0.932557 11100 0.128124 I want to generate a new dataframe, in essence, by applying fn to every row of base_df, and concatenating the resulting dataframes vertically. More specifically, the desired result would look like this: F I S key 0 a 01011 0.592845 10100 0.844266 b 11110 0.997185 01000 0.932557 11100 0.128124 1 a 01101 0.185082 01110 0.931541 b 00100 0.070725 11011 0.839949 11111 0.121329 11000 0.569311 IOW, conceptually, the desired dataframe is obtained by generating one "sub-dataframe" for each row of base_df, and concatenating these sub-dataframes vertically. The sub-dataframe corresponding to each row has a 3-level multi-index. The first two levels (I and S) of this multi-index come from base_df's multi-index value for that row, while its last level (key), as well as the values for the (lone) F column come from the dataframe returned by fn for that row's seed value. The part I'm not clear on is how to propagate the row's original multi-index value to the rows of the dataframe created by fn for that row's seed value. IMPORTANT: I'm looking for a way to do this that is agnostic to the names of the base_df's multi-index's levels, and their number. I tried the following base_df.apply(lambda row: fn(row.seed), axis=1) ...but the evaluation fails with the error ValueError: Shape of passed values is (4, 2), indices imply (4, 1) Is there some convenient way to do what I'm trying to do? Here's the definition of fn. Its internals are unimportant as far as this question is concerned. What matters is that it takes an integer seed as argument, and returns a dataframe, as described earlier. import numpy def fn(seed, _spec='{{0:0{0:d}b}}'.format(5)): numpy.random.seed(int(seed)) n = numpy.random.randint(2, 5) r = numpy.random.rand(n) k = map(_spec.format, numpy.random.randint(0, 31, size=n)) result = pandas.DataFrame(r, columns=['F'], index=k) result.index.name = 'key' return result 1 In this example, these keys happen to correspond to the binary representation of some integer between 0 and 31, inclusive, but this fact plays no role in the question. A: Option 1 groupby base_df.groupby(level=[0, 1]).apply(fn) F I S key 0 a 11010 0.385245 00010 0.890244 00101 0.040484 b 01001 0.569204 11011 0.802265 00100 0.063107 1 a 00100 0.947827 00100 0.056551 11000 0.084872 b 11110 0.592641 00110 0.130423 11101 0.915945 Option 2 pd.concat pd.concat({t.Index: fn(t.seed) for t in base_df.itertuples()}) F key 0 a 11011 0.592845 00011 0.844266 b 00101 0.997185 01111 0.932557 00000 0.128124 1 a 01011 0.185082 10010 0.931541 b 10011 0.070725 01010 0.839949 01011 0.121329 11001 0.569311
{ "pile_set_name": "StackExchange" }
Q: C# | How Do I Select a Word or Tag in a TextBox by Mouse Location? In Windows Forms, if you double click on a word in a textbox, say with text "Do you want to play a game?", the textbox has the uncanny behaviour of selecting a word and the space after it. It gets worse if you want to select a tag in text like "<stuff><morestuff>My Stuff</morestuff></stuff>" If you double-click in "<stuff>" it selects "<stuff><morestuff>My " Lovely! I want it to just select the word, or the tag in those examples. Any suggestions? A: I see that DoubleClick's EventArgs does not have a mouse position. But MouseDown does provide "MouseEventArgs e", which provides e.Location. So here is what I came up with using control key and mouse down to select a tag like <stuff>. private void txtPattern_MouseDown(object sender, MouseEventArgs e) { if ((ModifierKeys & Keys.Control) == Keys.Control && e.Button == System.Windows.Forms.MouseButtons.Left) { int i = GetMouseToCursorIndex(txtPattern, e.Location); Point p = AreWeInATag(txtPattern.Text, i); txtPattern.SelectionStart = p.X; txtPattern.SelectionLength = p.Y - p.X; } } private int GetMouseToCursorIndex(TextBox ptxtThis, Point pptLocal) { int i = ptxtThis.GetCharIndexFromPosition(pptLocal); int iLength = ptxtThis.Text.Length; if (i == iLength - 1) { //see if user is past int iXLastChar = ptxtThis.GetPositionFromCharIndex(i).X; int iAvgX = iXLastChar / ptxtThis.Text.Length; if (pptLocal.X > iXLastChar + iAvgX) { i = i + 1; } } return i; } private Point AreWeInATag(string psSource, int piIndex) { //Are we in a tag? int i = piIndex; int iStart = i; int iEnd = i; //Check the position of the tags string sBefore = psSource.Substring(0, i); int iStartTag = sBefore.LastIndexOf("<"); int iEndTag = sBefore.LastIndexOf(">"); //Is there an open start tag before if (iStartTag > iEndTag) { iStart = iStartTag; //now check if there is an end tag after the insertion point iStartTag = psSource.Substring(i, psSource.Length - i).IndexOf("<"); iEndTag = psSource.Substring(i, psSource.Length - i).IndexOf(">"); if (iEndTag != -1 && (iEndTag < iStartTag || iStartTag == -1)) { iEnd = iEndTag + i + 1; } } return new Point(iStart, iEnd); }
{ "pile_set_name": "StackExchange" }
Q: Your mobile device as controller for webapps I'm creating a multiplayer game just for fun and exploring different techniques like isometric games, node.js and socket.io. The point is that I've tried to make an alternative approach on multiplayer gaming in a browser. Have a look here; http://ny.scsterallure.nl/ The second player connects to the game by going on his mobile device to http://ny.scsterallure.nl/index.mobile.html All though I'm not finished with the game and controls, I think the mobile device controller shouldn't be a webpage but an app. Since the webpage doesn't handle double taps and other events well. So my question is; are there already some generic (virtual) mobile gamepad apps or is this something new? Also what are your opinions on the whole controller interaction. A: Such a thing already exists -- see Google's ChannelConnect API. I built a game for a client using this technology to do exactly what you're suggesting. I'd post a link, but unfortunately it was a 1-day banner ad game on Youtube. It was hooked up for iOS and Android, using a browser-based controller. And TBH, I don't think it's the world's greatest idea, mainly for reasons of latency. As far as I -- and I think most networked game developers -- are concerned, a game isn't playable when the delay between your manipulating a controller and seeing the effect of that manipulation onscreen is more than a tenth of a second, let alone half a second. So the mobile network had better be damned reliable -- which you cannot guarantee with your players on so many different providers, at different times of day.
{ "pile_set_name": "StackExchange" }
Q: Best practices on load a form inside a main form, both residing in an external DLL assembly I've loaded an external DLL into your project like this Dim assembly As Assembly = Assembly.LoadFile(libraryPath & "filename.dll") Dim type As Type = assembly.[GetType]("NameSpace.ClassName") // i'm loading as a form here but can be any control Dim frm As Form = TryCast(Activator.CreateInstance(type), Form) What are the best practices if you're loading a class or a control inside the loaded form (above) that resides also inside the same assembly ? for instance: Lets say you loaded an assembly consisted of several forms. You load the assembly and create the instance of one of the forms, frm. But inside the loaded form, frm is also loaded another 2nd form, frm2 also belonging to the same assembly. How do i instantiate the second form? do i need to load the assembly again ? Edit: The assembly is a. Net 4.8 class library, that holds several forms, modules and abstract classes. Is being loaded into a winforms also in. Net 4.8. This question applies to both VB and C#. But on my case I'm coding on VB. A: You can load your external assembly in the StartUp event of your application. Open Project->Properties->Application and click the View Application Events button. This will open or generate the ApplicationEvents.vb class file (you'll see, in some comments, the events that are more often handled using the My.Application class). Here, we add a handler to the StartUp event: this event is raised before the application startup form is loaded and shown. We define a Public class object that references the external Library containing the Form resources. This public class object is visible by all other classes in the Application, through the My.Application reference. This class exposes a Public Method, LoadForm(), that allows to load an external Form by Name. Imports System.IO Imports System.Reflection Imports Microsoft.VisualBasic.ApplicationServices Namespace My Partial Friend Class MyApplication Public FormResources As ResourceBag Protected Overrides Function OnStartup(e As StartupEventArgs) As Boolean FormResources = New ResourceBag() Return MyBase.OnStartup(e) End Function Friend Class ResourceBag Private Shared libraryPath As String = "[Your Library path]" Private Shared asm As Assembly = Nothing Public Sub New() Dim resoursePath As String = Path.Combine(libraryPath, "[Your .dll Name].dll") If File.Exists(resoursePath) Then asm = Assembly.LoadFile(resoursePath) End If End Sub Public Function LoadForm(formName As String) As Form If asm Is Nothing Then Throw New BadImageFormatException("Resource Library not loaded") Return TryCast(Activator.CreateInstance(asm.GetType($"[Library Namespace].{formName}")), Form) End Function End Class End Class End Namespace Now, let's assume you have a Form named Form1 in your external library. You can make Form1 load another Form from the external Library or a Form from your assembly using either the LoadForm() method (it creates an instance of a Form in the external library) or the New keyword to create an instance of local Form class. ► If Form1 of the external Library already shows another Form from the same Library, e.g., clicking a Button, there's nothing we have to do: the external new Form is generated as usual. In the sample code that follows, we are instead adding two Buttons to the external Form1 class: One Button loads a Form, Form2, from the external library, using the public method previously defined: Using extForm1 As Form = My.Application.FormResources.LoadForm("Form1") The other Button loads a Form also named Form2, which is instead part of the current Application, using the New keyword: Dim f2 As New Form2() ► The external Form1 instance is created with a Using statement because the ShowDialog() method is used to show the new Form: this requires that we dispose of the Form when it closes, otherwise it cannot dispose of itself when show like this. If you use Show() or Show(Me), the Using block needs to be removed otherwise the Form will be closed instantly. The Form and its Controls/components will be disposed of when it closes anyway. ► The Form2 Form class of your Application cannot have Controls added from the Application Settings (these Control will be disposed of and generate an exception if the Form is shown a second time) Using extForm1 As Form = My.Application.FormResources.LoadForm("Form1") If extForm1 IsNot Nothing Then Dim btnExt = New Button() With { .Location = New Point(20, 50), .Size = New Size(100, 30), .Text = "Lib Form2" } AddHandler btnExt.Click, Sub() Dim f2ext = My.Application.FormResources.LoadForm("Form2") f2ext.Show() End Sub Dim btn = New Button() With { .Location = New Point(140, 50), .Size = New Size(100, 30), .Text = "My Form2" } AddHandler btn.Click, Sub() Dim f2 As New Form2() f2.Show() End Sub extForm1.Controls.AddRange({btnExt, btn}) btnExt.BringToFront() btn.BringToFront() extForm1.StartPosition = FormStartPosition.CenterParent extForm1.ShowDialog(Me) End If End Using
{ "pile_set_name": "StackExchange" }
Q: Translate of $F_{\sigma}$, $G_{\delta}$ and a set of measure $0$ I want to prove the following: Show that (i) the translate of an $F_{\sigma}$ set is also $F_{\sigma}$,(ii) the translate of an $G_{\delta}$ set is also $G_{\delta}$, and (iii) the translate of a set of measure zero also has measure zero. First, if $E$ has measure zero, then since the measure if translation invariant, we have: $$m(E) = 0 \wedge m(E) = m(E + y) \Rightarrow 0 = m(E+y).$$ Now, let $G \subset \mathbb{R} $ to be a $G_{\delta}$ set, then there exist a countable family $\{\mathcal{O}_k: k \in \mathbb{N}\}$ of open sets such that $G = \bigcap_{k \in \mathbb{N}} \mathcal{O}_k$. Now, we have that if $\mathcal{A}$ is a set of subsets of $\mathbb{R}$, then for any element $y \in \mathbb{R}$, we have: $$\left(\bigcap_{A\in\mathcal A}A\right)+y=\bigcap_{A\in\mathcal A}(A+y). \quad \quad (1)$$ Proof: Let $x \in \left(\bigcap_{A\in\mathcal A}A\right)+y$. Then, we have that $x = a + y$, where $\forall A \in \mathcal{A}(a \in A)$, but then this implies that $$\forall A \in \mathcal{A}(a \in A \wedge x = a+y) \Rightarrow x \in \bigcap_{A\in\mathcal A}(A+y).$$ Now, let $x \in \bigcap_{A\in\mathcal A}(A+y)$, then $\forall A \in \mathcal{A}(x = a + y)$, but this means that $a \in \bigcap_{A \in \mathcal{A}}A$, thus $$x \in \left(\bigcap_{A\in\mathcal A}A\right)+y$$ On the other hand, we have that the translate of an open set remains open, in other words, $$ \text{If }I \subset \mathbb{R} \text{ is open } \Rightarrow I+y \text{ is open } \quad \quad (2)$$ Proof: Let $x \in I+y \Rightarrow x-y \in I,$ since $I$ is open there exist $c',d' \in I$ such that $x-y \in (c',d')$,but then $x \in (c,d)$, where $c = c'+y$ and $d = d'+y$. Therefore, $I + y$ is open. Now,using (1) and (2), we have that: $$G + y = (\bigcap_{k \in \mathbb{N}} \mathcal{O}_k) + y = \bigcap_{k \in \mathbb{N}} (\mathcal{O}_k+y),$$ which is a $G_{\delta}$ set, since is a countable intersection of open sets. We thus conclude that $G_{\delta}$ is translation invariant. Now, to prove that $F_{\sigma}$ is translation invariant, it's enough to see that the complement of a $G_{\delta}$ set is a $F_{\sigma}$ set, that is $$ G^c = (\bigcap_{k \in \mathbb{N}} (\mathcal{O}_k))^c = \bigcup_{k \in \mathbb{N}} \mathcal{O}_k^c,$$ where $\mathcal{O}_k^c$ is closed, since $\mathcal{O}_k$ is open.It remains to show that if $A \subset \mathbb{R}$ and $y \in \mathbb{R}$, then: $$(A+y)^c = A^c + y.$$ Proof: $$\begin{align*} x \in A^c +y &\Leftrightarrow x-y \in A^c \\ &\Leftrightarrow x-y \notin A \\ &\Leftrightarrow x \notin A + y \\ &\Leftrightarrow x \in (A+y)^c \end{align*}$$ We thus conclude that a $F_{\sigma}$ set is translation invariant, since: $$G^c+y = (\bigcap_{k \in \mathbb{N}} (\mathcal{O}_k+y))^c = \bigcup_{k \in \mathbb{N}} (\mathcal{O}_k+y)^c = \bigcup_{k \in \mathbb{N}} \mathcal{O}_k^c+y$$ Alternative way: Let $A \subset \mathbb{R}$ to be a $F_{\sigma}$ set, then there exist a family $\{F_k: k \in \mathbb{N}\}$ of closed sets such that: $$A = \bigcup_{k \in \mathbb{N}}F_k.$$ We want to prove that for $y \in \mathbb{R}$, we have: $$A + y \text{ is closed }$$ Clearly, we have $A +y = (\bigcup_{k \in \mathbb{N}}F_k) +y$. Now, notice the following: $$\begin{align*} (\bigcup_{k \in \mathbb{N}}F_k) +y &= \{a+y | a\in \bigcup_{k \in \mathbb{N}}F_k\} \\ &= \exists k \in \mathbb{N}\{a+y|a \in F_k\} \\ &=\bigcup_{k \in \mathbb{N}}\{a+y|a \in F_k\} \\ &= \bigcup_{k \in \mathbb{N}}(F_k +y) \end{align*}$$ It is enough to prove that $F_k+y$ is closed.Indeed, if $x \notin F_k + y \Rightarrow x-y \notin F_k$. Now, since $F_k$ is closed, there exist $r > 0$ such that $$[((x-y)-r,(x+y)+r)]\cap F_k = \emptyset \Rightarrow (x-r,x+y)\cap (F_k + y) = \emptyset,$$ thus $F_k + y$ is closed. A: You seem to have gone off-track. You are quite correct that since $G$ is $G_\delta,$ then there exists a family of open sets $\{\mathscr{O}_k: k \in \mathbb{N}\},$ and I assume that you are wanting to say that the intersection of all of these open sets is exactly $G.$ Unfortunately, that's not what you've said. Rather, you should say that $G=\bigcap_{k\in\Bbb N}\mathscr O_k.$ Then we easily have $$G+y=\left(\bigcap_{k\in\Bbb N}\mathscr O_k\right)+y,$$ but we should justify that this is equal to $\bigcap_{k\in\Bbb N}(\mathscr O_k+y)$. Fortunately, it isn't too difficult to prove that if $\mathcal A$ is a set of subsets of $\Bbb R,$ then for any $y\in\Bbb R,$ we have $$\left(\bigcap_{A\in\mathcal A}A\right)+y=\bigcap_{A\in\mathcal A}(A+y).$$ Now, your claim that $G+y$ is open is unfounded. After all, $\{0\}$ is a $G_\delta$ set, and no translate of $G$ is open! Rather, you need to justify that $\mathscr{O}_k+y$ is open for all $k\in\Bbb N.$ It is enough to prove that the translate of an open interval is open. (Why?) Thus, as a countable intersection of open sets, $G+y$ is a $G_\delta$ set, as desired. All that is left is to prove that if $A\subseteq\Bbb R$ and $y\in\Bbb R,$ then $(A+y)^c=A^c+y,$ whence we can apply DeMorgan's Laws together with the previous results to get the rest. Edit: It looks better! Again, I must note that $G+y$ is not (necessarily) an open set, but a $G_\delta$ set. Regarding your proof that $I+y$ is open: you should show (unless you're relying on previous results) that for any $x\in I+y,$ there exist $c,d\in I+y$ such that $x\in(c,d).$ Use openness of $I$ to find $c',d'\in I$ such that $x-y\in(c',d'),$ and proceed. Regarding your proof that $A^c+y=(A+y)^c,$ we should proceed in a related fashion. Since $x\in A^c+y$ iff $x-y\in A^c$ iff $x-y\notin A$ iff $x\notin A+y$ iff $x\in(A+y)^c$ (which is fairly straightforward to justify), then we're done. Also, "$a+y^c$" doesn't really make sense--what would be the complement of a number? It looks good, otherwise (from what these tired eyes can see).
{ "pile_set_name": "StackExchange" }
Q: Precompiling MVC ASP.NET application via publish, Are the resultant files IL Code or Native Images? Just wanted to check whether the precompiled files from "publish" are IL or Native. The file extension are .compiled for the views, and dlls for others. I have seen some comment that imply that one of the advantages for doing this is to eliminate startup lag due to JIT, but this implies that they are native, but I am not sure. I have chosed "no merging" of files for my first attempt. Confirmation appreciated. Thanks. EDIT Is there any potential difference if I select x86, or "mixed platforms" or "any cpu". The latter 2 might imply IL code whereas x86 could be native. I am targetting a 32bit Azure Websites instance. I am trying to get rid of the warmup period issue. A: It is IL. You can confirm it by running CorFlags.exe. The CorFlags section of the header of a portable executable image will indicate whether its 32bit or AnyCPU etc. Another utility that comes in handy is DUMPBIN.EXE. Even if you precompile your web applications, there's going to be an initial hit when you access the website. That process is described here. Its a tad dated, but much of it still applies. But the hit with a precompiled website is going to be substantially less than a non-precompiled website. When compiling, select "Any CPU" and control whether its a 32bit or 64bit application via IIS, Azure or the hosting environment. Let the framework do what the framework does best.
{ "pile_set_name": "StackExchange" }
Q: current analysis with pre-carried current in the inductor .- confused The direction of the reference i(t) current is certain. When we add the pre-existing currents, it will be -12 amperes, thats okay. But why did we multiply it by - (minus) when we integrating the expression Voltage and multiply it by inductance (I marked it with a yellow marker)? A: I had to do (initial current) - (integral expression) because the current is running out. I get it now
{ "pile_set_name": "StackExchange" }
Q: ClassNotFoundException using ClassLoader in a FileWalker I have a program where the User selects a Directory to begin a FileWalk from; the FileWalker visits each file in the directory structure loading .class files with a CLassLoader so I can use Reflection on them to display information about that class in a GUI. If the user selects the folder FileReader which has this strucuture: D:\Users\Ste\Documents\Eclipse Workspace\Project Tests\File Reader │ ├───+bin │ │ ReadFile.class | │ └───+src │ ReadFile.java The ClassLoader has no problem loading ReadFile.class However if I select the same directory with an added class in the package Test: D:\Users\Ste\Documents\Eclipse Workspace\Project Tests\File Reader │ ├───+bin │ │ ReadFile.class │ │ │ └───+Test │ TestClass.class │ └───+src │ ReadFile.java │ └───+Test TestClass.java Eclipse throws a java.lang.ClassNotFoundException: Test.TestClass. So why am I getting a java.lang.ClassNotFoundException? Below is my code with some System.out.println() to show some values as it goes through. (The directory structure is the same as the strucuture above) public class ReflectOnClasses extends SimpleFileVisitor<Path> { //Starts the file walk from a starting directory public static void startFileWalk(String directory){ //The startingDir is the directory the user selects on the Main UI Part Path startingDir = FileSystems.getDefault().getPath(directory, ""); System.out.println("Staring Directory the user selected: " + startingDir); System.out.println("--------------------------------------------------------------------------------------------------------"); //Create an instance of my FileVisitor ReflectOnClasses reflectOnClasses = new ReflectOnClasses(); try { //Walk the files from my startingDir using reflectOnClasses Files.walkFileTree(startingDir, reflectOnClasses); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("An Error Occured"); e.printStackTrace(); } } //Visit files and do something with them @Override public FileVisitResult visitFile(Path filesPath, BasicFileAttributes attr) { //If we find a .class file get it and reflect upon it if(filesPath.toString().endsWith(".class")){ //Create a File object of the files directory File parentDir = new File(filesPath.getParent().toString()); System.out.println("Parent Directory: " + filesPath.getParent().toString()); try{ //Convert parentDir to URL URL url = parentDir.toURL(); URL[] urls = new URL[]{url}; //Create a new class loader with the directory ClassLoader cl = new URLClassLoader(urls); /* * To load a class we need the class name and the package it belongs too in the format * "example.package.name\FooBar". We can easily get the class name by getting the name * of filesPath and removing the .class on the end */ String className = filesPath.getFileName().toString().replace(".class", ""); System.out.println("The className: " + className); //classesPackage + className String classToLoad = getPackageName(filesPath) + className; System.out.println("The classToLoad: " + classToLoad); //Load in the class Class<?> cls = cl.loadClass(classToLoad); System.out.println("--------------------------------------------------------"); //Pass the name of the class to addClassToVariableTree in CreatUI so it can be added as a TreeItem CreateMainUI.addClassToVariableTree(classToLoad); //Do the same for addClassToMethodTree CreateMainUI.addClassToMethodTree(classToLoad); //Array of the declared fields in the class Field[] fieldsInClass = cls.getDeclaredFields(); //For each field in fieldsInClass we add it as a TreeItem using addVariableToClassTreeItem for( Field field: fieldsInClass){ CreateMainUI.addVariableToClassNameTreeItem(field.getGenericType().toString(), field.getName()); } //Array of all methods in the class Method[] methodsInClass = cls.getDeclaredMethods(); //For each method we pass through the string representation of it, the class it belongs too and it's name. It will be formatted in CreateUI for (Method method : methodsInClass) { CreateMainUI.addMethodToClassNameTreeItem(method.toString(), classToLoad, method.getName()); } } catch (MalformedURLException e) { System.out.println("URL BAD"); } catch (ClassNotFoundException e){ System.out.println("Class couldnt be found"); e.printStackTrace(); } } return CONTINUE; } private String getPackageName(Path filesPath){ /* * To get the package name we will have to construct it manually. If the class * was already loaded we could get the package info using built in Java methods, but we * haven't loaded the class yet and can't without this package information hence we will * build a package name up be traversing back up to the bin folder adding the folder titles * to a String Builder as we go */ File currentFolder = filesPath.toFile().getParentFile(); String classesPackage = ""; while(true){ if(!(currentFolder.getName().equals("bin"))){ classesPackage = currentFolder.getName() + "." + classesPackage; currentFolder = currentFolder.getParentFile(); } else{ break; } } return classesPackage; } } Console output: Staring Directory the user selected: D:\Users\Ste\Documents\Eclipse Workspace\Project Tests\File Reader ---------------------------------------------------- Parent Directory: D:\Users\Ste\Documents\Eclipse Workspace\Project Tests\File Reader\bin The className: ReadFile The classToLoad: ReadFile -------------------------------------------------------- Parent Directory: D:\Users\Ste\Documents\Eclipse Workspace\Project Tests\File Reader\bin\Test The className: TestClass The classToLoad: Test.TestClass Class couldnt be found java.lang.ClassNotFoundException: Test.TestClass at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at ste.wootten.honoursproject.mainpart.reflection.ReflectOnClasses.visitFile(ReflectOnClasses.java:146) at ste.wootten.honoursproject.mainpart.reflection.ReflectOnClasses.visitFile(ReflectOnClasses.java:1) at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:135) at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:199) at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:199) at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:199) at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:69) at java.nio.file.Files.walkFileTree(Files.java:2591) at java.nio.file.Files.walkFileTree(Files.java:2624) at ste.wootten.honoursproject.mainpart.reflection.ReflectOnClasses.startFileWalk(ReflectOnClasses.java:41) at ste.wootten.honoursproject.mainpart.CreateMainUI.selectDirectoryAndBeginFileWalk(CreateMainUI.java:258) at ste.wootten.honoursproject.mainpart.CreateMainUI.createInterface(CreateMainUI.java:159) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:859) at org.eclipse.e4.core.internal.di.InjectorImpl.inject(InjectorImpl.java:111) at org.eclipse.e4.core.internal.di.InjectorImpl.internalMake(InjectorImpl.java:319) at org.eclipse.e4.core.internal.di.InjectorImpl.make(InjectorImpl.java:240) at org.eclipse.e4.core.contexts.ContextInjectionFactory.make(ContextInjectionFactory.java:161) at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.createFromBundle(ReflectionContributionFactory.java:102) at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.doCreate(ReflectionContributionFactory.java:71) at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.create(ReflectionContributionFactory.java:53) at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer.createWidget(ContributedPartRenderer.java:141) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createWidget(PartRenderingEngine.java:896) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:630) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:732) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$2(PartRenderingEngine.java:703) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$7.run(PartRenderingEngine.java:697) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:682) at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1114) at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:67) at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:41) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:180) at org.eclipse.swt.widgets.Display.syncExec(Display.java:4687) at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:187) at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:38) at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:81) at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:58) at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer.postProcess(LazyStackRenderer.java:103) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:646) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:732) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$2(PartRenderingEngine.java:703) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$7.run(PartRenderingEngine.java:697) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:682) at org.eclipse.e4.ui.workbench.renderers.swt.SWTPartRenderer.processContents(SWTPartRenderer.java:59) at org.eclipse.e4.ui.workbench.renderers.swt.PerspectiveRenderer.processContents(PerspectiveRenderer.java:59) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:642) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:732) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$2(PartRenderingEngine.java:703) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$7.run(PartRenderingEngine.java:697) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:682) at org.eclipse.e4.ui.workbench.renderers.swt.PerspectiveStackRenderer.showTab(PerspectiveStackRenderer.java:103) at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:67) at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:41) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:180) at org.eclipse.swt.widgets.Display.syncExec(Display.java:4687) at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:187) at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:38) at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:81) at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:58) at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) at org.eclipse.e4.ui.model.application.ui.advanced.impl.PerspectiveStackImpl.setSelectedElement(PerspectiveStackImpl.java:135) at org.eclipse.e4.ui.model.application.ui.advanced.impl.PerspectiveStackImpl.setSelectedElement(PerspectiveStackImpl.java:1) at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer.postProcess(LazyStackRenderer.java:103) at org.eclipse.e4.ui.workbench.renderers.swt.PerspectiveStackRenderer.postProcess(PerspectiveStackRenderer.java:77) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:646) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:732) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$2(PartRenderingEngine.java:703) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$7.run(PartRenderingEngine.java:697) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:682) at org.eclipse.e4.ui.workbench.renderers.swt.SWTPartRenderer.processContents(SWTPartRenderer.java:59) at org.eclipse.e4.ui.workbench.renderers.swt.WBWRenderer.processContents(WBWRenderer.java:639) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:642) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:732) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$2(PartRenderingEngine.java:703) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$7.run(PartRenderingEngine.java:697) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:682) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:964) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:923) at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86) at org.eclipse.e4.ui.internal.workbench.swt.E4Application.start(E4Application.java:150) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584) at org.eclipse.equinox.launcher.Main.run(Main.java:1438) at org.eclipse.equinox.launcher.Main.main(Main.java:1414) As you can see it finds ReadFile.class and loads that fine, but when I want to load Test.TestClass it says ClassNotFoundException. Any ideas?? A: When you walk TestFile.class File parentDir = new File(filesPath.getParent().toString()); System.out.println("Parent Directory: " + filesPath.getParent().toString()); After this, you have parentDir = "D:\Users\Ste\Documents\Eclipse Workspace\Project Tests\File Reader\bin\Test" URL url = parentDir.toURL(); URL[] urls = new URL[]{url}; //Create a new class loader with the directory ClassLoader cl = new URLClassLoader(urls); After this, you have your class loader search directory to be file:///D:/Users/Ste.../bin/Test which is not correct (there's no /Test/TestClass.class from here to match the compiled Test.TestClass) In this case, you should create your class loader from startingDir + "/bin" and not from parentDir. Here is a very basic Java Package Tutorial in case you need help to understand what is happening.
{ "pile_set_name": "StackExchange" }
Q: XAML Radio Buttons I Have a bound Data grid view to the below Questions Class: public class Questions() { public int QuestionId{get; set;} public string Question {get; set;} public List<Answers> AvailableAnswers {get; Set;} public string SelectedAnswer {get; set;} } public class Answers() { public int AnswerId {get; set;} public string Answer {get; set;} public bool IsSelected {get; set;} } What I need is within my Datagrid to show the Available Answers as Radio buttons and when the user selects one of the radio buttons for the AnswerId to be set as the SelectedAnswer property in the Questions Class. Can anyone help as i have been going round in circles trying to do this A: There are a few ways you can do this if you are using MVVM within your view-model you can create a public property such as private bool _isAnswer1; public bool IsAnswer1 { get { return _isAnswer1; } set { _isAnswer1 = value; NotifyPropertyChanged(m => m.IsAnswer1); //I used i notify property changed but this is inherited from the base class } } And then in the UI binding similar to <CheckBox x:Name="testCheckBox" IsChecked="{Binding IsAnswer1} /> Assuming you have the data context set at the grid or main view to the view model. You could then bind this property to the UI and when checked it could then invoke a different action or method for another element. It just depends upon how you implement this. If you are not using mvvm and you want to handle this in the ui you can use elementName binding. Here you basically bind property of one element on the value of another (Example check a checkbox and have a value appear in the UI) Here is a link from MSDN on element name binding MSDN Link Here
{ "pile_set_name": "StackExchange" }
Q: How to store results of loop If statement in another worksheet columns? I need to store the results of my for each If statement in the results worksheet of the active workbook. My loop works but I need to be able to store the results in column a and c from the results worksheet This is the code for the loop For Each cel In Range("A4:A85") With cel If (.Value Like "boston*" Or .Value Like "manfield*" Or _ .Value Like "barnes*" Or.Value Like "langley*") _ And .Offset(0, 2).Value Like "mass*" Then MsgBox cel.Value & Chr(13) & Chr(10) & cel.Offset(0, 2).Value I was thinking about something like this Pseudocode: worksheets worksheetname column.value = cel.value and cell.offset(0,2).value =cell.offset(0,2).value A: Perhaps something like: Sub Michael() Dim v As String, WhichRow As Long Dim cel As Range WhichRow = 1 For Each cel In Range("A4:A85") v = cel.Value If (v Like "boston*" Or v Like "manfield*" Or v Like "barnes*" Or v Like "langley*") And cel.Offset(0, 2).Value Like "mass*" Then MsgBox cel.Value & Chr(13) & Chr(10) & cel.Offset(0, 2).Value Sheets("results").Cells(WhichRow, "A").Value = cel.Value & Chr(13) & Chr(10) & cel.Offset(0, 2).Value WhichRow = WhichRow + 1 End If Next cel End Sub
{ "pile_set_name": "StackExchange" }
Q: How to set the IIS File Security to Integrated Windows authentication with a Web Setup Project installer? I wrote an ASP.NET web application with an installer. For the installer, I'm using the Web Setup Project under the Setup and Deployment project types in Visual Studio 2008. How do I set the IIS File Security to Integrated Windows Authentication on only one .aspx page or directory during the installation process using a Web Setup Project? If it is not possible with the Web Setup Project how would I automate that task? Currently I'm installing the application with the installer and manually setting the security permissions. A: Look at the CustomAction Class for the Install Method. Here's a sample: http://www.codeproject.com/KB/install/SetIISettings.aspx
{ "pile_set_name": "StackExchange" }
Q: python XML-RPC sending a list of parameters to the server I am trying to send a list( specifically numpy or python's list) of numbers and get the sum of them using xml-rpc, to be familiar with the environment. I get an error always in the client side. <Fault 1: "<type 'exceptions.TypeError'>:unsupported operand type(s) for +: 'int' and 'list'"> Server side code: from SimpleXMLRPCServer import SimpleXMLRPCServer def calculateOutput(*w): return sum(w); server = SimpleXMLRPCServer(("localhost", 8000)) print "Listening on port 8000..." server.register_function(calculateOutput,"calculateOutput"); server.serve_forever() Client side code: import xmlrpclib proxy = xmlrpclib.ServerProxy("http://localhost:8000/") print(proxy.calculateOutput([1,2,100]); Does anyone know how to fix this problem? A: Send through proxy.calculateOutput([1,2,100]) as proxy.calculateOutput(1,2,100) or change the arguments for your server-side function from def calculateOutput(*w): to def calculateOutput(w):. As an aside, you don't need the semi-colons. The reason for this behaviour can be illustrated with a short example >>> def a(*b): >>> print b >>> a(1,2,3) (1, 2, 3) >>> a([1,2,3]) ([1, 2, 3],) As you can see from the outputs, using the magic asterix will package up however many arguments you pass through to the function as a tuple itself so it can handle n amount of arguments. As you were using that syntax, when you sent through your arguments already contained in a list they were then packaged further into a tuple. sum() only expects a list/tuple as the argument, hence the error you were receiving when it tried to sum a contained list.
{ "pile_set_name": "StackExchange" }
Q: Why must a provider be defined before a config block I have a module. It has a config block, a provider, and a constant defined. The config block references both the constant and the provider. I notice that my constant can be defined before or after my config block. The provider however must be defined BEFORE the config block or else I get an error. Error: [$injector:modulerr] Failed to instantiate module loadOrder due to: [$injector:unpr] Unknown provider: greetingsProvider Here is some sample code: var myModule = angular.module('loadOrder', []); //if I define this after the config block, I get an error angular.module('loadOrder').provider('greetings',[ function(){ this.$get = [function(){ return { greet: function(){ return "Hola"; } }; }]; }]); myModule.config(['$provide', 'greetingsProvider', 'planetName', function($provide, loadOrderProvider, planetName){ $provide.value('someVals',[3,6,8]); console.log("Lets go to", planetName); }]); myModule.constant('planetName', 'Saturn'); Why is this? Why can't I define my provider after my config block? A: When you call provider, config or constant nothing happens immediately. The calls are registered, put in a queue and run during the initialization of the application. The funny thing with constant is that it is put at the front of the queue. Thus it's available before config, no matter what.
{ "pile_set_name": "StackExchange" }
Q: Disabling JMX in a spring application I'm trying to disable jmx so that i don't get org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mbeanExporter'anymore. I've found a partial answer saying that I should include this in the application.properties file: spring.datasource.jmx-enabled=false So I created the file with that one line. But how do I make sure that Spring acutally reads it? Do I need to edit something in spring.xml? If so, where? A: You need to disable the setting in your application.properties file (it is automatically turned on if not set). Either edit or create this file: src/main/resources/config/application.properties That is for a maven project, so if not in maven, just put 'resources' at the same level as your java folder. You will just need this single line in the file (it can be blank otherwise): spring.jmx.enabled=false If you want to add other settings, here are all the options: http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html A: In my case, it was IntelliJ. IntelliJ have a setting "Enable JMX agent" in the run configuration. This should be unchecked to disable JMX. If checked, this will override any setting that you make in the application via properties/yml. A: Are you using spring boot? If so you just need to place the file in src\main\resources\application.properties by default You can check sample projects here https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples
{ "pile_set_name": "StackExchange" }
Q: Strange css priority behavior for font-family in Chrome I need to customize styles for my menu. In IE, it works fine, but in Chrome, I find I cannot modify the font-family for links in the menu. For text in span or div, it's OK. I use simple selector to make my rule prior to default rule. But the development tool shows like this: You can see that my rule doesn't override the default rule. I tried to add important, development tool shows OK as below, but the font doesn't change at all: The only thing I tried to make my rule work is to delete the original CSS rule ".tundra .dijitMenuItem" in "Menu.css". But it is the default rule given by framework, I don't want to modify it. The element in dom is shown below: How can this happen, and how to make my rule work? Updated: I tried many ways to test the behaviors. Seems like if only I put my rule to .dijitMenuItem or it's children, it can override the default. Otherwise, no matter how specific my selector is, it won't be applied. I made a simple example like below: the complete example is on JsFiddle: .theme .sub-container { font-family: Arial; } body.theme div.container { font-family: sans-serif; //this doesn't work } .theme .sub-container2 { font-family: sans-serif; } body.theme div.sub-container2 { font-family: Arial; //this works } Can anyone explain this? Does font-family's inherit and overridden are different with other CSS properties? A: try to Set the font family in your anchor tag. i think it should be work.
{ "pile_set_name": "StackExchange" }
Q: How to get jQuery ajax to execute error function I have looked around and followed the instructions on this post but I still can not get the error function to execute. What I want to do is have my PHP script return either error or success along with a message. Eventually it will be data returned from a database that will be put inside of a div but for now I just need to get the error handling working. I am hoping someone here can help me out with this. I have included my code below. This is obviously my AJAX request. function getProductInfo() { if($("#serialNumber").val() != '') { serialNumber = $("#serialNumber").serialize(); $.ajax({ type: "POST", url: 'post.php', data: serialNumber + "&getSerialNumber=" + 1, dataType: 'json', success: function(data, textStatus, jqXHR) { console.log("SUCCESS"); }, error: function(jqXHR, textStatus, errorThrown) { console.log("ERROR"); } }); } } This is my php function that will return the error and message as JSON function getSerialNumber() { $serial = $_POST['serial']; $product = new Inventory; if($product->GetSerial($serial)) { $productInfo = $product->GetSerial($serial)->first(); echo '{"error": false, "message": "Successfully got serial number"}'; } else { echo '{"error": true, "message": "failed to get serial number"}'; } } As the current code stand it will only keep outputting SUCCESS regardless if it actually has an error or not. A: You need to send an http status code other than 200: if($product->GetSerial($serial)) { $productInfo = $product->GetSerial($serial)->first(); header('Content-Type: application/json', true, 200); die(json_encode(["error"=> false, "message"=> "Successfully got serial number"])); } else { header('Content-Type: application/json', true, 400); die(json_encode(["error"=> true, "message"=> "failed to get serial number"])); } Also, when sending json, set the content type accordingly, and never try and manually build a json string, use the built in json_encode function instead, and its a good idea to use die() or exit() rather than echo, to avoid any accidental additional output That said, although sending appropriate status codes seems like a good idea, you may well find it a lot easier to always return 200 and parse the response, and keep the error handler for unexpected errors
{ "pile_set_name": "StackExchange" }
Q: Split sound effects and music when recording Nintendo 3DS/Switch audio I am recording the audio with an aux cable connecting the Nintendo's headphone jack to my laptop's microphone jack adapter. The program I use is audacity. Is there a way to separate the sound effects (i. e. button presses or attack sounds) and the background music into two audio tracks? A: No, the audio is already mixed together when it is coming through the headphone jack. You would need to do it before it is mixed, but that requires modifying the game code which presumably you can't do.
{ "pile_set_name": "StackExchange" }
Q: Retrieve json of place api i searched all the morning how can I retrieve my json data from a google api, but after I saw a lot of questions I still cannot figure out what i've to do. I think I'm confused about this point, so please if you will downvote could you kindly give me at least a comment or something that can really help me ? Expected behaviour i expect to console log or to access something like this [ { "restaurantName":"Bronco", "address":"39 Rue des Petites Écuries, 75010 Paris", "lat":48.8737815, "long":2.3501649, "ratings":[ { "stars":4, "comment":"Great! But not many veggie options." }, { "stars":5, "comment":"My favorite restaurant!" } ] }, { "restaurantName":"Babalou", "address":"4 Rue Lamarck, 75018 Paris", "lat":48.8865035, "long":2.3442197, "ratings":[ { "stars":5, "comment":"Tiny pizzeria next to Sacre Coeur!" }, { "stars":3, "comment":"Meh, it was fine." } ] } ] Code this is my javascript about the gmaps, autocomplete and the input search. function initAutocomplete() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: -33.8688, lng: 151.2195}, zoom: 13, mapTypeId: 'roadmap' }); initialize(); google.maps.event.addListener(map, 'rightclick', function(event) { placeMarker(event.latLng); console.log(event.latLng); }); function placeMarker(location) { var marker = new google.maps.Marker({ position: location, map: map }); } // Create the search box and link it to the UI element. var input = document.getElementById('pac-input'); var searchBox = new google.maps.places.SearchBox(input); // Bias the SearchBox results towards current map's viewport. map.addListener('bounds_changed', function() { searchBox.setBounds(map.getBounds()); }); var markers = []; // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener('places_changed', function() { //check if the first sectin is already Up if(!sectionShow){ $(".columnsContainer").fadeIn(); sectionShow=true; } //automatic movements of the scroll document.querySelector('#map').scrollIntoView({ behavior: 'smooth' }); var places = searchBox.getPlaces(); if (places.length == 0) { return; } review = []; //this jquery line delete the previous card if you start another research $(".card-grid").parent().find('.card-wrap').remove(); // Clear out the old markers. markers.forEach(function(marker) { marker.setMap(null); }); markers = []; // For each place, get the icon, name and location. var bounds = new google.maps.LatLngBounds(); places.forEach(function(place) { //hai aggiunto bounds, ricorda che stai cercando di passare le coordinate posto per posto. if (!place.geometry) { console.log("Returned place contains no geometry"); return; } containerPlace=places; var photos = place.photos; if (!photos) { return; } var icon = { url: place.icon, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: new google.maps.Size(25, 25) }; // remember to make an object instead of these variables var photo = photos[0].getUrl({'maxWidth': 800, 'maxHeight': 900}) var title = place.name; var rating = place.rating; var address = place.formatted_address; var idPlace = place.place_id; console.log(idPlace); printCard(photo, title, rating, address, idPlace); initMap(idPlace, map); if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); map.fitBounds(bounds); }); infoWindow = new google.maps.InfoWindow; // GeoLocation from Here if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; $(".columnsContainer").fadeIn(); document.querySelector('#map').scrollIntoView({ behavior: 'smooth' }); infoWindow.setPosition(pos); infoWindow.setContent('You are here'); infoWindow.open(map); map.setCenter(pos); }, function() { handleLocationError(true, infoWindow, map.getCenter()); }); } else { // Browser doesn't support Geolocation handleLocationError(false, infoWindow, map.getCenter()); } } My Try I tried to add this lines of codes, but it doesn't work $.getJSON("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=36.950030,14.537220&radius=500&type=restaurant&key=AIzaSyDWb4mliJPGjwsAhNvdDEveAd0dTe9KXxE&callback=?", function(data){ console.log("Data: " + data); }); I have this console log with the answer of @markymark : Access to XMLHttpRequest at from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Questions that helps me Getting JSON of Google Places Nearby Search How to capture and parse JSON returned from Google Maps v3 API? ( this is really interesting ) https://developers.google.com/places/web-service/search codepen Codepen Here So i read about the CORS in this question A: This is your URL fixed, you had your callback still from the javascript API. You can fetch those with a simple URL. You can just paste it in the browser and see the results. https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=36.950030,14.537220&radius=500&type=restaurant&key=AIzaSyDWb4mliJPGjwsAhNvdDEveAd0dTe9KXxE An example for nearby Libraries in SF https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.7749,-122.4194&radius=1000&type=library&key=AIzaSyDWb4mliJPGjwsAhNvdDEveAd0dTe9KXxE Please remember to delete your API keys. These are your keys.
{ "pile_set_name": "StackExchange" }
Q: Error finding a Class even when it's predefined class Slice ; class Apple{ ... Slice x; }; class Slice{ ... }; Even though I defined that class Slice exists. When I call it in my class Apple to create a Slice object 'x', the compiler gives me an error:field x has an incomplete type. If I swap the order of classes, so that Slice gets made first, the error is gone and program compiles with no problems. Very similar problem to what In which order should classes be declared in C++? had. But for some reason predefining classes doesnt work for me. Picture of my problem if you need specific http://gyazo.com/cf6fdf2894c34afba4ef0e352510fcfd Its just some gibberish code I made for learning how to change state of an object when its inside another object. A: class Slice; Forward declarations work if you are subsequentally declaring pointers or references to the incomplete type, and not when you're using an instance of the type. Your Apple class is using a full instance of Slice, so the compiler needs to know what Slice actually is so as to properly layout the Apple class. Since Slice is an incomplete type, the compiler gives you the error. To address your issue, you can declare a pointer or reference to Slice in your Apple class.
{ "pile_set_name": "StackExchange" }
Q: MYSQL - Check if all group members have the same type I have the following table: SomeID GroupID TYPE 1 1 1 2 1 2 3 1 2 4 2 1 5 2 1 6 3 2 What i want to find is, is there a GROUP that all of its members have the same type. I also want to know what is the type of the group. For example group 1 have 2 types (1 and 2), group 2 have 1 type (1) and also group 3 have 1 type (2) How i can implement it in MySQL? A: SELECT GroupID, COUNT(DISTINCT type) totalType, GROUP_CONCAT(DISTINCT TYPE ORDER BY TYPE) TypeList FROM TableName GROUP BY GroupID SQLFiddle Demo OUTPUT ╔═════════╦═══════════╦══════════╗ ║ GROUPID ║ TOTALTYPE ║ TYPELIST ║ ╠═════════╬═══════════╬══════════╣ ║ 1 ║ 2 ║ 1,2 ║ ║ 2 ║ 1 ║ 1 ║ ║ 3 ║ 1 ║ 2 ║ ╚═════════╩═══════════╩══════════╝
{ "pile_set_name": "StackExchange" }
Q: Insert Interval into a disjoint set of intervals Given sorted disjoint sets (p,q) where ‘p’ is the start time and ‘q’ is the end time. You will be given one input interval. Insert it in the right place. And return the resulting sorted disjoint sets. Eg: (1,4);(5,7);(8,10);(13,18) Input interval – (3,7) Result : (1,7);(8,10);(13,18) Input Interval – (1,3) Result: (1,4);(5,7);(8,10);(13,18) Input interval – (11,12) Result: (1,4);(5,7);(8,10);(11,12);(13,18) Inserting an interval in a sorted list of disjoint intervals , there is no efficient answer here A: Your question and examples imply non-overlapping intervals. In this case you can just perform a binary search - whether comparison is done by start time or end time does not matter for non-overlapping intervals - and insert the new interval at the position found if not already present. UPDATE I missed the merging occurring in the first example. A bad case is inserting a large interval into a long list of short intervals where the long interval overlaps many short intervals. To avoid a linear search for all intervals that have to be merged one could perform two binary searches - one from the left comparing by start time and one from the right comparing by the end time. Now it is trivial to decide if the interval is present, must be inserted or must be merged with the intervals between the positions found by the two searches. While this is not very complex it is probably very prone to off-by-one errors and requires some testing.
{ "pile_set_name": "StackExchange" }
Q: Why does שמי שמים mean "the loftiest heavens"? In the Artscroll translation of מנוחה ושמחה (The Interlinear Family Zemiros p.58), it translates the phrase שְׁמֵי שָׁמַיִם as "the loftiest heavens". What is the etymology of the first word in this construct that the phrase should mean lofty? It doesn't seem to come from the root שׁמה or שׁמם so I can't think what the root of it could be. A: Rav Hirsch in explaining Bereishis 1:1 explains the usage of Shamaim as he had developed it in Jeshurun vol. VIII pg. 274 as the designation of the whole extra-terrestrial world. He then explains the usage in 1:8 as well. Thus, there are different levels called שָׁמַיִם based on what they are being separated from. This then means the highest of those levels. The phrase שְׁמֵי שָׁמַיִם means the ultimate level of the separations that are called by the term שָׁמַיִם which is therefore above all the others. Since we regard the earth as the position at we we have our point of view, the heavens are above us and we are looking up toward each level. The furthest heaven is thus (to our eyes) the highest or loftiest.
{ "pile_set_name": "StackExchange" }
Q: How to access the orm with celery tasks? I'm trying to flip a boolean flag for particular types of objects in my database using sqlalchemy+celery beats. But how do I access my orm from the tasks.py file? from models import Book from celery.decorators import periodic_task from application import create_celery_app celery = create_celery_app() # Create celery: http://flask.pocoo.org/docs/0.10/patterns/celery/ # This task works fine @celery.task def celery_send_email(to,subject,template): with current_app.app_context(): msg = Message( subject, recipients=[to], html=template, sender=current_app.config['MAIL_DEFAULT_SENDER'] ) return mail.send(msg) #This fails @periodic_task(name='release_flag',run_every=timedelta(seconds=10)) def release_flag(): with current_app.app_context(): <<< #Fails on this line books = Book.query.all() <<<< #Fails here too for book in books: book.read = True book.save() I'm using celery beat command to run this: celery -A tasks worker -l INFO --beat But I'm getting the following error: raise RuntimeError('working outside of application context') RuntimeError: working outside of application context Which points back to the with current_app.app_context() line If I remove the current_app.app_context() line I will get the following error: RuntimeError: application not registered on db instance and no application bound to current context Is there a particular way to access the flask-sqlalchemy orm for celery tasks? Or would there be a better approach to what I'm trying to do? So far the only workaround which works was to add the following line after db.init_app(app) in my application factory pattern: db.app = app I was following this repo to create my celery app https://github.com/mattupstate/overholt/blob/master/overholt/factory.py A: You're getting that error because current_app requires an app context to work, but you're trying to use it to set up an app context. You need to use the actual app to set up the context, then you can use current_app. with app.app_context(): # do stuff that requires the app context Or you can use a pattern such as the one described in the Flask docs to subclass celery.Task so it knows about the app context by default. from celery import Celery def make_celery(app): celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery celery = make_celery(app)
{ "pile_set_name": "StackExchange" }
Q: Unite Collection of Collections into Collection in a method in Java I've created a Collection class that extends ArrayList to add some useful methods. It looks like this: public class Collection<T> extends ArrayList<T> { //some methods... } I want to be able to unite a Collection of Collections to a single Collection, like this: {{1, 2}, {2,3}, {1}, {2}, {}} -> {1, 2, 2, 3, 1, 2} I have an idea of how a static method should look like: public static<E> Collection<E> unite(Collection<Collection<E>> arr) { Collection<E> newCollection = new Collection<>(); for(Collection<E> element : arr) { newCollection.merge(element); } return newCollection; } But I don't know how to make this method non-static(so that it accepts no arguments, like this: Collection<E> list = listOfLists.unite(); ). Is that even possible? If it is, can you please help me with it? A: It doesn't make sense to do it for any concrete type T. If T is not of a Collection type, then unite() is an irrelevant method (if you have a ArrayListModified<Double>, for example, you can't flatten it because that's absurd). So you either have to make T bounded to collections: public class ArrayListModified<E, T extends Collection<E>> extends ArrayList<T> { public Collection<E> unite() { Collection<E> newCollection = new ArrayList<>(); for (Collection<E> element : this) { newCollection.addAll(element); } return newCollection; } } Or use a static method that takes one ArrayListModified<ArrayListModified<E>> parameter just as in your current implementation (though it wouldn't be required to be static).
{ "pile_set_name": "StackExchange" }
Q: Hibernate select before update In my work i'm using spring with exidirect, hibernate on the server side and extjs on client side. When i post a form, on the server side spring converts it to the entity. Entity has a id field, that supposes update operation. I'm calling service save method, but instead one sql update query i get many many select queries and just then update. It takes much time. And there is no need for this operation. I was looking similar questions and was trying to use persist method. This case i get error: detached entity passed to persist. I do not have enough experience of hibernate. May be i need to configure related entities (OneToMany, ManyToOne and cascade types). Entities are generated by Spring roo tool. Any suggestions ? Thank you. A: This is not a final answer for your question but I hope it can work as a high level guideline. When you create an Entity with Spring, that Entity is detached and Hibernate performs these SELECT statements because it needs to attach your Entity before persisting it. Additionally, as far as I know any attempt to attach an Entity is going to trigger SELECT statements. Therefore, I strongly believe that there is not any way to save/persist your detached Entities without these SELECT statements (I might be wrong here). If you are concern about performance you can try adding some cache functionality to your application. Moreover, you can also include JDBC solutions only for operations which are suffering with performance.
{ "pile_set_name": "StackExchange" }
Q: How and when should I use pitched pointer with the cuda API? I have quite a good understanding about how to allocate and copy linear memory with cudaMalloc() and cudaMemcpy(). However, when I want to use the CUDA functions to allocate and copy 2D or 3D matrices, I am often befuddled by the various arguments, especially concerning pitched pointers which are always present when dealing with 2D/3D arrays. The documentation is good for providing a couple examples on how to use them but it assumes that I am familiar with the notion of padding and pitch, which I am not. I usually end up tweaking the various examples I find in the documentation or somewhere else on the web, but the blind debugging that follows is quite painful, so my question is: What is a pitch? How do I use it? How do I allocate and copy 2D and 3D arrays in CUDA? A: Here is an explanation about pitched pointer and padding in CUDA. Linear memory vs padded memory First, lets start with the reason for the existence of non linear memory. When allocating memory with cudaMalloc, the result is like an allocation with malloc, we have a contiguous memory chunk of the size specified and we can put anything we want in it. If we want to allocate a vector of 10000 float, we simply do: float* myVector; cudaMalloc(&myVector, 10000*sizeof(float)); and then access ith element of myVector by classic indexing: float element = myVector[i]; and if we want to access the next element, we just do: float next_element = myvector[i+1]; It works very fine because accessing an element right next to the first one is (for reasons I am not aware of and I don't wish to be for now) cheap. Things become a little bit different when we use our memory as a 2D array. Lets say our 10000 float vector is in fact a 100x100 array. We can allocate it by using the same cudaMalloc function, and if we want to read the i-th row, we do: float* myArray; cudaMalloc(&myArray, 10000*sizeof(float)); int row[100]; // number of columns for (int j=0; j<100; ++j) row[j] = myArray[i*100+j]; Word alignment So we have to read memory from myArray+100*i to myArray+101*i-1. The number of memory access operation it will take depends on the number of memory words this row takes. The number of bytes in a memory word depends on the implementation. To minimize the number of memory accesses when reading a single row, we must assure that we start the row on the start of a word, hence we must pad the memory for every row until the start of a new one. Bank conflicts Another reason for padding arrays is the bank mechanism in CUDA, concerning shared memory access. When the array is in the shared memory, it is split into several memory banks. Two CUDA threads can access it simultaneously, provided they don't access memory belonging to the same memory bank. Since we usually want to treat each row in parallel, we can ensure that we can access it simulateously by padding each row to the start of a new bank. Now, instead of allocating the 2D array with cudaMalloc, we will use cudaMallocPitch: size_t pitch; float* myArray; cudaMallocPitch(&myArray, &pitch, 100*sizeof(float), 100); // width in bytes by height Note that the pitch here is the return value of the function: cudaMallocPitch checks what it should be on your system and returns the appropriate value. What cudaMallocPitch does is the following: Allocate the first row. Check if the number of bytes allocated makes it correctly aligned. For example that it is a multiple of 128. If not, allocate further bytes to reach the next multiple of 128. the pitch is then the number of bytes allocated for a single row, including the extra bytes (padding bytes). Reiterate for each row. At the end, we have typically allocated more memory than necessary because each row is now the size of pitch, and not the size of w*sizeof(float). But now, when we want to access an element in a column, we must do: float* row_start = (float*)((char*)myArray + row * pitch); float column_element = row_start[column]; The offset in bytes between two successive columns can no more be deduced from the size of our array, that is why we want to keep the pitch returned by cudaMallocPitch. And since pitch is a multiple of the padding size (typically, the biggest of word size and bank size), it works great. Yay. Copying data to/from pitched memory Now that we know how to create and access a single element in an array created by cudaMallocPitch, we might want to copy whole part of it to and from other memory, linear or not. Lets say we want to copy our array in a 100x100 array allocated on our host with malloc: float* host_memory = (float*)malloc(100*100*sizeof(float)); If we use cudaMemcpy, we will copy all the memory allocated with cudaMallocPitch, including the padded bytes between each rows. What we must do to avoid padding memory is copying each row one by one. We can do it manually: for (size_t i=0; i<100; ++i) { cudaMemcpy(host_memory[i*100], myArray[pitch*i], 100*sizeof(float), cudaMemcpyDeviceToHost); } Or we can tell the CUDA API that we want only the useful memory from the memory we allocated with padding bytes for its convenience so if it could deal with its own mess automatically it would be very nice indeed, thank you. And here enters cudaMemcpy2D: cudaMemcpy2D(host_memory, 100*sizeof(float)/*no pitch on host*/, myArray, pitch/*CUDA pitch*/, 100*sizeof(float)/*width in bytes*/, 100/*heigth*/, cudaMemcpyDeviceToHost); Now the copy will be done automatically. It will copy the number of bytes specified in width (here: 100xsizeof(float)), height time (here: 100), skipping pitch bytes every time it jumps to a next row. Note that we must still provide the pitch for the destination memory because it could be padded, too. Here it is not, so the pitch is equal to the pitch of a non-padded array: it is the size of a row. Note also that the width parameter in the memcpy function is expressed in bytes, but the height parameter is expressed in number of elements. That is because of the way the copy is done, someway like I wrote the manual copy above: the width is the size of each copy along a row (elements that are contiguous in memory) and the height is the number of times this operation must be accomplished. (These inconsistencies in units, as a physicist, annoys me very much.) Dealing with 3D arrays 3D arrays are no different that 2D arrays actually, there is no additional padding included. A 3D array is just a 2D classical array of padded rows. That is why when allocating a 3D array, you only get one pitch that is the difference in bytes count between to successive points along a row. If you want to access to successive points along the depth dimension, you can safely multiply the pitch by the number of columns, which gives you the slicePitch. The CUDA API for accessing 3D memory is slightly different than the one for 2D memory, but the idea is the same : When using cudaMalloc3D, you receive a pitch value that you must carefully keep for subsequent access to the memory. When copying a 3D memory chunk, you cannot use cudaMemcpy unless you are copying a single row. You must use any other kind of copy utility provided by the CUDA utility that takes the pitch into account. When you copy your data to/from linear memory, you must provide a pitch to your pointer even though it is irrelevant: this pitch is the size of a row, expressed in bytes. The size parameters are expressed in bytes for the row size, and in number of elements for the column and depth dimension.
{ "pile_set_name": "StackExchange" }
Q: PHP MySQL Prepared Query using IN I have a couple of situations where I have an array of input, such as: $myArray = array( "apple", "banana", "orange", "pear" ); Where the array could have any number of fruits in it. I want to use MySQL prepared statements in PHP to create a query similar to: SELECT * FROM fruitcart WHERE fruitname IN ('apple','banana','orange','pear'); Previously, I was accomplishing this by doing something like: $query = "SELECT * FROM fruitcart WHERE fruitname IN ('" . implode( "','", $myArray ) . "')"; but I'd like to know if there is a way I could do something similar with prepared statements? A: There is no way to do that with a prepared statement. The only possibility is to do something like this: $query = "SELECT * FROM fruitcart WHERE fruitname = ? OR fruitname = ? OR fruitname = ? ... You can easily build a statement like this with an foreach loop. But be aware that, since your array will probably have different amounts of values, this might cause some confusion in the database optimizer algorithms. For optimal performance you might want to prepare statements with for example 128, 64, 32, 16, 8, 4, 2, 1 slots and then use the biggest one you can fill until you got all your values from the database. That way the optimizer is able to deal with a much more limited amount of statement skeletons. You can also use a temporary table for this. For example create a table that only contains the values (apple, banana, ...) and an id for your value set. You can then insert the array of values into the database using a unique set-id (php offers a guid function for example) and then selecting them in a subquery: $query = "SELECT * FROM fruitcart WHERE fruitname IN (SELECT fruitname FROM temptable WHERE setid = ?)" That's easily preparable and will perform quite good. You can use an in-memory table for the temptable so it will be very fast.
{ "pile_set_name": "StackExchange" }
Q: What is the function equivalent of prepending the 'b' character to a string literal in Python 2? What function can I apply to a string variable that will cause the same result as prepending the b modifier to a string literal? I've read in this question about the b modifier for string literals in Python 2 that prepending b to a string makes it a byte string (mainly for compatibility between Python 2 and Python 3 when using 2to3). The result I would like to obtain is the same, but applied to a variable, like so: def is_binary_string_equal(string_variable): binary_string = b'this is binary' return convert_to_binary(string_variable) == binary_string >>> convert_to_binary('this is binary') [1] True What is the correct definition of convert_to_binary? A: First, note that in Python 2.x, the b prefix actually does nothing. b'foo' and 'foo' are both exactly the same string literal. The b only exists to allow you to write code that's compatible with both Python 2.x and Python 3.x: you can use b'foo' to mean "I want bytes in both versions", and u'foo' to mean "I want Unicode in both versions", and just plain 'foo' to mean "I want the default str type in both versions, even though that's Unicode in 3.x and bytes in 2.x". So, "the functional equivalent of prepending the 'b' character to a string literal in Python 2" is literally doing nothing at all. But let's assume that you actually have a Unicode string (like what you get out of a plain literal or a text file in Python 3, even though in Python 2 you can only get these by explicitly decoding, or using some function that does it for you, like opening a file with codecs.open). Because then it's an interesting question. The short answer is: string_variable.encode(encoding). But before you can do that, you need to know what encoding you want. You don't need that with a literal string, because when you use the b prefix in your source code, Python knows what encoding you want: the same encoding as your source code file.* But everything other than your source code—files you open and read, input the user types, messages coming in over a socket—could be anything, and Python has no idea; you have to tell it.** In many cases (especially if you're on a reasonably recent non-Windows machine and dealing with local data), it's safe to assume that the answer is UTF-8, so you can spell convert_to_binary_string(string_variable) as string_variable.encode('utf8'). But "many" isn't "all".*** This is why text editors and web browsers let the user select an encoding—because sometimes only the user actually knows. * See PEP 263 for how you can specify the encoding, and why you'd want to.. ** You can also use bytes(s, encoding), which is a synonym for s.encode(encoding). And, in both cases, you can leave off the encoding argument—but then it defaults to something which is more likely to be ASCII than what you actually wanted, so don't do that. *** For example, many older network protocols are defined as Latin-1. Many Windows text files are created in whatever the OEM charset is set to—usually cp1252 on American systems, but there are hundreds of other possibilities. Sometimes sys.getdefaultencoding() or locale.getpreferredencoding() gets what you want, but that obviously doesn't work when, say, you're processing a file that someone uploaded that's in his machine's preferred encoding, not yours. In the special case where the relevant encoding is "whatever this particular source file is in", you pretty much have to know that somehow out-of-band.* Once a script or module has been compiled and loaded, it's no longer possible to tell what encoding it was originally in.** But there shouldn't be much reason to want that. After all, if two binary strings are equal, and in the same encoding, the Unicode strings are also equal, and vice-versa, so you could just write your code as: def is_binary_string_equal(string_variable): binary_string = u'this is binary' return string_variable == binary_string * The default is, of course, documented—it's UTF-8 for 3.0, ASCII or Latin-1 for 2.x depending on your version. But you can override that, as PEP 263 explains. ** Well, you could use the inspect module to find the source, then the importlib module to start processing it, etc.—but that only works if the file is still there and hasn't been edited since you last compiled it.
{ "pile_set_name": "StackExchange" }
Q: Finite ways to write $1 =\sum_{i=1}^{h}\frac{1}{n_i}$ Let $h\geqslant 1$ an integer. Can we show (simply), without using group actions, that there exists a finite number of decomposition of the form $\displaystyle 1 =\sum_{i=1}^{h}\frac{1}{n_i}$, with $n_i$ positive integers. P.S.: With group actions, I got it. A: Show by induction on $h$: For any $s$ there is at most a finite number of decompositions of the form $s=\sum_{i=1}^h\frac1{n_i}$ with $n_i$ positive integers. The claim is trivial for $h=0$. For the induction step $h-1\to h$, note that for any decomposition $s=\sum_{i=1}^h\frac1{n_i}$ we may assume wlog. that $n_h=\min\{n_1,\ldots, n_h\}$. Then $n_h\le\frac hs$, so there are only finitely many choices for $n_h$ and for each choice of $n_h$ there are only finitely many deompositions $s-\frac1{n_h}=\sum_{i=1}^{h-1}\frac1{n_i}$.
{ "pile_set_name": "StackExchange" }
Q: File sharing between Mac OS and Ubuntu I am pretty new to Ubuntu so please if you can answer to this question explicitly. I have two laptops one is running on MAC OS X 10.8.5 (OS X Mountain Lion) and the other one running Ubuntu 14.04 LTS. I want to connect the two laptops via terminal such that I will able to share files between the two. A file sharing system like Dropbox is my aim but of course private, meaning to have a folder on both laptops where I can upload files on one laptop and it then appears on the other. How would one do this? is it even possible? Thanks. A: One project/piece of software you might want to look into is NitroShare. This project is actually developed by a couple of guys from this site (NathanOsman & Mateo) and it's nice and simple, is cross-platform, and works between platforms without much hassle at all. Basically, you install the program, launch it, and it sits in the background until you need it. Taskbar Menu: Device Menu: This isn't quite like Dropbox where it automatically syncs, but it is a very useful tool and you can send whole directories at a time.
{ "pile_set_name": "StackExchange" }
Q: Retrieve Circle Points In OpenCV, i know how to draw circles, but is there a way to get back all the points that makeup the circle? I hope I dont have to go through calculating contours. Thanks A: If you know how to draw the circle, Create a black image with the same size of as that of original image Then draw the circle on the black image with white color Now in this black image, check the points which are white If you are using Python API, you can do as follows : import numpy as np import cv2 img = np.zeros((500,500),np.uint8) cv2.circle(img,(250,250),100,255) points = np.transpose(np.where(img==255))
{ "pile_set_name": "StackExchange" }
Q: How do I set focus on component html tag I need to set focus on tag in my functional component when it loads. I cannot make it work properly. Please help! Below is my code; Detail.js import React,{useState,useEffect} from 'react'; const Detail=({course})=>{ const [myfocus]=useState(null); useEffect(() => { setState({ this.myfocus.focus(); //? how to set id myfocus to this.myfocus.focus() }); return ( <div> <h4 tabindex="0" id="myfocus"> {course.SUBJECT} {course.CATALOG_NBR} </h4> </div> ); }; export default Detail; A: We have autoFocus prop in React, so you can try <h4 autoFocus />. But you can also solve this with the ref: const h4 = useRef() useEffec(() => h4.current.focus() )[]; return( <h4 ref={h4} /> ) You are right, that tabIndex (use camel case in React) is probably required to make it work for the h4 element.
{ "pile_set_name": "StackExchange" }
Q: Сделать фрагмент неактивным [![Имеется 2 фрагмента: фрагмент меню, и собственно фрагмент "Предложение дня." При нажатии на кнопку BUTTON, фрагмент "предложение дня" становится невидимым (.hide()). Нужно реализовать, пока фрагмент ПРЕДЛОЖЕНИЕ ДНЯ - видимый, фрагмент МЕНЮ был неактивный (я не мог его листать) и был затемнен.]1]] A: Мне кажется то что у вас на скриншоте можно сделать через простой диалог с собственной разметкой. Вы можете указать при создании диалога что его нельзя скрыть тапом за его пределами. Так же вы можете затемнить окружающее пространство вокруг этого диалога. Чтобы его все-таки скрыть я вам советую там сделать кнопку для закрытия диалога. Ниже привожу пример создания такого диалога: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <EditText android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:hint="Enter Email" android:inputType="textEmailAddress" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter your password" android:inputType="textPassword" /> </LinearLayout> Дальше вы делаете класс для того чтобы обработать то что в вашем диалоге нажимается: public class CustomLoginDialog extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = getActivity().getLayoutInflater().inflate(R.layout.custom_login_layout, null); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Login"); builder.setView(view); final EditText emailText = view.findViewById(R.id.email); final EditText passwordText = view.findViewById(R.id.password); builder.setNegativeButton("Cancel", null); builder.setPositiveButton("Login", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getActivity(), "Email is " + emailText.getText().toString() + " and password is" + passwordText.getText().toString(), Toast.LENGTH_SHORT).show(); } }); return builder.create(); } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); Toast.makeText(getActivity(), "Dialog Canceld", Toast.LENGTH_SHORT).show(); } } и дальше вы его уже создаете из фрагмента или активности: CustomLoginDialog customLoginDialog = new CustomLoginDialog(); customLoginDialog.show(getSupportFragmentManager(), "login_dialog"); Это я привел сложноватый пример, можно и попроще: final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.custom); dialog.setTitle("Title..."); // set the custom dialog components - text, image and button TextView text = (TextView) dialog.findViewById(R.id.text); text.setText("Android custom dialog example!"); ImageView image = (ImageView) dialog.findViewById(R.id.image); image.setImageResource(R.drawable.ic_launcher); Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK); // if button is clicked, close the custom dialog dialogButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); второй пример вы можете использовать непосредственно где вам вздумается, и так же можно здесь указать что нельзя скрыть диалог кликом за его пределами. Надеюсь один из способов вам поможет. Удачи :)
{ "pile_set_name": "StackExchange" }
Q: Read binary file into array in MIPS I've got a file named trace.dat that contains 4 byte integers. Can anybody tell me how to open and read the file, and store each integer in an array called arr (in MIPS)? Thanks! So far I have this: li $v0, 13 la $a0, file #file contains the file name li $a1, 0 li $a2, 0 syscall add $s0, $v0, $0 A: The code you have merely opens the file, and does not read it. In order to actually read the contents of a file you've opened into a buffer, you need to use syscall number 14, like this : li $v0, 14 move $a0, $s0 la $a1, arr li $a2, 32 syscall bltz $v0, error This code assumes that $s0 contains the file descriptor of the opened file, which you already have in there due to add $s0, $v0, $0. It also assumes that the size of arr is 32 bytes. If your file is larger than 32 bytes, you can write a loop that runs until syscall 14 returns 0 or a value smaller than the size of the buffer. Then, you can process the data read from the file inside the loop.
{ "pile_set_name": "StackExchange" }
Q: Using Eigen - how to solve sparse (SPD) linear systems with zero columns? (I'm using Eigen C++ library) I need to solve a system of equations with the form of Ax = 0 in order to find the x vector (A is sparse). EDIT: A is SPD (symmetric positive definite) Because some of the x values are known, I removed them out of A to create Af and into another matrix Ac with the same dimensions as A, and multiplied -Ac with a vector that has the known x values and zeros in all other places to create a vector b. Now I try to solve Af * x = b using SparseLU<SparseMatrix<float>>, but it fails because the factorization doesn't work. I get this error: THE MATRIX IS STRUCTURALLY SINGULAR ... ZERO COLUMN AT 480 Why is it a problem that I have a zero column? A zero row would have been a problem for sure but a zero column? I just changed something like this: x_1 + x_2 = 0 x_2 = 3 to x_1 + 0 = -3 The solution is x_1 = -3 & x_2 = 3 even though I would have had a zero column had I put the equations in a matrix. How can I solve this problem? A: You have "A" and "b = 0" given, and know A is symmetric positive definite. Because A is spd, it has no nontrivial null-space (this is an important property). That is, the only "x" that exists such that Ax = b = 0 is x = 0. So you won't find a solution if given nonzero values. It will always be x = 0. I say this to emphasize Eigen can't solve the problem, by the way it's formulated.
{ "pile_set_name": "StackExchange" }
Q: Materialize date picker is not working when I create a textbox using JQuery I have used Materialize CSS ( https://materializecss.com/ ) Date Picker. But, I couldn't able to access the date picker when I create the textbox dynamically using JQuery. I'm not sure It's not working. But, Can able to access date picker when we create a textbox manually. Please check my code. Manual textbox creation: <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <input type="text" class="datepicker"> <script> $(document).ready(function(){ $('.datepicker').datepicker(); }); </script> Using my above code can able to access the date picker. Dynamic textbox creation <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <button id="add">add</button> <div id="createtextbox"></div> <script> $(document).ready(function(){ $('#add').click(function(){ $("#createtextbox").append('<input type="text" class="datepicker" value="" />'); }); $('.datepicker').datepicker(); }); </script> Using this code, I couldn't able to access the date picker. Please help me to solve this? Thanks in advance :) A: You are invoking the datepicker() before the input is being created. In addition, you are creating a multiple input elements on every element (I assume this is not the required behavior). Your flow is basically: - Document is ready -- Invoke datepicker() //There is no datepicker input avaiable here --- (Click) - Create and append a datepicker input --- (Click) - Create and append a datepicker input --- (Click) - Create and append a datepicker input ... Your code execution order is as follows (look at the comments): $(document).ready(function(){ //1- document is ready $('#add').click(function(){ //Event listener is being registered but is not fired as no one clicked a button $("#createtextbox").append('<input type="text" class="datepicker" value="" />'); }); $('.datepicker').datepicker(); //2 invoke datepicker... but wait, there is no input - as no one pressed the button }); You should change it to: $(document).ready(function(){ //1- document is ready $('#add').click(function(){ //Event listener is being registered, this time when it will be fired it will invoke date picker as it was created in step 2 $('.datepicker').datepicker(); }); $("#createtextbox").append('<input type="text" class="datepicker" value="" />'); //2 Create the input which will be used as the datepicker - BEFORE the click event is fired }); Which will make a correct flow of: - Document is ready -- Create and append a datepicker input --- (Click) - Invoke datepicker() //There is datepicker input --- (Click) - Invoke datepicker() //There is datepicker input --- (Click) - Invoke datepicker() //There is datepicker input ...
{ "pile_set_name": "StackExchange" }
Q: Linear independent $V$ is a vector space over a field $\mathbb{R}$. Let $S,T$ be subspaces of $V$ with $S\cap T=\{\vec0\}$ and let $A$ be a set. Suppose $f\in \text{ Fun}(A,S)$, $g\in\text{ Fun}(A,T)$, where $\text{Fun}(A,S)=\{f:A\to S \text{ is a function}\}$ Show that, regarded as vectors in $\text{Fun}(S,V)$, the vectors $f$ and $g$ are linearly independent. First, suppose that $f,g$ are linearly dependent. Then there exists not all zero $\alpha,\beta\in\mathbb{R}$ such that $\alpha f+\beta\ g=\vec{0}$. ($\vec{0}(x)=0$ for all $x\in A$) So $\forall x\in A$, $(\alpha f+\beta g)(x)=\vec{0}(x)\Leftrightarrow \alpha f(x)+\beta g(x)=0$ WLOG let $\alpha \neq0$. Then $f(x)=\frac{-\beta}{\alpha}g(x)$ So $f=\frac{-\beta}{\alpha}g\in \text{ Fun}(A,T)$ I can't find contradiction. Could anyone help me? A: I think there are several things missing in your post that caused some misconception. First, you most likely mean that $f,g \in \text{Fun}(A,V)$ and not $f,g \in \text{Fun}(S,V)$. Second, your task should be to show that these functions are linearly indepedent under the simple assumption that both aren't null functions. Then all of it makes sense. The proof then gives you $f \in \text{Fun}(A,T)$, but since you know that $f \in \text{Fun}(A,S)$ you can tell as $S \cap T=\{0\}$ that $f(x)=0$ for all $x$ (i.e. $f$ is a null function) which contradicts your assumption of $f$ not being a null function. PS: It's also important that $A$ is a non-empty set.
{ "pile_set_name": "StackExchange" }
Q: Correct way to Office.initialize in Office add-ins with angularjs I want to build an Office add-in with angular and angular-ui-router. I don't know what's the correct place to put Office.initialize. At the moment, I use in index.html: <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script> <script src="https://cdn.rawgit.com/devote/HTML5-History-API/master/history.js"></script> <script src="/javascripts/angularApp.js"></script> ... <body ng-app="myApp"> <ui-view ng-cloak></ui-view> </body> And angularApp.js: Office.initialize = function (reason) { $(document).ready(function () { angular.element(document).ready(function () { angular.bootstrap(document, ['myApp']) }) }); } var app = angular.module('myApp', ['ui.router', 'ui.bootstrap']) app.config(['$stateProvider', function ($stateProvider) { $stateProvider .state('ttt', { url: '/ttt', template: 'ttt', controller: 'tttCtrl' }) .state('addinTest', { url: '/addin/test', template: '<a href="ttt" target="_self">ttt</a><br/><br/><a href="addin/another" target="_self">another page</a>' }) }]) app.controller('tttCtrl', [function() { console.log('console ttt') }]) And manifest.xml: <bt:Url id="Contoso.Taskpane3.Url" DefaultValue="https://localhost:3000/addin/test" /> So loading the add-in shows test page with 2 buttons. Clicking on ttt loads ttt page. However, my test shows that console ttt is displayed twice. If I remove angular.element(document).ready(...) from Office.initialize, console ttt is correctly displayed only once. However, when opening another page which interacts with Excel, I got an error: Office.context is undefined. So could anyone tell me if we should use angular.bootstrap(...)? And what's the correct way to do Office.initialize in Office add-in with angularjs? Many random odd behaviours occur because of this... A: The reason why console ttt is displayed twice, is I have <body ng-app="myApp"> and angular.bootstrap at the same time. If I remove angular.element(document).ready(...) from Office.initialize, console ttt is correctly displayed only once. However, when opening another page which interacts with Excel, I got an error: Office.context is undefined. I have not tested, but removing the Office.initialize block completely and keeps <body ng-app="myApp"> may fix the problem...
{ "pile_set_name": "StackExchange" }