text
stringlengths
64
89.7k
meta
dict
Q: Simple Table with dplyr on Sequence Data I would like to make a simple table with dplyr and summarise But I can't really figure out how ... (Even though it should be quite simple). I have a matrix of sequences. When I simply tabulate table(dta) I have the result I want. dta acquaintance alone child notnotnot nuclear 1 2 17 19 131 nuclear and acquaintance nuclear and acquaintance nuclear and acquaintance nuclear and acquaintance partner 1 1 1 35 2 However, I can't figure out how to do the same with summarise Any suggestion ? dta = structure(c("nuclear", "nuclear", "child", "child", "child", "acquaintance", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "child", "child", "child", "alone", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "child", "child", "child", "child", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "child", "child", "child", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "child", "child", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "partner", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "partner", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear and acquaintance", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear", "nuclear", "nuclear", "nuclear", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear", "nuclear", "nuclear", "nuclear", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear", "nuclear", "nuclear", "nuclear", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear", "nuclear", "nuclear", "nuclear", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear", "nuclear", "child", "nuclear", "notnotnot", "nuclear", "nuclear", "nuclear", "nuclear", "nuclear and acquaintance", "nuclear", "nuclear", "child", "alone", "notnotnot", "nuclear" ), .Dim = c(10L, 21L), .Dimnames = list(c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), c("12:10", "12:20", "12:30", "12:40", "12:50", "13:00", "13:10", "13:20", "13:30", "13:40", "13:50", "14:00", "14:10", "14:20", "14:30", "14:40", "14:50", "15:00", "15:10", "15:20", "15:30"))) A: You just have to convert your data to a data.frame to use dplyr and then you can easily get your desired output: require(dplyr) # ungrouped data_frame(var = c(dta)) %>% group_by_("var") %>% summarise(n()) ## var n() ## 1 acquaintance 1 ## 2 alone 2 ## 3 child 17 ## 4 notnotnot 19 ## 5 nuclear 131 ## 6 nuclear and acquaintance 1 ## 7 nuclear and acquaintance 1 ## 8 nuclear and acquaintance 1 ## 9 nuclear and acquaintance 35 ## 10 partner 2 If you want to do this for each column seperately, you can use tidyr to first gather the result and then spread it again. require(tidyr) # grouped dta %>% as.data.frame %>% gather %>% group_by(key, value) %>% summarise(N = n()) %>% spread(key, N) ## value 12:10 12:20 12:30 12:40 12:50 13:00 13:10 13:20 13:30 13:40 13:50 14:00 14:10 ## 1 acquaintance 1 NA NA NA NA NA NA NA NA NA NA NA NA ## 2 alone NA 1 NA NA NA NA NA NA NA NA NA NA NA ## 3 child 3 3 4 3 2 NA NA NA NA NA NA NA NA ## 4 notnotnot 1 1 1 1 1 1 1 1 1 1 1 NA NA ## 5 nuclear 3 3 3 4 5 7 7 7 7 7 7 7 7 ## 6 nuclear and acquaintance NA NA NA NA NA NA NA NA NA NA NA NA NA ## 7 nuclear and acquaintance NA NA NA NA NA NA NA NA NA NA NA NA NA ## 8 nuclear and acquaintance NA NA NA NA NA NA NA NA NA NA NA NA NA ## 9 nuclear and acquaintance 2 2 2 2 2 2 2 2 2 2 2 2 2 ## 10 partner NA NA NA NA NA NA NA NA NA NA NA 1 1 ## Variables not shown: 14:20 (int), 14:30 (int), 14:40 (int), 14:50 (int), 15:00 (int), 15:10 (int), 15:20 (int), ## 15:30 (int)
{ "pile_set_name": "StackExchange" }
Q: Node.js script stops without any error I've written a scraper using the scraper module and the queue function of async module. I read the list of URLs to scrap from a json file and write the informations in another JSON file. This is my script: var fs = require("fs"); var scrap = require("scrap"), async = require("async"); var errors = []; // Queue a list of URLs var queue = JSON.parse(fs.readFileSync("products.json", "utf8")); var len = queue.products.length; var q = async.queue(function (url, done) { scrap(url, function(err, $) { var product = {}; product.name = $("#page-body h2").first().text().trim(); product.myarr = []; product.picture = $(".content img").first().attr("src"); try { if (product.picture.indexOf("someword") > 1) { delete product.picture; } } catch (e) { console.error(e); } $(".content [style^=\"color: #\"] [style=\"font-weight: bold\"], .content [style=\"font-weight: bold\"] [style^=\"color: #\"]").each(function() { product.myarr.push($(this).text().trim().toLowerCase()); }); if (product.myarr.length) { fs.appendFile("products-parsed.json", JSON.stringify(product) + ",\n", function (err) { console.log(queue.products.indexOf(url), len, err); if (err) { errors.push(queue.products.indexOf(url)); } done(); }); } }); }, 20); q.drain = function() { console.log(errors); }; q.push(queue.products); When I run it, after about 3.000 pages, it stops (quit) and it does not give any error, I have to start from the latest worked page using: q.push(queue.products.slice(lastWorkedPage, queue.products.length - 1)); How can I fix this problem? A: Not sure why, by the way seems like the problem was caused by this row: console.log(queue.products.indexOf(url), len, err); Commenting it has solved the problem, feel free to give a more accurate answer which explains the solution and I'll set it as accepted.
{ "pile_set_name": "StackExchange" }
Q: refname is ambiguous and pull failing I ran the following command as I wanted to move my production branch back without having to checkout first: git branch -f production HEAD~1 I am now getting the following warning when I checkout production: warning: refname 'production' is ambiguous. I then run: git pull And I receive the following error: First, rewinding head to replay your work on top of it... Fast-forwarded production to 7463e01c536ad52746b8879ef3d70ffd5a8db31e. error: Ref refs/heads/production is at 252038dfa22caba8a816a68dcb005c625e44c51f but expected ae5b621609c1b5b430e3d30711157298f842942a fatal: Cannot lock the ref 'refs/heads/production' Could not move back to refs/heads/production I can pull on other branches though. How can I fix this? Further Info git tag doesn't return any output. I previously had a production repository, but I've now renamed it to live > ~/repo (chris-membership-fees)$ git show-ref | grep production 88e0c37c9ae4ff6967ddd027b62b62fa2c0ac272 refs/heads/production 9d739cff44a898f0c68da33fb22a230985e479ce refs/remotes/backup/production ~/repo (chris-membership-fees)$ git branch -a | grep production production remotes/backup/production Log I tagged the first revision as a and the second as b (note that the revision numbers have changed as production is now different). This is the log, simplified by decoration * commit 7463e01c536ad52746b8879ef3d70ffd5a8db31e (**tag: a**, backup/live-master, production, live-master) | | Date: Wed Dec 28 11:47:49 2011 +1100 | | Merge remote-tracking branch 'origin/joseph-quick-fix' | * commit f35f0259c4e36d46dd1df71b3293bef6105cef98 (origin/hotfix-googleplusdirectconnect) | | Date: Fri Dec 23 12:25:27 2011 +1100 | | Add google plus link tag to home page for direct connect | * commit 8b3a30ef2909439ac18b65ebbb316eb0cdd2d61c |\ Merge: f696f3e 88e0c37 | | | | Date: Wed Dec 21 14:28:45 2011 +1100 | | | | Merge branch 'master' into chris-hotfix | | * | commit f696f3e2b8f4a19ec2b2c2a3638c68e7a52836e3 (origin/chris-hotfix, backup/chris-hotfix, chris-hotfix) | | | | Date: Wed Dec 21 11:56:10 2011 +1100 | | | | Fixed buyer price info | | | * commit 88e0c37c9ae4ff6967ddd027b62b62fa2c0ac272 | |\ Merge: c9655da ae5b621 | |/ |/| Date: Wed Dec 21 11:53:36 2011 +1100 | | | | Merge branch 'master' of git.freelancer.com:production into production | | * | commit ae5b621609c1b5b430e3d30711157298f842942a (HEAD, **tag: b**) | | | | Date: Wed Dec 21 10:51:47 2011 +1100 | | | | Merge branch 'master' of git.freelancer.com:production | | | * commit c9655da9c1627ab53720ae818affdd1e6f14119f (origin/game-shadow2) | | | | Date: Tue Dec 20 18:41:57 2011 -0500 | | | | * Removed debugging code | | | * commit ca88d33538bd3b99ea7c186b5b531e611847989d | |\ Merge: 99e983a c397a8b | |/ |/| Date: Tue Dec 20 17:25:24 2011 -0500 | | | | Merge remote-tracking branch 'production/master' into shadow2 A: If you just want to remove the warning: git config --global core.warnambiguousrefs false The warning is coming because you have a branch named production and also a remote named production. It will be ideal to rename either of the two to something else. A: > ~/repo (chris-membership-fees)$ git show-ref | grep production 88e0c37c9ae4ff6967ddd027b62b62fa2c0ac272 refs/heads/production 9d739cff44a898f0c68da33fb22a230985e479ce refs/remotes/backup/production 88e0c37c9ae4ff6967ddd027b62b62fa2c0ac272 refs/remotes/production/master refs/heads/production is ambiguos due to refs/remotes/production. Resolution is generic and independent of the reference-type prefix, thus branches, tags, remotes and even custom ref names must not collide. A: Thanks to Johannes Sixt on the Git mailing list. The most likely reason is that you have a ref 'production' directly in the .git directory. Perhaps you or one of your scripts created it accidentally using 'git update-ref production ae5b621', i.e., without giving the full ref path name It wasn't actually in the .git root directory, but I had an empty production folder in branches.
{ "pile_set_name": "StackExchange" }
Q: Display entries from channel if checked on publish page I have a page where I am allowing the client to choose which channel entries are displayed on the page, which is controlled by a field with checkboxes on the publish page. If rides is checked, I need to display entries from the ride channel. If rides and gear is checked, I need to display entries from both. I have never had to use checkboxes as a field before, and am unsure how to display content only if a specific checkbox is checked. The values of my checkboxes are: Rides Gear Group The name of my custom checkbox field is choose_entries {exp:channel:entries channel="pages" limit="1" url_title="{segment_1}"} {if choose_entries == "Rides"} <h2 class="section-title">Rides<span class="green"></span></h2> {embed="views/.rides"} <img src="content/img/bike.png" /> {/if} {if choose_entries == "Gear"} <h2 class="section-title">Gear<span class="orange"></span></h2> {embed="views/.gear"} {/if} {if choose_entries == "Groups"} <h2 class="section-title">Groups<span class="blue"></span></h2> {embed="views/.groups"} {/if} {/exp:channel:entries} I'm pretty sure my conditionals are incorrect at present, I need some help getting them to work properly. Thank you! And in case it's needed, here is an example of one of the embedded templates, but they display properly on their own. {exp:channel:entries channel="rides" orderby="date" dynamic="no" sort="asc" limit="5" show_future_entries="yes"} <article class="rides left"> <img src="{ride_img:excerpt}" alt="{title}, ${event:price}" /> <div class="content"> <h2>{title}</h2> <p class="lead">${event:price}</p> <p>{ride_excerpt}</p> {if "{event:can_purchase}" == "y"} <p class="read-more"><a class="blue" href="{path=checkout/quantity/{event:id}}">Book now</a></p> {if:else} <p><strong>Tickets are not available</strong></p> {/if} </div> </article> {/exp:channel:entries} Note: I am using Pages and Better Pages to make use of a template across multiple pages, if that complicates matters any. A: The problem in your code stems from the placement of your conditional. Because you haven't started with a channel:entries call EE has no idea what choose_entries is. But you cant put a channel:entries call within another (nested) so you would need to do something like this. {exp:channel:entries (any relevant parameters to pull the correct entry)} {if choose_entries == "Rides"} {embed="includes/.rides"} {/if} {if choose_entries == "Gear"} {embed="includes/.gear"} {/if} {if choose_entries == "Groups"} {embed="includes/.groups"} {/if} {/exp:channel:entries} in the embed calls if you are not familiar with them 'includes' is the template group and '.rides' is the template. I like to use a . before any template i dont want to be accessible via the web. On the embeded templates just add your chunk of specific code as above ie. Rides {exp:channel:entries channel="rides" orderby="date" sort="asc" limit="5" show_future_entries="yes"} <article class="rides left"> <img src="{ride_image:excerpt}" alt="{title}, ${ride_price}" /> <div class="content"> <h2>{title}</h2> <p class="lead">${ride_price}</p> <p>{ride_excerpt}</p> <p class="read-more"><a class="blue" href="/san-diego">Learn more about this ride &raquo;</a></p> </div> </article> {/exp:channel:entries} <img src="content/img/bike.png" /> Hope that makes sense. There is at least one other way you could do this by passing info to a single embedded template but this way is the easiest to explain.
{ "pile_set_name": "StackExchange" }
Q: Grammar for a list within a list that does not start with a colon I'm trying to make sure my writing is correct for the following sentence: Our scanners are not affected by rain, snow, glare from the sun, or electrical interference from cell phones, radios, Wi-Fi, etc. Another case comes later in the same document that I'm working on: At no additional cost we will customize your scanner with logos, images, or text such as Maintenance, Expiration Date, or anything else your business needs. Are these structurally correct or do I need to remove the "or" from the first set of items? For example: At no additional cost we will customize your scanner with logos, images, text such as Maintenance, Expiration Date, or anything else your business needs In the first sentence all of the electronics are part of the electrical interference, just as in the second sentence "maintenance, expiration date, and anything else" is referring to text. What is the correct way to structure this? A: At no additional cost, we will customize your scanner with logos, images, text such as "Maintenance" and "Expiration Date," or anything else your business needs.
{ "pile_set_name": "StackExchange" }
Q: set permission for sendBroadcast function android I want to use context.sendBroadcast(intent, receiverPermission); in my application, so please any body help me how to set receiver permission in function as well as manifest file A: In your manifest file: <uses-permission android:name="com.example.permission.RECEIVE_MY_BROADCAST" />
{ "pile_set_name": "StackExchange" }
Q: Fast selection of a Timestamp range in hierarchically indexed pandas data in Python Having a DataFrame with tz-aware DatetimeIndex the below is a fast way of selecting multiple rows between two dates for left inclusive, right exclusive intervals: import pandas as pd start_ts = pd.Timestamp('20000101 12:00 UTC') end_ts = pd.Timestamp('20000102 12:00 UTC') ix_df = pd.DataFrame(0, index=[pd.Timestamp('20000101 00:00 UTC'), pd.Timestamp('20000102 00:00 UTC')], columns=['a']) EPSILON_TIME = pd.tseries.offsets.Nano() ix_df[start_ts:end_ts-EPSILON_TIME] The above solution is fairly efficient as we do not create a temporary indexing iterable as I'll do later, nor do we run a lambda expression in Python to create the new data frame. In fact I believe the selection is around O(log(N)) at most. I wonder if this is also possible on a particular axis of a MultiIndex, or I have to create a temporary iterable or run a lambda expressions. E.g.: mux = pd.MultiIndex.from_arrays([[pd.Timestamp('20000102 00:00 UTC'), pd.Timestamp('20000103 00:00 UTC')], [pd.Timestamp('20000101 00:00 UTC'), pd.Timestamp('20000102 00:00 UTC')]]) mux_df = pd.DataFrame(0, index=mux, columns=['a']) Then I can select on the first (zeroth) level of the index on the same way: mux_df[start_ts:end_ts-EPSILON_TIME] which yields: a 2000-01-02 00:00:00+00:00 2000-01-01 00:00:00+00:00 0 but for the second level I have to chose a slow solution: values_itr = mux_df.index.get_level_values(1) mask_ser = (values_itr >= start_ts) & (values_itr < end_ts) mux_df[mask_ser] yielding correctly: a 2000-01-03 00:00:00+00:00 2000-01-02 00:00:00+00:00 0 Any fast workarounds? Thanks! Edit: Chosen Approach Ended up with this solution after all, when having realized I also need slicing: def view(data_df): if len(data_df.index) == 0: return data_df values_itr = data_df.index.get_level_values(0) values_itr = values_itr.values from_i = np.searchsorted(values_itr, np.datetime64(start_ts), side='left') to_i = np.searchsorted(values_itr, np.datetime64(end_ts), side='left') return data_df.ix[from_i:to_i] Then do view(data_df).copy(). Note: my values in the first level of the index are in fact sorted. A: Well you are actually comparing apples to oranges here. In [59]: N = 1000000 In [60]: pd.set_option('max_rows',10) In [61]: idx = pd.IndexSlice In [62]: df = DataFrame(np.arange(N).reshape(-1,1),columns=['value'],index=pd.MultiIndex.from_product([list('abcdefghij'),date_range('20010101',periods=N/10,freq='T',tz='US/Eastern')],names=['one','two'])) In [63]: df Out[63]: value one two a 2001-01-01 00:00:00-05:00 0 2001-01-01 00:01:00-05:00 1 2001-01-01 00:02:00-05:00 2 2001-01-01 00:03:00-05:00 3 2001-01-01 00:04:00-05:00 4 ... ... j 2001-03-11 10:35:00-05:00 999995 2001-03-11 10:36:00-05:00 999996 2001-03-11 10:37:00-05:00 999997 2001-03-11 10:38:00-05:00 999998 2001-03-11 10:39:00-05:00 999999 [1000000 rows x 1 columns] In [64]: df2 = df.reset_index(level='one').sort_index() df In [65]: df2 Out[65]: one value two 2001-01-01 00:00:00-05:00 a 0 2001-01-01 00:00:00-05:00 i 800000 2001-01-01 00:00:00-05:00 h 700000 2001-01-01 00:00:00-05:00 g 600000 2001-01-01 00:00:00-05:00 f 500000 ... .. ... 2001-03-11 10:39:00-05:00 c 299999 2001-03-11 10:39:00-05:00 b 199999 2001-03-11 10:39:00-05:00 a 99999 2001-03-11 10:39:00-05:00 i 899999 2001-03-11 10:39:00-05:00 j 999999 [1000000 rows x 2 columns] When I reset the index (iow create a single-level index), it IS NOT LONGER UNIQUE. This makes a big difference, because it searches diffently. So you cannot really compare indexing on a single-level unique index vs a multi-level. Turns out using the multi-index slicers (introduced in 0.14.0). Makes indexing pretty fast on any level. In [66]: %timeit df.loc[idx[:,'20010201':'20010301'],:] 1 loops, best of 3: 188 ms per loop In [67]: df.loc[idx[:,'20010201':'20010301'],:] Out[67]: value one two a 2001-02-01 00:00:00-05:00 44640 2001-02-01 00:01:00-05:00 44641 2001-02-01 00:02:00-05:00 44642 2001-02-01 00:03:00-05:00 44643 2001-02-01 00:04:00-05:00 44644 ... ... j 2001-03-01 23:55:00-05:00 986395 2001-03-01 23:56:00-05:00 986396 2001-03-01 23:57:00-05:00 986397 2001-03-01 23:58:00-05:00 986398 2001-03-01 23:59:00-05:00 986399 [417600 rows x 1 columns] Compare this with a non-unique single-level In [68]: %timeit df2.loc['20010201':'20010301'] 1 loops, best of 3: 470 ms per loop Here is a UNIQUE single-level In [73]: df3 = DataFrame(np.arange(N).reshape(-1,1),columns=['value'],index=date_range('20010101',periods=N,freq='T',tz='US/Eastern')) In [74]: df3 Out[74]: value 2001-01-01 00:00:00-05:00 0 2001-01-01 00:01:00-05:00 1 2001-01-01 00:02:00-05:00 2 2001-01-01 00:03:00-05:00 3 2001-01-01 00:04:00-05:00 4 ... ... 2002-11-26 10:35:00-05:00 999995 2002-11-26 10:36:00-05:00 999996 2002-11-26 10:37:00-05:00 999997 2002-11-26 10:38:00-05:00 999998 2002-11-26 10:39:00-05:00 999999 [1000000 rows x 1 columns] In [75]: df3.loc['20010201':'20010301'] Out[75]: value 2001-02-01 00:00:00-05:00 44640 2001-02-01 00:01:00-05:00 44641 2001-02-01 00:02:00-05:00 44642 2001-02-01 00:03:00-05:00 44643 2001-02-01 00:04:00-05:00 44644 ... ... 2001-03-01 23:55:00-05:00 86395 2001-03-01 23:56:00-05:00 86396 2001-03-01 23:57:00-05:00 86397 2001-03-01 23:58:00-05:00 86398 2001-03-01 23:59:00-05:00 86399 [41760 rows x 1 columns] Fastest so far In [76]: %timeit df3.loc['20010201':'20010301'] 1 loops, best of 3: 294 ms per loop Best is a single-level UNIQUE without a timezone In [77]: df3 = DataFrame(np.arange(N).reshape(-1,1),columns=['value'],index=date_range('20010101',periods=N,freq='T')) In [78]: %timeit df3.loc['20010201':'20010301'] 1 loops, best of 3: 240 ms per loop And by far the fastest method (I am doing a slightly different search here to get the same results, as the semantics of the above searches include all dates on the specified dates) In [101]: df4 = df3.reset_index() In [103]: %timeit df4.loc[(df4['index']>='20010201') & (df4['index']<'20010302')] 100 loops, best of 3: 10.6 ms per loop In [104]: df4.loc[(df4['index']>='20010201') & (df4['index']<'20010302')] Out[104]: index value 44640 2001-02-01 00:00:00 44640 44641 2001-02-01 00:01:00 44641 44642 2001-02-01 00:02:00 44642 44643 2001-02-01 00:03:00 44643 44644 2001-02-01 00:04:00 44644 ... ... ... 86395 2001-03-01 23:55:00 86395 86396 2001-03-01 23:56:00 86396 86397 2001-03-01 23:57:00 86397 86398 2001-03-01 23:58:00 86398 86399 2001-03-01 23:59:00 86399 [41760 rows x 2 columns] Ok, so why is the 4th method the fastest. It constructs a boolean indexing array then uses nonzero, so pretty fast. The first three methods use searchsorted (twice) after already determining that the index is unique and monotonic, to figure out the endpoints, so you have multiple things going on. Bottom line, boolean indexing is pretty fast, so use it! (results may different and the first 3 methods may become faster depending on WHAT you are selecting, e.g. a smaller selection range may have different performance characteristics).
{ "pile_set_name": "StackExchange" }
Q: Unit testing, Black-box testing and white box testing What is Unit testing, Black-box testing and White-Box testing? I googled but all the explanation I found was very technical. Can anyone answer this question in a simple way with an appropriate example? A: In black box testing, you don't care how the internals of the thing being tested work. You invoke the exposed API and check the result; you don't care what the thing being tested did to give you the result. In white box testing, you do care how the internals of the thing being tested work. So instead of just checking the output of your thing, you might check that internal variables to the thing being tested are correct. Unit testing is a way of testing software components. The "Unit" is the thing being tested. You can do both black and white box testing with unit tests; the concept is orthogonal to white/black-box testing. A: A very non technical explaination lacking any details.... Here comes.. Blackbox Testing : Testing an application without any knowledge of how the internal application works Whitebox Testing: Testing an application with knowledge of how the internal works, such as by having the source code side by side while you are doing your test. Unit Testing: This is where you create tests which interact directly with your application. You would check a function in your application and assert that the response should return with value X. Unit Tests are usually, but not always created by the developers themselves as well, whereas if a company does whitebox and blackbox testing, it can be done by anyone. This is a very basic explaination.
{ "pile_set_name": "StackExchange" }
Q: C# dll import function correctly I am trying to import a function from a c dll into C#. The c function looks like this unsigned short write_buffer( unsigned short device_number, unsigned short word_count, unsigned long buffer_link, unsigned short* buffer) my attempt at a C# import looks like this [DllImport("sslib32.dll", CharSet = CharSet.Ansi, SetLastError = true)] private static extern ushort write_buffer(ushort deviceNumber, ushort wordCount, UInt32 bufferLink, IntPtr buffer) In C# i have a Dictionary of messages that i would like to pass to this function. The Dictionary looks like this: Dictionary<string, List<ushort>> msgs I am a bit confused how to make a make a proper call to pass msgs as the buffer. deviceNumber is 2, wordCount is 32, and buffLink is 0. So i know the call should look something like this write_buffer(2,32,0, msgs[key]); Obviously i am getting an invalid argument for the IntPtr. What is the proper way to make this call? A: It is quite unclear what buffer should contain and in which direction its data flows. Your dictionary suggests it should be an array. Just declare it that way: private static extern ushort write_buffer(.., ushort[] buffer); And use msgs[key].ToArray() in the call. Using constants in the write_buffer() call does not make that a likely scenario though, there ought to be msgs[key].Count in there somewhere.
{ "pile_set_name": "StackExchange" }
Q: Keep Touch Bar active when app isn't active I am trying to keep the Touch Bar of my app active in the app controls part of the Touch Bar even when using a different app. How can I do this? I know this can be done because I have seen apps e.g. BetterTouchTool to do this. For more information I am using Swift A: Apple does not provide anything for this and apps such as BetterTouchTool use their own code to do this which would be quite complicated.
{ "pile_set_name": "StackExchange" }
Q: Failed to establish initial TCP/IP connection (Chilkat-Python) I'm trying to send a file from raspberry pi to my Windows pc using python-chilkat module. However it is returning this kind of error: ChilkatLog: Connect_Ssh: DllDate: Dec 21 2018 ChilkatVersion: 9.5.0.76 UnlockPrefix: 30-day trial Architecture: Little Endian; 32-bit Language: armhf linux Python 3.* VerboseLogging: 0 connectInner: hostname: 192.168.1.4 port: 22 sshConnect: connectSocket: connect_ipv6_or_ipv4: getsockopt indicates an error. socketErrno: 111 socketError: Connection refused --connect_ipv6_or_ipv4 connect_ipv6_or_ipv4: getsockopt indicates an error. socketErrno: 111 socketError: Connection refused --connect_ipv6_or_ipv4 connect_ipv6_or_ipv4: getsockopt indicates an error. socketErrno: 111 socketError: Connection refused --connect_ipv6_or_ipv4 connect_ipv6_or_ipv4: getsockopt indicates an error. socketErrno: 111 socketError: Connection refused --connect_ipv6_or_ipv4 --connectSocket Failed to establish initial TCP/IP connection hostname: 192.168.1.4 port: 22 --sshConnect --connectInner Failed. --Connect_Ssh --ChilkatLog Can someone explain to me why Im getting these error? A: See this online example which experiments with different failure cases to see what errors are returned: https://www.example-code.com/chilkat2-python/socket_connect_fail.asp In some of the test cases, you'll see "connection rejected" which is the same as "connection refused". In other cases you'll get a timeout. The cases that result in "connection rejected" are the most likely causes for the failure. PS> I understand that the example I'm pointing to is for a simple TCP socket connection, but SSH begins with a simple TCP connection, and that is what is failing.
{ "pile_set_name": "StackExchange" }
Q: Additional Parameters on Windows Notification Server I try sending push notification, I'm on server-side. Is there a way in WNS, the push service for Windows 8, to send additional parameters, that will not be displayed. On Windows Phone 7, I use the wp:Param as Follow : <?xml version="1.0" encoding="utf-8"?> <wp:Notification xmlns:wp="WPNotification"> <wp:Toast> ..... <wp:Param></wp:Param> </wp:Toast> </wp:Notification> Is there an equivalent for toast for exemple ? A: For toast notifications, use the launch attribute in the toast notification XML: <toast launch="additionalContextParameters"> ... </toast> The value specified in the launch attribute can be retrieved from the Arguments attribute passed into the OnLaunched handler (more details on MSDN).
{ "pile_set_name": "StackExchange" }
Q: Why does including this module not override a dynamically-generated method? I'm trying to override a dynamically-generated method by including a module. In the example below, a Ripple association adds a rows= method to Table. I want to call that method, but also do some additional stuff afterwards. I created a module to override the method, thinking that the module's row= would be able to call super to use the existing method. class Table # Ripple association - creates rows= method many :rows, :class_name => Table::Row # Hacky first attempt to use the dynamically-created # method and also do additional stuff - I would actually # move this code elsewhere if it worked module RowNormalizer def rows=(*args) rows = super rows.map!(&:normalize_prior_year) end end include RowNormalizer end However, my new rows= is never called, as evidenced by the fact that if I raise an exception inside it, nothing happens. I know the module is getting included, because if I put this in it, my exception gets raised. included do raise 'I got included, woo!' end Also, if instead of rows=, the module defines somethingelse=, that method is callable. Why isn't my module method overriding the dynamically-generated one? A: Let's do an experiment: class A; def x; 'hi' end end module B; def x; super + ' john' end end A.class_eval { include B } A.new.x => "hi" # oops Why is that? The answer is simple: A.ancestors => [A, B, Object, Kernel, BasicObject] B is before A in the ancestors chain (you can think of this as B being inside A). Therefore A.x always takes priority over B.x. However, this can be worked around: class A def x 'hi' end end module B # Define a method with a different name def x_after x_before + ' john' end # And set up aliases on the inclusion :) # We can use `alias new_name old_name` def self.included(klass) klass.class_eval { alias :x_before :x alias :x :x_after } end end A.class_eval { include B } A.new.x #=> "hi john" With ActiveSupport (and therefore Rails) you have this pattern implemented as alias_method_chain(target, feature) http://apidock.com/rails/Module/alias_method_chain: module B def self.included(base) base.alias_method_chain :x, :feature end def x_with_feature x_without_feature + " John" end end Update Ruby 2 comes with Module#prepend, which does override the methods of A, making this alias hack unnecessary for most use cases.
{ "pile_set_name": "StackExchange" }
Q: Signalr not sending data on Azure host I am developing a web app where I use two hubs on a specific page to push notifications from server to clients and handle messages between clients. However I've come across a scenario oon my Azure production app service where the notifications hub won't transmit data back to the client even though the query is bringing the correct data. Client code: // Declare a proxy to reference the hub. var notifHub = $.connection.NotificationHub; var chat = $.connection.ChatHub; var maxTabs = 10, index = 1; // Start the connection. $.connection.hub.start().done(function () { notifHub.server.getNotifications(); /* Some more code irrelevant to this question */ }); notifHub.client.getNotifications = function (notification) { // Html encode display name and message. const notifications = JSON.parse(notification); // Add the message to the page. $("#Notifications").empty(); notifications.forEach(function (notification) { const notificationDate = new Date(notification.CreationDate); let alertColor = ""; if (((new Date) - notificationDate) < oneMinute) alertColor = "alert-success"; else if (((new Date) - notificationDate) > oneMinute && ((new Date) - notificationDate) < fiveMinutes) alertColor = "alert-warning"; else if (((new Date) - notificationDate) > fiveMinutes) alertColor = "alert-danger"; //language=html var notificationTemplate = "<div class ='alert " + alertColor + "' role='alert' data-request-id='{{RequestId}}' data-connection-id='{{ConnectionId}}' data-requester='{{RequesterName}}' data-group-name='{{RequesterGroup}}' data-request-date-time='{{CreationDate}}'><strong>Usuario</strong>: {{RequesterName}}<br /><strong>Fecha</strong>: {{CreationDate | datetime}}</div>"; $("#Notifications").append(Mustache.render(notificationTemplate, notification)); }); }; Hub code public void GetNotifications() { var db = new Entities(); db.Database.Log = s => Debug.WriteLine(s); var companyId = Context.User.Identity.GetCompanyId(); var notifications = (from notification in db.AgentRequestNotification where notification.AttendedByAgent == false && notification.CompanyId == companyId orderby notification.CreationDate select notification).ToList(); Clients.All.getNotifications(JsonConvert.SerializeObject(notifications)); } Code works perfectly on my local environment as seen on the following screenshot But not on production environment On my Azure App settings I've enabled Websockets and disabled ARR Affinity. I've debugged remotely with VS and this is the output I get, not sure what's causing about that WebSocketException shown after EF query log Opened connection at 1/15/2018 9:03:46 PM +00:00 SELECT [Project1].[RequestId] AS [RequestId], [Project1].[ConnectionId] AS [ConnectionId], [Project1].[RequesterName] AS [RequesterName], [Project1].[RequesterGroup] AS [RequesterGroup], [Project1].[AttendedByAgent] AS [AttendedByAgent], [Project1].[CreationDate] AS [CreationDate], [Project1].[CompanyId] AS [CompanyId], [Project1].[AttendedByAgentDate] AS [AttendedByAgentDate] FROM ( SELECT [Extent1].[RequestId] AS [RequestId], [Extent1].[ConnectionId] AS [ConnectionId], [Extent1].[RequesterName] AS [RequesterName], [Extent1].[RequesterGroup] AS [RequesterGroup], [Extent1].[AttendedByAgent] AS [AttendedByAgent], [Extent1].[CreationDate] AS [CreationDate], [Extent1].[CompanyId] AS [CompanyId], [Extent1].[AttendedByAgentDate] AS [AttendedByAgentDate] FROM [dbo].[AgentRequestNotification] AS [Extent1] WHERE (0 = [Extent1].[AttendedByAgent]) AND ([Extent1].[CompanyId] = @p__linq__0) ) AS [Project1] ORDER BY [Project1].[CreationDate] ASC -- p__linq__0: '1' (Type = Int32, IsNullable = false) -- Executing at 1/15/2018 9:03:49 PM +00:00 -- Completed in 25 ms with result: SqlDataReader Closed connection at 1/15/2018 9:03:49 PM +00:00 The thread 0x1520 has exited with code 0 (0x0). The thread 0x2904 has exited with code 0 (0x0). Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll Exception thrown: 'System.Net.WebSockets.WebSocketException' in System.Web.dll Exception thrown: 'System.Net.WebSockets.WebSocketException' in mscorlib.dll Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll Exception thrown: 'System.Net.WebSockets.WebSocketException' in mscorlib.dll Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll Exception thrown: 'System.Net.WebSockets.WebSocketException' in System.Web.dll Exception thrown: 'System.Data.SqlClient.SqlException' in mscorlib.dll Exception thrown: 'System.Net.WebSockets.WebSocketException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.dll Exception thrown: 'System.Net.WebSockets.WebSocketException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll w3wp.exe Error: 0 : Error while closing the websocket: System.Net.WebSockets.WebSocketException (0x800704CD): An operation was attempted on a nonexistent network connection at System.Web.WebSockets.WebSocketPipe.<>c__DisplayClass8_0.<WriteCloseFragmentAsync>b__0(Int32 hrError, Int32 cbIO, Boolean fUtf8Encoded, Boolean fFinalFragment, Boolean fClose) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.WebSockets.AspNetWebSocket.<>c__DisplayClass46_0.<<DoWork>b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.WebSockets.AspNetWebSocket.<DoWork>d__45`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.WebSockets.AspNetWebSocket.<>c__DisplayClass32_0.<<CloseOutputAsyncImpl>b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.<>c.<<CloseAsync>b__13_0>d.MoveNext() Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.SqlServer.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in Microsoft.Owin.Security.Cookies.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in mscorlib.dll Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in Microsoft.Owin.Host.SystemWeb.dll The thread 0x219c has exited with code 0 (0x0). Here's the SignalR client log [17:56:53 GMT-0500 (Eastern Standard Time)] SignalR: No hubs have been subscribed to. The client will not receive data from hubs. To fix, declare at least one client side function prior to connection start for each hub you wish to subscribe to. [17:56:53 GMT-0500 (Eastern Standard Time)] ignalR: Negotiating with '/signalr/negotiate? clientProtocol=1.5&connectionData=%5B%5D'. [17:56:53 GMT-0500 (Eastern Standard Time)] SignalR: webSockets transport starting. [17:56:53 GMT-0500 (Eastern Standard Time)] SignalR: Connecting to websocket endpoint 'ws://samiweb.azurewebsites.net/signalr/connect? transport=webSockets&clientProtocol=1.5&connectionToken=yKn2ns1bOenZLiUtCiOSSfQg YCl%2FyVAvxKejSZx2x0svkyzIJJ85qjNMk7IBjy8Nes0Lg9W%2BUTAPW21z6rVHTwXbb4wxaZhVwn1J vzrNra0WhYCuXMiu6kLYs0FWuRUy&connectionData=%5B%5D&tid=1'. [17:56:54 GMT-0500 (Eastern Standard Time)] SignalR: Websocket opened. [17:56:54 GMT-0500 (Eastern Standard Time)] SignalR: webSockets transport connected. Initiating start request. [17:56:54 GMT-0500 (Eastern Standard Time)] SignalR: The start request succeeded. Transitioning to the connected state. [17:56:54 GMT-0500 (Eastern Standard Time)] SignalR: Now monitoring keep alive with a warning timeout of 13333.333333333332, keep alive timeout of 20000 and disconnecting timeout of 30000 [17:56:54 GMT-0500 (Eastern Standard Time)] SignalR: Invoking saminotificationhub.GetNotifications [17:56:54 GMT-0500 (Eastern Standard Time)] SignalR: Invoked saminotificationhub.GetNotifications Any help will be appreciated! A: From your SignalR client log: No hubs have been subscribed to. The client will not receive data from hubs. To fix, declare at least one client side function prior to connection start for each hub you wish to subscribe to. AFAIK, the normal client log would look like: Client subscribed to hub 'notificationhub'. You could try to declare your client side methods prior to $.connection.hub.start().
{ "pile_set_name": "StackExchange" }
Q: Declare numerical-sequence set in AMPL .dat file Suppose I want an AMPL set to contain the integers 1 through 5. How can I declare this in the .dat file? I can do it in the .mod file, like this: things.mod: set THINGS := 1..5; Console: ampl: model things.mod; ampl: display THINGS; set THINGS := 1 2 3 4 5; ampl: display THINGS diff {2}; set THINGS diff {2} := 1 3 4 5; But now suppose I do this: things.mod: set THINGS; things.dat: set THINGS := 1..5; Console: ampl: model things.mod; ampl: data things.dat; ampl: display THINGS; set THINGS := 1..5; ampl: display THINGS diff {2}; set THINGS diff {2} := 1..5; AMPL seems to be treating 1..5 as a string rather than as an sequence of integers. Why, and how do I fix it? A: The .. operator cannot be used in the data section (i.e. it won't be expanded, see the AMPL FAQ). What you can do is to declare the limits in the model, e.g. param n; set things := 1..n; and define them in the data file param n := 5;
{ "pile_set_name": "StackExchange" }
Q: Triggering a click for a control in a update panel problems I'm using a RadListView and i want to click a checkbox/button (It displays as a checkbox but its designer code shows it as a button). But every time i call the click method the page refreshes instead of updating the update panel which contains the list view. How do i call the click event without the page posting back instead of the update panel? <asp:Button ID="SelectButton" runat="server" CausesValidation="False" CommandName="Select" CssClass="rlvBSel" Text=" " ToolTip="Select" /> Code: $(".rlvI, .rlvA").click(function () { $(this).find(".rlvBSel").click(); }); A: I assume that your page does a full postback instead of an asynchronous. Is the Button inside of the UpdatePanel or outside? If the latter(or it's ChildrenAsTriggers is set to false) you must define an AsyncPostBackTrigger in the UpdatePanel. For example: <Triggers> <asp:AsyncPostBackTrigger ControlID="SelectButton" EventName="Click" /> </Triggers> Maybe it'll solve your issue if you set clientIDMode="AutoID" <pages clientIDMode="AutoID"></pages> http://www.aspnetajaxtutorials.com/2011/05/linkbutton-inside-listview-cause-full.html
{ "pile_set_name": "StackExchange" }
Q: Kotlin direct access to Button in android.support.v4.app.Fragment null object reference I'm trying to get direct access to a button in a fragment (android.support.v4) and this is what it's throwing: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference at com.....fragments.HomeFragment._$_findCachedViewById(HomeFragment.kt) at com.....fragments.HomeFragment.onCreateView(HomeFragment.kt:25) This is the button I'm trying to get access to in fragment_home.xml: <Button android:id="@+id/batteryInstallationButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/battery_installation" android:layout_weight="1" android:textSize="12sp" android:background="@drawable/custom_button" android:textColor="@color/white" android:layout_marginStart="5dp" android:layout_marginEnd="5dp"/> This is the Kotlin code in HomeFragment.kt import android.content.Context import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import kotlinx.android.synthetic.main.fragment_home.* class HomeFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater!!.inflate(R.layout.fragment_home, container, false) batteryInstallationButton?.setOnClickListener { Toast.makeText(context, "ehere", Toast.LENGTH_SHORT).show(); } return rootView } companion object { fun newInstance(): HomeFragment { val fragment = HomeFragment() return fragment } } } Anyone know why I can't get the direct access to the Button? A: Here you have two options: Access batteryInstallationButton from onActivityCreated where the view will be already inflated and it will find the button. Use: import kotlinx.android.synthetic.main.fragment_home.view.* see the .view that I added to the synthetic and use it directly from the view that you already inflated: val rootView = inflater!!.inflate(R.layout.fragment_home, container, false) rootView.batteryInstallationButton?.setOnClickListener..... Please let me know if this fix your issue. Regards!
{ "pile_set_name": "StackExchange" }
Q: Sugestões de Ferramentas apache para desenvolver em php com Postgresql Bom pessoal, estou querendo desenvolver em php, e pra isso é preciso instalar uma ferramenta que faça meu pc virar metade servidor, como todo mundo sabe existem várias ferramentas dessas para baixar, como: XAMP, WAMP, EASYPHP etc. Só que todas essas dão suporte ao SGBD MYSQL. Queria saber se existem ferramentas desse tipo, mas que venham por padrão com suporte ao SGBD POSTGRESQL para me indicarem. (É um projeto para faculdade, professor exigiu usar O SGBD POSTGRESQL). OBS: Eu encontrei uma ferramenta da Bitnami chamada WAPP STACK, só que não gostei, quando atualizo o arquivo php, ele demora pra atualizar no navegador. A: Existem dois drivers para fazer conexão com o postgres o pgsql que permite usar as função pg_* e o driver para PDO. A instação é feita da seguinte maneira abra o php.ini e procure as linhas: ;extension=php_pgsql.dll ;extension=php_pdo_pgsql.dll Descomente (remova o ponto e vírgula) de ambas. Reinice o apache, para testar se foram instaladas corretamente crie um arquivo php com apenas: <?php phpinfo(); Isso vai mostrar todas as configuraçõe do php. Se tiver o php configurado na linha de comando pode fazer php -m
{ "pile_set_name": "StackExchange" }
Q: Show the number of solutions Show that the number of solutions of $x^2+y^2=m$, where $m=2^{\alpha}r$ and $r$ is odd, is given by $U(m)=4\sum_{u|r}(-1)^{\frac{u-1}{2}}=4\gamma(m)$, where $\gamma(m)$ denotes the number of positive divisors of $m$ A: If $X^2+Y^2=p^{n+2k}$ where $X,Y,n>0,k\ge 0$ are integers with $(X,Y)=p^k$ and $p$ is an odd prime, let $\frac X x=\frac Y y=p^k$, so, $x^2\equiv -y^2\pmod {p^n}\implies z^2\equiv-1\pmod {p^n}$ where $z=\frac x y$ We know $p^n$ has primitive roots, so taking discrete logarithm w.r.t. one of the primitive roots $r$ we get, $2 ind_rz\equiv \frac{\phi(p^n)}2\pmod{\phi(p^n)}$ or $2 ind_r z\equiv \frac{p^{n-1}(p-1)}2\pmod{p^{n-1}(p-1)}$ which is a linear congruence equation (compare with $ax\equiv b\pmod c$) which is solvable if $(p^{n-1}(p-1),2)\mid \frac{p^{n-1}(p-1)}2$ i.e, $2\mid \frac{p-1}2\implies p\equiv 1\pmod 4$ to admit any solution. If $p\equiv 1\pmod 4$, there will be $(p^{n-1}(p-1),2)=2$ solutions. Clearly, if $z>0$ is one solution, so is $-z$ . $z=\frac x y$ and $\frac {-x} {-y}$ and $-z=\frac {-x} y$ and $\frac x {-y}$ So, there will be exactly one positive integral solution to $X^2+Y^2=p^{n+2k}$ if $p\equiv 1\pmod 4.$ If $p\equiv -1\pmod 4,$ then $p^{2m}$ can be expressed uniquely in term of non-negative numbers as $(p^m)^2+0^2$ If $p=2,X^2+Y^2=2^{h+2k},$ If $(X,Y)=2^k$, like earlier we can reach to $x^2+y^2=2^h$ where $(x,y)=1$ if $h=0, x^2+y^2=1$ else $x,y$ must be odd as both must have the same parity as $h\ge 1$ But $(2a+1)^2+(2b+1)^2=8\frac{a(a+1)+b(b+1)}{2}+2\equiv 2\pmod 8\implies h=1$ So, $x^2+y^2=2^h$ reduces to $x^2+y^2=2$ which has exactly one solution $(1,1)$ So, $X^2+Y^2=2^{h+2k}$ has exactly one solution. Now if $X^2+Y^2=m_1$ and $X^2+Y^2=m_2$ have $t_1,t_2$ solutions respectively, in non-negative integers where $(m_1,m_2)=1$, then $X^2+Y^2=t_1+t_2$ solutions in non-negative integers the reason being $(a^2+b^2)(c^2+d^2)=(ac\pm bd)^2+(ad∓bc)^2$ If $m=2^a\prod p_i^{b_i}\prod q_i^{c_i},$ where $p_i\equiv 1\pmod 4$ and $q_i\equiv -1\pmod 4$ $x^2+y^2=m$ will have no solution if at least one of $c_i$ is odd and it will have $(1+$ the number of unique $p_i$) solution in non-negative integers. Now, if $(a,b)$ is a solution to $X^2+y^2=m,$ so are $(a,-b),(-a,-b),(-a,b)$ So there will be $4(1+$ the number of unique $p_i$) solution in integers in the later case.
{ "pile_set_name": "StackExchange" }
Q: Code won't stop running. Seems trivial but I cannot figure it out Here's my code for approximating exp(x). I know there's probably a function for factorial but I wanted to make sure I could create one myself :) def factorial(n): """Computes factorial of a number n""" fac = n while n != 1: fac = fac * (n-1) n -= 1 return fac def exp_x_approx(x, n): """estimates exp(x) using a taylor series with n+1 terms""" s = 0 for i in range(0, n+1): s = s + ((x**i)/factorial(i)) print (s) return s print(exp_x_approx(2,8)) There's no error until I ^c to stop it from running, at which point it reads: File "/Users/JPagz95/Documents/exp_x_approx.py", line 18, in <module> print(exp_x_approx(2,8)) File "/Users/JPagz95/Documents/exp_x_approx.py", line 13, in exp_x_approx s = s + ((x**i)/factorial(i)) File "/Users/JPagz95/Documents/exp_x_approx.py", line 5, in factorial fac = fac * (n-1) KeyboardInterrupt I believe it's endlessly looping but I cannot figure out why. Any help would be appreciated! A: In your function def factorial(n): """Computes factorial of a number n""" fac = n while n != 1: fac = fac * (n-1) n -= 1 return fac You can modify it like this def factorial(n): if n < 0: return "some error info." fac = 1 while n>=1: fac = fac * n n -= 1 return fac You should set your initial condition as fac=1 and set you terminate condition as n>=1 rather than n!=1. Think about what if I give a number -2?
{ "pile_set_name": "StackExchange" }
Q: Parse a large JSON file in ActionScript 3 I need to parse a large trace file (up to 200-300 MB) in a Flex application. I started using JSON instead of XML hoping to avoid these problems, but it did not help much. When the file is bigger than 50MB, JSON decoder can't handle it (I am using the as3corelib). I have doing some research and I found some options: Try to split the file: I would really like to avoid this; I don't want to change the current format of the trace files and, in addition, it would be very uncomfortable to handle. Use a database: I was thinking of writing the trace into a SQLite database and then reading from there, but that would force me to modify the program that creates the trace file. From your experience, what do you think of these options? Are there better options? The program that writes the trace file is in C++. A: I found this library which is a lot faster than the official one: https://github.com/mherkender/actionjson I am using it now and works perfectly. It also has asynchronous decoder and encoder
{ "pile_set_name": "StackExchange" }
Q: Solucionar error has leaked IntentReceiver en Android Tengo una clase extendida de BroadcastReceiver en MainActivity.java lanzo el listener registerReceiver( new ConnectivityChangeReceiver(), new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); Me encuentro que cuando salgo de la app me muestra el siguiente error en el log: E/ActivityThread: Activity com.webserveis.app.myconnection.MainActivity has leaked IntentReceiver com.webserveis.app.myconnection.ConnectivityChangeReceiver@32ad932e that was originally registered here. Are you missing a call to unregisterReceiver()? android.app.IntentReceiverLeaked: Activity com.webserveis.app.myconnection.MainActivity has leaked IntentReceiver com.webserveis.app.myconnection.ConnectivityChangeReceiver@32ad932e that was originally registered here. Are you missing a call to unregisterReceiver()? that was originally registered here. Are you missing a call to unregisterReceiver() En onStop() me gustaria desregistrar el listener, pero no ser como implementarlo A: Cuando se implementa un BroadcastReceiver, es importante saber que tenemos que registrar y desregistrar el receiver, pero NO es buena practica cancelar el receiver en onStop() y esta es la razón, la cual puedes ver en la documentación: Cuando tu implementación requiere el registro en onResume() existe una consideración importante. Si está registrando un receiver en Activity.onResume(), debes anular el registro en Activity.onPause(). (No recibirá intents cuando este en pausa, y esto puede reducir innecesaria sobrecarga del sistema) En cuanto a tu error: MainActivity has leaked IntentReceiver la documentación misma lo señala : No olvides cancelar el registro de receiver registrado en forma dinámica mediante el método Context.unregisterReceiver(). Si se olvida de esto, el sistema Android reporta un Leaked error. Por ejemplo, si registraste un receiver en onResume() de su actividad, se debe cancelar el registro en el método onPause(). Por lo tanto : En el método onResume() generalmente se realiza el registro del receiver. En el método onPause() generamente se realiza el desregistro del receiver. Agrego un ejemplo: public class MyActivity extends Activity { private final BroadcastReceiver mybroadcast = new BroadcastReceiver (); //REGISTRA! public void onResume() { IntentFilter filter = new IntentFilter(); filter.addAction("android.provider.Telephony.SMS_RECEIVED"); registerReceiver(mybroadcast, filter); } //CANCELA! public void onPause() { unregisterReceiver(mybroadcast); } } A: Deberías de guardar tu BroadcastReceiver en una variable de tu MainActivity y en tu onStop() poner unregisterReceiver(myBroadcastReceiver); Debes de tener en cuenta que si pasases por el onStop()sin haber registrado el BroadcastReceiver previamente, te saltará una excepción. Un saludo
{ "pile_set_name": "StackExchange" }
Q: Add New Line and Save in VB.Net Following the example below, I want to add a new line accordingly, and what I write in the four Textbox boxes (for Answers). In the text file (Answer) the first word will always be empty space, and only after we start writing the words. Following the example below, I want to add a new line accordingly, and what I write in the four Textbox boxes (for Answers). Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.Text = System.IO.File.ReadAllText(My.Application.Info.DirectoryPath + ("\Data\Question.dat")) TextBox2.Text = System.IO.File.ReadAllText(My.Application.Info.DirectoryPath + ("\Data\Answer.dat")) End Sub End Class A: In that case, here are two different ways of doing it: Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Output As String = TextBox1.Text My.Computer.FileSystem.WriteAllText("c:/Junk/Textfile1.txt", vbCrLf & Output, False) End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim OutputFile2 As System.IO.StreamWriter OutputFile2 = My.Computer.FileSystem.OpenTextFileWriter("c:/Junk/Textfile2.txt", True) OutputFile2.WriteLine() OutputFile2.WriteLine(TextBox1.Text) OutputFile2.Close() End Sub Textbox1.text can replaced with a file location/name if you don't want to pull it into a textbox first. I just did it this way because that looks like what you are currently doing.
{ "pile_set_name": "StackExchange" }
Q: When is a module finitely generated over its endomorphism ring? If $R$ is a simple Artinian ring with simple module $M$ then $M$ is finitely generated as an $\mathrm{End}_R(M)$-module. This is usually proven in an indirect way: By Artin-Wedderburn-Theory we may assume that $R = \mathcal{M}_n(D)$ is a matrix ring over a division ring $D$, and $M = D^n$. Then it is obvious that $M$ is finite dimensional over $\mathrm{End}_R(M) \cong D^{op}$. Is there a more direct / more elegant way to show that $M$ is finitely generated over $\mathrm{End}_R(M)$ which avoids matrix rings? Are there more general conditions on $R$ and $M$ under which the conclusion remains true? A: There is the following theorem by Morita [Lang, Algebra - Theorem 7.1]: Let $R$ be a ring and $M$ an $R$-module. Then $M$ is a generator iff $M$ is balanced and finitely generated projective over $R' = \mathrm{End}_R(M)$. This generalizes the statement above, as if $R$ is simple Artinian and $M$ is simple, then $R \cong M^{(n)}$ for some $n$, so $M$ is in particular a generator. Here is an elementary proof of the implication “$M$ is a generator $\implies M$ is f.g. over $R'$”: Proof. Let $M$ be a right $R$-module, so it can be considered as a left $R'$-module. Being a generator means that $R$ is an epimorphic image of $M^{(n)}$ for some $n$, so there are elements $x_1, \dots, x_n \in M$ and homomorphisms $\varphi_1, \dots, \varphi_n \colon M \to R$ such that $\sum_i \varphi_i x_i = 1$. For any $x \in M$ let $\alpha_x$ be the unique homomorphism $R \to M$ with $\alpha_x(1) = x$. Then for all $x \in M$ we have $$ x = \alpha_x(1) = \alpha_x \left( \sum_i \varphi_i x_i \right) = \sum_i (\alpha_x \varphi_i) x_i. $$ Since $\alpha_x \varphi_i \in R'$ for all $i$, this means that $M$ is generated by $x_1, \dots, x_n$ as an $R'$-module. $\square$
{ "pile_set_name": "StackExchange" }
Q: Dealing with Quotes in Query Result PHP So I am trying to pull a series of strings from a mysql database to be used in a php page. I use this function: function getText(){ $mysqli = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME ); $texts = $mysqli->query('SELECT * FROM texts;'); return $texts; } I then do this: array = $tests->fetch_assoc() to get a row of the associative array. I then access the text with $array["text"] The problem I am having is that the text that I am retrieving needs to have " in them because of the use case but the $array["text"] only includes the text before the first ". What is the best way to remedy this? A: If sql returns something that is cut off then there are two (simple) answers This is what was in the database encoding problems. The 2nd is not an issue here. The 1st items could be a case. You have too short field for text. Your insert is erasing the data after 1st " because its not escaped If you may var_dump($texts); in your function you will see if data from database have errors already or its somewhere deeper in your code. If its deeper then i would suggest you to add addslashes or entity encode for the ,,corruept'' strings - that can prevent your code from messing with it later.
{ "pile_set_name": "StackExchange" }
Q: Express 2104 as the sum of four squares How to write 2104 as the sum of four squares. I know the general equation for factoring a number into the sum of four squares but I don't know how to go about this when some of the prime factors are large, for example, one of 2104's prime factors is 263 and I can't figure out how to write 263 as the sum of four squares. A: very easy by computer, and the way to go if you need all such representations. By hand, the first thing is that the $w^2 + x^2 + y^2 + z^2$ can be divisible by $4$ with all entries odd, as $1+1+1+1=4$ for example, but if divisible by $8$ all entries must be even. So, we are going to write $2104 / 4 = 526$ as the sum of four squares and double those entries. Next, $23^2 = 529$ is too big. $22^2 = 484$ is small enough, and $526-484 = 42$ is the sum of three squares $42 = 25 + 16 + 1.$ So, $$526 = 22^2 + 5^2 + 4^2 + 1^2, $$ $$2104 = 44^2 + 10^2 + 8^2 + 2^2. $$
{ "pile_set_name": "StackExchange" }
Q: Task causing lots of GC I have created a thread so that I can get the current position of my MediaPlayer without disturbing the UI but I seen to be getting a lot of garbage collection when the timer is running, is it normal? Also to avoid the risk of spamming, does anyone else know a better way to display the position of a MediaPlayer which is more efficient? private void processThread() { final MediaPlayer MP; MP = MediaPlayer.create(this, R.raw.sleepaway); MP.start(); new Thread(){ public void run(){ handler.post(new Runnable(){ @Override public void run() { myText.setText(getTimeString(MP.getCurrentPosition())); handler.postDelayed(this,10); } }); } }.start(); } The messages I receive about three times a second: 08-14 05:44:27.385: DEBUG/dalvikvm(32100): GC freed 10820 objects / 524656 bytes in 75ms A: The thread you are creating is completely useless, just do the post(Runnable). Also, you are creating an infinite "loop" with your postDelayed().
{ "pile_set_name": "StackExchange" }
Q: I’m facing a performance issue in SharePoint online app parts The custom app parts in SharePoint add-ins (SharePoint hosted) gives bad performance when adding them into a custom page in the hosted site. Is there a solution for this problem? A: The slow performance is most likely caused by the way the app parts are placed on the SharePoint page - each app part is contained within it's own iFrame which points to the app web. When the page loads, another full HTTP call has to be performed for the content from each app part placed on the page. Unfortunately - this behaviour is a part of the Add-in model and cannot be changed. Source: How to add SharePoint-hosted add-in as an app part It has it's positives, as it allows to display content from provider-hosted apps in a web-part like manner. The biggest downside is - it treats SharePoint-hosted apps the same way. To boost the performance I would suggest (if possible) switching to the SharePoint Framework, which is client-side only, doesn't use internal app webs and renders directly inside the page's DOM without being wrapped with any iFrames. Take a look here: Build your first SharePoint client-side web part
{ "pile_set_name": "StackExchange" }
Q: Do parenthesis in array declaration matter? Does (Excel) VBA distinguish between: Dim Ghadafi as Variant and Dim Ghadafi() as Variant ? A: First syntax is ONE variant variable, while second represent an array of variant. You can do Ghadafi = 5.25 You can do Redim Preserve Ghadafi(3) Ghadafi(1) 5.25 Ghadafi(2) = 6.10
{ "pile_set_name": "StackExchange" }
Q: Change password for iCloud keychain / prevent it from being unlocked with computer password I use iCloud Keychain across iOS devices and my MacBook Pro. I recently discovered that on my Mac I can access the passwords stored in the iCloud keychain simply with my (admin) login credentials. Is there a way to give the iCloud Keychain a specific password? I would like to prevent the iCloud Keychain from being unlockable with my computer login (password and Touch ID) and, ideally, on my iOS devices also with my online Apple ID. Alternatively, if the above is not possible, can I use a different Keychain for syncing? I know, on the Mac I can create personal Keychains that have their own unique passwords. Is there a way to sync these Keychains across devices? So far I was unable to get them to show up on my iPhone. Thank you very much! EDIT: Following suggestions from bmike's answer below who refers to this question, there are possibilities how to specifically change either the login password (using passwd) or the password of a specific keychain (using security ... – follow the link for further information). However, what I am trying to do is to change the iCloud keychain password. The iCloud keychain shows up as a separate keychain in the sidebar of Keychain Access, but it doesn't seem to be stored in any accessible place (i.e., in a .keychain-db file) the password of which could be changed via the methods suggested. If I get the info from any item in the iCloud keychain I can simply show the password by entering my login password. It asks me for the "Local Items" keychain, which seems to be the same like my login keychain (at least it obeys the login password). Even when I try to specify "Access Control" for an item, I'm not allowed. In regular items, I can click "Ask for Keychain password" under the "Access Control" tab. But in the items under iCloud Keychain it displays "Access for this item cannot be edited" there. Any further help is much appreciated! A: I’m afraid the cloud keychain is the only one you can not lock your account out of so you'll likely fail to do what you ask. All other keychains are trivial to choose an different password - even the log in keychain is easy since you can change your log in password with the passwd command line tool. Then, each time you log in to your Mac - the keychain password will be what it was before you changed the log in password and have to enter the second password. Most people hate that situation, but you could run that way intentionally if that suits you. The iCloud Keychain is tied to secure tokens so that you can have different passwords on different devices and I believe it uses your iCloud password to generate the unlock tokens. If so, you’ll have to disable iCloud Keychain syncing in all likelihood to lock / change it via passwords.
{ "pile_set_name": "StackExchange" }
Q: NameError: uninitialized constant Object::User I searched the other posts that had this issue and could not find one that fixed my particular issue. My irb is going crazy. I am trying to change user roles in my database but I can't even get to my users! irb(main):001:0> User.all NameError: uninitialized constant Object::User from (irb):1 from c:/Ruby192/bin/irb:12:in `<main>' It was working fine, stopped working, was fine, and now stopped again. I have a User model and users added. I cannot pinpoint the issue. Let me know what code you need to see. Thanks! A: You should run ruby script/console # Rails < 3 or rails c # Rails 3.x But not (I believe you've just run this) irb A: Make sure you're actually using the rails console command rather than just running irb in your project folder.
{ "pile_set_name": "StackExchange" }
Q: Weblogic 12.2 - CXF 3.1 - JAXB 2.2 - Deployment : Error javax.xml.ws.WebServiceException: java.lang.IllegalStateException: The prefix X is not bound Error occurs when starting weblogic server: Problem with the wsdl generated: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '': Invocation of init method failed; nested exception is javax.xml.ws.WebServiceException: java.lang.IllegalStateException: The prefix X is not bound. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) Caused by: javax.xml.ws.WebServiceException: java.lang.IllegalStateException: The prefix X is not bound. at org.apache.cxf.jaxws.EndpointImpl.doPublish(EndpointImpl.java:375) at org.apache.cxf.jaxws.EndpointImpl.publish(EndpointImpl.java:255) at org.apache.cxf.jaxws.EndpointImpl.publish(EndpointImpl.java:543) Caused by: java.lang.IllegalStateException: The prefix X is not bound. at org.apache.ws.commons.schema.SchemaBuilder.getRefQName(SchemaBuilder.java:823) at org.apache.ws.commons.schema.SchemaBuilder.getRefQName(SchemaBuilder.java:831) Namespace not found on the element root while it's defined in the @XmlRootElement Here the SchemaBuilder.getRefQName source code : https://github.com/wso2/wso2-xmlschema/blob/master/xmlschema/src/main/java/org/apache/ws/commons/schema/SchemaBuilder.java prefix = pName.substring(0, offset); uri = NodeNamespaceContext.getNamespaceURI(pNode, prefix); if (uri == null || Constants.NULL_NS_URI.equals(uri)) { if (schema.parent != null && schema.parent.getNamespaceContext() != null) { uri = schema.parent.getNamespaceContext().getNamespaceURI( prefix); } } if (uri == null || Constants.NULL_NS_URI.equals(uri)) { throw new IllegalStateException("The prefix " + prefix + " is not bound."); } Any idea please? A: Another solution which seems to be better to avoid version compatibility problems is to force your project to use weblogic libraries.
{ "pile_set_name": "StackExchange" }
Q: Micropython Xbee - How do I get the Xbee serial number and convert it to a string? I am using an Xbee3 pro with micropython. I'm trying to convert the device serial number to a string. Here is the code. import xbee from time import sleep serial = xbee.atcmd("SL") serial = serial.decode("utf-8") while True: print("Sending broadcast data >> %s" % serial) try: xbee.transmit(xbee.ADDR_BROADCAST, serial) print("Data sent successfully") except Exception as e: print("Transmit failure: %s" % str(e)) sleep(2) The data transmits successfully, but I only get three ugly characters that are unreadable. The result of: serial = xbee.atcmd("SL") print(serial) is 'A\x92\xa4\xbf' I really just need to convert 'A\x92\xa4\xbf' to 4192A4BF. A: I believe this should work: ''.join('{:02x}'.format(x).upper() for x in xbee.atcmd("SL")) You're taking each byte of the bytearray (for x in ...) and formatting it as two uppercase hexadecimal characters ('{:02x}'.format().upper()), then joining those together with nothing in between (''.join()).
{ "pile_set_name": "StackExchange" }
Q: Injecting a dependency into a base class I'm starting out with Dependency Injection and am having some trouble injecting a dependency into a base class. I have a BaseController controller which my other controllers inherit from. Inside of this base controller I do a number of checks such as determining if the user has the right privileges to view the current page, checking for the existence of some session variables etc. I have a dependency inside of this base controller that I'd like to inject using Ninject however when I set this up as I would for my other dependencies I'm told by the compiler that: Error 1 'MyProject.Controllers.BaseController' does not contain a constructor that takes 0 argument This makes sense but I'm just not sure how to inject this dependency. Should I be using this pattern of using a base controller at all or should I be doing this in a more efficient/correct way? A: your BaseController constructor should be like this BacseConctoller(Info info) { this.info = info } then for all inheritence class their constructor ChildController(Info info):base(info) { } in this case you can inject Info object to the base controller class
{ "pile_set_name": "StackExchange" }
Q: Help needed to write a comparator for my job interview code sample I need help to write a comparator :- I want this output :- Martin Joseph Male 4/2/1979 Green Ramya Patil Female 5/4/2009 Red Don kelly Male 5/6/1986 Yellow Van Shinde female 3/4/1984 Green But i am getting the following output :- Output 1: Van Shinde female 3/4/1984 Green Don kelly Male 5/6/1986 Yellow Ramya Patil Female 5/4/2009 Red Martin Joseph Male 4/2/1979 Green how do i sort on last name keeping the order of the list intact .. i mean i want to output female first sorting on last name and then male sorted on last name ... please help me guys .. this is the comparator i am using after i use the gender comparator :- public class LastNameComparator implements Comparator<Person> { public int compare(Person name_one, Person name_two) { // TODO Auto-generated method stub if(name_one.getGender().equals(name_two.getGender())){ return name_one.getLast_name().compareTo(name_two.getLast_name()); }else{ return name_one.getLast_name().compareTo(name_two.getLast_name()); } } } A: public int compare(Person a, Person b) { int ret = a.getGender().compareTo(b.getGender()); if (ret == 0) { ret = a.getLastName().compareTo(b.getLastName()); } return ret; }
{ "pile_set_name": "StackExchange" }
Q: MS Word OLE - replacing text with an image. First block of code works, second does not I am editing some code in lotusscript to create a word document off a template using OLE, and am doing a find and replace to add an image. This works for the first image, however not the second one. objWord.Selection.Find.Execute "{{image1}}",False, True,,,,, 1,,,,,,, objWord.Selection.Extend If (objWord.Selection.Characters.Count > 1) Then If (signaturefilename = "") Then objWord.Selection.Find.Execute "{{image1}}", False, True,,,,, 1,, " ", 2,,,, Else Call objWord.Selection.InlineShapes.AddPicture(tempdir + "\" + imagefilename, False, True,) End If End If objWord.Selection.Find.Execute "{{image2}}",False, True,,,,, 1,,,,,,, objWord.Selection.Extend If (objWord.Selection.Characters.Count > 1) Then If (signaturefilename = "") Then objWord.Selection.Find.Execute "{{image2}}", False, True,,,,, 1,, " ", 2,,,, Else Call objWord.Selection.InlineShapes.AddPicture(tempdir + "\" + imagefilename, False, True,) End If End If The first section of code works perfectly, however the second one does not replace the second piece of text with the image, as I had expected. I had expected the second Find.Execute to find the second block of text, however it ends up replacing all the text in the document. Is there something obvious I have overlooked? Thanks, A A: Okay - worked it out. It was the: objWord.Selection.Extend that needed to be removed. Although it was not selecting the whole document on the first instance, on the second it was. This is now working perfectly. Thanks Richard for the pointer. In addition, I used the: objWord.Visible = True to assist with debugging.
{ "pile_set_name": "StackExchange" }
Q: AngularJS Best Practice - Factory with multiple methods I have a factory that serves up three different $http.get methods. angular.module('myApp') .factory('getFactory', function ($http, $q) { return { methodOne: function () { var deferred = $q.defer(); $http.get('path/to/data') .then(function successCallback (data) { deferred.resolve(data); },function errorCallback (response) { console.log(response); }); return deferred.promise; }, methodTwo: function (arg1, arg2) { var deferred = $q.defer(); $http.get('path/to/' + arg1 + '/some/' + arg2 + 'more/data') .then(function successCallback (data) { deferred.resolve(data); },function errorCallback (response) { console.log(response); }); return deferred.promise; }, methodThree: function (arg1, arg2, arg3) { var deferred = $q.defer(); $http.get('path/to/' + arg1 + '/some/' + arg2 + '/more/' + arg3 + '/data') .then(function successCallback (data) { deferred.resolve(data); },function errorCallback (response) { console.log(response); }); return deferred.promise; }, }; }); Basically, these methods only differ in the path it gets the data from. The data these methods get are handled in the controller. I have been reading a lot of Angular best practices on the side and have been seeing DRY (Don't Repeat Yourself) tips. I feel the code I have above is too repetitive. Is there a better way of coding this the Angular way? **Note: I used the yeoman generator to scaffold the directories of my project. A: angular.module('myApp') .factory('getFactory', function ($http, $q) { //Using revealing Module pattern var exposedAPI = { methodOne: methodOne, methodTwo: methodTwo, methodThree: methodThree }; return exposedAPI; //Private function, not required to be exposed function get(url){ //$http itself returns a promise, so no need to explicitly create another deferred object return $http.get(url) .then(function (data) { //Create deferred object only if you want to manipulate returned data }, function (msg, code) { console.log(msg, code); }); } function methodOne() { //DRY return get('path/to/data'); } function methodTwo(arg1, arg2) { return get('path/to/' + arg1 + '/some/' + arg2 + 'more/data'); } function methodThree(arg1, arg2, arg3) { return get('path/to/' + arg1 + '/some/' + arg2 + '/more/' + arg3 + '/data'); } });
{ "pile_set_name": "StackExchange" }
Q: Flash/ActionScript3 crashes on getPixel/32 Question: The below code crashes flash... Why? The crash causing lines seem to be //var uiColor:uint = bmpd.getPixel(i,j); var uiColor:uint = bmpd.getPixel32(i,j); trace("Color: "+ uiColor); I am trying to take a snapshot of a movieclip and iterate through all pixels in the image and get the pixel's color. import flash.display.BitmapData; import flash.geom.*; function takeSnapshot(mc:MovieClip):BitmapData { var sp:BitmapData = new BitmapData(mc.width, mc.height, true, 0x000000); sp.draw(mc, new Matrix(), new ColorTransform(), "normal"); return sp; } var mcMyClip:MovieClip=new MovieClip() var xxx:cMovieClipLoader=new cMovieClipLoader(); xxx.LoadImageAbsSize(mcMyClip,"http://localhost/flash/images/picture.gif", 500,500) //this.addChild(mcMyClip); function WhenImageIsLoaded() { var bmpd:BitmapData=takeSnapshot(mcMyClip); var i,j:uint; for(i=0; i < bmpd.width;++i) { for(j=0; j < bmpd.height;++j) { //var uiColor:uint = bmpd.getPixel(i,j); var uiColor:uint = bmpd.getPixel32(i,j); trace("Color: "+ uiColor); } } var myBitmap:Bitmap = new Bitmap(bmpd); this.addChild(myBitmap); } setTimeout(WhenImageIsLoaded,1000); A: Solved. There were 3 problems at once: 1. It has transparency, so only GetPixel32 works 2. mcMyClip.width & height returns a wrong value mcMyClip.getBounds(mcMyClip).width & height returns the correct value (because the original movieclip is a resized one) 3. 800x600 picture = 480'000 points * 1 trace messages in the blink of a second, which is the cause for the crash (might actually be a Vista problem...)
{ "pile_set_name": "StackExchange" }
Q: Blocking specific urn on tomcat webapp Have a specific need where we need to block a specific urn under a web app Eg we have a web app /siebel , under it /siebel/app/ this should work , but the /siebel/smc should not Tried giving the context path as under the /META-INF folder context.xml <Context path="/siebel/smc" debug="0" privileged="true"> <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127.0.0.1"/> </Context> also tried <Context antiJARLocking="true" path="/siebel/smc"> <Valve className="org.apache.catalina.valves.RemoteIpValve" /> <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127.0.0.1" /> </Context> This ends up in blocking both urls /siebel/smc and /siebel/app Tried adding the context path in server.xml as well , same result. Played with deny option with deny="*" , but still same. Is there any way to handle this ? Thanks A: OK then. You have the right idea but are applying it in the wrong location. META-INF/context.xml applies only to the web application it is placed in and the path attribute is ignored (the path will be derived from the WAR/dir name). I am assuming you have a web application deployed at webapps/siebel.war or webapps/siebel and that the context path for that web application is '/siebel`. We are going to take advantage of a requirement of the Servlet specification which is, when matching URIs to web applications, filters and servlets, the first step is to select the web application by finding the longest matching context path. Therefore if we deploy a new web application to /siebel/smc and block all access this should have the effect you want. Assuming a default Tomcat installation (with unchanged engine and host names) place the following content at $CATALINA_BASE/conf/Catalina/localhost/siebel#smc.xml <Context> <Valve className="org.apache.catalina.valves.RemoteAddrValve" deny=".*"/> </Context> You will also need to create the empty directory $CATALINA_BASE/webapps/siebel#smc
{ "pile_set_name": "StackExchange" }
Q: Angular 5 HttpClient Interceptor JWT refresh token unable to Catch 401 and Retry my request I am trying to implement a catch for 401 responses and tried obtaining a refresh token based on Angular 4 Interceptor retry requests after token refresh. I was trying to implement the same thing, but I never was able to Retry that request, and I am really not sure if that is the best approach to apply the refresh token strategy. Here is my code: @Injectable() export class AuthInterceptorService implements HttpInterceptor { public authService; refreshTokenInProgress = false; tokenRefreshedSource = new Subject(); tokenRefreshed$ = this.tokenRefreshedSource.asObservable(); constructor(private router: Router, private injector: Injector) { } authenticateRequest(req: HttpRequest<any>) { const token = this.authService.getToken(); if (token != null) { return req.clone({ headers: req.headers.set('Authorization', `Bearer ${token.access_token}`) }); } else { return null; } } refreshToken() { if (this.refreshTokenInProgress) { return new Observable(observer => { this.tokenRefreshed$.subscribe(() => { observer.next(); observer.complete(); }); }); } else { this.refreshTokenInProgress = true; return this.authService.refreshToken() .do(() => { this.refreshTokenInProgress = false; this.tokenRefreshedSource.next(); }).catch( (error) => { console.log(error); } ); } } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { this.authService = this.injector.get(AuthenticationService); request = this.authenticateRequest(request); return next.handle(request).do((event: HttpEvent<any>) => { if (event instanceof HttpResponse) { // do stuff with response if you want } }, (err: any) => { if (err instanceof HttpErrorResponse) { if (err.status === 401) { return this.refreshToken() .switchMap(() => { request = this.authenticateRequest(request); console.log('*Repeating httpRequest*', request); return next.handle(request); }) .catch(() => { return Observable.empty(); }); } } }); } } The issue is that SwitchMap is never reached in... if (err.status === 401) { return this.refreshToken() .switchMap(() => { and the do operator as well... return this.authService.refreshToken() .do(() => { so that took me to my authService refreshToken method... refreshToken() { let refreshToken = this.getToken(); refreshToken.grant_type = 'refresh_token'; refreshToken.clientId = environment.appSettings.clientId; return this.apiHelper.httpPost(url, refreshToken, null) .map ( response => { this.setToken(response.data, refreshToken.email); return this.getToken(); } ).catch(error => { return Observable.throw('Please insert credentials'); }); } } It returns a mapped observable, and I know it needs a subscription if I replaced the do in... return this.authService.refreshToken() .do(() => { With subscribe I'll break the observable chain I guess. I am lost and I've playing with this for a long time without a solution. :D A: I'm glad that you like my solution. I'm going to put just the final solution here but if anybody wants to know the process that I fallowed go here: Refresh Token OAuth Authentication Angular 4+ Ok, First I created a Service to save the state of the refresh token request and Observable to know when the request is done. This is my Service: @Injectable() export class RefreshTokenService { public processing: boolean = false; public storage: Subject<any> = new Subject<any>(); public publish(value: any) { this.storage.next(value); } } I noticed that It was better if I have two Interceptors one to refresh the token and handle that and one to put the Authorization Header if exist. This the Interceptor for Refresh the Token: @Injectable() export class RefreshTokenInterceptor implements HttpInterceptor { constructor(private injector: Injector, private tokenService: RefreshTokenService) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const auth = this.injector.get(OAuthService); if (!auth.hasAuthorization() && auth.hasAuthorizationRefresh() && !this.tokenService.processing && request.url !== AUTHORIZE_URL) { this.tokenService.processing = true; return auth.refreshToken().flatMap( (res: any) => { auth.saveTokens(res); this.tokenService.publish(res); this.tokenService.processing = false; return next.handle(request); } ).catch(() => { this.tokenService.publish({}); this.tokenService.processing = false; return next.handle(request); }); } else if (request.url === AUTHORIZE_URL) { return next.handle(request); } if (this.tokenService.processing) { return this.tokenService.storage.flatMap( () => { return next.handle(request); } ); } else { return next.handle(request); } } } So here I'm waiting to the refresh token to be available or fails and then I release the request that needs the Authorization Header. This is the Interceptor to put the Authorization Header: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(private injector: Injector) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const auth = this.injector.get(OAuthService); let req = request; if (auth.hasAuthorization()) { req = request.clone({ headers: request.headers.set('Authorization', auth.getHeaderAuthorization()) }); } return next.handle(req).do( () => {}, (error: any) => { if (error instanceof HttpErrorResponse) { if (error.status === 401) { auth.logOut(); } } }); } } And my main module is something like this: @NgModule({ imports: [ ..., HttpClientModule ], declarations: [ ... ], providers: [ ... OAuthService, AuthService, RefreshTokenService, { provide: HTTP_INTERCEPTORS, useClass: RefreshTokenInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { } Please any feedback will be welcome and if I'm doning something wrong tell me. I'm testing with Angular 4.4.6 but I don't know if it work on angular 5, I think should work.
{ "pile_set_name": "StackExchange" }
Q: Audio Player with Play All Capability I've been hunting around for a jQuery plugin that plays audio in the browser, and can automatically play the next audio file once the previous one is finished. Also, the ability to play only one audio file at a time; so if the user is playing one audio file, and clicks play on another, the first audio file should stop playing. In essence, I'm looking for something similar to how sounds are played on a page on SoundCloud. I've been looking at packages like SoundManager2 and jPlayer, but it doesn't look like they can do this. So in bullet points: once one audio file is done, auto-start the next one only one audio file plays at a time; so, if an audio file is playing and the user clicks play on another, the first one should stop playing. Any suggestions would be awesome, even if it's just pointing me in a general direction. A: SoundManager2 can do everything you're asking for, see here.
{ "pile_set_name": "StackExchange" }
Q: Jackson Data Binding: Reading into existing object Is there a way I can do something like the following using Jackson Data Binding? Obviously this won't compile but for example (psuedoCode): MyObject myObject = new MyObject(); String json = "{ name: "hello" }"; ObjectMapper.readValue(json, myObject); myObject.getName() -> returns "hello"; Basically what I want to do is write a string data into an existing object and not pass Jackson data binding a class like objectMapper.readValue(json, MyObject.class); A: Jackson provides ObjectMapper#readerForUpdating(Object) which gives you an ObjectReader you can use to fill in the blanks.
{ "pile_set_name": "StackExchange" }
Q: How do I get into this kind of faucet to fix a drip? How can I get this thing apart? Using this question I was able to take out a bolt of some sort inside the top from behind the blue/red thing, but the top still doesn't come off. It's dripping, and I wanted to fix whatever is wrong on the inside. Here's a short video showing what I tried: https://www.youtube.com/watch?v=n_XXLcKhsdE A: Note the manufacturer and google this repair giving the model and manufacturer; you should find information on this repair. Go to the home store and look for a repair kit for this manufacturer. Note that you must turn off the hot and cold supply to this faucet before you release the ring which holds the inner parts in place. For example I Googled: youtube repair of single handle kitchen faucet and got this video https://www.youtube.com/watch?v=huxSQljCrIc
{ "pile_set_name": "StackExchange" }
Q: Prism - can deactivating a view affect on other module parts? I have an idea for an application which I'm not sure if possible, I'd appreciate your insights: I'd like to have a ToolBar in my Shell, where every module that is loaded can add its buttons. The Shell will also have content regions that show the modules' relevant views. Some modules share the same regions though, is there a mechanism in Prism that can help with removing buttons that are currently irrelevant? For example, if ModuleA adds "Get Help" button and ModuleB adds "Send Message" button and they share the same region (only one of them is visible at a given time), when ModuleA is visible, I'd like the "Send Message" button temporarily removed - or at least deactivated - from the ToolBar (but back in the same position when ModuleB's view is activated). Does this approach fit when using MVVM? Thanks. A: It is possible with MVVM and prism. I am doing something similar where I have a switchboard of buttons and it will be populated from a list. Each button represents a form and clicking the button obviously opens that form. I created and ISwitchboard interface that each form implements that desires to be part of the Switchboard. Therefore, each ISwitchboard Interface Item implements ShowDialogForm, and a WPF command etc. It would be too cumbersome for this post to explain all details that you need to do. However, these are the basic principals by which my code works: In my bootstrapper I override the GetModuleCatelog() method to add any modules I wish. Each module represents an application (form) that will be opened from the switchboard and must inherit from an interface I created so the view model knows how to open it or whether to show it when it needs it. You may not need to use the modules for what you want but that's your design choosing. That said, if your buttons will open applications, you will need modules. My view model then exposes a list of available modules that use my custom interface that have been added using prism. I am able to get the list of modules through the IModuleCatalog interface which I pass into the VM's constructor. The list is an observable collection. If I want to implement user rights, then I can restrict the list in that way if I wish. My view then has an itemscontrol which binds to the switchboard list. I can present them how I wish from there. I created an item template to be displayed for each item in the list and it is bound to the Command exposed by the SwitchboardItem interface.
{ "pile_set_name": "StackExchange" }
Q: How to reference an external jar in an Android Library project in Eclipse Oh Android. How I love your verbiage. I have a workspace with a few projects in it. App1 and App2 are Android applications. Common is an Android library project. App1 and App2 depend upon Common (linked via the Android tab). Common has some external dependencies, namely httpmime & apache-mime4j, which exist as jar files. For some reason, it appears that I need to add my mime jars to the build path of App1 and App2 for compilation to succeed. This seems really dumb. In normal Java, I would add Common to the build path of App1 and App2 and things would work. Is this expected that I have to add my jars to every Android application? -Andy Note: If I don't configure the build path as described above, I get "The type org.apache.james.mime4j.message.SingleBody cannot be resolved. It is indirectly referenced from required .class files | DataCallUtil.java | /App1/Common/util | line 364" A: I think omermuhammed and Amit didn't get the fact that Visser is talking about a Android Library Project. For those project, I don't think it is possible to create a jar. ( jar has nothing to do with all the Android resources thing ). From my experience with Android Library Project, this kind of project are just, basically, the sources and the ressources packaged, and ready to be included in another project. But the settings are not part of the package, so you have to include the libs for each application. In my experience, this setting is not something that changes often, so it is not so bad. Android Library Project are still way from being perfect, but still a huge improvement from what was there before ( ie nothing ).
{ "pile_set_name": "StackExchange" }
Q: Book Lenders Puzzle (Answer with the least amount of steps in 5 days wins!) You are a Book lender who strangely lends books of equal length and difficulty ever time. You have people who you lend your books to, but you want to find out who is the fastest reader of the group and who is the slowest reader of the group. This is the situation. There are ten people who all read books at different speeds and they will always read the books you give them in the same amount of time that they read all the other books. - When you lend a book because of the way your book lending system is set up, the book is shared between three people. Meaning when the first person receives the book they will read it in the time it takes them, then give it to the next person to read, then they will give the third and last person the book to read and they will return it to you. - You as the book keeper get to choose which three people get the book at anytime. The only information you are given is the amount of time it took all three of your selected people too read the book(the sum of all three of their reading times) - All of the people are perfect actors so they will never change the amount of time that it takes them to read a book and there will be no transition time between giving the book to each other. - You have an infinite amount of books to lend so you can take as many steps as you would like in which you select three of ten each time and see the sum of those three's reading time. Remember you are trying to find the fastest and the slowest reader by lending these books. So how would you do it? A: Okay, I'll start with a correct but not great answer: The problem is, we have ten positive numbers A,B,C,D,E,F,G,H,I,J and we are allowed to ask for the sums of any groups of three of them. * With 4 steps: A+B+C, A+B+D, A+C+D, B+C+D * Then we know A,B,C,D: because ((A+B+C)+(A+B+D)+(A+C+D)-2(B+C+D))/3 = A, and so on. * With 6 more steps: A+B+E, A+B+F, A+B+G, A+B+H, A+B+I, A+B+J. * Then (A+B+E)-(A+B+D) = E-D, and we know D, so we know E, and the rest. * So, in 10 steps, we can tell how long each person in the group takes to read a book. * Conversely, to find out how long each person in the group takes to read a book, it looks like we would need at least 10 steps, since there are 10 numbers to find out. So this is correct, and "optimal" in its own way, but not the way we want because we don't actually need to know how long each person in the group takes to read a book, we just need to know who is fastest and who is slowest in the group. But I have a funny feeling that, you might need ten steps anyway, so I will "win" ;-) but I don't know. (EDIT TO ADD:) Here's an example to substantiate that feeling: Let's say our 9 steps are A+B+C, B+C+D, C+D+E, D+E+F, E+F+G, F+G+H, G+H+I, H+I+J, and I+J+A. Now suppose A=B=D=E=G=H=J=-1 and C=F=I=2. Then all 9 sums will come out zero. (-1 -1 2 -1 -1 2 -1 -1 2 -1) is an "eigenvector with eigenvalue zero". What I mean by that is, even though it has negative numbers, we can add it to a sufficient large set of ten numbers to get a second set of ten numbers which is 'indistinguishable' from the first, as far as those 9 steps are concerned. Like so: ( 2 3 4 5 6 7 8 9 10 11) (-1 -1 +2 -1 -1 +2 -1 -1 +2 -1) ----------------------------- ( 1 2 6 4 5 9 7 8 12 10) And indeed, for (2 3 4 5 6 7 8 9 10 11) and (1 2 6 4 5 9 7 8 12 10), the nine sums are the same in both cases: (9 12 15 18 21 24 27 30 23). But in one case the largest is J=11, and in the other, I=12. So this can't work. Now here's some voodoo: Imagine we make a 10x10 matrix of ones and zeros. The first 9 rows each have 3 ones and 7 zeros. The last row has 10 zeros. This represents taking 9 (or fewer) steps. But this matrix has determinant zero. No matter what, it must have a zero eigenvector. Like above, we can use that eigenvector to construct a pair of examples which are indistinguishable to those 9 steps, but where the largest and/or smallest number is in a different place. So it looks like nine steps or fewer doesn't work, I "win"! ;-) A: Proof that ten steps are the minimum necessary: Ten steps are the minimum required. Credit:@deep thought. Let us assume there is a method with 9 steps, that solves this puzzle. Then the 9 equations can be represented as a 10x9 matrix, where each row has 3 ones and 7 zeroes. When it is converted to reduced row echelon form, there will be only nine pivot variables. This means that only nine of their values can be nailed down, whereas the tenth value will not be found. This can lead to interesting contradictions, including identical totals when adding a zero eigenvector to the numbers. This leads to a contradiction, completing our proof. Old answer: Edit: never mind, I’m wrong. Ten steps is the minimum. I think the answer is 9. Though we need 10 to establish absolute reading speeds, we need only 9 to establish the ratio between them. Method: We start off by passing a ‘window’ over the reading speeds, but we take a in each group. So let us list our groups: a, b, c. a, c, d. a, d, e. a, e, f. a, f, g. a, g, h. a, h, i. a, i, j. a, j, b. Next, we see that a is common in all, so if their values were t1 through t9, we can change them into b + c = t1 + a, and so on. Now, we add them all up, but we take the first positive, second negative, and so on, stopping at a,i,j. We find that we get an absolute value for b-j. Adding this to the a-dependent value of b+j, we find a value for b dependent on a, and can derive one for j as well. In similar fashion, we find the values for b through j relative to a. What about a? Well, since we found b and c relative to a, we can substitute into a+b+c to get a value for a. Since we only need to find who is fastest and slowest, not individual speeds, this hound be sufficient.
{ "pile_set_name": "StackExchange" }
Q: Update mysql big table hang too time Performance problem on update MySql MyISAM big table making column ascending order based on an index on same table My problem is that the server have only 4 GB memory. I have to do an update query like this: previous asked question Mine is this: set @orderid = 0; update images im set im.orderid = (select @orderid := @orderid + 1) ORDER BY im.hotel_id, im.idImageType; On im.hotel_id, im.idImageType I have an ascending index. On im.orderid I have an ascending index too. The table have 21 millions records and is an MyIsam table. The table is this: CREATE TABLE `images` ( `photo_id` int(11) NOT NULL, `idImageType` int(11) NOT NULL, `hotel_id` int(11) NOT NULL, `room_id` int(11) DEFAULT NULL, `url_original` varchar(150) COLLATE utf8_unicode_ci NOT NULL, `url_max300` varchar(150) COLLATE utf8_unicode_ci NOT NULL, `url_square60` varchar(150) COLLATE utf8_unicode_ci NOT NULL, `archive` int(11) NOT NULL DEFAULT '0', `orderid` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`photo_id`), KEY `idImageType` (`idImageType`), KEY `hotel_id` (`hotel_id`), KEY `hotel_id_idImageType` (`hotel_id`,`idImageType`), KEY `archive` (`archive`), KEY `room_id` (`room_id`), KEY `orderid` (`orderid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; The problem is the performance: hang for several minutes! Server disk go busy too. My question is: there is a better manner to achieve the same result? Have I to partition the table or something else to increase the performance? I cannot modify server hardware but can tuning MySql application db server settings. best regards A: Tanks to every body. Yours answers help me much. I think that now I have found a better solution. This problem involve in two critical issue: efficient paginate on large table update large table. To go on efficient paginate on large table I have found a solution by make a previous update on the table but doing so I fall in issues on the 51 minute time needed to the updates and consequent my java infrastructure time out (spring-batch step). Now by yours help, I found two solution to paginate on large table, and one solution to update large table. To reach this performance the server need memory. I try this solution on develop server using 32 GB memory. common solution step To paginate follow a fields tupla like I needed I have make one index: KEY `hotel_id_idImageType` (`hotel_id`,`idImageType`) to achieve the new solution we have to change this index by add the primary key part to the index tail KEY hotel_id_idImageType (hotel_id,idImageType, primary key fields): drop index hotel_id_idImageType on images; create index hotelTypePhoto on images (hotel_id, idImageType, photo_id); This is needed to avoid touch table and use only the index file ... Suppose we want the 10 records after the 19000000 record. The decimal point is this , in this answers solution 1 This solution is very practice and not needed the extra field orderid and you have not to do any update before the pagination: select * from images im inner join (select photo_id from images order by hotel_id, idImageType, photo_id limit 19000000,10) k on im.photo_id = k.photo_id; To make the table k on my 21 million table records need only 1,5 sec because it use only the three field in index hotelTypePhoto so haven't to access to the table file and work only on index file. The order was like the original required (hotel_id, idImageType) because is included in (hotel_id, idImageType, photo_id): same subset... The join take no time so every first time the paginate is executed on the same page need only 1,5 sec and this is a good time if you have to execute it in a batch one on 3 months. On production server using 4 GB memory the same query take 3,5 sec. Partitioning the table do not help to improve performance. If the server take it in cache the time go down or if you do a jdbc params statment the time go down too (I suppose). If you have to use it often, it have the advantage that it do not care if the data change. solution 2 This solution need the extra field orderid and need to do the orderid update one time by batch import and the data have not to change until the next batch import. Then you can paginate on the table in 0,000 sec. set @orderid = 0; update images im inner join ( select photo_id, (@orderid := @orderid + 1) as newOrder from images order by hotel_id, idImageType, photo_id ) k on im.photo_id = k.photo_id set im.orderid = k.newOrder; The table k is fast almost like in the first solution. This all update take only 150,551 sec much better than 51 minute!!! (150s vs 3060s) After this update in the batch you can do the paginate by: select * from images im where orderid between 19000000 and 19000010; or better select * from images im where orderid >= 19000000 and orderid< 19000010; this take 0,000sec to execute first time and all other time. Edit after Rick comment Solution 3 This solution is to avoid extra fields and offset use. But need too take memory of the last page read like in this solution This is a fast solution and can work on online server production using only 4GB memory Suppose you need to read last ten records after 20000000. There is two scenario to take care: You can start read it from the first to the 20000000 if you need all of it like me and update some variable to take memory of last page read. you have to read only the last 10 after 20000000. In this second scenario you have to do a pre query to find the start page: select hotel_id, idImageType, photo_id from images im order by hotel_id, idImageType, photo_id limit 20000000,1 It give to me: +----------+-------------+----------+ | hotel_id | idImageType | photo_id | +----------+-------------+----------+ | 1309878 | 4 | 43259857 | +----------+-------------+----------+ This take 6,73 sec. So you can store this values in variable to next use. Suppose we named @hot=1309878, @type=4, @photo=43259857 Then you can use it in a second query like this: select * from images im where hotel_id>@hot OR ( hotel_id=@hot and idImageType>@type OR ( idImageType=@type and photo_id>@photo ) ) order by hotel_id, idImageType, photo_id limit 10; The first clause hotel_id>@hot take all records after the actual first field on scrolling index but lost some record. To take it we have to do the OR clause that take on the first index field all remained unread records. This take only 0,10 sec now. But this query can be optimized (bool distributive): select * from images im where hotel_id>@hot OR ( hotel_id=@hot and (idImageType>@type or idImageType=@type) and (idImageType>@type or photo_id>@photo ) ) order by hotel_id, idImageType, photo_id limit 10; that become: select * from images im where hotel_id>@hot OR ( hotel_id=@hot and idImageType>=@type and (idImageType>@type or photo_id>@photo ) ) order by hotel_id, idImageType, photo_id limit 10; that become: select * from images im where (hotel_id>@hot OR hotel_id=@hot) and (hotel_id>@hot OR (idImageType>=@type and (idImageType>@type or photo_id>@photo)) ) order by hotel_id, idImageType, photo_id limit 10; that become: select * from images im where hotel_id>=@hot and (hotel_id>@hot OR (idImageType>=@type and (idImageType>@type or photo_id>@photo)) ) order by hotel_id, idImageType, photo_id limit 10; Are they the same data we can get by the limit? To quick not exhaustive test do: select im.* from images im inner join ( select photo_id from images order by hotel_id, idImageType, photo_id limit 20000000,10 ) k on im.photo_id=k.photo_id order by im.hotel_id, im.idImageType, im.photo_id; This take 6,56 sec and the data is the same that the query above. So the test is positive. In this solution you have to spend 6,73 sec only the first time you need to seek on first page to read (but if you need all you haven't). To real all other page you need only 0,10 sec a very good result. Thanks to rick to his hint on a solution based on store the last page read. Conclusion On solution 1 you haven't any extra field and take 3,5 sec on every page On solution 2 you have extra field and need a big memory server (32 GB tested) in 150 sec. but then you read the page in 0,000 sec. On solution 3 you haven't any extra field but have to store last page read pointer and if you do not start reading by the first page you have to spend 6,73 sec for first page. Then you spend only 0,10 sec on all the other pages. Best regards Edit 3 solution 3 is exactly that suggested by Rick. Im sorry, in my previous solution 3 I have do a mistake and when I coded the right solution then I have applied some boolean rule like distributive property and so on, and after all I get the same Rich solution! regards
{ "pile_set_name": "StackExchange" }
Q: reduce whitespace between header and content in scrlttr2 I am using scrlttr2 and want to reduce the amount of whitespace between the header and the content of the letter (see picture) Here is the corresponding code: \documentclass[fontsize=12pt, paper=a4, enlargefirstpage=on, pagenumber=headright, headsepline=off, parskip=half, fromphone=on, fromrule=off, fromfax=off, fromemail=on, fromurl=off, fromlogo=off, addrfield=on, backaddress=off, subject=beforeopening, locfield=narrow, foldmarks=off, numericaldate=off, refline=narrow]{scrlttr2} %--------------------------------------------------------------------------- \usepackage[T1]{fontenc} \usepackage[latin1]{inputenc} \usepackage[utf8]{inputenc} %--------------------------------------------------------------------------- \usepackage{lmodern} \usepackage{color} \usepackage{marvosym} \usepackage{ifthen} \definecolor{firstnamecolor}{rgb}{0.65,0.65,0.65} \definecolor{familynamecolor}{rgb}{0.45,0.45,0.45} \definecolor{footersymbolcolor}{rgb}{0.20,0.40,0.65} \definecolor{addresscolor}{rgb}{0.35,0.35,0.35} %grau \newcommand*{\addressfont}{\small\sffamily\mdseries\slshape} \newcommand{\footersymbol}{~~\color{footersymbolcolor}\normalfont\textbullet\color{addresscolor}\addressfont~~~} %--------------------------------------------------------------------------- \setkomafont{fromname}{\sffamily \LARGE} \setkomafont{fromaddress}{\sffamily}%% Instead of \small \setkomafont{pagenumber}{\sffamily} \setkomafont{subject}{\mdseries} \setkomafont{backaddress}{\mdseries} \usepackage{mathptmx} %--------------------------------------------------------------------------- \begin{document} %--------------------------------------------------------------------------- \LoadLetterOption{KOMAold} \makeatletter \@setplength{sigbeforevskip}{50pt} \@setplength{firstfootvpos}{300mm} page \@setplength{firstheadvpos}{10mm} \@setplength{firstheadwidth}{\paperwidth} \ifdim \useplength{toaddrhpos}>\z@ \@addtoplength[-2]{firstheadwidth}{\useplength{toaddrhpos}} \else \@addtoplength[2]{firstheadwidth}{\useplength{toaddrhpos}} \fi \@setplength{foldmarkhpos}{6.5mm} %\@setplength{refvpos}{\useplength{toaddrvpos}} \makeatother %--------------------------------------------------------------------------- % Sender information \newcommand{\myFirstname}{John} \newcommand{\myFamilyname}{Odd} \newcommand{\myStreet}{Street} \newcommand{\myTown}{NY} \newcommand{\myZipcode}{11233} \newcommand{\myPhone}{+123 456 4879} \newcommand{\myMail}{[email protected]} \setkomavar{signature}{\myFirstname\ \myFamilyname} %--------------------------------------------------------------------------- \firsthead{ \begin{flushright} \renewcommand{\baselinestretch}{0.8} \sffamily\mdseries\Large\color{firstnamecolor}\myFirstname\ \color{familynamecolor}\myFamilyname\\ \parbox{\textwidth}{\color{footersymbolcolor}\rule{\textwidth}{2pt}} \normalfont\small\color{black} \myStreet \\ \myZipcode, \myTown \\ \myMail \\\myPhone \end{flushright} } %--------------------------------------------------------------------------- \setkomavar{place}{\myTown} \setkomavar{date}{\today} %--------------------------------------------------------------------------- \setkomavar{enclseparator}{: } %--------------------------------------------------------------------------- \pagestyle{myheadings}%% No header \begin{letter}{International Company Coorporation\\ Mrs. Jane Doe\\ Some street 11 \\ SF, 54321} %--------------------------------------------------------------------------- % Further options \KOMAoptions{} %--------------------------------------------------------------------------- \setkomavar{subject}{subject} %--------------------------------------------------------------------------- \opening{Dear,} text \closing{KR} \encl{enclosed} \end{letter} \end{document} I am thankful for any hints. A: If you want to change the vertical position of the address field change the pseudolength toaddrvpos using either \@setplength or \@addtoplength. Additionally you may want to change the pseudolength refvpos to move the refline and the contents of the letter up. Maybe you want to use the values from DINmtext.lco: \@setplength{toaddrvpos}{27mm} \@setplength{refvpos}{80.5mm} Note that you will then get a warning because of your head is too high for the settings. Additional remarks: Do not load a package twice with different options. In the example I will use \usepackage[utf8]{inputenc} and remove the other line. I will remove the word "page" after \@setplength{firstfootvpos}{300mm}. Replace the deprecated command \firsthead{...} by \setkomavar{firsthead}{...}. \documentclass[fontsize=12pt, paper=a4, enlargefirstpage=on, pagenumber=headright, headsepline=off, parskip=half, fromphone=on, fromrule=off, fromfax=off, fromemail=on, fromurl=off, fromlogo=off, addrfield=on, backaddress=off, subject=beforeopening, locfield=narrow, foldmarks=off, numericaldate=off, refline=narrow]{scrlttr2} %--------------------------------------------------------------------------- \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} %--------------------------------------------------------------------------- \usepackage{lmodern} \usepackage{color} \usepackage{marvosym} \usepackage{ifthen} \definecolor{firstnamecolor}{rgb}{0.65,0.65,0.65} \definecolor{familynamecolor}{rgb}{0.45,0.45,0.45} \definecolor{footersymbolcolor}{rgb}{0.20,0.40,0.65} \definecolor{addresscolor}{rgb}{0.35,0.35,0.35} %grau \newcommand*{\addressfont}{\small\sffamily\mdseries\slshape} \newcommand{\footersymbol}{~~\color{footersymbolcolor}\normalfont\textbullet\color{addresscolor}\addressfont~~~} %--------------------------------------------------------------------------- \setkomafont{fromname}{\sffamily \LARGE} \setkomafont{fromaddress}{\sffamily}%% Instead of \small \setkomafont{pagenumber}{\sffamily} \setkomafont{subject}{\mdseries} \setkomafont{backaddress}{\mdseries} \usepackage{mathptmx} %--------------------------------------------------------------------------- \begin{document} %--------------------------------------------------------------------------- \LoadLetterOptions{KOMAold} \makeatletter \@setplength{toaddrvpos}{27mm}% <- added \@setplength{refvpos}{80.5mm}% <- added \@setplength{sigbeforevskip}{50pt} \@setplength{firstfootvpos}{300mm} \@setplength{firstheadvpos}{10mm} \@setplength{firstheadwidth}{\paperwidth} \ifdim \useplength{toaddrhpos}>\z@ \@addtoplength[-2]{firstheadwidth}{\useplength{toaddrhpos}} \else \@addtoplength[2]{firstheadwidth}{\useplength{toaddrhpos}} \fi \@setplength{foldmarkhpos}{6.5mm} %\@setplength{refvpos}{\useplength{toaddrvpos}} \makeatother %--------------------------------------------------------------------------- % Sender information \newcommand{\myFirstname}{John} \newcommand{\myFamilyname}{Odd} \newcommand{\myStreet}{Street} \newcommand{\myTown}{NY} \newcommand{\myZipcode}{11233} \newcommand{\myPhone}{+123 456 4879} \newcommand{\myMail}{[email protected]} \setkomavar{signature}{\myFirstname\ \myFamilyname} %--------------------------------------------------------------------------- \setkomavar{firsthead}{% <- changed \begin{flushright} \renewcommand{\baselinestretch}{0.8} \sffamily\mdseries\Large\color{firstnamecolor}\myFirstname\ \color{familynamecolor}\myFamilyname\\ \parbox{\textwidth}{\color{footersymbolcolor}\rule{\textwidth}{2pt}} \normalfont\small\color{black} \myStreet \\ \myZipcode, \myTown \\ \myMail \\\myPhone \end{flushright} } %--------------------------------------------------------------------------- \setkomavar{place}{\myTown} \setkomavar{date}{\today} %--------------------------------------------------------------------------- \setkomavar{enclseparator}{: } %--------------------------------------------------------------------------- \pagestyle{myheadings}%% No header \begin{letter}{International Company Coorporation\\ Mrs. Jane Doe\\ Some street 11 \\ SF, 54321} %--------------------------------------------------------------------------- % Further options \KOMAoptions{} %--------------------------------------------------------------------------- \setkomavar{subject}{subject} %--------------------------------------------------------------------------- \opening{Dear,} text \closing{KR} \encl{enclosed} \end{letter} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Replace a dot with a comma inside a jQuery template U have a very simple jQuery template where I say the following: <dt>${Math.round(ShippingCost*100)/100} kr.</dt> However, that results in a value such as 200.00 kr. Now I want to replace my dot with a comma, which I do like this: <dt>${(Math.round(ShippingCost*100)/100).replace(".",",")} kr.</dt> Which then results in: Uncaught SyntaxError: Unexpected token { Any idea how to fix it? A: Wrap your expression inside ${} into parentheses: ${((Math.round(ShippingCost*100)/100).toString().replace(".",","))} Looks like something confuses template engine without it. Another thing you need to fix is that you have to cast result of Math.round to string type, since replace is a method of String, not number. You can use simple toString() for this.
{ "pile_set_name": "StackExchange" }
Q: Restore deleted links from left navigation I have deleted few links from the current navigation by clicking on edit links and then clicking on cross sign. I need the same navigation to restore there but i dont remember the links and their title. Is there any way to do this? A: Eric is correct, the links are not moved to the recycle bin. If you need to rebuild the links, you might want to look into doing a restore to another site collection, then use the visual queue to rebuild the links.
{ "pile_set_name": "StackExchange" }
Q: How to change my logic to print numbers in jsp? Here my code is working fine but i need the order of elements in different order. This is my code. <body> <% out.println("<table >"); int apps = 9; double rowColumn = Math.sqrt(apps); for (double i = rowColumn; i > 0; i--) { out.println("<tr>"); for (double j = rowColumn; j > 0; j--) { out.println("<td>" + apps + "</td>"); apps--; } out.println("</tr>"); } out.println("</table>"); %> </body> It is printing values as follows: 9 8 7 6 5 4 3 2 1 But i need values as follows : 7 8 9 6 5 4 1 2 3 if apps =16 then i need out put as follows: 16 15 14 13 9 10 11 12 8 7 6 5 1 2 3 4 Could anybody guide me how to change the logic. A: Try this, store the values in a variable and print out after the for loop: <body> <% out.println("<table >"); int apps = 16; double rowColumn = Math.sqrt(apps); boolean flag = true; for (double i = rowColumn; i > 0; i--) { String rowContent = ""; out.println("<tr>"); if(flag) flag = false; else flag = true; for (double j = rowColumn; j > 0; j--) { if(flag) { rowContent = "<td>" + apps + "</td>" + rowContent; } else { rowContent = rowContent +"<td>" + apps + "</td>"; } //out.println("<td>" + apps + "</td>"); apps--; } out.println(rowContent); out.println("</tr>"); } out.println("</table>"); %> </body>
{ "pile_set_name": "StackExchange" }
Q: Формирование разных переменных за каждый клик по кнопке Совсем туплю под вечер, но не клеится. Должно быть: клик 1: создание переменной worker1 клик 2: создание переменной worker2 клик 3: создание переменной worker3 и т.д. по количеству кликов. document.getElementById('button').addEventListener('click', function(event){ let counter = 1; let worker = 'worker'; for(let i=0; i <= counter; i++) { if(event.target) { worker += counter; } counter++; } console.log(worker) }) <button id="button">Button</button> A: let counter = 1; document.getElementById('button').addEventListener('click', function(event){ let worker = 'worker' + counter; console.log(worker); counter++; }) <button id="button">Button</button>
{ "pile_set_name": "StackExchange" }
Q: How can I retain checkboxes checked state after page submit and reload? I have a table called property_amenities which has columns; amenity_id and amenity_name whose values are populated on a form as checkboxes. Upon form submission, the checked values are inserted into property_listings table on column property_amenities as an array. <?php $db_host="localhost"; $db_name="cl43-realv3"; $db_user="root"; $db_pass=""; try { $DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass); $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { $e->getMessage(); } if (isset($_POST['list_property'])) { if (isset($_POST['property_amenities'])) { $property_amenities = implode(",",$_POST['property_amenities']); }else{ $property_amenities = "";} } ?> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> <div class="row clearfix"> <div class="col-lg-12 col-md-6 col-sm-12"> <?php $stm = $DB_con->prepare("SELECT * FROM property_amenities"); $stm->execute(array( )); while ($row = $stm->fetch()){ $amenity_id = $row['amenity_id']; $amenity_name = $row['amenity_name']; $List[] ="<label class=checkbox> <input type=checkbox name='property_amenities[]' value='$amenity_name'> $amenity_name</label>"; } $allamenities = $stm->rowCount(); $how_many_chunks = $allamenities/3; $roster_chunks = array_chunk($List, round($how_many_chunks), true); ?> <label>Property Amenities</label></small> <?php foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value) { echo "<div class='col-lg-3 col-md-6 col-sm-12'>"; echo join($roster_chunk_value); echo '</div>'; } ?> </div> </div><!-- end row --> <button type="submit" class="btn btn-primary" name="list_property" >SUBMIT PROPERTY</button> </form> </body> </html> The above code works fine. The only problem is that when I submit the form and the page reloads all the checkboxes of property_amenities are unchecked, what I want is the checkboxes that were checked before page submit to be checked. How can I achieve this? Here is the property_amenities table -- -- Table structure for table `property_amenities` -- CREATE TABLE `property_amenities` ( `amenity_id` int(11) NOT NULL, `amenity_name` varchar(60) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `property_amenities` -- INSERT INTO `property_amenities` (`amenity_id`, `amenity_name`) VALUES (1, 'Outdoor Balcony'), (2, 'Outdoor Yard Access'), (3, 'Large Windows/Natural Light'), (4, 'Closet Space'), (5, 'Storage Space'), (6, 'Laundry in Unit'), (7, 'Parking Garage'), (8, 'Ample Parking'), (9, 'Stainless Steel Appliances'), (10, 'Open Floor Plan'), (11, 'Newly Renovated'), (12, 'Close to Social Amenities'), (13, 'Swimming Pool'), (14, 'Courtyard'), (15, 'Electric Fence'), (16, 'Intercom'), (17, 'Patio'), (18, 'Internet'), (19, 'Guest Quarters'), (20, 'Gym / Workout Room'), (21, 'Kitchenette'), (22, 'Day And Night Guards'), (23, 'Borehole'), (24, 'Street Lights'), (25, '3 Phase Power'), (26, 'Dhobi Area'), (27, 'Wheelchair Access '), (28, 'Generator'); A: Simply check in your database which checkboxes were checked and include the checked attribute to those who were when you echo the checkboxes: $checked = (condition) ? "checked" : ""; $List[] = "<label class=checkbox> <input type=checkbox name='...' value='$amenity_name' $checked/> $amenity_name </label>"; Edit: (In response to the comment) Since the value of each checkbox is the name of the amenity, you can easily find the check checkboxes by using the $_POST['property_amenities'] array you get on submission of the form: First, create an empty array for the checked amenities ($amenities_checked). Then, check if there are any checked amenities using isset($_POST["property_amenities"]). If so, update the value of the array created above. Inside your while loop, check if the name of the amenity is in that array. Code for steps 1 & 2: # Initialise an array to store the amenities checked. $amenities_checked = []; # Check whether the form has been submitted. if (isset($_POST["list_property"])) { # Initialise the amenities string. $property_amenities = ""; # Check whether any checkbox has been checked. if (isset($_POST["property_amenities"])) { # Update the checked amenities array. $amenities_checked = $_POST["property_amenities"]; # Implode the array into a comma-separated string. $property_amenities = implode(",", $amenities_checked); } } Code for step 3: # Iterate over every amenity. while ($row = $stm -> fetch()) { # Cache the id and name of the amenity. list($amenity_id, $amenity_name) = [$row["amenity_id"], $row["amenity_name"]]; # Check whether the name of the amenity is in the array of the checked ones. $checked = in_array($amenity_name, $amenities_checked) ? "checked" : ""; # Insert the HTML code in the list array. $List[] = "<label class = checkbox> <input type = checkbox name = 'property_amenities[]' value = '$amenity_name' $checked/> $amenity_name </label>"; } Complete Code: (The snippet is used to collapse the code) <?php $db_host = "localhost"; $db_name = "cl43-realv3"; $db_user = "root"; $db_pass = ""; # Create a PDO database connection. try { $DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass); $DB_con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { $e -> getMessage(); } # Initialise an array to store the amenities checked. $amenities_checked = []; # Check whether the form has been submitted. if (isset($_POST["list_property"])) { # Initialise the amenities string. $property_amenities = ""; # Check whether any checkbox has been checked. if (isset($_POST["property_amenities"])) { # Update the checked amenities array. $amenities_checked = $_POST["property_amenities"]; # Implode the array into a comma-separated string. $property_amenities = implode(",", $amenities_checked); } } ?> <!DOCTYPE html> <html> <body> <form action = "<?= htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post"> <div class = "row clearfix"> <div class="col-lg-12 col-md-6 col-sm-12"> <?php # Fetch the amenities. $stm = $DB_con->prepare("SELECT * FROM property_amenities"); $stm -> execute([]); # Iterate over every amenity. while ($row = $stm -> fetch()) { # Cache the id and name of the amenity. list($amenity_id, $amenity_name) = [$row["amenity_id"], $row["amenity_name"]]; # Check whether the name of the amenity is in the array of the checked ones. $checked = in_array($amenity_name, $amenities_checked) ? "checked" : ""; # Insert the HTML code in the list array. $List[] = "<label class = checkbox> <input type = checkbox name = 'property_amenities[]' value = '$amenity_name' $checked/> $amenity_name </label>"; } # Save the number of amenities. $allamenities = $stm -> rowCount(); # Determine the number of chunks. $how_many_chunks = $allamenities / 3; $roster_chunks = array_chunk($List, round($how_many_chunks), true); ?> <label>Property Amenities</label> <?php # Iterate over every chunk. foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value) { echo "<div class='col-lg-3 col-md-6 col-sm-12'>" . join($roster_chunk_value) . "</div>"; } ?> </div> </div> <button type = "submit" class = "btn btn-primary" name = "list_property">SUBMIT PROPERTY</button> </form> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Why do I want follow different communities in StackExchange For my curiosity, I found StackExchange Database Administrators has groups or communities such as Database Administrators and Database Administrators Meta. What is the difference between both communities? Even my reputation and number of badges are different in both communities. Do I want to follow both? What is the major advantage(s) if I follow both communities? A: Database Administrators is the main Q & A site. Database Administrators meta is "the part of the site where users discuss the workings and policies of DBA Stack Exchange rather than discussing database administration itself". See What is "meta"? How does it work? in the Help Centre. A: Just to address a couple of other points: Your reputation should be the same on both sites, but can sometimes appear to be slightly off due to synchronization and/or caching, because in some areas on the sites the number can come from different places (in the past there have been ways to see this even within a single site, but those do generally get addressed over time). On the main Stack Overflow site, its meta site was originally completely separate, including reputation, but they fixed that by making it follow the behavior of other sites with a meta site for discussing policies etc. for Stack Overflow on its own (meta.stackoverflow.com) and splitting off the original meta site into a "meta meta" site for discussing policies etc. for the entire network (meta.stackexchange.com). The badges are tracked separately. This is likely to encourage similar activity and patterns on the meta site as well, rather than dismissing things like editing or flagging because you already have those badges.
{ "pile_set_name": "StackExchange" }
Q: vue-btn doesn't submit on enter key I have this usual login form with submit button on the end, I have to click the button with mouse to submit the button. I want to submit the form with just enter key this is my button code <v-btn color="gray" padding="20" data-cy="button-login" @click="login" > SIGN IN </v-btn> this is my javascript login function methods: { login () { let params = { mail: this.email, password: this.password } this.$store.dispatch('login', params).then((response) => { this.$router.push({name: 'dashboard', params: {'userId': String(response.data.user_id)}}) }).catch(() => { this.submitsnackbar = true }) } } It will help me a lot if I can just press enter to login Thank you A: Move login method call to form element and declare v-btn type as submit- <v-form @submit="login"> <v-btn color="gray" padding="20" data-cy="button-login" type="submit" > SIGN IN </v-btn> </v-form>
{ "pile_set_name": "StackExchange" }
Q: Python 2.7 xml.etree. Getting sibling I got xml with a structure similar to following example [...] <a> <list> <section> <identifier root="88844433"></templateId> <code code="6664.2" display="Relevant"></code> <title>Section title </title> </section> </a> </list> [...] How can I get title block searching it by root attribute of identifier block using xml.etree in Python2.7? A: below import xml.etree.ElementTree as ET xml = ''' <a> <list> <section> <templateId root="12"></templateId> <code code="6664.2" display="Relevant"></code> <title>Section title </title> </section> </list> </a>''' root = ET.fromstring(xml) section = root.find(".//section/templateId[@root='12']/..") print(section.find('title').text) output Section title
{ "pile_set_name": "StackExchange" }
Q: WinAPI Documentation contradicting itself? So I've just been looking through the Windows Documentation just to read up on some stuff and to get a broader understanding as to how the WinAPI works and so on, however, I couldn't help but notice the fact that the documentation seems to contradict itself in some cases and I need some reassurance as to which way of doing things is really the correct way of doing things. The specific example I'm looking at deals with the GetMessage() function and the 'Window Message Loop'. The first site (Window Messages) states that the correct syntax for the message loop is the following... MSG msg = { }; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } (if you scroll down it's right before the 'Posted Messages versus Sent Messages' heading near the bottom of the page) The doc explains that the WM_QUIT message causes the function to return 0 which in turn will lead to the while loop breaking and the application terminating. Otherwise, the function will return a non-zero value causing the while loop to continue. The second site (The one for the GetMessage() function) explicitly states to avoid writing code like the one previously explained. This site says that the GetMessage() function can return a value of -1 in case of an error and that using code like this while (GetMessage( lpMsg, hWnd, 0, 0)) ... would cause the application to continue running if the function returns -1 even though it should handle the error and terminate appropriately. The valid implementation for the message loop should then be this... BOOL bRet; while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0) { if (bRet == -1) { // handle the error and possibly exit } else { TranslateMessage(&msg); DispatchMessage(&msg); } } I have always done it this way so that I could catch the -1 error if there happens to be one. But after seeing Microsoft basically make the supposed mistake themselves now I am confused. So which is it Microsoft? Is it valid or not valid to do this? MSG msg = { }; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } A: You are not comparing like with like. The documentation states that -1 is returned if hWnd is invalid. In the first case the loop is passing NULL while (GetMessage(&msg, NULL, 0, 0)) and so -1 cannot be returned. But in the second example while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0) the variable hWnd is being passed so there can be an error.
{ "pile_set_name": "StackExchange" }
Q: How can I return the current column name in columnDefs jquery datatables? Like this I can return the value of the current row: "columnDefs": [ { "render": function (data, type, row) { return data ; }, What I am actually looking for is the name of the current column. I tried: "columnDefs": [ { "render": function (data, type, row) { return column().name ; }, But this did not work. A: If you specify a targets in your columnDefs you could do the following by adding a meta parameter : "columnDefs": [ { targets: 0, "render": function (data, type, row, meta) { var title = $('#example').DataTable().columns( meta.col ).header(); var columnName = $(title).html(); return columnName; } }, ] JSFiddle example (check the log) : https://jsfiddle.net/1jot32nz/
{ "pile_set_name": "StackExchange" }
Q: Javascript call() method I understand this code works: var links = document.querySelectorAll('div'); for (var i = 0; i < links.length; i++) { (function(){ console.log(this); }).call(links[i]); } but why does this work: var links = document.querySelectorAll('div'); for (var i = 0; i < links.length; i++) { console.log.call(this, links[i]); } isn't this supposed to be window object in context of calling every iteration? A: It's no different from calling var links = document.querySelectorAll('div'); for (var i = 0; i < links.length; i++) { console.log(links[i]); } You are right, in this scope the this keyword is bound to the window object, if you run the snippet bellow, you can see that I append a new property SomeUniqueValue to the window object which becomes accessible inside the scope of the look when using the call function. Now, if you wrap that block inside a function, you can see the the this keyword is limited to the scope of the calling block, hence in the last example only the span gets logged to the console. var links = document.querySelectorAll('div'); for (var i = 0; i < links.length; i++) { console.log(links[i]); } window.SomeUniqueValue = "WAWAWIWA"; for (var i = 0; i < links.length; i++) { console.log.call(this, SomeUniqueValue); } var someFunction = function() { 'use strict'; var links = document.querySelectorAll('span'); for (var i = 0; i < links.length; i++) { console.log.call(this, links[i]); } } someFunction(); <div>This</div> <div>Works</div> <div>Fine</div> <span>Inner Scope</span>
{ "pile_set_name": "StackExchange" }
Q: Symfony 2 Previous URL How to check in symfony2 controller previous URL, like in symfony 1.x ? Something equivalent to: $request->getReferer(); A: To check controller previous URL in symfony 2 : $this->getRequest()->headers->get('referer')
{ "pile_set_name": "StackExchange" }
Q: Safe to run backup script as root? or other way to aproach privileges? I'm writing a backup script in BASH on a linux machine (gentoo) The script will backup all folders in a certain directory. The folders will have varying privileges and belong to different users and groups. In order to make sure my backup script has read privileges to all the the files and folders I'm tempted to run the backup script as root. Is this safe? Are there any specific techniques to achieve this without root privileges? A: cron is the best way to do that, and yes certain scripts need to run with root otherwise you are not able to read from users home directory with 700 privileges.
{ "pile_set_name": "StackExchange" }
Q: Language comparison in template file My site has 3 languages. ​In my node--service.tpl.php, I've put the following: <?php if ($language = 'es'): ?> <div class="more"><a href="<?php print $base_url . $node_url ?>">Leer más</a></div> <?php elseif ($language = 'en'): ?> <div class="more"><a href="<?php print $base_url . $node_url ?>">Read more</a></div> <?php else: ?> <div class="more"><a href="<?php print $base_url . $node_url ?>">Leere más</a></div> <?php endif; ?> However, it only shows me the language es even a page en, i.e. it only shows me the first div. Any idea? A: node--TYPE.tpl.php doesn't include the global $language variable as you can see in this document but you can still use it by bringing the variable into scope, using global. I've updated your code below to show you how to get this working. <?php global $language; ?> <?php if ($language->language == 'es'): ?> <div class="more"><a href="<?php print $base_url . $node_url ?>">Leer más</a></div> <?php elseif ($language->language == 'en'): ?> <div class="more"><a href="<?php print $base_url . $node_url ?>">Read more</a></div> <?php else: ?> <div class="more"><a href="<?php print $base_url . $node_url ?>">Leere más</a></div> <?php endif; ?>
{ "pile_set_name": "StackExchange" }
Q: 10.10 boots to command line login prompt I recently installed Ubuntu 10.10 on a computer that was previously running 10.04 (that worked fine). Now, each time I boot up, it starts up in a command line login prompt. I can login and it stays at the command line (as expected). I can then manually start gdm with sudo start gdm and it works fine. I can also enable compiz (using proprietary nvidia drivers) so I'm reasonably confident that it's not a driver problem (at least not in the sense that the drivers just flat out aren't working). Interestingly, if I leave it at the command prompt without logging in, after about 5 or 10 minutes, gnome starts up on its own. I'm not sure what is causing this. This is what dmesg | tail gives me after a manual start of gdm: [ 15.664166] NVRM: loading NVIDIA UNIX x86_64 Kernel Module 270.18 Tue Jan 18 21:46:26 PST 2011 [ 15.991304] type=1400 audit(1297543976.953:11): apparmor="STATUS" operation="profile_load" name="/usr/share/gdm/guest-session/Xsession" pid=990 comm="apparmor_parser" [ 16.606986] eth0: link up, 100Mbps, full-duplex, lpa 0xCDE1 [ 18.798506] EXT4-fs (sda1): re-mounted. Opts: errors=remount-ro,commit=0 [ 26.740010] eth0: no IPv6 routers present [ 90.444593] EXT4-fs (sda1): re-mounted. Opts: errors=remount-ro,commit=0 [ 189.252208] audit_printk_skb: 21 callbacks suppressed [ 189.252213] type=1400 audit(1297544150.218:19): apparmor="STATUS" operation="profile_replace" name="/usr/lib/cups/backend/cups-pdf" pid=1876 comm="apparmor_parser" [ 189.252584] type=1400 audit(1297544150.218:20): apparmor="STATUS" operation="profile_replace" name="/usr/sbin/cupsd" pid=1876 comm="apparmor_parser" [ 351.159585] lo: Disabled Privacy Extensions A: Fixed when I upgraded to 11.04
{ "pile_set_name": "StackExchange" }
Q: Trying to find instance of regex pattern ['"]rm[ ].*['"] using grep I'm trying to find lines similar to these input strings. Basically -a single or double quote -followed by 1 or more blanks -followed by rm -followed by 1 or more spaces Below would be some example matches. build2('rm myfile') build2(" rm myfile') 'rm myfile' I can use a regex tester like regexpal dot com and it works fine but how would I do it using grep if my input file is called myfile.txt? I've tried the command from shell prompt below but grep does nothing but response with a > character on the next line. grep "['"] *rm *" myfile.txt A: You use double quotes around your call to grep. Therefore, you need to escape the double quote inside your pattern. grep "['\"] *rm *" myfile.txt
{ "pile_set_name": "StackExchange" }
Q: How to interpret following regex? I have a regex but i am not able to interpret it: \w\1. I thought it would match : aa since it had word a twice and first group would be a word for this regex. But its not behaving in this manner. Does back referencing work only if we place parentheses around regex ? Any help would be appreciated. Thanks. A: \n refers to the nth capturing group. However, there are no capturing groups in your regex to refer to. You likely want: (\w)\1 demo As a Java string that would be "(\\w)\\1".
{ "pile_set_name": "StackExchange" }
Q: SearchDisplayController search multiple arrays Currently I'm populating my tableviewcells with the contents of multiple arrays representing a name, id, etc. My question comes when I start to use the search display controller. I have an array with a list of names, a list of IDs, a list of barcodes, and a list of Aliases. When the user types in the search bar I need to be able to search all 4 arrays. When it finds the result in 1 array it has to pair the result with the 3 other arrays.. Example Names (apple,carrot,banana, dog) alias (red, orange, yellow, brown) barcode (1,2,10,20) id (30, 40, 50, 60) So if the user types "a" I should populate the table view with Apple, Carrot, Banana and the associated alias, barcode, id. If the user were to type 2 I should only get carrot and dog. If the user were to type 0 I would get all of those items. Any ideas how to accomplish this? UPDATE: This is how I did it. -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { BOOL shouldReturn = FALSE; [searchResults removeAllObjects]; for (int i = 0; i < [itemIDRows count]; i++) { BOOL foundResult = FALSE; if ([[itemIDRows objectAtIndex:i] rangeOfString:searchString].location != NSNotFound) { foundResult = TRUE; } if ([[nameRows objectAtIndex:i] rangeOfString:searchString].location != NSNotFound) { foundResult = TRUE; } if ([[barcodeRows objectAtIndex:i] rangeOfString:searchString].location != NSNotFound) { foundResult = TRUE; } if ([[aliasRows objectAtIndex:i] rangeOfString:searchString].location != NSNotFound) { foundResult = TRUE; } if (foundResult) { NSNumber *result = [NSNumber numberWithInt:i]; if ([self searchResults] == nil) { NSMutableArray *array = [[NSMutableArray alloc] init]; [self setSearchResults:array]; [array release]; } [searchResults addObject:result]; shouldReturn = YES; } } return shouldReturn; } Then when I'm populating the tableview I do something like this if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]) { [cell setCellContentsName:[NSString stringWithFormat:@"%@", [nameRows objectAtIndex:[[searchResults objectAtIndex:indexPath.row] integerValue]]]; } else { [cell setCellContentsName:[NSString stringWithFormat:@"%@", [nameRows objectAtIndex:indexPath.row]]; } However when I type something like 9999 it brings up instances where only 1 9 is in the ID or barcode. Any ideas how to fix that? UPDATE2: Solved the problem by having the list always refresh instead of only reloading the data if a result was found. Now it works perfectly :D A: The search display controller calls the UISearchDisplayDelegate method: searchDisplayController:shouldReloadTableForSearchString: Inside this method, you need to implement your logic. This logic will need to search all 4 of your arrays for hits, and do the appropriate lookups (i.e. to get from orange to carrot, or from 50 to banana). Each time you get a hit, I would put it in an NSMutableSet (to prevent dupes). Then when you're done searching all arrays, copy the set into the array that your table's data source reads from. If you want to show the user WHY a given row is a hit (i.e. they typed 50 and got banana), you'd have to display all 4 of the attributes in your table cell. And you'd need to highlight the part that matched. If you do this, I'd create a small container class, something like "searchHit" that contains all 4 attributes, as well as a flag for which attribute got the hit, and possibly the substring of the attribute that got the hit (so you can use a yellow background for this substring, for example.) The tableView's data source would then have an array of these searchHit objects to display, and your cellForRowAtIndexPath would need to decode this object and display the hit appropriately.
{ "pile_set_name": "StackExchange" }
Q: How do I replace specific characters idiomatically in Rust? So I have the string "Hello World!" and want to replace the "!" with "?" so that the new string is "Hello World?" In Ruby we can do this easily with the gsub method: "Hello World!".gsub("!", "?") How to do this idiomatically in Rust? A: You can replace all occurrences of one string within another with std::str::replace: let result = str::replace("Hello World!", "!", "?"); // Equivalently result = "Hello World!".replace("!", "?"); println!("{}", result); // => "Hello World?" For more complex cases, you can use regex::Regex::replace_all from regex: use regex::Regex; let re = Regex::new(r"[A-Za-z]").unwrap(); let result = re.replace_all("Hello World!", "x"); println!("{}", result); // => "xxxxx xxxxx!" A: Also you can use iterators and match expression: let s:String = "Hello, world!".chars() .map(|x| match x { '!' => '?', 'A'..='Z' => 'X', 'a'..='z' => 'x', _ => x }).collect(); println!("{}", s);// Xxxxx, xxxxx?
{ "pile_set_name": "StackExchange" }
Q: RxJava - how to stop PublishSubject from publishing even if onNext() is called I have a look in which i am calling the following: // class member var myPublishSubject = PublishSubject.create<SomeObservable>() // later on in the class somewhere: while(true){ myPublishSubject.onNext(someObservable) } I would like to stop the emission but have the while loop continue forever. So I want the onNext call to do nothing. But I'm worried that if I call myPublishSubject.onComplete() that eventually the subject will be null and I will get a NPE. Is there anymore just to silence it even if onNext() is repeatedly called. Is the best way just to unsubscribe? A: Few notes This is a pretty much a rare case, but if you can show us your real intention with the Observable, we might help you out architecting it, if not best, better. What you can do For my examples, I have only used a flag variable which is pretty straightforward, this could be changed on whatever trigger you have for your project. Option 1 You can directly invoke onComplete on the subject publisher val maxEmittedItemCount = 10 var currentEmittedItemCount = 0 val someStringValue = "Some observable" // Create whatever observable you have val publishSubject = PublishSubject.create<String>() publishSubject.subscribe({ currentEmittedItemCount++ println(it) }, { println(it) }) while (currentEmittedItemCount != maxEmittedItemCount) { // Print indication that the loop is still running println("Still looping") // Publish value on the subject publishSubject.onNext(someStringValue) // Test flag for trigger if (currentEmittedItemCount == maxEmittedItemCount) publishSubject.onComplete() } Option 2 You can also hold a reference to the subscription then dispose it afterwards, this is a little bit more semantic than the previous one as it will execute the code block without calling onNext(t) when the resource is disposed. lateinit var disposable: Disposable // Will hold reference to the subscription var maxEmittedItemCount = 10 var currentEmittedItemCount = 0 var someStringValue = "Some observable" // Create whatever observable you have var publishSubject = PublishSubject.create<String>() disposable = publishSubject.subscribeWith(object : DisposableObserver<String>() { override fun onComplete() { // Print indication of completion for the subject publisher System.out.println("Complete") } override fun onNext(t: String) { // Test flag count synchonizer currentEmittedItemCount++ // Print out current emitted item count System.out.println(currentEmittedItemCount) // Print current string System.out.println(t) } override fun onError(e: Throwable) { // Print error System.out.println(e) } }) while (currentEmittedItemCount != maxEmittedItemCount) { // Publish value on the subject if (!disposable.isDisposed) publishSubject.onNext(someStringValue) // Test flag for trigger if (currentEmittedItemCount == maxEmittedItemCount) { publishSubject.onComplete() // optional if you need to invoke `onComplete()` block on the subject disposable.dispose() } // Print indication that the loop is still running System.out.println("Still looping") } Read more on https://medium.com/@vanniktech/rxjava-2-disposable-under-the-hood-f842d2373e64 https://medium.com/@nazarivanchuk/types-of-subjects-in-rxjava-96f3a0c068e4 http://reactivex.io/RxJava/javadoc/io/reactivex/disposables/Disposable.html
{ "pile_set_name": "StackExchange" }
Q: Как опять победить URLmanager? возник такой вопрос вот правила 'serials/<slug:\w*>' => 'serial/category/list', 'serials/<id>' => 'serial/category/oneserial', пишу такие ссылки Yii::$app->urlManager->createUrl(['/serial/category/oneserial','id'=>$model->slug_serial]) //ссылка формируется такая /serials/serial-nazvanie-seriala Yii::$app->urlManager->createUrl(['/serial/category/list','slug'=>$ct->slug_category])//ссылка формируется такая /serials/сategory но если добавить тире к примеру /serials/nazvanie-сategory то в адресной строке получаю serials?slug=nazvanie-category пытался решить так 'serials/<slug:\w*>' => 'serial/category/list', 'serials/<slug:[\w_\-]+>' => 'serial/category/list', 'serials/<id>' => 'serial/category/oneserial', теперь вот /serials/nazvanie-сategory это получается хорошо но вот этот адрес /serials/serial-nazvanie-seriala теперь использует тоже второе правило и парсит на этот адрес serial/category/list что выбрасывает на главную страницу если честно 1 я не понимаю почему и 2 как это исправить. A: Не очень понял в чем вопрос. Что бы получить адрес вида /serials/serial-nazvanie-seriala надо иметь правило: 'serials/<slug:[\w_\-]+>' => 'serial/category/list', и генерировать так: Yii::$app->urlManager->createUrl(['/serial/category/list','slug'=>'serial-nazvanie-seriala']) Нет необходимости делать два правила. Вот так: 'serials/<id:\d+>' => 'serial/category/oneserial', 'serials/<slug:[\w_\-]+>' => 'serial/category/list',
{ "pile_set_name": "StackExchange" }
Q: Questions regarding Lighttpd for Windows I am using lighty for windows, yes i know it's not linux, but atm can only afford local hosting, which then allows me to do a lot of learning and practicing my web skills. I am aware that fast-cgi, does not work on windows, but I am wondering what other ways, to improve performance are there? Also I was wondering how to hide all those lightpd.exe window/boxes that come up, everytime anyone or a bot visits the site...can lighttpd be run from the background? I am running it as a service, and that is fine... But all in all, why is there so little support for lighty on windows? And I really could care less for 1 more lecture on why everything should be on linux or windows...That discussion is really a waste of time...mine and yours... If you have some useful information, I definitely want to hear it. I guess I am one of those guys, who always wants to learn how to improve things, it's like a drug for me, to eak out any percent more in performance... Like for example, I have added a subdomain, because yslow loves subdomain hosting of images,css and javascript... I really like lighty, just hope I am not the only one there...using it on windows...and all the lighty for windows sites seem to be dead...or forgotten... Thank You for your time.. -Craig A: I also run lighttpd for Windows, but I've made my own very well optimized lighttpd mod with PHP and Python support which I run from a USB pen drive, since I switched to Windows 7 all the command line windows keep appearing whenever I access the server (I also don't know how to keep this from happening). I did several things to make my lighttpd server faster (since I run it from a USB pen drive): disable all kinds of logs (specially access logs) keep the config file as small as possible (mine has only 20 lines) activate PHP only on .php files, Python only on .py files disable all kinds of modules that you don't need, like SSL and so on (I only have 5) Here it is, my config file: var.Doo = "C:/your/base/path/here" # LightTPD Configuration File server.port = 80 server.name = "localhost" server.tag = "LightTPD/1.4.20" server.document-root = var.Doo + "/WWW/" server.upload-dirs = ( var.Doo + "/TMP/" ) server.errorlog = var.Doo + "/LightTPD/logs/error.log" server.modules = ( "mod_access", "mod_cgi", "mod_dirlisting", "mod_indexfile", "mod_staticfile" ) # mod_access url.access-deny = ( ".db" ) # mod_cgi cgi.assign = ( ".php" => var.Doo + "/PHP/php-cgi.exe", ".py" => var.Doo + "/Python/python.exe" ) # mod_dirlisting dir-listing.activate = "enable" # mod_indexfile index-file.names = ( "index.php", "index.html" ) # mod_mimetype mimetype.assign = ( ".css" => "text/css", ".gif" => "image/gif", ".html" => "text/html", ".jpg" => "image/jpeg", ".js" => "text/javascript", ".png" => "image/png", ".txt" => "text/plain", ".xml" => "text/xml" ) # mod_staticfile static-file.exclude-extensions = ( ".php", ".py" ) And the modules that I've active: mod_access mod_cgi mod_dirlisting mod_indexfile mod_staticfile Bottom line is, even when running from the USB pen the server still is blazing fast. PS: I also considered switching to nginx but given the current performance I can get and the even smaller user base of nginx I decided I would keep LightTPD.
{ "pile_set_name": "StackExchange" }
Q: How to scale and position a SCNNode that has a SCNSkinner attached? Using SceneKit, I'm loading a very simple .dae file consisting of a large cylinder with three associated bones. I want to scale the cylinder down and position it on the ground. Here's the code public class MyNode: SCNNode { public convenience init() { self.init() let scene = SCNScene(named: "test.dae") let cylinder = (scene?.rootNode.childNode(withName: "Cylinder", recursively: true))! let scale: Float = 0.1 cylinder.scale = SCNVector3Make(scale, scale, scale) cylinder.position = SCNVector3(0, scale, 0) self.addChildNode(cylinder) } } This doesn't work; the cylinder is still huge when I view it. The only way I can get the code to work is to remove associated SCNSKinner. cylinder.skinner = nil Why does this happen and how can I properly scale and position the model, bones and all? A: when a geometry is skinned it is driven by its skeleton. Which means that the transform of the skinned node is no longer used, it's the transforms of the bones that are important. For this file Armature is the root of the skeleton. If you translate/scale this node instead of Cylinder you'll get what you want.
{ "pile_set_name": "StackExchange" }
Q: What happens when no response is received for a request? I'm seeing retries The question I have is probably more of a browser related question I think, but its a pretty fundamental one I'd like to find the answer too as I venture into building a web application. In my client side code I am doing an $.ajax call. This Post can take a while to respond. What I'm seeing is after a certain amount of time the request is being send again. I thought it was my $.ajax call sending it again, but no matter how many times I see the POST request on the server, I only see the beforeSend callback called once. I am fairly sure my code isn't sending it more than once, so I think its the browser retrying? I know my server is getting the request more then once as I ran up Wireshark and can see the post request multiple times. So my assumption is this is something to do with HTTP? I.e., if a response isn't received within a certain amount of time then the request is resent? Here is a sample of my call below. $.ajax({ async: false, type: 'POST', url: '<%= url_for('importDevice') %>', data: { device: val }, retryLimit: 0, //callback success: function(data) { alert('calling import'); if ( data == 'nomaster') { // Display a warning toast, with a title toastr.warning('You must set the Master Key first!', 'Warning'); $.ismasterset = false; //reset the form contents after added } else { $("div#content").html(data); } }, beforeSend: function(){ alert('in before send'); } }); This is all of the relevent code, 'retryLimit' isn't being used, I just haven't removed it from my code and yes the problem was there before I put it in. EDITED with output from client and server. ok I installed 'Live Http headers for Firefox'. In the 'Generator' tab I see the one single call '#request# POST http://testhost/importdevice' I don't see the POST in the 'headers' section though, maybe thats because there's no response? In my webserver though I see 2 calls about 22 seconds apart. [Sun Jan 13 03:08:45 2013] [debug] POST /importdevice (Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0). [Sun Jan 13 03:09:07 2013] [debug] POST /importdevice (Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0). I can also see these same calls in wireshark... This is why I was asking if this is normal behaviour to try to resend the request if a response doesn't come back, in a similar fashion to a TCP handshake and the SYN retransmission. NEW UPDATE It doesn't seem to have anything to do with my Ajax call. If I create a button with a simple HREF. i.e <a href="/importdevice?device=serverA" class="btn btn-success">TestDirect</a> Then in my 'Live HTTP headers output I get... just one instance. #request# GET http://172.16.118.15/importdevice?device=serverA But once again in my server logs I get. [Sun Jan 13 03:20:25 2013] [debug] GET /importdevice (Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0). [Sun Jan 13 03:20:48 2013] [debug] GET /importdevice (Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0). And in wireshark on the server I'm seeing it twice as well... and as expected my server code is called twice too... This is REALLY confusing to me. A: Checkout this blog post that explains what is happening: http://geek.starbean.net/?p=393 According to HTTP/1.1 RFC 8.2.4: If an HTTP/1.1 client sends a request which includes a request body, but which does not include an Expect request-header field with the “100-continue” expectation, and if the client is not directly connected to an HTTP/1.1 origin server, and if the client sees the connection close before receiving any status from the server, the client SHOULD retry the request. Make sure you design your web app to tolerate these extra requests. And if you want the ajax request to do something only once, such as writing something to a database, then you need to design the request as idempotent. See: What is an idempotent operation? Also, this highlights the differences between GET and POST operations: http://www.cs.tut.fi/~jkorpela/forms/methods.html As a general design practice: -GET operations should be designed as idempotent -POST operations should be used for writing to databases, etc.
{ "pile_set_name": "StackExchange" }
Q: Is it better to start exercising with a program/dvd or running/walking/etc? I want to start exercising but not sure the right approach. I don't want to over do it by doing too much at first since I don't already have a routine. Would it be better to start off with a dvd program or would it be better to do short walks/runs and increase? Any techniques that others have tried and worked to help them start and keep a routine? Any help would be appreciated! I hope this is the right place to ask this question! Thanks! A: First, write down the goals you're trying to achieve: overall health, reduce weight, 5k run, etc. Then based on your goal, your ability to join a gym or get a personal trainer, the amount of time you have and your current health - you can ask again and the people here can give specific advice.
{ "pile_set_name": "StackExchange" }
Q: meteor app - how to display an empty template when the template helper returns no data In my meteor app I have a data collection form template, which looks like this: <template name="IntroductionWizard_Step_1"> {{#with contributor}} <div class="container"> <div class="hero-unit"> <h3 class="panel-title">Introduction Wizard Step 1: </h3> <form class="form-vertical" role="form"> <label for="name" class="control-label"><h5 class="text-muted">Name</h5></label> <input type="text" id="name" name="name" class="form-control-element" value="{{contributorName}}" placeholder="Name"> <label for="email" class="control-label">Email</label> <input type="text" id="email" name="email" class="form-control-element" value="{{contributorEmail}}" placeholder="Email"> <label for="phone" class="control-label">Phone</label> <input type="text" id="phone" name="phone" class="form-control-element" value="{{contributorPhone}}" placeholder="phone #"> <label for="orgRole" class="control-label">Org Role</label> <input type="text" id="orgRole" name="orgRole" class="form-control-element" value="{{contributorOrgRole}}" placeholder="Org Role"> </form> </div> </div> {{/with}} </template> And the helper for this template looks like this: Template["IntroductionWizard_Step_1"].helpers({ contributor: function(n) { return ContributorCollection.findOne({contributorName: "Jim Szczygiel"}); } }); It is acceptable for this helper to either return data, if it is found, or, not to return data. Currently, when the data is returned, it shows up in this form, but, when no data is returned, then this page shows up empty - the form template is not being displayed at all. What should I do to still show an empty template form even when there was no data returned? A: with acts like an if plus a namespace, so what you are seeing makes sense - the whole form would be conditionally removed. What will probably work is just to remove the with and instead use the full name for each value. e.g.: value="{{contributor.contributorName}}" I just did a little test and found that even if contributor isn't defined, it didn't seem to fail.
{ "pile_set_name": "StackExchange" }
Q: UserID and Data Driven Subscriptions I am trying to create a data driven subscription for a report that uses @UserID to filter the results (for security purposes). The solution I've seen referenced as the answer to several similar questions is a broken link. We'd like to have a version that a user can access online as well as the subscription report that is emailed. Is there any way to do this without having two versions of the report (one with userID and one without)? A: We have developed a solution that allows the same report to be used for live access as well as data-driven subscriptions (DDS). It is based on the concept found at the link provided by djphatic To start, we return the @User value using custom code added to the report, instead of the User!UserID function which will make the DDS choke. The code is similar to the Prologika solution, but I found it at another online source--my apologies for not remembering where I found it. The code is: Public Function GetHashedUser() Try Return Report.User!UserID Catch Return " " End Try End Function For the user parameter default value we use: =Code.GetHashedUser() This returns the User!UserID if the report is being run live. The data-driven subscription needs to have the user and other parameters passed using the query for the subscription. Since any parameters passed this way will be visible in the URL, we use a hashed version of the userID (called the userkey). The userkey corresponds to a value in our security table and can identify the user and their associated permissions. We don't encrypt the other filters, since they are based on the user and are used for drill-downs.
{ "pile_set_name": "StackExchange" }
Q: Operações aritmética onde alguns dados do DataFrame não são int no Python (pandas) Estou trabalhando com alguns dados do IBGE e me encontro com duas planilhas que preciso tirar a porcentagem delas. A formula para isso é bem simples, ou seja: porcentagem = (dividendo / divisor) * 100 Seguindo, tenho, a exemplo, os dois DataFrame: data1 = {'local': ['São Paulo', 'Rio de Janeiro', 'Curitiba', 'Salvador'], 'prod_1': [576, 456, 789, 963]} divisor = pd.DataFrame(data1) data2 = {'local': ['São Paulo', 'Rio de Janeiro', 'Curitiba', 'Salvador'], 'prod_2': [123, '-', 231, '-']} dividendo = pd.DataFrame(data2) Quando aplico a formula para obter as porcentagens: quociente = ( dividendo['prod_2'] / divisor['prod_1'] ) * 100 Eu tenho o seguinte erro, que já é esperado: TypeError: unsupported operand type(s) for /: 'str' and 'int' Contudo, o problema está em, como eu contorno isso para obter as porcentagens e ignorar os espaços que contem '-'? Usar for e if está fora de cogitação por ser mais ou menos 70 tabelas com 500 linhas. Além de que, dizem que não é uma boa prática de programação para o Pandas/Python. No final de tudo, precisarei fazer um merge de todas essas planilhas e criar uma com as 70 tabelas que eu quero, porém, estou perdido em não conseguir fazer a porcentagem de forma eficiente. A: Uma solução seria gerar duas Series uma para prod_1 e outra para prod_2 e as converter coercitivamente para um formato numérico através do método pandas.to_numeric() como parâmetro errors ajustado com coerce o que força a valores inválidos serem convertido para NAN e valores válidos para numpy.float64. import pandas as pd data1 = { 'local': ['São Paulo', 'Rio de Janeiro', 'Curitiba', 'Salvador'], 'prod_1': [576, 456, 789, 963] } data2 = { 'local': ['São Paulo', 'Rio de Janeiro', 'Curitiba', 'Salvador'], 'prod_2': [123, '-', 231, '-'] } dividendo = pd.Series(data2['prod_2']) divisor = pd.Series(data1['prod_1']) dividendo = pd.to_numeric(dividendo,errors = 'coerce') divisor = pd.to_numeric(divisor,errors = 'coerce') print(dividendo / divisor * 100) Resultando: 0 21.354167 1 NaN 2 29.277567 3 NaN dtype: float64 Teste o código no Repl.it: https://repl.it/repls/LightgreenYellowishPcboard
{ "pile_set_name": "StackExchange" }
Q: Private alternatives to LiveDocx I've been looking for a solution to generate PDF from some data I have on a database. Currently I put it on an HTML and then print to PDF, but they asked me to save directly to PDF. These are documents that vary a lot in design, so before it was easy to change a margin or a font size, but now they asking for a direct PDF output it's more difficult, so I saw that LiveDocx is a great solution for me... but these documents are very private (illneses, income...) and my bosses don't want to send any document to a server. So I'm looking for some other solutions. The perfect workaround is doing what LiveDocx proposes (You have a template in a Docx format that you can modify whenever you want, and then you can send some data to the template to fill the gaps and of course save to PDF) but in my own server. Do you know something like this? My platform is based on PHP+Zend Framework, so it should be compatible with that. Thank you!! A: Well instead of using LiveDocx, i found a really cool Library. mPDF an MIT Licensed library that transfers HTML Code to a pdf document. Its simple and great. Let me know if this helped you and if you need more help. AND ontop of all that, you can write your data directly to the pdf document. You can input an html file into the pdf writer IF you want. If not then yes you can use their write function to write data directly to pdf.
{ "pile_set_name": "StackExchange" }
Q: Framework7 formToData not working I have a screen login in my aplication and to get the form data in framework i need to use formtoData but it wasnt working, so i decided to create another project and copy paste framework docs script but still isnt working. Index.html(the test project) <div class="pages navbar-through toolbar-through"> <!-- Page, "data-page" contains page name --> <div data-page="index" class="page"> <!-- Scrollable page content --> <div class="page-content"> <form id="my-form" class="list-block"> <ul> <li> <div class="item-content"> <div class="item-inner"> <div class="item-title label">Name</div> <div class="item-input"> <input type="text" name="name" placeholder="Your name"> </div> </div> </div> </li> </ul> </form> <div class="content-block"> <a href="#" class="button form-to-data">Get Form Data</a> </div> </div> </div> </div> js (test project) // Initialize app var myApp = new Framework7(); // If we need to use custom DOM library, let's save it to $$ variable: var $$ = Dom7; $$('.form-to-data').on('click', function(){ alert("dwdq"); var formData = myApp.formToData('#my-form'); alert(formData); }); Does anyone know why is it not working? thx in advance. A: They changed the function, instead of formToData now is formToJSON
{ "pile_set_name": "StackExchange" }
Q: Why large companies never use flat design? I am so curious about it and can’t find an answer. Apple, Facebook, Twitter, Google, etc. Can you imagine flat design from Apple? Probably never. By flat I mean using ANY of the features of this approach (not merely copying the whole thing). For instance, ALL those companies use very small elements (buttons, fonts, icons) , with much higher density. So why basically they all choose not to adopt it? Is it because it doesn’t speak to the mass? Seems there is a single reason shared among designers. A: Because they are not followers of trends. They are trend setters. Whole thing about Apple is "think different". You got 20 e-mails with "see what's IN in design in 201X" and it's something that Big Companies will never do. They need/want to stand out of the crowd not to blend in. It's exactly because such design speak to the mass. And Facebook/Apple/Twitter are not "one of those social sites". They are THE social sites. Can you imagine Mercedes doing a makeover every year to switch their colors to "Pantone of the year"? Can you image going into Apple store and seeing phones that are EXACTLY like the rest (like you have with clothes in chain stores)? As a Brand you cannot lead if you are part of the crowd. You need to differentiate yourself. A: Not sure what qualifies as a 'large company' and exactly what you expect to see in a 'flat design', but some of the latest Android interfaces do look pretty flat to me. Also, Facebook's app interface does have flat elements and the iPhone looks much more flat than it did a few years back. I assume Microsoft is also large by any standards and also looks pretty flat. So I wouldn't generally agree with the title, this question is likely either broad or unclear. What do you mean? :)
{ "pile_set_name": "StackExchange" }
Q: LINQ to SQL delete producing "Specified cast is not valid" error I've got a painfully simple table that is giving me a "Specified cast is not valid" error when I try to delete one or more rows. The table has two columns, an "id" as the primary key (INT), and a "name" (VARCHAR(20)), which maps to a String in the LINQ to SQL dbml file. Both of these statements produce the error: dc.DeleteOnSubmit(dc.MyTables.Where(Function(x) x.id = 1).SingleOrDefault) dc.DeleteAllOnSubmit(dc.MyTables) I iterated through "MyTable" just to make sure there was no weird data, and there are only two rows: id = 1, name = "first" id = 2, name = "second" The exception is happening on SubmitChanges. Here is the stack trace: [InvalidCastException: Specified cast is not valid.] System.Data.Linq.SingleKeyManager`2.TryCreateKeyFromValues(Object[] values, V& v) +59 System.Data.Linq.IdentityCache`2.Find(Object[] keyValues) +28 System.Data.Linq.StandardIdentityManager.Find(MetaType type, Object[] keyValues) +23 System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues) +48 System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) +142 System.Data.Linq.ChangeProcessor.BuildEdgeMaps() +233 System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +59 System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +331 System.Data.Linq.DataContext.SubmitChanges() +19 InpatientCensus.MaintenanceController.DeleteSoleCommunity(Int32 id) in C:\Documents and Settings\gregf\My Documents\Projects\InpatientCensus\InpatientCensus\Controllers\MaintenanceController.vb:14 lambda_method(ExecutionScope , ControllerBase , Object[] ) +128 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24 System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +52 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +254 System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +192 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +399 System.Web.Mvc.Controller.ExecuteCore() +126 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +27 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7 System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +151 System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +57 System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75 Removing the association added to the DBML file allows rows to be deleted. Why would the association be causing the error? The associated columns are both VARCHAR(20) in the database and resolve to Strings in the DBML file. What could possibly be causing a casting error? A: Okay, upon seeing the update, the issue is the association between your two tables. This is a known bug in .NET 3.5 SP1 and will be fixed in .NET 4.0. Try your code on a .NET 4.0 Beta if you can.
{ "pile_set_name": "StackExchange" }
Q: Cannot read property 'createManager' of undefined I need sails.js to dynamically create a new datastore adapter and connection url, and I come across this solution https://sailsjs.com/documentation/reference/waterline-orm/datastores/driver, where it stated that I can use the stateless driver to do it. But somehow I ended up with this error TypeError: Cannot read property 'createManager' of undefined Here is my sample code: let Driver = sails.getDatastore().driver; let connectionUrl = `postgresql://postgres:postgres@localhost/test-db`; let manager = ( await Driver.createManager({ connectionString: connectionUrl }) ).manager; By the way, my sails version is 1.2.1 A: Thanks, I was able to do it with npm package - machinepack-postgresql instead: https://github.com/node-machine/driver-interface let dynamicDb = require('machinepack-postgresql'); let connectionUrl = `postgresql://postgres:postgres@localhost/test-db`; let manager = ( await dynamicDb.createManager({ connectionString: connectionUrl }) ).manager; let db; try { db = ( await dynamicDb.getConnection({ manager: manager }) ).connection; } catch (err) { await dynamicDb.destroyManager({ manager: manager }); return err; } let [err, data] = await flatry(dynamicDb.sendNativeQuery({ connection: db, nativeQuery: 'select * from table1' })); if (err) { return err; } await dynamicDb.destroyManager({ manager: manager });
{ "pile_set_name": "StackExchange" }
Q: Using Switch Statements in Javascript Okay big question about switch statements. I'm new to JS. I'm trying to make a switch statement that takes input from an input box, looks for "Multiplication" "Subtraction" "Addition" and "Division" among letters and numbers in the input string and separates non-numbers from numbers and then does the typed operation on the set of numbers. So for instance, the input box might look like this: 1 a 2 b 3 c 4 multiply d 5 e So far, I've been able to separate numbers from non-numbers into arrays that would look like this given the input above: numberArray === [1,2,3,4,5] letterArray === [a,b,c,multiply,d,e] and I have functions set to add, subtract, multiply, and divide the number array, so how would I incorporate using a switch statement to find one of those many possible inputs in my array of letters? Another thing, all the loops used for the mathematical operations are similar, for instance, subtraction looks like this: for (; i < numberArray.length; i++ ) { if (i === 0) { sub = numberArray[0] } else { sub = sub - numberArray[i] } } and multiplication looks like this: for (; i < numberArray.length; i++ ) { if (i === 0) { sub = numberArray[0]; } else { sub = sub * numberArray[i]; } } Would it be possible to use the same switch statement to consolidate all four operation functions into one function, instead of calling each separate function for each case? Edited to explain my letter and number arrays, also to change the title and tags from another topic that was entirely unrelated. A: //strings === array of strings //numbers === array of numbers // list of all the operations and the function associated with it var operations = { add: function(a, b) { return Number(a) + Number(b); }, substract: function(a, b) { return a - b; }, multiply: function(a, b) { return a * b; }, divide: function(a, b) { return a / b; } } // check if an operation exist var found = false; var op; for(op in operations) { // loop through the key of the operations object if(strings.indexOf(op) != -1) { // if strings contain that operation found = true; // then we have found one break; // stop the search } } if(found && numbers.length) { // if we have found an operation and there is numbers var result = numbers[0]; for(var i = 1; i < numbers.length; i++) // apply the function associated with the operation on all the numbers result = operations[op](result, numbers[i]); alert(result); } else // if there is an error (no operation or no numbers) alert("no number or no operation!"); Addition explanation: Since + is used to either sum numbers or to concatenate strings the operands of the addition should be explicitly converted to numbers using parseInt (if they're integers) or parseFloat (if they're float) or Number (if not sure) like: return parseFloat(a) + parseFloat(b); // or return parseInt(a) + parseInt(b); // or return Number(a) + Number(b); Or implicitly by using a unary + like: return +a + +b; // to force the interpretter to interpret them as numbers Why the other operations didn't cause the problem? Because -, * and / are used only for numbers. So, the operands are implicitly interpretted as numbers (kind of the second solution for the addition using the unary +).
{ "pile_set_name": "StackExchange" }
Q: What is the explanation of the apparent staining inside this airliner window [photo]? On a recent flight, I noticed a pattern of staining or dust particles inside the window, on the plastic reveal within the cavity. It looked as though a long-term and consistent pressure differential between the cabin and the cavity had drawn a stream of air into the cavity, resulting in what looked like a sooty stain. And even more oddly, as you can see in the picture, right opposite the vent, the mark is very concentrated, as though formed by a high-pressure stream - which I presume isn't actually the case. A: I believe the stain is caused by air going through the hole relatively fast due to compression of the cabin. Assuming the window is 40x40 cm large, and there is 10 cm between the panels, the volume of air in it is 16.000.000 mm3. About 30% of this air comes out due to the lower pressure at altitude, that is 4.800.000 mm3. Assuming it takes 600 seconds (10 min) to pressurize the space again, the flow will be 800 mm3/s. Assuming the hole has a diameter of 2 mm, it has an area of 3.14 mm2. The average flow velocity is then 254 mm/s. It looks like the spot is only 20 mm away from the hole, so it would take a dirt particle less than 0,1 second to get to the spot from the hole. I think that is not much time to deflect, hence the concentration in the middle.
{ "pile_set_name": "StackExchange" }
Q: Can't connect using TCP though UDP/ICMP works My office changed IP addresses yesterday and since then we can't access any site hosted by mediatemple.net plus a couple of other sites. The office connection is ADSL (PPPoA). Both MT and my ISP support can't help. Pinging and tracerouting both work. All TCP attempts time out: HTTP, HTTPS, SSH, POP3, SMTP, telnetting random ports. I can use ssh via a ubuntu netbook connected through 3G so can do testing from both ends. I have been running tcpdump on the Media Temple (dv) box. Normal traceroute and ping both show packets in the tcpdump. I have found traceroute -T appears to work but the packets aren't actually making it to the other host. (When using that option from the netbook, the packets are visible) The new office IP address is 14.x.x.x which was only allocated to APNIC 6 months ago so I thought it might be on a bogon filter somewhere. MT support has said there's no filtering of that kind in their network. The old IP was 203.x.x.x, which was changed from a 59.x.x.x: both of them worked and no settings were changed on our end. I use the same ISP at home (203.x.x.x IP) with no problems. Any other ideas? Edit: I got a new IP address from my ISP which allowed it to work. It is not clear whether it is a problem in my ISP network or some sort of bogon filtering in Media Temple. A: There was an old bogon filter in MT's upstream and this was rectified. There were other non-MT sites affected, and other users of the same ISP were affected: see http://forums.whirlpool.net.au/forum-replies.cfm?t=1568752
{ "pile_set_name": "StackExchange" }
Q: delete capitalized items from NSArray I have an NSArray that contains a bunch of strings. Some of the items in the NSArray are capitalized; some are not. I want to delete all of the items that are capitalized from the NSArray. My code is below. If you have a mac, you can run this code, since all macs come loaded with the file I am loading into the NSArray. // Read in a file as a huge string (ignoring the possibility of an error) NSString *wordString = [NSString stringWithContentsOfFile:@"/usr/share/dict/words" encoding:NSUTF8StringEncoding error:NULL]; // Break it into an array of strings NSArray *words = [wordString componentsSeparatedByString:@"\n"]; for example, if my NSArray contains the following two items ['wolf','Wolf'] I want Wolf to be deleted. A: Here's one way. Not necessarily the best/fastest: NSCharacterSet *uppercaseSet = [NSCharacterSet uppercaseLetterCharacterSet]; NSMutableArray *itemsToDelete = [NSMutableArray new]; for ( NSString *word in words ) { if ( (word.length > 0) && [uppercaseSet characterIsMember:[word characterAtIndex:0]] ) [itemsToDelete addObject:word]; } NSMutableArray *newArray = [words mutableCopy]; [newArray removeObjectsInArray:itemsToDelete]; After looking at the code above, I realized the code below would be much faster. Turns out to be about 40x faster because it's not deleting items from an array, just appending them, which is a faster operation: NSCharacterSet *uppercaseSet = [NSCharacterSet uppercaseLetterCharacterSet]; NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:words.count]; for ( NSString *word in words ) { if ( (word.length > 0) && ![uppercaseSet characterIsMember:[word characterAtIndex:0]] ) [newArray addObject:word]; }
{ "pile_set_name": "StackExchange" }
Q: Arduino Emacs development I would like to use Emacs as a development environment for Arduino programming. What are some tips or links to use Emacs to program Arduino? Is there an official (or de facto) Emacs mode? Also, am I going to miss something in Arduino IDE if I use Emacs exclusively? A: There's a nice Arduino mode on GitHub. Just wraps cc-mode, but it does a nice job. Update: The EmacsWiki has a page dedicated to Ardunio Support for Emacs. The setup has a few steps but once done it allows you to compile and upload sketches from inside Emacs. A: You can enable an external editor option that will allow you to edit projects using external editors and then use the Arduino IDE as some kind of terminal just for compiling and uploading. I just edit stuff in Emacs, then switch to the IDE to just hit compile and upload. No need for makefiles. A: Arduino code is just C++ wearing a dress and hat. You should be able to use that mode in Emacs without problems. You may miss the one-click-compile-and-transfer button, as well as the organization of the libraries from the official IDE. You can replicate either in Emacs of course. There is nothing the official IDE does that Emacs can't do.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to add Menu Items to a context menu during implementation? I hope I asked the right question, but here's my situation. I have a TreeViewItem that I'm implementing. Inside it I set/add various properties, one of them being a ContextMenu. All I want to do is add MenuItems to the ContextMenu without passing to functions and such. Here's how I implement my TreeViewItem with ContextMenu: public static TreeViewItem Item = new TreeViewItem() //Child Node { ContextMenu = new ContextMenu //CONTEXT MENU { Background = Brushes.White, BorderBrush = Brushes.Black, BorderThickness = new Thickness(1), //**I would like to add my MENUITEMS here if possible } }; Thanks a lot! A: Sonhja answer is correct. Providing a example for your case. TreeViewItem GreetingItem = new TreeViewItem() { Header = "Greetings", ContextMenu = new ContextMenu //CONTEXT MENU { Background = Brushes.White, BorderBrush = Brushes.Black, BorderThickness = new Thickness(1), } }; MenuItem sayGoodMorningMenu = new MenuItem() { Header = "Say Good Morning" }; sayGoodMorningMenu.Click += (o, a) => { MessageBox.Show("Good Morning"); }; MenuItem sayHelloMenu = new MenuItem() { Header = "Say Hello" }; sayHelloMenu.Click += (o, a) => { MessageBox.Show("Hello"); }; GreetingItem.ContextMenu.Items.Add(sayHelloMenu); GreetingItem.ContextMenu.Items.Add(sayGoodMorningMenu); this.treeView.Items.Add(GreetingItem);
{ "pile_set_name": "StackExchange" }
Q: Spotfire IronPython set document property I'm using an IronPython script to reset all filters and also set some document propertries. The document property below "FUTUREONLY" is a drop-down property control with 3 possible selections based on expressions. When I run the script it reset the document property to '--' and causes all visualizations affected by it to be blank. In case it's a list, I've tried ... = ["FUTUREONLY"][1] as well as ... ["FUTUREONLY"] = "SECOND TEXT ITEM IN DROP DOWN STRING" as well as ... ["FUTUREONLY"] = expression used to create drop down item. Any idea how to specifically set a drop-down item currently in the drop-down list? Below is a code snippet (it works but sets the property drop-down to '--' instead of 'SECOND TEXT ITEM IN DROP DOWN STRING': dp = Document.Properties dp["FUTUREONLY"] = "" Thank you, Chris A: you can do this on one line like: Document.Properties["FUTUREONLY"] = "myvalue" the reason your dropdown is being set to "---" is because "myvalue" doesn't exist in the list. you must select a valid value that you've specified in the property control options.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to box an integer to a custom type object? Possible Duplicate: C# Implicit/Explicit Type Conversion I have an int that I am attempting to box, so as to use it in a constructor which takes as a parameter object of CustomType. An example of what I mean. int x = 5; object a = x; CustomType test = new CustomType(a) //constructor in question public CustomType(CustomType a) { //set some variables etc } Howver I get the following error The best overloaded method match for X has some invalid arguments. So obviously I'm way off the mark. Where am I going wrong? Is boxing the right solution or should i be looking at type casting? A: That constructor takes a CustomType type as a parameter; you're passing it an int. An int is not a CustomType, and the C# language knows of no implicit conversions from int to CustomType. That's why you're getting an error. Casting the int to an object doesn't change the fact that it's still not a CustomType. Looking at that particular constructor, it's a copy constructor. It takes a type of itself as a parameter. There is (one would hope) another constructor that takes another parameter, whether that's an int, or some other type that you haven't mentioned, or possibly no parameters and you need to just set a property after creating a default object. As for actual solutions, there are many. Here are a few: Add an additional constructor to CustomType that accepts an int. Define a function that takes an int as a parameter and returns a CustomObject; this would be a "conversion" function that you could use. Use a default constructor of CustomType and set a property with your integer (may or may not be applicable, depending on what CustomType does. Boxing doesn't seem to be related to the issue at hand. It's not something that you should use to pass an integer to a custom type. If you would like to know more about what boxing is, how it works, or when it's useful then consider asking a question that addresses those points because this particular problem would be harmed by using boxing as a solution, not helped.
{ "pile_set_name": "StackExchange" }
Q: How long do I have to complete the bracer guild requests based on the terms? The Bracer guild has 3 different lengths they will be available to complete, Short Medium and Long. How do I judge whether or not they will expire, though? There is no indication that a request is going to expire regardless of term length. A: The remaining time for the guild requests advances with in-game time. The in-game time advances each time you advance the main story. The easiest way to see if the in-game time has advanced, is to check if NPCs have new dialog. The time progression for the requests is: Long -> Medium -> Short -> Failed
{ "pile_set_name": "StackExchange" }
Q: Google Maps : How to remove mini preview? What is that box and how to remove that? Here is my code var mapOptions = { zoom: 6, center: new google.maps.LatLng(lat, lng), mapTypeId: google.maps.MapTypeId.ROADMAP, panControl:false, mapTypeControl:false, scaleControl:false, streetViewControl:false, overviewMapControl:false, rotateControl:false }; map = new google.maps.Map(document.getElementById('google-map'), mapOptions); google.maps.event.addDomListener(window, 'load', initialize); A: Removing the center attribute did the thing for me. var mapOptions = { zoom: 6, /*center: new google.maps.LatLng(lat, lng),*/ mapTypeId: google.maps.MapTypeId.ROADMAP, panControl:false, mapTypeControl:false, scaleControl:false, streetViewControl:false, overviewMapControl:false, rotateControl:false }; map = new google.maps.Map(document.getElementById('google-map'), mapOptions); google.maps.event.addDomListener(window, 'load', initialize);
{ "pile_set_name": "StackExchange" }
Q: Temporary loss of engine power when headlights flashed after jump start I had a battery drain on my 1986 Porsche 944S which left the battery completely drained (solved, it was the radio). I jumped it successfully and took it on a drive to charge the battery up. As I was driving I flashed my brights and was surprised when the engine seemed to almost completely cut out for a fraction of a second. As I drove around more I kept flashing my brights and this dip in power got less and less severe until it disappeared and flashing my brights made no impact. I checked the voltage with a multimeter, when running I am seeing about 14.3 volts DC. My question: is this typical behavior when running on a flat battery, or is it a symptom of a problem? A: To put it simply; Your alternator was working very hard to charge the battery while you were driving. The additional load of flashing your high beams added to the amperage draw which in turn added to the load on the engine turning the alternator. As the battery became charged, it was able to help buffer the amp draw until the charging was minimal and the load on the alternator was normal again. It would be ideal to charge the battery with an external charger rather than put that much strain on the alternator. But in this case, it is most likely normal behavior and not any problem (since you know what drained the battery in the first place). Sources mechanical load of an alternator alternator operation
{ "pile_set_name": "StackExchange" }
Q: Ampersand and mixins in SCSS Searched but can't find an answer.. I have an element which gets generated (by an external platform) with the following classes: p-button and button. Now the SCSS is like this: .p-button { &.button { margin: 10px; } } But I want to refactor using mixin includes (this is a big project so there is no other way of making this code better except using mixins). The mixin takes the given selector and applies a . to it. I can't change the mixin, as it is used by many other teams, so I can't pass the ampersand together with the selector. I tried this: .p-button { & { @include button-appearance("button") { margin: 10px; } } } But that doesn't work (puts a space between it). You can't do this: .p-button { &@include button-appearance("button") { margin: 10px; } } Anyone have a clue? EDIT: Here is the mixin @mixin button-appearance( $appearance-class, $show, $background-color, $background-image, $background-position) { $sel: $button-selector; @if $appearance-class { $sel: $sel + '.' + $appearance-class; } #{$sel} { @include normalized-background-image($background-image); @include show($show); background-color: $background-color; background-position: $background-position; } @content; } EDIT 2: Here is the $button-selector (I can not edit this in the platform, but maybe overwrite it in my own project?) $button-class: 'p-button'; $button-selector: '.#{$button-class}'; A: Everyone, finally found the solution. I just removed the &.button from the .p-button mixin include and now it works: @include button-appearance ("button") { *styles* } @include button-appearance () { *styles* }
{ "pile_set_name": "StackExchange" }
Q: So can anybody indicate whether it is worthwhile trying to understand what Mochizuki did? So I am looking at some math stuff and I start looking at the abc-conjecture. Naturally I run into the name Mochizuki and so start trying to see what he did. Well, he is starting look like another Galois. Frankly it was getting frustrating ... the lack of information. It seems like no one understands what he did. Well, if Mochizuki invented a new area of mathematics that solves big problems then wouldn't it be valuable to study his work? Why aren't a lot of people moving to understand what he did? There just seems to be a contradiction between his claims and the response by the mathematical community at large. The fact that it is 2014 with no new news indicates an issue. It would be nice if someone can resolve or explain this. A: As indicated in Mochizuki's Report concerning activities devoted to the verification of IUTeich in December 2013, Go Yamashita is going to give a three-week lecture series starting in September 2014 in Kyushu University. All together it is planned that he spends 63hours, see here. Maybe his 200-300 pages detailed survey will be finished aswell at that time. Update (5.10.2014) Yamashita gave his first part of his 3weeks lecture series, the next one will be hold in March 2015. Interestingly, at his homepage, he has now an entry in subsections "Articles": A proof of abc conjecture after Mochizuki. In preparation. Update (2.11.2014) According to Mochizuki there will be a two-week workshop at RIMS from 9.03.2015-20.03.2015, called On the verification and further development of inter-universal Teichmuller theory. During that time, Yamashita will give his two-week lecture (68.h in total) lecture on Inter-universal Teichmuller theory and its Diophantine consequences.. Proceedings will be published in english in RIMS Kôkyûroku Bessatsu. I guess after this workshop, many people will have a chance to investigate Mochizuki's work. Update (25.12.2014) Mochizuki uploaded a 17 pages long report on the verification-process in 2014. He's mentioning that three researchers have now read the preparation-papers as well as the full IUTT papers several times, have had dozents of seminars with him, preparing a detailed independent write-up. He is spending much space to describe the problem of motivating other people to go through the theory (due to the potential time it takes to fully grasp it), and explains some of his thoughts on how to proceed. Very interesting! Update (03.05.2015) A workshop on Mochizuki's work is planned by the Clay Mathematical Institute, at University of Oxford, in December 2015. Very well known participants will be there, amother others, Andrew Wiles, Peter Scholze; Ivan Fesenko (who recently wrote a survey trying to connect IUTT with well-known mathematics), Yuichiro Hoshi and Mohamed Saidi (two of the three people who studied IUTT extensively, also together with Mochizuki), Minhyong Kim (who wrote several long posts on mathoverflow on IUTT), Paul Vojta (who's conjecture seem to be [at least] discussced by Mochizuki's 4 papers), and many others. It seems like the status of IUTT will become much clearer in the end of this year. Update (15.12.2015) The Workshop on IUT Theory in Oxford has happened, and there are some interesting comments by participants: Felipe Voloch blogged on the different days (day 1, 2, 3, 4, 5), Brian Conrad wrote a post here (thanks Barry Smith). And Peter Woit also wrote about the conference here. Update (17.12.2015) There is a Nature article concering the workshop, quoting several people attending it. In the end, there is a long comment by Ivan Fesenko, the organiser of the meeting. It seems things are now going to happen. Update (22.12.2015) There is a long Quanta article concering the workshop, also quoting several of the attending people. Also the organizer Ivan Fesenko wrote a short report on his view. Update (13.05.2016) There will be a Workshop on IUTT in Kyoto, Japan, co-organized by Ivan Fesenko (University of Oxford, who organized the Oxford Workshop in December 2015) and Shinichi Mochizuki (who developed IUTT) and Yuichiro Taguchi. The participation list shows many internationals, among them Edward Frenkel (Berkley), Paul Vojta (who proposed the Vojta Conjecture for hyperbolic curves, which is claimed to be solved by Mochizuki alongside the ABC conjecture) and Vesselin Dimitrov (who is doing research on Mochizuki's work, for example here), and many others. Update (12.07.2016) Mochizuki released a new 115 pages survey paper on IUT. Update (29.07.2016) The workshop on Mochizuki's proposed proof in Kyoto, Japan seem to be much more successful than the one 9 months ago. Ivan Fesenko (organizer) writes his brief thoughts, Christelle Vincent covered 6 days from the workshop. There will be a workshop in Vermont for an introduction to concepts involved in Mochizuki’s work on the ABC conjecture, intended for non-experts. in September 2016 (see also Peter Woit's summary). Update (01.09.2017) Go Yamashita has published a long-awaited paper A proof of abc conjecture after Mochizuki. (see update 3 years ago). The document has 294 pages. [As a sidenote: Yamahita writes "He also sincerely thanks the executives in TOYOTA CRDL, Inc. for offering him a special position in which he can concentrate on pure math research." - which is quite impressive.] Update (27.11.2017) According to Edward Frenkel via twitter, Mochizuki's proof is in an advanced state of peer-review. He also referes to an interview with Ivan Fesenko about further details. Update (20.12.2017): Some critical comments appear by Peter Woit (who summarizes several recent events) and in a blog by a number theoretist (with a long comment by Terence Tao). Update (22.12.2017): Some very concrete critics come from Peter Scholze and Brian Conrad on Corollary 3.12 in IUTT3. In addition, both say they talked with people who invested much time in IUT, but they could not solve the confusion. Update (30.07.2018): Peter Scholze and Jacob Stix have apparently met with Mochizuki discussing their concerns. More can be read at Peter Woits blog. (Thanks Nagase) Update (24.08.2018): The manuscript from Peter Scholze and Jocaob Stix has been published, including the statements from Mochizuki at Mochizuki's website. A very informative article about these developments can seen at Quanta, and discussions can be seen at Peter Woits blog. A: There is one main problem with this proof being verified; Mochizuki's argument involves a new set of ideas he has developed that he calls “Inter-Universal Teichmuller Theory” (IUTeich), they are explained in a set of four papers, which total over 500 pages. Now in principle, you should be able to go through the papers line by line and check the arguments, making sure that no counterexample can be found for any of the steps. The problem is that most of these steps depend on a long list of “preparatory papers”, which run to yet another set of more than 500 pages. So, one is faced with an intricate argument of over 1000 pages, involving all sorts of unfamiliar material. I believe the only person to have completely gone through the papers is Go Yamashita, and he is now writing a 200-300 page survey, that should hopefully be more understandable. You can read more here: https://www.math.columbia.edu/~woit/wordpress/?p=6514
{ "pile_set_name": "StackExchange" }
Q: How to specify an optstring in the getopt function? I'm not sure how to correctly use optstring in the getopt function in C. How should that string be formatted? I saw examples where letters are next to each other, sometimes separated by a semicolon, sometimes by two semicolons. What does it mean? A: It is just a string, and each character of this string represents an option. If this option requires an argument, you have to follow the option character by :. For example, "cdf:g" accepts the options c, d, f, and g; f requires an additional argument. An option in command line looks like -option, so you can use the options -c, -d, -f argument and -g. A: The getopt(3) manpage makes it pretty clear : the string itself is used for specifying the legal options that can appear on the commandline, if the option is followed by a :, then that option has a required parameter - not specifying it will cause the function to fail, if the option is followed by a ::, then that option has an optional parameter. The options are one-letter identifiers. For example, specifying a string like aB:cD:: as the optstring will mean that your program takes options a, B with a required parameter, c, and D with an optional parameter.
{ "pile_set_name": "StackExchange" }
Q: jQuery DataTables getting hidden column data I have one table where I have 2 columns that get hidden by the dataTables api. From which when I delete a row from the table I need to pass the data in these columns via ajax so that it gets removed from the database as well.. I have been deleting my rows prior that didn't have data I need in them directly, without any issue. Now I need to change it up for this need and catch those values. Problem is no matter how I have tried to spin it one thing or another breaks. delete_row = $(this).closest("tr").get(0); This is what I used to catch the row I want to delete to pass it along when confirmation of deleting the row is made. And that works fine. Now I need to match the logic in creating two new vars that can be read if confirmation is made to pass through my ajax call. Which I have tried: var aPos = throttleTable.fnGetPosition($('td:eq(0)', delete_row)); var aData = throttleTable.fnGetData(aPos[0]); Along with a few different spins to catch the column I want to get the data from. The above breaks the script altogether. The thought came from var aPos = throttleTable.fnGetPosition(throttle_delete_row); var aData = throttleTable.fnGetData(aPos[0]); Which does work but only in returning every column in that row as a string. Which isn't desired. I would run a loop over it but that is problematic as a loop can be expensive, and also there is no distinct method of splitting the data up, as one of the values in one of the hidden columns is a CSV in it of itself. So the loop would be invalid for the need there as well if I split and delimited it by , So my ultimate question is, how can I break it down to get column specific? A: Well, alright then. Apparently the problem was I was attempting to do to much when all I needed was the fnGetData() bit. Turns out after playing around with whats actually going on and dumping it all into the console.log() I was able to sort out that all I truly needed to do was throttleTable.fnGetData(throttle_delete_row, 0) for sake of example, to get the hidden column(s) I seek.
{ "pile_set_name": "StackExchange" }
Q: Error:Failed to resolve: com.firebaseui:firebase-ui-auth:1.2.0 on libgdx build.gradle i'm trying to add a login with Google on my game. To do that i decide to use FirebaseUI (https://github.com/firebase/FirebaseUI-Android). But i'm having problems to sync my Gradle file. i'm reciving the error: Error:Failed to resolve: com.firebaseui:firebase-ui-auth:1.2.0 here is my build.gradle (Project) buildscript { repositories { mavenLocal() mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } maven { url 'https://maven.fabric.io/public'} jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.2' classpath 'com.google.gms:google-services:3.1.0' } } allprojects { apply plugin: "eclipse" apply plugin: "idea" version = '1.0' ext { appName = "mystore" gdxVersion = '1.9.6' roboVMVersion = '2.3.1' box2DLightsVersion = '1.4' ashleyVersion = '1.7.0' aiVersion = '1.8.0' } repositories { mavenLocal() mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } maven { url "https://oss.sonatype.org/content/repositories/releases/" } maven { url 'https://maven.fabric.io/public'} } } project(":android") { apply plugin: "android" configurations { natives } dependencies { compile project(":core") compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86_64" compile "com.firebaseui:firebase-ui-auth:1.2.0" // Failed to resolve } } project(":core") { apply plugin: "java" dependencies { compile "com.badlogicgames.gdx:gdx:$gdxVersion" } } tasks.eclipse.doLast { delete ".project" } And here my build.grade (Module:android) android { buildToolsVersion "25.0.3" compileSdkVersion 25 sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] jniLibs.srcDirs = ['libs'] } instrumentTest.setRoot('tests') } packagingOptions { exclude 'META-INF/robovm/ios/robovm.xml' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' } defaultConfig { applicationId "br.com.edney.mystore" minSdkVersion 16 targetSdkVersion 25 } } // called every time gradle gets executed, takes the native dependencies of // the natives configuration, and extracts them to the proper libs/ folders // so they get packed with the APK. task copyAndroidNatives() { file("libs/armeabi/").mkdirs(); file("libs/armeabi-v7a/").mkdirs(); file("libs/arm64-v8a/").mkdirs(); file("libs/x86_64/").mkdirs(); file("libs/x86/").mkdirs(); configurations.natives.files.each { jar -> def outputDir = null if(jar.name.endsWith("natives-arm64-v8a.jar")) outputDir = file("libs/arm64-v8a") if(jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a") if(jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi") if(jar.name.endsWith("natives-x86_64.jar")) outputDir = file("libs/x86_64") if(jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86") if(outputDir != null) { copy { from zipTree(jar) into outputDir include "*.so" } } } } task run(type: Exec) { def path def localProperties = project.file("../local.properties") if (localProperties.exists()) { Properties properties = new Properties() localProperties.withInputStream { instr -> properties.load(instr) } def sdkDir = properties.getProperty('sdk.dir') if (sdkDir) { path = sdkDir } else { path = "$System.env.ANDROID_HOME" } } else { path = "$System.env.ANDROID_HOME" } def adb = path + "/platform-tools/adb" commandLine "$adb", 'shell', 'am', 'start', '-n', 'br.com.mystore/br.com.mystore.AndroidLauncher' } // sets up the Android Eclipse project, using the old Ant based build. eclipse { // need to specify Java source sets explicitly, SpringSource Gradle Eclipse plugin // ignores any nodes added in classpath.file.withXml sourceSets { main { java.srcDirs "src", 'gen' } } jdt { sourceCompatibility = 1.6 targetCompatibility = 1.6 } classpath { plusConfigurations += [ project.configurations.compile ] containers 'com.android.ide.eclipse.adt.ANDROID_FRAMEWORK', 'com.android.ide.eclipse.adt.LIBRARIES' } project { name = appName + "-android" natures 'com.android.ide.eclipse.adt.AndroidNature' buildCommands.clear(); buildCommand "com.android.ide.eclipse.adt.ResourceManagerBuilder" buildCommand "com.android.ide.eclipse.adt.PreCompilerBuilder" buildCommand "org.eclipse.jdt.core.javabuilder" buildCommand "com.android.ide.eclipse.adt.ApkBuilder" } } // sets up the Android Idea project, using the old Ant based build. idea { module { sourceDirs += file("src"); scopes = [ COMPILE: [plus:[project.configurations.compile]]] iml { withXml { def node = it.asNode() def builder = NodeBuilder.newInstance(); builder.current = node; builder.component(name: "FacetManager") { facet(type: "android", name: "Android") { configuration { option(name: "UPDATE_PROPERTY_FILES", value:"true") } } } } } } } apply plugin: "com.google.gms.google-services" A: No problem in injection of firebase-ui-auth artifact to android module through root build.gradle. Add jcenter() in repositories for all projects repositories { mavenLocal() mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } maven { url "https://oss.sonatype.org/content/repositories/releases/" } maven { url 'https://maven.fabric.io/public'} jcenter() } Sync & build.
{ "pile_set_name": "StackExchange" }
Q: Why can't I display alert if text box has a value? I'm trying to get a function to run an if statement only if something has no value. <script src="https://jqueryvalidation.org/files/lib/jquery-1.11.1.js"></script> <script type="text/javascript"> function checkNSC() { var confirmNSC = $("#SelectNsc"); if (confirmNSC.length == 0) { alert("Please ensure all required fields are filled out") } else { alert("NSC has value") } } </script> HTML: <input type="text" id="SelectNsc" /> <button onclick="checkNSC();" id="myButton">My Button</button> </div> I'm trying to say if the value is 0 then to display an alert saying (Please ensure all fields are filled out". Otherwise say "NSC has a value" Thanks, A: Should be, var confirmNSC = $("#SelectNsc").val(); Because $("#SelectNsc") return a jquery object, so that $("#SelectNsc").length will always return a value greater than 0. <script src = "https://jqueryvalidation.org/files/lib/jquery-1.11.1.js" > < /script> <script type = "text/javascript" > $(document).ready(function() { $("#myButton").click(function() { var confirmNSC = $("#SelectNsc").val().trim(); if (confirmNSC.length == 0) { alert("Please ensure all required fields are filled out") } else { alert("NSC has value") } }); }) </script> Fiddle
{ "pile_set_name": "StackExchange" }
Q: Upgrading to a new Java version: code analysis I was wandering if there is a code analysis tool able to suggest code changes when upgrading to a new Java version. For example: look for .close() calls for autocloseable resources when upgrading to Java 7 look for multiple catch clauses with the same body when upgrading to Java 7 look for unnecessary manual boxing and unboxing when upgrading to Java 5 ... Are there specific tools or rules by existing ones (e.g., Checkstyle) that could help? A: IntelliJ has a set of inspections tagged as "Language migration", that can help you spot locations where you could benefit from new language structures such as the enhanced for loop. It can even automatically apply such advices to your whole codebase at once - if it's a no-risk transformation of course.
{ "pile_set_name": "StackExchange" }
Q: Finding Centre of a Trapezoid for rotation I'm trying to find the centre of a trapezoid, and am attempting to then rotate it around its centre. Right now, i'm finding the centre, translating it to the origin, rotating it around the origin, and then translating it back to its original position. If you view the trapezoid as this: a--------b / \ c------------d centreX = (((a.x + b.x) / 2.0) + ((c.x + d.x) / 2.0)) / 2.0; centreY = ((a.y + c.y) / 2.0); To find the two centre coordinates but this isn't rotating it around the correct spot. To do the rotation, I am using this formula on every point: For clockwise: tempX = (point.x * cos(angleToRad(10))) - (point.y * sin(angleToRad(10))); tempY = (point.x * sin(angleToRad(10))) + (point.y * cos(angleToRad(10))); For counter clockwise: tempX = (point.x * cos(angleToRad(350))) - (point.y * sin(angleToRad(350))); tempY = (point.x * sin(angleToRad(350)) + (point.y * cos(angleToRad(10350)); i.e. the rotations can only be 10 CW or 10 CCW. Is there something wrong with my formula that i'm not getting the desired rotation? Thank you! A: Hint: 1) Find the coordinate $(x_c,y_c)$ of the center with the method suggested in the comment of @pizza, or intersecting the two diagonal of the trapezoid. 2)Translate the center of the coordinate system to $x_c,y_c$. This means that you perform the transformation $(x,y)\rightarrow(X,Y)=(x-x_c, y-y_c)$ for all points (note the minus sign!). 3) Rotate the new coordinates with the formulas in OP: $$ R_\theta(X,Y)(X',Y')=(X\cos \theta-Y\sin \theta,X\sin \theta+Y\cos \theta) $$ 4) Return to the old coordinate system with an inverse transaltion of the origin:$(X',Y')\rightarrow(x',y')=(X'+x_c, Y'+y_c)$
{ "pile_set_name": "StackExchange" }