text
stringlengths
64
89.7k
meta
dict
Q: Getting from Kochi to Kodanad by public transport How to get to Kodanad Elephant Training Center from Fort Kochi (early in the morning) by public transport? I know that there are taxis and tours available but 1000-1200 rupees for such a trip seems a bit too much. Related - Where in India can one wash and play with elephants A: From Kochi KSRTC bus stand catch bus to Perumbavoor. From Perumbavoor you will get bus to Kodanad Elephant Training Center.
{ "pile_set_name": "StackExchange" }
Q: How to list wine processes on the terminal screen? I'm aware that I can run Task Manager by: wine taskmgr. However I'd like to have wine processes listed on the terminal screen similar to ps (but without using it), but for processes within Wine environment only. How this can be achieved using Wine command-line tools? A: I've found that this can be listed by using winedbg command, e.g. winedbg --command "info proc" Use the info proc winedbg command to list running processes and their Win32 pids. See: man winedbg.
{ "pile_set_name": "StackExchange" }
Q: How to calculate time period? I have the starting and ending dates and times. And I need to calculate the night time in this period (from 10 pm (22) to 6 am (6)). Example: starting date and time is {2015, 1, 4, 3, 10} ending date and time is {2015, 3, 4, 18, 10} Total (this is the result of function)= 1090 min (18 h 10 min) How can I do this? Thanks! A: d1 = {2015, 4, 1, 3, 10}; d2 = {2015, 4, 3, 18, 10}; j[d_, s_, h_] := Join[DatePlus[d, s][[1 ;; 3]], {h, 00}] abst = AbsoluteTime; l1 = DateRange[j[d1, -2, 22], j[d2, 2, 22]]; l2 = DateRange[j[d1, -1, 6], j[d2, 3, 6]]; ints = Interval /@ Map[abst, Transpose@{l1, l2}, {2}]; iu = IntervalUnion@@(IntervalIntersection[Interval[abst/@{d1,d2}], #] & /@ ints); res = DateList @@ ((Differences /@ (List @@ iu) // Total)); DateDifference[{1900, 1, 1}, res, "Minute"] (* {1130, "Minute"} *) Note that your arithmetic is wrong and you're interchanging the month and day places in your lists
{ "pile_set_name": "StackExchange" }
Q: Table not outputting all columns I am having a nightmare with this pretty simple table I have. I am trying to create a draft type board. I have users and players. I want users to be displayed as the <th> and then 14 players <td> under each player. Somewhat like this.. http://lockerroomfantasysports.com/wp-content/uploads/2013/08/FantasySports-Fantasy-Football-Draft-Board.jpg However, my page is showing up like this... It is only creating two columns of players for the users. Rather than one for each. It is also not displaying the db content where it should be. The player that is shown should only be in the first location it is (the left one). This is the code for it. $draft_order_stmt = mysqli_query($con,"SELECT * FROM user_players ORDER BY `id`"); $draft_order_stmt2 = mysqli_query($con,"SELECT username FROM user_players ORDER BY `id`"); ?> <table class="draft_border_table"> <tr> <th class="draft_table_number_th">RND</th> <?php while ($draft_user_row = mysqli_fetch_array($draft_order_stmt2)) { $username = $draft_user_row['username']; echo "<th class='draft_table_th'><div>" . $username . "</div></th>"; } ?> </tr> <?php for ($count = 1; $count < 15; $count++) { $col = "player" . $count; $query = "SELECT $col FROM user_players ORDER BY id"; $draft_order_stmt2 = mysqli_query($con, $query); $draft_order_row = mysqli_fetch_array($draft_order_stmt2); echo "<tr><td>" . $count . "</td>"; foreach ($draft_order_row as $player) { echo "<td><div class=\"draftBorder\">"; if (is_null($player)) { $player = "&nbsp;"; } echo $player . "</div></td>"; } echo "</tr>"; } ?> </table> I also tried this initially and it is displaying all of the player inputs, but the player inputs are all in one block. Like this... user1 user2 user3 all 14 player inputs Again all 14 player inputs Again all 14 player inputs etc.. This is my code for that... $draft_order_stmt = mysqli_query($con,"SELECT * FROM user_players ORDER BY `id`"); $draft_order_stmt2 = mysqli_query($con,"SELECT username FROM user_players ORDER BY `id`"); ?> <table class="draft_border_table"> <tr> <th>Rnd</th> <?php while($draft_username_row = mysqli_fetch_array($draft_order_stmt2)) { $username = $draft_username_row['username']; ?> <th><?php echo "<div>" . $username . "</div>"; ?></th> <?php } ?> </tr> <?php $count = 1; while($draft_order_row = mysqli_fetch_array($draft_order_stmt)) { $count + 1; $player1 = $draft_order_row['player1']; $player2 = $draft_order_row['player2']; $player3 = $draft_order_row['player3']; $player4 = $draft_order_row['player4']; $player5 = $draft_order_row['player5']; $player6 = $draft_order_row['player6']; $player7 = $draft_order_row['player7']; $player8 = $draft_order_row['player8']; $player9 = $draft_order_row['player9']; $player10 = $draft_order_row['player10']; $player11 = $draft_order_row['player11']; $player12 = $draft_order_row['player12']; $player13 = $draft_order_row['player13']; $player14 = $draft_order_row['player14']; ?> <tr> <td><?php echo $count; ?></td> <td><?php echo "<div class='draftBorder'>" . $player1 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player2 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player3 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player4 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player5 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player6 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player7 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player8 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player9 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player10 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player11 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player12 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player13 . "</div>"; ?></td> <td><?php echo "<div class='draftBorder'>" . $player14 . "</div>"; ?></td> </tr> <?php } ?> </table> Does anyone have any idea how I can fix this? A: <?php $userPlayerStore = array(); ?> <table class="draft_border_table"> <tr> <th>Rnd</th> <?php // Output usernames as column headings $userResults = mysqli_query($con, 'SELECT * FROM user_players ORDER BY `id`'); while($userPlayer = mysqli_fetch_array($userResults)) { $userPlayerStore[] = $userPlayer; echo '<th><div>' . $userPlayer['username'] . '</div></th>'; } ?> </tr> <?php // Output each user's player 1-14 in each row $totalPlayerNumbers = 14; for ($playerNum = 1; $playerNum <= $totalPlayerNumbers; $playerNum++) { echo '<tr><td><div class="draftBorder">' . $playerNum . '</div></td>'; foreach ($userPlayerStore as $userPlayer) { echo '<td><div class="draftBorder">' . $userPlayer['player' . $playerNum] . '</div></td>'; } echo '</tr>'; } ?> </table>
{ "pile_set_name": "StackExchange" }
Q: Can EntityManager know that it is dead? My code: emf = Persistence.createEntityManagerFactory("cassandra_pu"); em = emf.createEntityManager(); I change the persistence.xml dynamically to change to IP address of the cassandra_pu unit. However maybe it is executing too fast thus the old entity manager is returned instead of new one. Is there any way to check whether the created em entity manager good enough to use or not? A: It might depend on the EJB container in use, but in general changes to persistence.xml won't be reflected until the next redeploy of the application - so the "old" entity manager will be returned over and over again until you redeploy.
{ "pile_set_name": "StackExchange" }
Q: Mysql join two tables issue I have two tables in my database. Am struggling to join those tables to get data. My game table look like this way My fb_request table look like this way My aim is to get game information from game table like venue, game_date, logo for user_id = 17. I have set game_selected as foreign key in my fb_requests table. Please help me to write a join query for these two tables. Thank in advance. Now am using separate select query to fetch data A: Select g.venue,g.game_date,g.logo,fb.game_selected as game_id,fb.accept_status,fb.request_id from fb_request fb left join game g on (fb.game_selected=g.id) where fb.user_id=17;
{ "pile_set_name": "StackExchange" }
Q: UISearchDisplayController showing white instead of gray table cell borders I came across this issue a long time ago, and fixed it, but now I have no clue how I did it, and I'm coming across it in another controller. I am using the following code to make the keyboard automatically show up when I show my view that as a search bar: [self.rootController.changeClientViewController.searchDisplayController.searchBar becomeFirstResponder]; [self.rootController.changeClientViewController.searchDisplayController setActive:YES]; The keyboard pops up, like it should, but the lines in between each table cell are white, instead of dark-grey, and it looks bad. I am using the same code in another place to automatically pop up the keyboard; and there the lines are dark-grey as expected. Has anyone come across this? I could link to a screenshot if it would be helpful... A: Here's one way to fix it: becomeFirstResponder after a minuscule delay, i.e. [self.rootController.changeClientViewController.searchDisplayController.searchBar performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.0];
{ "pile_set_name": "StackExchange" }
Q: from javascript two arrays to php variables and values on js side I have two arrays arra = ['what', 'when', 'why']; arrb = ['sea', 'tomorrow', 'because of sun']; In reality the arrays are much longer. what is the shortest (jquery) way to get this on php side: echo $what; // result: sea echo $when; // result: tomorrow echo $why; // result: because of sun A: Create an object whose keys are the values from arra and values come from arrb. Then pass that as the data option in $.ajax(). var dataObj = {}; for (var i = 0; i < arra.length; i++) { dataObj[arra[i]] = arrb[i]; } $.ajax({ url: "yourscript.php", type: "POST", data: dataObj }); Then in PHP these will be in the $_POST array. $what = $_POST['what']; $when = $_POST['when']; $why = $_POST['why']; or more generally: foreach ($_POST as $key => $value) { echo "$key: $value<br>"; }
{ "pile_set_name": "StackExchange" }
Q: Segue won't perform when activated without a button xcode Swift 2 I'm trying to make an IOS application and checking whether the user has logged in or not. When a user is not logged in, it should display a login form. Ive created multiple View Controllers and connected them with segue's. Than I used self.performSegueWithIdentifier("userLoggedOff", sender: self) to activate the segue. But the error EXC_BAD_ACCESS appears. However, when I try to activate the same segue with the same code linked to a button, it all works. Really frustrating... Thnx for your help. This is the full code. I used JSON to get the user's account info. It's probably not the way to do it, but i'm a beginner in xcode, swift and app-making in general. import UIKit import WebKit class StartController: UIViewController { override func viewDidLoad() { super.viewDidLoad() checkLoginStatus_main() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func checkLoginStatus_main(){ let requestURL: NSURL = NSURL(string: "https://www.example.net/account/accountinfo.php")! let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(urlRequest) { (data, response, error) -> Void in let httpResponse = response as! NSHTTPURLResponse let statusCode = httpResponse.statusCode if (statusCode == 200) { do{ let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) if let accounts = json["account"] as? [[String: AnyObject]] { for account in accounts { if let status = account["status"] as? String { if let name = account["name"] as? String { if(status == "true"){ print("LoggedIn") // THIS WORKS self.continueScanner() } else { print("LoggedOut") // THIS WORKS self.continueLoginForm() } } } } } }catch { print("Error with Json: \(error)") } } } task.resume() } func continueLoginForm(){ self.performSegueWithIdentifier("userLoggedOff", sender: self) } func continueScanner(){ self.performSegueWithIdentifier("userLoggedIn", sender: self) } } This is the error: Screenshot of the error Here is the full output: LoggedOut 1 0x18771c654 <redacted> 2 0x1834bcfe4 <redacted> 3 0x1834b1e50 _os_once 4 0x1834ba728 pthread_once 5 0x1886a6d98 <redacted> 6 0x1886a6680 WebKitInitialize 7 0x188c4bfa0 <redacted> 8 0x100791a3c _dispatch_client_callout 9 0x1007928b4 dispatch_once_f 10 0x182ebcfc8 <redacted> 11 0x182ec38b8 <redacted> 12 0x182ecdd78 <redacted> 13 0x188f9c130 <redacted> 14 0x188f9c2cc <redacted> 15 0x188f9be9c <redacted> 16 0x188ca9ff4 <redacted> 17 0x188f9c154 <redacted> 18 0x188f9be9c <redacted> 19 0x188e780a0 <redacted> 20 0x188f9c154 <redacted> 21 0x188f9c2cc <redacted> 22 0x188f9be9c <redacted> 23 0x188e773d4 <redacted> 24 0x188d19140 <redacted> 25 0x188addfcc <redacted> 26 0x1889a07ec <redacted> 27 0x1889a0744 <redacted> 28 0x18928f504 <redacted> 29 0x188cfcca0 <redacted> 30 0x188d22a04 <redacted> 31 0x188d257a0 <redacted> A: @Paulw11 has solved the problem in the comments on my post. dispatch_async(dispatch_get_main_queue(), { self.performSegue... Thanks for your help everyone!
{ "pile_set_name": "StackExchange" }
Q: Swift UITableView custom Cell ordering Drag Drop? i am trying to resort UITableView cell's by long press then drag and drop the cell , its not working when i use Custom cell view any idea why ! Here is the TableView viewcontroller : override func viewDidLoad() { super.viewDidLoad() // Then delegate the TableView self.tableView.delegate = self self.tableView.dataSource = self // Register table cell class from nib let bundle = Bundle(for: type(of: self)) let cellNib = UINib(nibName: "tbc_song_vertical", bundle: bundle) self.tableView.register(cellNib, forCellReuseIdentifier: "tbc_song_vertical") //Loading Template let nib_tbc_loading = UINib(nibName: "tbc_loading", bundle: bundle) self.tableView.register(nib_tbc_loading, forHeaderFooterViewReuseIdentifier: "tbc_loading") //Automated ell height self.tableView.estimatedRowHeight = 44.0 self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.reloadData() self.tableView.isEditing = true } // MARK: - Sorting func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .none } func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return false } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let movedObject = self.data[sourceIndexPath.row] data.remove(at: sourceIndexPath.row) data.insert(movedObject, at: destinationIndexPath.row) // To check for correctness enable: self.tableView.reloadData() } //loading footer func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "tbc_loading") as! tbc_loading footerView.startAnimate() return footerView } //loading footer func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return ( self.is_fetching ) ? 40 : 0 } //Pagination func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { //Bottom Refresh if scrollView == tableView{ if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height ) { } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : tbc_song_vertical = tableView.dequeueReusableCell(withIdentifier: "tbc_song_vertical", for: indexPath) as! tbc_song_vertical cell.fillwithInfo(dto: self.data[indexPath.row] ) return cell } // Tabbed Cell func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } func numberOfSections(in tableView: UITableView) -> Int { return 1 } } only if i use custom view its not working , but when i hold my finger on the right side of any cell to drag it up or down its dragging all the table A: Add the following method func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true }
{ "pile_set_name": "StackExchange" }
Q: Is a change required only in the code of a web application to support HSTS? If I want a client to always use a HTTPs connection, do I only need to include the headers in the code of the application or do I also need to make a change on the server? Also how is this different to simply redirecting a user to a HTTPs page make every single time they attempt to use HTTP? A: If you just have HTTP -> HTTPS redirects a client might still try to post sensitive data to you (or GET a URL that has sensitive data in it) - this would leave it exposed publicly. If it knew your site was HSTS then it would not even try to hit it via HTTP and so that exposure is eliminated. It's a pretty small win IMO - the bigger risks are the vast # of root CAs that everyone trusts blindly thanks to policies at Microsoft, Mozilla, Opera, and Google.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET MVC AntiForgeryToken and Caching I am currently working on an ASP.NET MVC project and came upon an error that seemed peculiar. In the ASP.NET MVC Templates forms always get an AntiForgeryToken (thus leading me to believe that this is a best practice). However AntiForgeryTokens don't seem to work well with caching. For example when I open a site with a form including an AntiForgeryToken and I duplicate the browser window both windows have the exact same AntiForgeryToken leading to an exception when posting the form. This problem does not exist when caching is disabled (via ActionFilter NoCache, see Disable browser cache for entire ASP.NET website). So I guess my question is: Is this supposed to be that way? Is there any other way besides disabling the cache to tackle the problem? Especially the fact that the default ASP.NET MVC templates contain AntiForgeryTokens but don't disable the cache (and therefore are open to the error described above) makes me wonder. Thanks in advance! A: This is the expected behavior. Caching nicely caches the answer, including the value of the AntiForgeryToken. Disable caching on forms, and in particular on pages that use AntiForgeryToken. If you think about this further, if you're in a data-entry app, do you want to cache your data-entry forms? Probably not. However you do want to cache heavy reports -- even if it's just micro-caching -- a second or two.
{ "pile_set_name": "StackExchange" }
Q: Sharing an int or an integer object between multiple threads in Java I have a multithreaded program that includes data structures like ConcurrentHashMap and ConcurrentLinkedList, however I also need every thread to access a shared integer value. The threads themselves are custom thread classes I've made that extend class Thread. My two concerns here are: How can I make each thread see the same integer value? I don't think a primitive int would work as it would not be "passed by reference" (or rather passed by value of the object pointer). The integer needs to be mutable and any changes to one integer by a thread needs to be seen by all the other threads. Would using an Integer Object fix this, what about AtomicInteger? What should I use to preserve thread safety? Each thread will check the integer everytime a loop in them runs but it will change the integer when a thread has finished it's task and is about to return. Thanks in advance! A: You should use an AtomicInteger. I would however consider AtomicInteger as a fairly low level primitive. I would question the design. Have you considered using ExecutorService, Callable, Futures, Semaphore, CountDownLatch, the Fork/Join framework or other classes from the high level java.util.concurrent API?
{ "pile_set_name": "StackExchange" }
Q: Get the variables out of the while loop I would understand if there is a way to store the variables out of the while loop. For example, I have a slide show that shows the images for each category present and a button to see the images gallery related to the category. The button, for graphical issues, should stay out of the CSS class that contains the while. This is the current code: <div class="carousel-inner"> <!-- start carousel --> $macrocat = "SELECT * FROM tbl_category WHERE cat_parent_id = 0"; $result = dbQuery($macrocat); while($row = dbFetchAssoc($result)) { extract($row); echo $cat_name; echo $cat_description; } </div> <!-- end carousel --> and the class out of the while where I have to get cat_id: <div class="social-caption"> <a class="btn btn-large btn-primary" href="categorie.php?id=<?php echo $cat_id; ?>">Gallery</a> </div> How can I fix the problem? Thanks! A: Store the categories first: <div class="carousel-inner"> <!-- start carousel --> $macrocat = "SELECT * FROM tbl_category WHERE cat_parent_id = 0"; $cats = array[]; $result = dbQuery($macrocat); while($row = dbFetchAssoc($result)) { extract($row); echo $cat_name; echo $cat_description; $cats[] = $cat_id; } </div> <!-- end carousel --> Then later you can use them: foreach($cats as $cat) { echo "<div>".$cat."</div>"; }
{ "pile_set_name": "StackExchange" }
Q: Returning single object using from ... in linq? is it possible to change this query so that it does not return an Ienumerable List but a single object? In my case it is guranteed a single object or null. .First() seems to be not available? var as= from s in entities.Subscriptions join or in entities.OrderRates on s.OrderRateId equals or.OrderRateId join oo in entities.OrderOfferings on or.OrderOfferingId equals oo.OrderOfferingId join ov in entities.OrderVendors on oo.OrderVendorId equals ov.OrderVendorId where s.CustomerId == customerId select new {...} A: .First() will throw an exception if the source sequence is empty. So if your where condition is not resulting any items, you will get an exception. You can use the SingleOrDefault method if you are sure there will be only a single item or null yields from your where condition. var customer = (from s in entities.Subscriptions join or in entities.OrderRates on s.OrderRateId equals or.OrderRateId join oo in entities.OrderOfferings on or.OrderOfferingId equals oo.OrderOfferingId join ov in entities.OrderVendors on oo.OrderVendorId equals ov.OrderVendorId where s.CustomerId == customerId select new { //your mapping for new annonymous object goes here} ).SingleOrDefault(); SingleOrDefault/FirstOrDefault resides in the System.Linq namespace. So make sure you have a using statement to import that namespace to the class where you are using this using System.Linq;
{ "pile_set_name": "StackExchange" }
Q: mutually exclusive event vs independent event Can you illustrate with examples, what is "mutual exclusive event" and what is "independent event". Without math equations, please elaborate it.. Thanks in advance A: If I roll a die and toss a coin "The coin shows head" and "The coin shows tails" are mutually exclusive "The die shows 6" and "the die shows 3" are mutually exclusive "The die shows a perfect square number" and "The die shows a prime" are also mutually exclusive "The coin shows head" and "The die shows a 5" are independent "The die shows a prime number" and "The die shows an even number" are neither mutually exclusive nor independent "The die shows a 7" and "The coin shows head" are both mutually exclusive and independent.
{ "pile_set_name": "StackExchange" }
Q: Auto Layout constraints for container view inside UITableView header broken for different devices I have an issue that makes no sense to me. I have the following setup: | UITableView | || UITableView header || ||| UIView ||| So inside my UITableView header I have a container view that has leading, trailing and top constraints to its superview. Everything is set up correctly for my test device size (which is iPhone 8). If I change the test device to iPhone 8 Plus I get a strange offset for my trailing constraint - 39pt to the right edge, which is exactly the difference between iPhone 8 plus width in points and iPhone 8. When I switch between devices in Xcode and see that the trailing constraint is not correct I just make an adjustment myself (change trailing to 1 and then back to 0) and the problem goes away for the particular device. Initially I thought it is bug in Xcode but when I tested on a device the problem is still there. I tried setting up a new view controller and adding the same elements but with no effect. I am attaching screenshots to make my issue clearer. Before: Adjusting the desired constraints After: Switching to a device with different size A: At first I accepted DonMag's answer (thanks for your time) as this really seemed to be an Xcode Interface Builder bug. As I investigated further when having the scenario I mentioned auto layout constraints are not updating the layout when I need it hence not giving me the right view.bounds. I tried getting it in viewDidLayoutSubviews() without success as well - it was still giving me a size that suits another device. What did the trick was calling view.layoutIfNeeded() before working with view's bounds. What it does is to update the view's layout immediately. As a result you can access the desired view's bounds.
{ "pile_set_name": "StackExchange" }
Q: ADB command exec-out in subprocess.Popen() not working I am trying to pull a screenshot from an ADB device connected from python. Instead of capturing and pulling it from the device which works well, I tried to use exec-out adb exec-out screencap -p > D:\\Screenshot.png This works from command prompt but when I try this from python subprocess, screenshot is not fetched args = ['adb','exec-out','screencap','-p','>','D:\\Screenshot.png'] cmdp = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self.__output, self.__error = cmdp.communicate() retcode = cmdp.wait() The code executes without any error but the screenshot is not pulled. Please help :) A: Please try with shell=True for subprocess.Popen.
{ "pile_set_name": "StackExchange" }
Q: How to perform a Like type query using WhereParameters and EntityDataSource In the code-behind I want to apply a dynamic where clause for the entitydatasource, but I want this where to be like and not equal. I have this code working which is equal I want an equivalence code that somehow translates this into a Like statement. EntityDataSource1.WhereParameters.Add("Name", TypeCode.String, tbxSearch.Text); Solution after reading Jupaol comment : Xaml: <WhereParameters> <asp:ControlParameter ControlID="tbxSearch" Name="Name" Type="String" /> </WhereParameters> Code Behind: (on load event) if (string.IsNullOrEmpty(tbxSearch.Text)) { this.EntityDataSource1.Where = "1=1"; //fetch all data if empty } else { this.EntityDataSource1.Where = "it.Name like '%' + @Name + '%'"; //filter } A: In that code you are only adding a parameter, the place where you need to define your like comparison, is in the where clause The code you posted can be translated into: <asp:EntityDataSource runat="server" ID="eds" ..... Where="it.fname like '%' + @Name + '%'" <WhereParameters> <asp:ControlParameter ControlID="tbxSearch" Name="Name" DefaultValue="" /> </WhereParameters> To Add the where in code behind: this.eds.Where = "it.fname like '%' + @Name + '%'"; Edit1: For some reason, if I place the parameter declaration like yours (in code), it is not working, however if I place the parameter in the markup like this: <WhereParameters> <asp:ControlParameter ControlID="tbxSearch" Name="Name" Type="String" DefaultValue="" /> </WhereParameters> And in Page_Load this.eds.Where = "it.fname like '%' + @Name + '%'"; It works
{ "pile_set_name": "StackExchange" }
Q: Badge is not shown on profile I've been awarded a silver badge (Necromancer) but the badge is not shown on my profile; is this a bug? A: I also cannot see that badge in your profile, and you don't appear in the list of Necromancer winners. How do you know it was awarded to you? Did you get a notification bar at the top of MSO? Sometimes it takes a few hours or even days for the system to award an earned badge. Normally, I'd say that if you were tracking the criteria (Answered a question more than 60 days later with score of 5 or more.) manually, you might just need to wait a bit. In your case, though, I'm not sure you've met the criteria. (I'm also not sure you haven't.) I only see one answer for you, posted Feb 23 for a question asked Dec 4. That's >60 days, so the first criterion is met. Its score is 3 (+5/-2). It's possible that its net score was 5 at one point, but if it was downvoted to below 5 before the Necromancer award script was run, you wouldn't get the badge.
{ "pile_set_name": "StackExchange" }
Q: How to change error message of the webform Possible Duplicate: preprocess_node_webform is not working How can I change the default error message of the webform ? For example "The name field is required" to "Please enter your name". Where should I make changes to achieve this ? A: You can use drupal_set_message().
{ "pile_set_name": "StackExchange" }
Q: Several WordPress sites to share plugin data I am wondering if there is a way to have two WordPress installations with separate databases or table prefixes, but install a plugin and use data generated by it on both websites. For example, if I hade website1.com and website2.com. Website1 has s1 table prefix, Website2 has s2. At this point, they are still two separate websites. Now, I'd like to install a plugin which, of course, comes with its own set of tables and whatnot. Is there a way to share that data between these two websites? Make s2 point to s1 tables just for this purpose, or create a third prefix and point both websites to it? Or is there a completely different approach I'm not thinking of? Is this at all possible? A: Possible? Yes, absolutely. The plugin could create its own database table and both sites would need to query this table to get whatever data they need from it. The how-to-do-it part is up to you. Writing a plugin that creates a database table isn't difficult (in your case, you don't want it to use the prefix of either of your sites to make it evident that this plugin's database table is site-independent). Check the official documentation, there's a working example there on how to create a database table on plugin activation. Now, having your two sites get data from it is where the fun begins and that is also up to you to sort out. The $wpdb object will be useful in this particular case. And yes, you can have two WordPress sites share the same database without using multisite. Just make sure both setups are on separate folders and that each site uses their own database table prefix and you're good to go. Happy coding!
{ "pile_set_name": "StackExchange" }
Q: Executenonquery requires an open and available connection. the connection current state is closed Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim response As MsgBoxResult response = MsgBox("Do you want to save the data ?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm") If response = MsgBoxResult.Yes Then Try Dim cm As New OleDb.OleDbCommand Dim cn As New OleDb.OleDbConnection cm = New OleDb.OleDbCommand With cm .Connection = cn .CommandType = CommandType.Text .CommandText = "INSERT INTO Drug (DrugCode, DrugName, Branch Code, Branch Name, Dosage, UM, Quantity, Date, ConsPRN, EMPCode, EMPName, EMPPos) VALUES ('DCode', 'DName', 'BCode', 'BName')" .Parameters.Add(New System.Data.OleDb.OleDbParameter("DCode", System.Data.OleDb.OleDbType.VarChar, 255, Me.DCode.Text)) .Parameters.Add(New System.Data.OleDb.OleDbParameter("DName", System.Data.OleDb.OleDbType.VarChar, 255, Me.DName.Text)) .Parameters.Add(New System.Data.OleDb.OleDbParameter("BCode", System.Data.OleDb.OleDbType.VarChar, 255, Me.BCode.Text)) .Parameters.Add(New System.Data.OleDb.OleDbParameter("BName", System.Data.OleDb.OleDbType.VarChar, 255, Me.BName.Text)) ' RUN THE COMMAND cm.Parameters("DCode").Value = Me.DCode.Text cm.Parameters("DName").Value = Me.DName.Text cm.Parameters("BCode").Value = Me.BCode.Text cm.Parameters("BName").Value = Me.BName.Text cm.ExecuteNonQuery() MsgBox("Record saved.", MsgBoxStyle.Information) Me.DCode.Text = "" Me.DName.Text = "" Me.BCode.Text = "" Me.BName.Text = "" Exit Sub End With Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.Critical) Finally End Try ' MsgBox("Unable to save data. Please input blank fields!", MsgBoxStyle.Question + MsgBoxStyle.OkOnly, "Error") ElseIf response = MsgBoxResult.No Then Exit Sub End If End Sub A: add a cn.Open() before your cm.ExecuteNonQuery, and then add a cn.Close before you exit sub cm.Parameters("DCode").Value = Me.DCode.Text cm.Parameters("DName").Value = Me.DName.Text cm.Parameters("BCode").Value = Me.BCode.Text cm.Parameters("BName").Value = Me.BName.Text cn.Open() '<----- open the connection cm.ExecuteNonQuery() cn.Close() '<--- close the conenction MsgBox("Record saved.", MsgBoxStyle.Information) Me.DCode.Text = "" Me.DName.Text = "" Me.BCode.Text = "" Me.BName.Text = "" also, double check your cn oledb connection. It has no defined Connection String
{ "pile_set_name": "StackExchange" }
Q: Sketch complex inequalities Problem Sketch complex inequalities to complex plane. (a)$$|z-2i|<1 $$ (b) $$ |z-1-2i|>3 $$ Attempt to solve My intuition would tell me that (a) is area inside circle and (b) is area outside of circle in complex plane. However if i try to explicitly solve these inequalities i get answer that doesn't make any sense to me. I tried with simplified version without inequality ( should contain only points from rim of the circle ) I form expression for length of the radius with Pythagoras. $$|z|=\sqrt{(\operatorname{Re}(z)^2+(\operatorname{Im}(z))^2}$$ $$ \sqrt{z^2+(-2)^2}=1 $$ $$ z^2+4=1 $$ $$ z^2=-3 $$ $$ z=\pm \sqrt{-3} = \pm i\sqrt{3} $$ I tried to solve where this circles radius is exactly 1. It would seem there is gap in my intuition and cant seem to make sense of this. A: For $$|z-2i|<1$$ you are looking for all points in the complex plane whose distance from $2i$ is less that $1$. That is the open disk centered at $z=2i$ and radius $1$ With center at $(0,2) $and radius $1$ we get $$ x^2+(y-2)^2<1$$ For $$|z-1-2i|>3$$ you are looking for all the points in complex plane whose distance from $ 1+2i$ is greater than $3$. That is the outside region of the disk with center $(1,2)$ and radius $3$ You can write the inequality to describe it.
{ "pile_set_name": "StackExchange" }
Q: Using android sql lite database Good day! I have 1000 list of items that I want to add in the SQL Database in Android. 900 of the items is already be existing and I need to store it because it can be edited. 100 of these will be added by the user using CRUD. How can I input the 900 items and do it only once? I am planning to create outside the database first then just add it on the android. I am following this tutorial but upon creating the table, i don't know how i can input the 900 items. I am planning to create outside the database first then just add it on the android and just use that database (e.g. where should i put the database? how can i call it using the java code). But how can i do this? Thank you. A: If you're creating the database outside of Android then you can create a text file with the SQL needed to add the records e.g. INSERT INTO <tablename> VALUES (<_id value>,<field value>, etc etc); name it foo.sql and then from the SQLite prompt sqlite> .read foo.sql If the db already exists in SQLite you can re-create the SQL statements by sqlite> .dump <tablename> This will create the sql statments to both create the table and do the INSERTS
{ "pile_set_name": "StackExchange" }
Q: iOS, Delete all data saved to device by app using NSFileManager I want my app to delete all the information it has saved to the device, and i was told you do this using the NSFile Manager, so i was wondering what the code was to do this? A: Simple , folderPath is the path of your Document Directory. NSString *folderPath; NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]; for (NSString *strName in dirContents) { [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:strName] error:&error]; } Hope it will be helpful to you
{ "pile_set_name": "StackExchange" }
Q: Identify 80s or 90s comics with ripped creatures (not dwarves) It was a comicbook series about fantasy creatures published in the 80s or 90s definitely not online since I was a kid and Internet didn't existed to me. The graphic style was European (bande dessinée) or American. These creatures were bare chested, or wore light clothes, because I remember them being ripped, with abs and pecs, and being mélée-focused but they were not dwarves. I mean they were not stocky, but athletic. I don't remember their overall size (I don't remember a scale). Maybe they were elves but not the tall-and-ranged-attack Tolkien type. A: Is it possible you're thinking of Elfquest? The elves in question definitely tend to very toned, and muscular. The degree of focus on mêlée varies with them using a mixture of primitive ranged weapons, and a variety of swords, knives, and clubs. Because elves were mentioned, I decided to try fantasy comic heavily muscled elves (which surprisingly did not lead me to highly NSFW results). One of the images was of Cutter, which reminded me of reading Elfquest as a child.
{ "pile_set_name": "StackExchange" }
Q: std future exception - already retrieved, std bug? I am trying to catch the Already-Retrieved exception as seen in http://www.cplusplus.com/reference/future/future_errc/ try { prom.get_future(); prom.get_future(); // throws std::future_error with future_already_retrieved } catch (std::future_error& e) { if (e.code() == std::make_error_condition(std::future_errc::future_already_retrieved)) std::cerr << "[future already retrieved]\n"; else std::cerr << "[unknown exception]\n"; } But I always receive a no-state excpetion. By looking at std future implementation: _Ty& _Get_value() const { // return the stored result or throw stored exception if (!valid()) // will check if already retrieved, and return false _Throw_future_error(make_error_code(future_errc::no_state)); return (_Assoc_state->_Get_value(_Get_only_once)); // only this // method can throw the already retrieved exception but its not // being hit because of previous valid() check } Is this a bug in Visual Studio 2013 or a feature? A: From cppreference which I find to be more reliable: Exception is thrown if *this has no shared state or get_future has already been called. What exceptions? Throws: future_error if *this has no shared state or if get_future has already been called on a promise with the same shared state as *this. (14.1) future_already_retrieved if get_future has already been called on a promise with the same shared state as *this . (14.2) no_state if *this has no shared state. So this is a bug in MSVC2013.
{ "pile_set_name": "StackExchange" }
Q: Async Image Downloading in UICollectionViewCell? I am making my UIcollectionviewcell to download the image async But only the last image is coming for the last cell. Below is my code - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { self.collectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; NSMutableDictionary *temperoryDictionary = [[NSMutableDictionary alloc] initWithDictionary:[self.weatherArray objectAtIndex:indexPath.row]]; NSString *imageURL = [[[temperoryDictionary valueForKey:@"weatherIconUrl"] objectAtIndex:0] valueForKey:@"value"]; [self downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) { if (succeeded) { self.collectionViewCell.weatherImage.image= image; } }]; return self.collectionViewCell; } - (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock{ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (!error) { UIImage *imageAsync = [[UIImage alloc] initWithData:data]; completionBlock(YES,imageAsync); } else { completionBlock(NO,nil); } }]; } I don't know what error i am making. A: Instead of self.collectionViewCell, you should use __block UICollectionViewCell * cell: - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { __block UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; NSMutableDictionary *temperoryDictionary = [[NSMutableDictionary alloc] initWithDictionary:[self.weatherArray objectAtIndex:indexPath.row]]; NSString *imageURL = [[[temperoryDictionary valueForKey:@"weatherIconUrl"] objectAtIndex:0] valueForKey:@"value"]; [self downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) { if (succeeded) { cell.weatherImage.image= image; } }]; return cell; } For custom cell, using __block CustomClass * cell. CustomClass is the class of custom cell.
{ "pile_set_name": "StackExchange" }
Q: Can't get inputs from html form I want to create a webapp in Django that converts orders in pdf to excel file. To be more flexible i want to retrive text from pdf and pass it to form on HTML page to be editable. If everythig will be ok then i want to download excel file with data from inputs. There is several inputs (depending on how much rows is in pdf with order) and i want to pass it all to my app. But below code dont work. Only result i have is token and value from button. print(request.POST.keys()) print(request.POST['Submit']) print(request.body) <form action="extract_pdf" method="post"> {% csrf_token %} <div class="row"> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <label class="input-group-text" for="inputGroupSelect01">Company ID</label> </div> <select class="custom-select" id="inputGroupSelect01"> {% for item in company %} <option value="a">{{item.1}}</option> {% endfor %} </select> </div> </div> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="company_name">Company Name</span> </div> <input type="text" class="form-control" id="name" aria-describedby="basic-addon3" value="{{info.company_name}}"> </div> </div> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="order_no">Order Number</span> </div> <input type="text" class="form-control" id="ord_no" aria-describedby="basic-addon3" value="{{info.order_number}}"> </div> </div> </div> {% for row in rows %} <div class="row"> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="item_nr">Jeeves Code</span> </div> <input type="text" class="form-control" id="item" aria-describedby="basic-addon3" value="{{row.item}}"> </div> </div> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="item_qty">Item Qty</span> </div> <input type="text" class="form-control" id="qty" aria-describedby="basic-addon3" value="{{row.qty}}"> </div> </div> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="item_price">Item price</span> </div> <input type="text" class="form-control" id="price" aria-describedby="basic-addon3" value="{{row.price}}"> </div> </div> </div> {% endfor %} <input type="submit" class="btn btn-success" value="Download" name="Submit" /> </form> Please help me find bug in my code :) A: You need to name your inputs. request.POST is a dictionary of key value pairs from the POST data, and if you do not provide names for the inputs there is no way for django to build that relationship and give you the data in your request.POST. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Web Form BOT Protection transparent to user I was thinking a lot for last few days on how to protect the web form that Bots uses. The usage is kindly abuse, around 800k bot's queries in ~8hours. Let's take a quick situation overview, any missing info - please ask for. The bot: The bot have different IPs. The bot changes it's user agents to the really existing ones. The unknown point whether the bot loads js and have a cookie or not. The problems: The form couldn't use hidden token field as may be submit from outside resources. The resourses such as different websites, that doesn't know about CSRF tokens, and can't generate them. Making impossible to use CSRF. The website MUST be cached in browser and the cache maybe reset only under exceptional situations, like suspected behavior. Database can't be used intensively(!). The way it is now: Cookie counter with expiration hashed into something + additional chars only systems knows when they inserted. If browser couldn't handle cookies, database logging used. Here is some difficulty with browser cache, when user doesn't reach the server - result: verification is not running, counter is not incremented. reCaptcha applied for user who exceeds attempts limit during X time. The ideas that came up: Serving iframe with some content and expires 0. iframe making simple cookie logic. Iframe : if cookie is not set - set it, if cookie is set, verify. if user didn't exceed the limit - set counter +1, if exceeded - send to specific page, that will show the warning with cache reset. The difficulty here, what if bot doesn't support cookie and the content being served from cache... the db doesn't write anything as the user doesn't reach the server. However if user changes keyword, it will reset the cache and the logic behind will work. The second difficulty: what if bot doesn't support JS (he will be thrown out when he switch keyword). but, cant be redirected while content served from cache. The third difficulty: What if bot deciphers ReCAPTCHA ? :) *The Questions: * What you were doing in this situation ? Please describe the steps you are thinking. Really appreciate your point of view on the things. Every idea will may be refined with other ideas and we can come up with a great protection scheme! Thank you, guys! A: So My Idea to fight the user's cache was: Using iframe 1x1. it's content being sent with Expires: 0, the iframe is served every time even when page loaded from cache. Another idea i just came up is to record mouse events. the onmousemove and onkeydown, these two catchs even F5 keydown. report to a server and set the flag. FINAL RESULT It is decided to use cloaked CSS, that sets system's variable that the user is loading contents normally. However, if "user" loading content normally, exctra protection is to implement javascript's events tracking (onmousemove,onkeydown,onclick) and receive send it to server to flag it. The request sends to server only once, when event first occurred and then doesn't track.
{ "pile_set_name": "StackExchange" }
Q: What should I do if I managed to solve my own problem without a logic solution? Yesteday, I've posted this question about a problem I had with finding WEP networks in airodump-ng. Today, surprisingly, I've been able to find my WEP network, without noticeable reason. What should I do with my original question? Should I answer it without any informative details? Should I just delete it? A: If you know why (i.e. you have a solution) then post an answer with details. If the question and any potential answer does not add to the community or no one else could benefit from your experience, I'd consider deleting the question.
{ "pile_set_name": "StackExchange" }
Q: How do I defeat Atlas? So, I am currently up against Atlas, but I can't beat him. I am enacting my 1-step battle plan (shoot at Atlas a lot), but it doesn't seem to be working. In addition, while I am doing this, he's tearing me to shreds because I can't seem to dodge his projectiles at all, even while sprinting! Am I maybe supposed to shoot something else in the environment, and not the giant boss itself? Am I simply not shooting him enough? Some tactics would be appreciated. If it helps at all, I have the N.R.G. Railgun at my disposal, with which I've been shooting his giant glowing noggin repeatedly — to little apparent effect. A: In the official game forums, a user has posted a video on YouTube on how to kill Atlas on insane. He also added some comments for the various phases. Hope this helps :) A: I thought I had to shoot at his head to but I soon found out that you have to aim at the parts of his body that glow orange. You have to defeat his orange armour twice and on the third time he goes berserk and rips out some sort of red gear and totally demolishes you no matter what. Im still trying find out how to beat him completely. Hope this helped :)
{ "pile_set_name": "StackExchange" }
Q: AngularJS & Firebase auth ngShow and ngClick delay? I'm just starting out with AngularJS and I'm running into an odd problem regarding Firebase authentication. I have a very simple body which shows to current user status (logged in, true or false) and a signIn and signOut option. When I click the Log-in button the first time, nothing happens. When I click it a second time, the logged in status changes and the ng-show and ng-hide divs switch. Same problem when clicking sign out. Why does it only happen after the second click? index.html: <div class="container" ng-controller="userCtrl"> <h1>User logged in: {{loggedIn}}</h1> <div ng-hide="loggedIn"> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" name="email" ng-model="user.email" /> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" name="password" ng-model="user.password" /> </div> <button type="button" class="btn btn-lg btn-success" ng-click="signIn()">Sign in</button> </div> <div ng-show="loggedIn"><button type="button" class="btn btn-lg btn-danger" ng-click="signOut()">Sign out</button></div> </div> Controller: var myApp = angular.module("tijdlozespelApp", ["firebase"]); myApp.controller("userCtrl", function ($scope, $firebaseObject) { $scope.loggedIn = false; $scope.signIn = function() { var email = $scope.user.email; var password = $scope.user.password; firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) { $scope.loggedIn = true; }).catch(function(error) { $scope.loggedIn = false; }); } $scope.signOut = function() { firebase.auth().signOut().then(function() { $scope.loggedIn = false; }); } }); A: Use $scope.$apply(function() {...}) to update your scope data when you use async handlers. Angular have problems with identifing scope changes for async operations. $scope.$apply(function() { $scope.loggedIn = true; });
{ "pile_set_name": "StackExchange" }
Q: Catching exceptions in ASP.NET Core MVC I have seen multiple ways of catching exceptions in ASP.NET MVC Core, but I need to understand why what I did doesn't work as I expected. I added the following: public abstract class GenericActionFilter : ActionFilterAttribute { protected readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (await OnBeforeActionExecutionAsync(context)) { var executed = await next(); if (executed.Exception != null && !executed.ExceptionHandled) { await OnExceptionAsync(context, executed.Exception); } else { await OnAfterActionExecutionAsync(context); } } } public virtual Task<bool> OnBeforeActionExecutionAsync(ActionExecutingContext context) { return Task.FromResult(true); } public virtual Task OnAfterActionExecutionAsync(ActionExecutingContext context) { return Task.CompletedTask; } public virtual Task OnExceptionAsync(ActionExecutingContext context, Exception ex) { return Task.CompletedTask; } } and use it like this: public class ExceptionFilter : GenericActionFilter { public IntegrationScenarioSettings Settings { get; set; } public override Task OnExceptionAsync(ActionExecutingContext context, Exception ex) { context.Result = new ContentResult { Content = Settings.ApiExecutionExceptionMessage, StatusCode = (int)HttpStatusCode.ServiceUnavailable }; //outputs to endpoint.log Logger.Error(ex); return Task.CompletedTask; } } The underlying code in the action is throwing an exception and rather then seeing the 503, I still the 500. What is it I'm missing here? A: In order to inform the ASP.NET Core MVC pipeline that you've handled an exception, you need to set ActionExecutedContext.ExceptionHandled to true. Because you don't have this in the code you've shown, the ASP.NET Core MVC pipeline uses its own error-handling logic to convert your (what it thinks is) unhandled exception into the 500 response. Now - this property exists on ActionExecutedContext and not on ActionExecutingContext (which you're using in your code). This makes sense, as ActionExecutingContext represents the state before the action runs and ActionExecutedContext represents the state after the action runs. This means you're going to need the following set of changes: Update your OnExceptionAsync function to take ActionExecutedContext instead of ActionExecutingContext. Update the call to OnExceptionAsync, providing executed instead of context. Whilst you're here, you could also collapse the method parameters down to just executed (I'll show this in the code, below). Set context.ExceptionHandled to true once you've, well, handled the exception. :) I've taken the code from your question, stripped out some of the code that isn't relevant to the issue and applied these changes, which I've called out with the corresponding numbers from above: public abstract class GenericActionFilter : ActionFilterAttribute { public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (await OnBeforeActionExecutionAsync(context)) { var executed = await next(); if (executed.Exception != null && !executed.ExceptionHandled) { await OnExceptionAsync(executed); // #2. } else { // NOTE: You might want to use executed here too. await OnAfterActionExecutionAsync(context); } } } // ... public virtual Task OnExceptionAsync(ActionExecutedContext context) // #1. { return Task.CompletedTask; } } public class ExceptionFilter : GenericActionFilter { public override Task OnExceptionAsync(ActionExecutedContext context) // #1, #2. { Logger.Error(context.Exception); // #2 (single parameter). context.Result = new ContentResult { ... }; context.ExceptionHandled = true; // #3. return Task.CompletedTask; } }
{ "pile_set_name": "StackExchange" }
Q: Django - many to many with post_save gridlock I want to send out an email when a model instance is saved. To do this I listen out for the post_save signal: #models.py @receiver(post_save, sender=MyModel, dispatch_uid="something") def send_email(sender, **kwargs): instance = kwargs['instance'] email = ModelsEmailMessage(instance) email.send() In my view I process the form and append subscribers to the object: #views.py object = form.save() object.subscribers.add(*users) My problem is that the form save triggers the post_save signal before the users have been added. But if I do this: object = form.save(commit=False) then I can't add m2m instances to an object that has no id. Heyulp! A: Most likely you will have to write your own signal to send email. Event though you are implemented that tries to send email when object is saved, but that is not what you want. You want to send email when object is saved and has some subscribers added after processing some view. i.e. its 2 step operation.
{ "pile_set_name": "StackExchange" }
Q: regex url matching I'm trying to write a regex that matches a url only if after '/' there's a dot. Here's what i've got so far: http://regexr.com/3cu85 my regex is the following: /facebook.com\/.*[.]/gm and i'm testing with this URls: facebook.com facebook.com/ facebook.com/test.user www.facebook.com www.facebook.com/ www.facebook.com/test.user https://www.facebook.com https://www.facebook.com/ https://www.facebook.com/test.user The problem is that I need to match the full url, and as you can it starts from the word "facebook". I tried different options, but none worked for me. Thanks for any help A: My suggestion is (https?:\/\/)?(w{3}\.)?facebook\.com\/[^\/]*\..* See the regex demo (the \n is added to the negated character class [^\/] so as to match the URLs on separate lines only, if you test individual strings, the \n is not necessary.) This regex matches: (https?:\/\/)? - optional (one or zero) occurrence of http:// or https:// (w{3}\.)? - optional (one or zero) occurrence of www facebook\.com - literal sequence facebook.com \/ - a literal / [^\/]* - zero or more characters other than / (BETTER: use [^\/.]* to match any char but a . and / to avoid redundant backtracking) \. - a literal . .* - any 0+ characters but a newline (BETTER: since the URL cannot have a space (usually), you can replace it with \S* matching zero or more non-whitespace characters). So, a better alternative: (https?:\/\/)?(w{3}\.)?\bfacebook\.com\/[^\/.]*\.\S*
{ "pile_set_name": "StackExchange" }
Q: Check if Usercontrol previously loaded on page Is there a way, within a .Net user control, to check if the control has been previously loaded on the page? I thought about trying storing a variable in a .Net session variable to track each control as it loads, then disposing of the variable in the page pre-render event. It seems to me that there has to be a better way to accomplish this. The reason I need to do this is because the usercontrols are loaded as sublayouts within sitecore, and I have no idea how many times a content author may have added the control to the page. If it is the first time the control is being called to the page I need to add a write out a div tag for a 3rd party service. If the div tag occurs more than once, the 3rd party service, gawks. A: Just use HttpContext.Current.Items to keep the information about loaded control. As the name indicates, HttpContext.Current is only for a single web request. No need to worry about disposing or clearing old data. if (HttpContext.Current.Items["I was here"] == null) { // do custom div magic HttpContext.Current.Items["I was here"] = true; }
{ "pile_set_name": "StackExchange" }
Q: php sum values of form check boxes when checked I have a form in php that displays checkboxes. These checkboxes are associated with a numerical value populated from mysql. What I'm looking to do is add the values of each checkbox, but only if the box is checked. The problem I am running into is no matter which boxes I have checked, the value from the first checkbox(es) are returned. For example, if there are 5 total checkboxes and I select the bottom 2, the returned sum is for the 2 top boxes not the bottom boxes. It seems my php code knows boxes are being checked, but just doesn't know which boxes are being checked. Here is my form code echo "<input type=\"hidden\" name=\"ID[]\" value=\"".$row['ID']."\" />"; echo "<tr><td>&nbsp;<input type=\"checkbox\" name=\"checked[]\" value=\"Y\"></td>"; echo "<input type=\"hidden\" name=\"amount[]\" value=\"".$row['amount']."\" />"; and here is my post if('POST' == $_SERVER['REQUEST_METHOD']) { $amt = 0; $totamt = 0; foreach($_POST['ID'] as $i => $id) { $id = mysql_real_escape_string($id); $checked = mysql_real_escape_string($_POST['checked'][$i]); $amt = mysql_real_escape_string($_POST['amount'][$i]); if ($checked == "Y") { $totamt = $totamt + $amt; $amt = 0; } } echo $totamt; } Thank you for your help. A: The only checkboxes that are sent from the form are the ones that are checked, and the array indexes will start from 0 no matter which ones they are. So there's no correspondence between the indexes of the checkboxes and the indexes of the hidden fields. There are a few ways to deal with this. One way is to put explicit indexes in the checkbox names: echo "<tr><td>&nbsp;<input type=\"checkbox\" name=\"checked[".$row['ID']."]\" value=\"Y\"></td>"; echo "<input type=\"hidden\" name=\"amount[".$row['ID']."]\" value=\"".$row['amount']."\" />"; Then you can add up: $totamt += $_POST['amount'][$_POST['checked'][$i]]; Another way is to put the amounts directly in the value of the checkboxes, instead of the useless Y value: echo "<tr><td>&nbsp;<input type=\"checkbox\" name=\"checked[]\" value=\"".$row['amount']."\" /></td>"; Then you do: $totamt += $_POST['checked'][$i]; A third way is to put explicit indexes in the names of all the fields, instead of letting PHP assign them when the form is submitted: echo "<input type=\"hidden\" name=\"ID[".$i."]\" value=\"".$row['ID']."\" />"; echo "<tr><td>&nbsp;<input type=\"checkbox\" name=\"checked[".$i."]\" value=\"Y\"></td>"; echo "<input type=\"hidden\" name=\"amount[".$i."]\" value=\"".$row['amount']."\" />"; where $i is a variable that you increment as you're generating the form. This will make the indexes work the way your form code expects.
{ "pile_set_name": "StackExchange" }
Q: How to remove JDK 7 and install JDK 8 in Linux Mint? JDK 7 is already installed in Linux Mint by default. I want to remove it and to install JDK 8 instead. I youtubed and i found a tutorial. I followed it. What i did was, first i downloaded JDK from http://www.oracle.com. after that, tar -zxvf jdk1.8* mv jdk1.8* /usr/lib/java/ sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/java/jdk1.8.0_45/bin/java" 1 sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/java/jdk1.8.0_45/bin/javac" 1 sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/java/jdk1.8.0_45/bin/javaws" 1 Also i appended bellow codes to /etc/profile export JAVA_HOME=/usr/lib/java/jdk1.7.0_65 set PATH="$PATH:$JAVA_HOME/bin" export PATH After a reboot, an error was displayed something related to environment variables that i appended to /etc/profile. So i removed those commands from the /etc/profile and tried codes in a terminal. No errors, but java -version still gives the old version of Java. A: You have to run this command: sudo update-alternatives --config java and select the proper number of java 8 (es. 1). Then the command: java -version should return the java version you wanted
{ "pile_set_name": "StackExchange" }
Q: Conditional merge on in pandas My question in simple I am using pd.merge to merge two df . Here's the line of code: pivoted = pd.merge(pivoted, concerned_data, on='A') and I want the on='B' whenever a row has column A value as null. Is there a possible way to do this? Edit: As an example if df1: A | B |randomval 1 | 1 | ty Nan| 2 | asd df2: A | B |randomval2 1 | Nan| tyrte 3 | 2 | asde So if on='A' and the value is Nan is any of the df (for a single row) I want on='B' for that row only Thank you! A: You could create a third column in your pandas.DataFrame which incorporates this logic and merge on this one. For example, create dummy data df1 = pd.DataFrame({"A" : [1, None], "B" : [1, 2], "Val1" : ["a", "b"]}) df2 = pd.DataFrame({"A" : [1, 2], "B" : [None, 2], "Val2" : ["c", "d"]}) Create a column c which has this logic df1["C"] = pd.concat([df1.loc[~df1.A.isna(), "A"], df1.loc[df1.A.isna(), "B"]],ignore_index=False) df2["C"] = pd.concat([df2.loc[~df2.A.isna(), "A"], df2.loc[df2.A.isna(), "B"]],ignore_index=False) Finally, merge on this common column and include only your value columns df3 = pd.merge(df1[["Val1","C"]], df2[["Val2","C"]], on='C') In [27]: df3 Out[27]: Val1 C Val2 0 a 1.0 c 1 b 2.0 d
{ "pile_set_name": "StackExchange" }
Q: iteritems() DateFrame output mechanics and append() output into a new DataFrame Ok, enough is enough. I need help with this iteritems() and append() procedeure... Here we have some Time Series Price Data for barrels of Beer, and Whiskey... Beer Whiskey Date 1978-12-29 22.60 86.50 1979-01-02 22.68 86.52 1979-01-03 21.86 87.41 1979-01-04 22.32 87.54 1979-01-05 22.55 87.49 1979-01-08 22.31 87.21 1979-01-09 22.40 87.61 1979-01-10 22.07 87.64 1979-01-11 22.07 88.12 1979-01-12 21.76 88.04 What I am trying to do is create rolling 5 day return values from this data. I have been using the iteritems() function and I am getting the right numbers. The first part that I don't understand is why this function repeats the output as many times as there are columns in the DataFrame (minus the index). This is the code and output... for value in test.iteritems(): print(((test - test.shift(5))*100)/test.shift(5)) OUTPUT Beer Whiskey Date 1978-12-29 NaN NaN 1979-01-02 NaN NaN 1979-01-03 NaN NaN 1979-01-04 NaN NaN 1979-01-05 NaN NaN 1979-01-08 -1.283186 0.820809 1979-01-09 -1.234568 1.259824 1979-01-10 0.960659 0.263128 1979-01-11 -1.120072 0.662554 1979-01-12 -3.503326 0.628643 Beer Whiskey Date 1978-12-29 NaN NaN 1979-01-02 NaN NaN 1979-01-03 NaN NaN 1979-01-04 NaN NaN 1979-01-05 NaN NaN 1979-01-08 -1.283186 0.820809 1979-01-09 -1.234568 1.259824 1979-01-10 0.960659 0.263128 1979-01-11 -1.120072 0.662554 1979-01-12 -3.503326 0.628643 Any ideas why this exact output is repeated? NEXT, I create a new DataFrame and I ask (very nicely!) to append this output into the dataframe. Here is the code... for value in test.iteritems(): df.append(((test - test.shift(5))*100)/test.shift(5)) This is the error I receive... TypeError Traceback (most recent call last) <ipython-input-133-006bdc416056> in <module>() 1 for value in test.iteritems(): ----> 2 df.append(((test - test.shift(5))*100)/test.shift(5)) TypeError: append() missing 1 required positional argument: 'other' My research says that this 'other' TypeError occurs when there is a reference missing in the code. I have tried different combinations of "key, value" with no avail. Further, the print function seems to not have any issues. Please let me know if you have any ideas. Thanks in advance A: pandas.iteritems iterates over pairs of the form name, column (series to be more precise), you can check that by looking at this example for value in test.iteritems(): print(value[0]) This outputs Beer Whiskey That's why you see multiple outputs of the same frame. A simple solution to your problem is returns = 100 * test.diff(5) / test.shift(5) print(returns) Beer Whiskey Date 1978-12-29 NaN NaN 1979-01-02 NaN NaN 1979-01-03 NaN NaN 1979-01-04 NaN NaN 1979-01-05 NaN NaN 1979-01-08 -1.283186 0.820809 1979-01-09 -1.234568 1.259824 1979-01-10 0.960659 0.263128 1979-01-11 -1.120072 0.662554 1979-01-12 -3.503326 0.628643
{ "pile_set_name": "StackExchange" }
Q: Command line doesn't refresh immidately after carriage return I have a code which does something similar to this one. while(1){ printf("Telegrams received %d\r",telegrams); //notice \r telegrams++; sleep(); // for 0.2s } The output from this is one line in a command line which is being updated. However my problem is, that the line isn't updated after every telegram, but only after every 17... (which takes something like 3 seconds). Is there any way, how to make this work to change every 0.2 seconds? (when I press enter, there is displayed everything...) I'm running this on raspberry pi with raspbian. Thanks A: Found an answer - I need to use fflush(stdout) after every printf.
{ "pile_set_name": "StackExchange" }
Q: Conditional formatting based on comparison of two values I have created a table in which I have Project Name, its planned budget and its actual budget. I want to highlight those rows in which the actual budget is exceeding the planned budget. Conditional Formatting is not helping in this scenario. A: It's not yet possible in Power BI. Related feature requests can be found here: Conditional formatting (cell highligh, font, etc) when comparing multiple fields Conditional Formatting - Whole Table Rows
{ "pile_set_name": "StackExchange" }
Q: Largest n digit octal number What will be the largest n digit octal number. I think $$\text{ for } n = 1 , \text{ans} = 7$$ $$\text{ for } n = 2 , \text{ans} = 77$$ $$\text{ for } n = 3 , \text{ans} = 777$$ So am I correct ? And it's general ans will be $$\frac{7.10^n - 1}{9}$$ I just want to know that if i am making correct formula or not? A: The largest $3$-digit octal number is indeed $777$, but only if this is interpreted as base $8$. To make this explicit, we can write it as $777_8$. So the largest $3$-digit octal number is $$777_8 = 7 \times 64_{10}+7\times 8 + 7 = 511_{10}$$ This is not the same as $7\times (10^3-1)/9=777_{10}$.
{ "pile_set_name": "StackExchange" }
Q: Calculate sum of two columns in order by clause - laravel I'm trying to convert the below mysql query into laravel equivalent. select email from emails order by call_count + receive_count desc; to Laravel DB::table('emails') ->select('email') ->orderBy(SUM('call_count','receive_count'), 'DESC') ->get(); Please let me know.. Thanks A: Try this DB::table('emails') ->select('email') ->orderBy(DB::raw("`call_count` + `receive_count`"), 'desc') ->get();
{ "pile_set_name": "StackExchange" }
Q: Duplicate-free version of array of objects I implemented a function that creates a duplicate-free version of an array, but it doesn't work for array of objects. I don't understand and I can't find information how to fix it. My function: function uniq(array) { var length = array.length; if (!length) { return; } var index = 0; var result = []; while (index < length) { var current = array[index]; if (result.indexOf(current) < 0) { result.push(current); } index++; } return result; } Example: var my_data = [ { "first_name":"Bob", "last_name":"Napkin" }, { "first_name":"Billy", "last_name":"Joe" }, { "first_name":"Billy", "last_name":"Joe", } ] uniq([1, 1, 2, 3]) // => [1, 2, 3] uniq(my_data) // => [ { "first_name":"Bob", "last_name":"Napkin" }, { "first_name":"Billy", "last_name":"Joe" }, { "first_name":"Billy", "last_name":"Joe" } ] Do you know someone how to creates a duplicate-free version of array of objects? A: indexOf() in javascript does not perform a deep comparison of objects. On top of that, any two objects that are created will never be "equal" to each other. If you do: var a = {}; var b = {}; a == b; //false a === b; //false You need to perform a deep comparison against all values (if that's even what you're looking to do, because there could be other equalities you're looking for). I won't go into how to do a deep comparison because, well, Google.
{ "pile_set_name": "StackExchange" }
Q: Using ecto to store custom information I am re-implementing an application I originally wrote in Rails in Phoenix in which users can create custom fields using PostgreSQL's JSONB record type. As an example, we have the following (simplified representation) schema: Client ID (int) Client Type ID (int) Name (string) Info (jsonb) Client Type ID (int) Name (string) Custom field definition ID (int) Client Type ID (int) Key (string) Label (string) In Rails, ActiveRecord magically converts JSONB to and from a hash, which allows me to use JSONB to very easily to store a schemaless set of custom fields. For example, each client type can define different custom field, and then when I display the information to the user, I loop through the definitions to get the keys, which I then use to get the data out of the JSONB document. I was trying to figure out a way to accomplish this using Ecto, and it looks like I should be looking at an embedded schema (I saw some good info here), however I don't think from looking at it that I can define a custom amount of fields to this at run-time, can I? I was just looking for some advice on this, as so far this is the only real road block I have come across that isn't solved almost immediately. Thanks again, I appreciate it! A: I was able to resolve this by changing my data structure a bit. The custom fields are now a JSONB array, which allows me to do an embeds_many relationship which is pretty elegant. I actually have not read the documentation at the link (http://blog.plataformatec.com.br/2015/08/working-with-ecto-associations-and-embeds/) closely enough, and after I did I realized my data wasn't really structured enough. So, instead of having a JSONB column that looks like { "name":"Something", "address":"123 Fake St" } it looks like [ { "field":"name", "value":"Something" }, { "field":"address", "value":"123 Fake St" }, ] This seems to be the best option for my use case, however it does take up a lot more space (since Ecto adds a required ID field to each object behind the scenes to ensure integrity). After changing to this structure, I simply created a model and associated them per the link. In a nutshell, it looks like this: defmodule UserManager.CustomField do use Ecto.Model embedded_schema do field :field field :value end @required_fields ~w(field value) @optional_fields ~w() @doc """ Creates a changeset based on the `model` and `params`. If no params are provided, an invalid changeset is returned with no validation performed. """ def changeset(model, params \\ :empty) do model |> cast(params, @required_fields, @optional_fields) end end defmodule UserManager.Client do # ... schema "clients" do # ... embeds_many :custom_fields, UserManager.CustomField # ... end # ... end
{ "pile_set_name": "StackExchange" }
Q: Diffeomorphism $f:U\to V$ then $Df:\mathbb{R^n}\to\mathbb{R^m}$ will be linear isomorphism hence $n=m$ ${\large let \ U\subset \mathbb{R^n,}V\subset \mathbb{R^m}}$ be open subsets. map $f:{\large U }\to{\large V }$ is called a diffeomorphism if is bijective and both $f$ and $f^{-1}$ are continuously differentiable. once there is diffeomorphism $f:{\large U }\to{\large V }$ then $Df:\mathbb{R^n}\to\mathbb{R^m}$ will be ${\large linear \ isomorphism }$ hence $n=m$. how is this a linear isomorphism??. i know $Df(a)$ is a linear map , but why this is one one and on to ?? A: Hint: What do you get when you apply the chain rule to $$f \circ f^{-1} = \text{Id}?$$ A: $f\circ f^{-1}=Id, f^{-1}\circ f=Id$ implies $Df\circ Df^{-1}=Id, Df^{-1}\circ Df=Id$. It implies $Df$ is an isomorphism.
{ "pile_set_name": "StackExchange" }
Q: DataGridViewColumn.Frozen with mono 2.10 I have a problem with Method DataGridViewColumn.Frozen with mono on Linux, and googling this problem doesn't helps me. I'm need to freeze couple of columns of DataGridView within C# mono application, and on Windows it's working as expected, but any time i copying my binary to Linux PC, method Frozen doesn't work at all. I have tried Columns[index].Frozen and Columns[name].Frozen both before and after filling the DataGridView. Is this a bug of my mono version, or i need some additional code to make this work? I'm using mono 2.10 (unfortunately, i cannot upgrade it) on SUSE Linux. UPD Made a simple application and tested it on mono 4.6.2: same with 2.10, method Frozen doesn't work. Code of testing app: DataTable _tbl = new DataTable(); _tbl.Columns.Add("Name", typeof(String)); _tbl.Columns.Add("val1", typeof(String)); _tbl.Columns.Add("val2", typeof(String)); _tbl.Rows.Add("1", "val11", "val22"); _tbl.Rows.Add("2", "val11", "val22"); dgvVars.DataSource = _tbl; dgvVars.Columns["Name"].Frozen = true; dgvVars.Columns[0].Frozen = true; A: Windows Forms is implemented in Mono on the top of System.Drawing. Thus, it is more or less easy to follow the code since there are not P/Invokes. At the time of writing (February, 2018), I have not found a mention to the property Frozen in the DataGridView.cs file. Also, I've found DataGridViewTest.cs in searchcode.com. If you do a text search for Frozen, you'll find: // /* NIE for the moment... */ Assert.AreEqual (true, cell.Frozen, "#cell.Frozen"); I think this means that Frozen is not implemented. Since Windows Forms has been abandoned by Xamarin, I would not expect to have that fixed anytime soon. I'm afraid you will have to implement it yourself. Hope this (somehow) helps.
{ "pile_set_name": "StackExchange" }
Q: distribute a usable python program to a python which doesn't have Distribute installed? How to distribute a usable python program to a python which doesn't have Distribute installed? I've created a Windows Binary installer using python setup.py bdist_wininst. The setup.py contains a console script entry point, so that a Windows .exe file is created and placed in %python%\Scripts on the destination machine, as per Automatic Script Creation. However running the installed script on a machine with a virgin python install yields: D:\Py3.2.5> scripts\foo.exe Traceback (most recent call last): File "D:\Py3.2.5\scripts\foo-script.py", line 5, in <module> from pkg_resources import load_entry_point ImportError: No module named pkg_resources No module named pkg_resources tells me this error is because Distribute is not installed. How do I get my installer to include Distribute so I don't have to tell our users "before you install our program you have to go install this other program"? A: Ahh, finally found something: Your users might not have setuptools installed on their machines, or even if they do, it might not be the right version. Fixing this is easy; just download distribute_setup.py, and put it in the same directory as your setup.py script. (Be sure to add it to your revision control system, too.) Then add these two lines to the very top of your setup script, before the script imports anything from setuptools: import distribute_setup distribute_setup.use_setuptools() That’s it. The distribute_setup module will automatically download a matching version of setuptools from PyPI, if it isn’t present on the target system. Whenever you install an updated version of setuptools, you should also update your projects’ distribute_setup.py files, so that a matching version gets installed on the target machine(s).
{ "pile_set_name": "StackExchange" }
Q: display database variables in file So I had my variables all hard coded into my page like so: $base_url = 'something'; $logo_url = 'somethingelse'; And then I went and put all these into a database for easier updating, Now I need to place them back into the config.php file so my website can use them. I tried doing the following: (database.php includes all the connection details) function get_identifiers() { require_once 'database.php'; $result = mysqli_query($con,"SELECT * FROM settings"); while($row = mysqli_fetch_array($result)) { $identifier = $row['identifier']; $value = $row['value']; $identifier = $value } mysqli_close($con); } But I got nothing. What can I do? A: You should set your identifiers in an array, return it, and then extract it: require_once 'database.php'; function get_identifiers() { $retval = array(); $result = mysqli_query($con,"SELECT * FROM settings"); while($row = mysqli_fetch_array($result)) { $identifier = $row['identifier']; $value = $row['value']; $retval[$identifier] = $value; } mysqli_close($con); return $retval; } Then run this on your page: extract(get_identifiers()); This will change all of your settings into variables, as you want.
{ "pile_set_name": "StackExchange" }
Q: How to set VB Application Proxy Settings to Default System Proxy Settings My application is supposed to work on a Company Network where proxy is enabled, By default when logged in all applications like browser and all can access internet normally But when i open my application "The remote server returned an error [407] Proxy Authentication Required" error is coming In normal internet connected PC it works well Is there any way to set manual proxy or more preferably set the system proxy as default to the application I am too novice in the programming field My code is Dim PartURL As String = "http://www.google.com" Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(PartURL) Dim response As System.Net.HttpWebResponse = request.GetResponse() Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream()) Dim sourcecode As String = sr.ReadToEnd() SearchPageSource = sourcecode Also my proxy settings is Address: abcserver04 Port: 8080 Ipconfig output on cmd prompt is Ethernet adapter local area connection Connection Specific DNS Suffix : abc.defgroup.net IP Address : 10.4.8.xx Subnet Mask : 255.255.255.0 Default Gateway : 10.4.8.254 A: Try this... request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
{ "pile_set_name": "StackExchange" }
Q: Cells gets overlapped and painted when Scroll happens in DataGridView Initially I display data in cells as user scrolls I need to load more data in DataGridView. I am using DataGridView CellPainting for drawing lines. When I start scrolling in datagridview the cells get overlapped and it completely changes the output. public partial class Display : Form { public Display() { InitializeComponent(); LoadData(); } // To create the rows and columns and fill some data private void LoadData() { int columnSize = 10; DataGridViewColumn[] columnName = new DataGridViewColumn[columnSize]; for (int index = 0; index < columnSize; index++) { columnName[index] = new DataGridViewTextBoxColumn(); if (index == 0) { columnName[index].Name = "Name"; columnName[index].HeaderText = "Name"; } else { columnName[index].Name = (index).ToString(); columnName[index].HeaderText = (index).ToString(); } columnName[index].FillWeight = 0.00001f; columnName[index].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; dataGridView1.Columns.Add(columnName[index]); } for (int rowIndex = 0; rowIndex < columnSize; rowIndex++) { dataGridView1.Rows.Add((rowIndex + 1).ToString()); dataGridView1.Rows[rowIndex].HeaderCell.Value = (rowIndex + 1).ToString(); } } private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { Rectangle rectPos1 = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false); Pen graphPen = new Pen(Color.Red, 1); Graphics graphics = this.dataGridView1.CreateGraphics(); Point[] points = { new Point(rectPos1.Left , rectPos1.Bottom), new Point(rectPos1.Right, rectPos1.Bottom), new Point(rectPos1.Right, rectPos1.Top) }; graphics.DrawLines(graphPen, points); e.PaintContent(rectPos1); e.Handled = true; } } Sample Download Link Which I have shown in the below image How can i avoid it please help me solve this issue. A: A couple of issues. First and foremost, you should almost always use the provided Graphics object you get from the PaintEventArgs. CreateGraphics is a temporary canvas that gets easily erased. One of the parameters you get is the CellBounds rectangle, so you can use that. Your lines are actually drawing outside of the rectangle, and you aren't clearing the previous contents, so your code should look something like this: Rectangle rectPos1 = e.CellBounds; e.Graphics.FillRectangle(Brushes.White, rectPos1); Graphics graphics = e.Graphics; // this.dataGridView1.CreateGraphics(); Point[] points = { new Point(rectPos1.Left , rectPos1.Bottom - 1), new Point(rectPos1.Right - 1, rectPos1.Bottom - 1), new Point(rectPos1.Right - 1, rectPos1.Top) }; graphics.DrawLines(Pens.Red, points); e.PaintContent(rectPos1); e.Handled = true;
{ "pile_set_name": "StackExchange" }
Q: Promisifying xml2js parse function (ES6 Promises) I'm trying to refactor some node code that is a whole mess of callbacks. I thought that would be nice give promises a try for this purpose. I'm trying to convert some xml string to json with the xml2js node module. The original code was: "use strict"; var xml2jsParser = require('xml2js').parseString; var string = "<container><tag3>option3</tag3></container>"; xml2jsParser(string, function(err, result) { console.log(result); }); and this displays: { container: { tag1: [ 'option1' ], tag2: [ 'option2' ], tag3: [ 'option3' ] } } Following the first answer on this question How do I convert an existing callback API to promises? I tried to wrap the xml2jsParser function using promises in the following way: "use strict"; var xml2jsParser = require('xml2js').parseString; function promisesParser(string) { return new Promise(function(resolve, reject) { xml2jsParser(string, resolve); }); } var string = "<container><tag3>option3</tag3></container>"; promisesParser(string).then(function(err, result){ console.log(result); }); This displays undefined through the console instead of the json object as expected. I don't understand why this happens as I was able to successfully do the same with other functions. I know something similar can be achieved with Bluebird promisify functionality but I'd like to do this on plain Javascript without any third party libraries. A: Another option is to use native util module's promisify method, available from Node 8.0: const xml2js = require('xml2js'); const util = require('util'); xml2js.parseStringPromise = util.promisify(xml2js.parseString); // await xml2js.parseStringPromise(.. your xml ..); A: You are going to need to wrap it up like this: return new Promise(function(resolve, reject) { xml2jsParser(string, function(err, result){ if(err){ reject(err); } else { resolve(result); } }); }); Then use it like this: promisesParser(string).then(function(result){ console.log(result); }).catch(function(err){ //error here }); A: There are 2 issues... You have to resolve with a value if it passes...and reject with an error when it fails You need to add a catch block to you promise handling chain to catch errors. var xml2jsParser = require('xml2js').parseString; function promisesParser(string) { return new Promise(function(resolve, reject) { xml2jsParser(string, function(err, result) { if (err) { return reject(err); } else { return resolve(result); } }); }); } var string = "<container><tag3>option3</tag3></container>"; promisesParser(string) .then(console.log) .catch(console.log);
{ "pile_set_name": "StackExchange" }
Q: Angular 5 - routing with wildcard I try to define a specific route in my module, but I don't know how to manage that : http://myserver.com/prefix-randomname/mycomponent randomname is a real random name with random chars, generated for only one session. I only know the prefix. But I want to open a route leading to mycomponent. Last but not least, I cannot remove prefix-randomname in the url, because the server will not work without that. A: Not entirely sure if it will work for you, but you can change the baseUrl at app initialisation using the APP_BASE_HREF constant. import {APP_BASE_HREF} from '@angular/common'; export function appBaseFactory(appInitService: AppInitializationService): () => string { return (): string => `/${location.pathname.split('/')[1]}` } @NgModule({ // ..., providers: [{provide: APP_BASE_HREF, useFactory: appBaseFactory}] ]) export class AppModule {} I believe this will keep your router happy If the appBaseFactory doesn't work, you might want to change it to immediately return the location.pathname stuff, instead of returning a Function
{ "pile_set_name": "StackExchange" }
Q: Trying to insert characters while using a KeyListener private void KeyAction(java.awt.event.KeyEvent evt) { if (evt.getKeyCode() == 91) { int pos = txt.getCaretPosition(); txt.insert("}",pos); } } The function is currently showing But why it's showing }{, but I'm expecting the output to be {}. How can I fix this? A: How about: txt.insert("}", pos + 1); Pos is the position of the current character. Inserting at pos puts the inserted item in front of the current character. For your code, the output you see is the expected result. Try inserting after the current character.
{ "pile_set_name": "StackExchange" }
Q: How can we use two types of UICollectionViewCell for a single UICollectionView? I have two types of UICollectionViewCell : one is gallery cell and another is recipe cell. There is a toggle button. First time the view loads, gallery cell is used to display in collection view. But on clicking the toggle button, I tried to load another cell:(recipe cell) but it crashed saying there is no property(actually this is the property of recipe cell) in gallery cell. Is there a way to load same collection view with another cell?? Thanks in advance. EDIT: if (isGalleryOnCollectionView) { ProfileFollowerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; NSString *followerName; if ([[arr_followerNames objectAtIndex:indexPath.row] isEqualToString:@""]) { followerName=[arr_followersEmail objectAtIndex:indexPath.row]; } else{ followerName=[arr_followerNames objectAtIndex:indexPath.row]; } NSLog(@"\n\n\n follower name is :: %@\n\n",followerName); cell.lbl_followerName.text = followerName; }else{ GalleryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; cell.lbl_recipeName.text = [[[dict_profileData valueForKey:@"recipes"] valueForKey:@"name"] objectAtIndex:indexPath.row]; } SOLUTION: [self.profleCollectionView registerClass:[ProfileFollowerCell class] forCellWithReuseIdentifier:@"followercell"]; After registering from the nib before dequeuing reusable identifier it works. A: Here is a good tutorial on creating custom UICollectionViewCell with xibs. What your missing is having this in your -(void)viewDidLoad UINib *cellNib = [UINib nibWithNibName:@"ProfileFollowerCellNib" bundle:nil]; [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"TheNibCellIdentifier"]; You also need to make sure to use the respective ReuseIdentifier when loading the cell: ProfileFollowerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TheNibCellIdentifier" forIndexPath:indexPath];
{ "pile_set_name": "StackExchange" }
Q: fast way to separate list of list into two lists I have got quite a good experience with C programming and I am used to think in terms of pointers, so I can get good performance when dealing with huge amount of datas. It is not the same with R, which I am still learning. I have got a file with approximately 1 million lines, separated by a '\n' and each line has got 1, 2 or more integers inside, separated by a ' '. I have been able to put together a code which reads the file and put everything into a list of lists. Some lines can be empty. I would then like to put the first number of each line, if it exists, into a separated list, just passing over if a line is empty, and the remaining numbers into a second list. The code I post here is terribly slow (it has been still running since I started wrote this question so now I killed R), how can I get a decent speed? In C this would be done instantly. graph <- function() { x <- scan("result", what="", sep="\n") y <- strsplit(x, "[[:space:]]+") #use spaces for split number in each line y <- lapply(y, FUN = as.integer) #convert from a list of lists of characters to a list of lists of integers print("here we go") first <- c() others <- c() for(i in 1:length(y)) { if(length(y[i]) >= 1) { first[i] <- y[i][1] } k <- 2; for(j in 2:length(y[i])) { others[k] <- y[i][k] k <- k + 1 } } In a previous version of the code, in which each line had at least one number and in which I was interested only in the first number of each line, I used this code (I read everywhere that I should avoid using for loops in languages like R) yy <- rapply(y, function(x) head(x,1)) which takes about 5 second, so far far better than above but still annoying if compared to C. EDIT this is an example of the first 10 lines of my file: 42 7 31 3 23 1 34 5 1 -23 -34 2 2 42 7 31 3 31 4 1 A: Base R versus purrr your_list <- rep(list(list(1,2,3,4), list(5,6,7), list(8,9)), 100) microbenchmark::microbenchmark( your_list %>% map(1), lapply(your_list, function(x) x[[1]]) ) Unit: microseconds expr min lq mean median uq max neval your_list %>% map(1) 22671.198 23971.213 24801.5961 24775.258 25460.4430 28622.492 100 lapply(your_list, function(x) x[[1]]) 143.692 156.273 178.4826 162.233 172.1655 1089.939 100 microbenchmark::microbenchmark( your_list %>% map(. %>% .[-1]), lapply(your_list, function(x) x[-1]) ) Unit: microseconds expr min lq mean median uq max neval your_list %>% map(. %>% .[-1]) 916.118 942.4405 1019.0138 967.4370 997.2350 2840.066 100 lapply(your_list, function(x) x[-1]) 202.956 219.3455 264.3368 227.9535 243.8455 1831.244 100 purrr isn't a package for performance, just convenience, which is great but not when you care a lot about performance. This has been discussed elsewhere. By the way, if you are good in C, you should look at package Rcpp.
{ "pile_set_name": "StackExchange" }
Q: Using blank-line delimited records and colon-separated fields in awk I'd like to be able to work with a file in awk where records are separated by a blank line and each field consists of a name followed by a colon, some optional whitespace to be ignored/discarded, followed by a value. E.g. Name: Smith, John Age: 42 Name: Jones, Mary Age: 38 Name: Mills, Pat Age: 62 I understand that I can use RS="" to have awk understand the blank-lines as record separators and FS="\n" to split the fields properly. However, I'd like to then create an array of name→value pairs that I can use for further processing of the form if a["Age"] > 40 {print a["Name"]} The order is usually consistent, but since it would be dumped in an associative array, the incoming order shouldn't matter or be assumed consistent. How can I transform the data into an awk associative array with the least fuss? A: Method 1 We use split to split each field into two parts: the key and the value. From these, we create associative array a: $ awk -F'\n' -v RS= '{for (i=1;i<=NF;i++) {split($i,arr,/: /); a[arr[1]]=arr[2];} if (a["Age"]+0>40) print a["Name"];}' file Smith, John Mills, Pat Method 2 Here, we split fields at either a colon or a newline. Then, we know that the odd numbered fields are keys and the even ones the values: $ awk -F':|\n' -v RS= '{for (i=1;i<=NF;i+=2) {a[$i]=$(i+1);} if (a["Age"]+0>40) print a["Name"];}' file Smith, John Mills, Pat Improvement Is there a chance that any record will be missing a value? If so, we should clear the array a between each record. In GNU awk, this is easy. We just add a delete statement: awk -F':|\n' -v RS= '{delete a; for (i=1;i<=NF;i+=2) {a[$i]=$(i+1);} if (a["Age"]+0>40) print a["Name"];}' file For other awks, you may be required to delete the array one element at a time like: for (k in a) delete a[k];
{ "pile_set_name": "StackExchange" }
Q: why GRPC AsyncClient throws Segfault when waiting for the Next result in the completion queue I am using version 1.23.1 of the GRPC library. I have an asynchronous RPC c++ Client class, which initiates each RPC with the following method: void Client::SendTaskAsync(const Task& task) { unique_lock<mutex> lock(mtx_); cout << "Sending task with id " << task.id() << endl; ClientContext context; Status status; unique_ptr<ClientAsyncResponseReader<Result>> rpc( stub_->PrepareAsyncSendTask(&context, task, &queue_)); rpc->StartCall(); // Allocating memory to store result from RPC Result* result = &results_.emplace_back(); int* tag = new int(results_.size() - 1); rpc->Finish(result, &status, static_cast<void*>(tag)); } In the main thread I call SendTaskAsync five times in a loop. The Client class has a background thread informing when each RPC has returned a Result: while (true) { void* tag; bool ok = false; { unique_lock<mutex> lock(mtx_); cout << "Waiting the for next result" << endl; const time_point<system_clock> deadline = system_clock::now() + milliseconds(1000); // SEGFAULT HERE, WHY? GPR_ASSERT(queue_.AsyncNext(&tag, &ok, deadline)); } if (ok) { int index = *static_cast<int*>(tag); cout << "Got result with tag " << index << endl; } else { cout << "Sleeping" << endl; sleep_for(milliseconds(1000)); } } If I start my client, the following log is observed: BACKGROUND: Waiting for the next result MAIN THREAD: Sending task with id 0 BACKGROUND: Sleeping MAIN THREAD: Sending task with id 1 MAIN THREAD: Sending task with id 2 MAIN THREAD: Sending task with id 3 MAIN THREAD: Sending task with id 4 BACKGROUND: Waiting for the next result BACKGROUND: Segmentation fault (core dumped) What happens is that Background thread checks if a queue_ contains a result, there is none yet, so it goes to sleep; Main thread makes 5 RPC that at the end should populate the queue_ with results; Background thread wakes up and checks if a queue_ contains a result, AND CRASHES. Any ideas why? A: The code in the question is written according to this tutorial, which sends only one request and waits for a reply in the same thread. If you want to use multiple threads, follow the client example here.
{ "pile_set_name": "StackExchange" }
Q: How to mimic Python modules without import? I’ve tried to develop a « module expander » tool for Python 3 but I've some issues. The idea is the following : for a given Python script main.py, the tool generates a functionally equivalent Python script expanded_main.py, by replacing each import statement by the actual code of the imported module; this assumes that the Python source code of the imported is accessible. To do the job the right way, I’m using the builtin module ast of Python as well as astor, a third-party tool allowing to dump the AST back into Python source. The motivation of this import expander is to be able to compile a script into one single bytecode chunk, so the Python VM should not take care of importing modules (this could be useful for MicroPython, for instance). The simplest case is the statement: from import my_module1 import * To transform this, my tool looks for a file my_module1.py and it replaces the import statement by the content of this file. Then, the expanded_main.py can access any name defined in my_module, as if the module was imported the normal way. I don’t care about subtle side effects that may reveal the trick. Also, to simplify, I treat from import my_module1 import a, b, c as the previous import (with asterisk), without caring about possible side effect. So far so good. Now here is my point. How could you handle this flavor of import: import my_module2 My first idea was to mimic this by creating a class having the same name as the module and copying the content of the Python file indented: class my_module2: # content of my_module2.py … This actually works for many cases but, sadly, I discovered that this has several glitches: one of these is that it fails with functions having a body referring to a global variable defined in the module. For example, consider the following two Python files: # my_module2.py g = "Hello" def greetings(): print (g + " World!") and # main.py import my_module2 print(my_module2.g) my_module2.greetings() At execution, main.py prints "Hello" and "Hello World!". Now, my expander tool shall generate this: # expanded_main.py class my_module2: g = "Hello" def greetings(): print (g + " World!") print(my_module2.g) my_module2.greetings() At execution of expanded_main.py, the first print statement is OK ("Hello") but the greetings function raises an exception: NameError: name 'g' is not defined. What happens actually is that in the module my_module2, g is a global variable, in the class my_module2, g is a class variable, which should be referred as my_module2.g. Other similar side effects happens when you define functions, classes, … in my_module2.py and you want to refer to them in other functions, classes, … of the same my_module2.py. Any idea how these problems could be solved? Apart classes, are there other Python constructs that allow to mimic a module? Final note: I’m aware that the tool should take care 1° of nested imports (recursion), 2° of possible multiple import of the same module. I don't expect to discuss these topics here. A: You can execute the source code of a module in the scope of a function, specifically an instance method. The attributes can then be made available by defining __getattr__ on the corresponding class and keeping a copy of the initial function's locals(). Here is some sample code: class Importer: def __init__(self): g = "Hello" def greetings(): print (g + " World!") self._attributes = locals() def __getattr__(self, item): return self._attributes[item] module1 = Importer() print(module1.g) module1.greetings() Nested imports are handled naturally by replacing them the same way with an instance of Importer. Duplicate imports shouldn't be a problem either.
{ "pile_set_name": "StackExchange" }
Q: Fix for null Navigation Controller when pushing view in didSelectRowAtIndexPath? I have built my table using Storyboards. I have a Table View embedded in a Navigation Controller. My Details View is also a Table View Controller embedded in a Navigation Controller. Here is my code: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NHCDependantDetailsViewController *detailView = [self.storyboard instantiateViewControllerWithIdentifier:@"AddDependant"]; [self.navigationController pushViewController:detailView animated:YES]; } I've discovered that the problem is that my Navigation Controller is null. Unfortunately, I have no idea how or where to correctly fix this. Thank you in advance. EDIT: I have followed the advice below to set the navigation controller as the initial view controller, but now I cannot reach my TableView. Perhaps the problem is evident in this image of my storyboard? Having two nav arrows there can't be good... A: I assume that your storyboard has 1 Table View which is embedded in a Navigation Controller and NHCDependantDetailsViewController which is also embedded in a Navigation Controller. First of all, you need to set the the Navigation Controller of your table view as the initial view controller by ticking "Is Initial View Controller" on the attribute inspector. Secondly, I think it is not necessary to embed NHCDependantDetailsViewController in a Navigation Controller as you can push many view controller to your main navigator controller.
{ "pile_set_name": "StackExchange" }
Q: Infinite loop excel VBA This would appear to be a simple problem yet no matter what I change or edit, I can't seem to fix this issue in a logical way. What I am trying to do is loop through every cell in the range, comparing the contents of the current cell in the loop to the cell above it. If these two cell values are not the same, then I insert 2 new rows. However, instead of 2 new, blank rows being inserted, it takes the contents of the row at rangeCell and inserts that instead. Thus, it gets stuck in an infinite loop because the cell above the one we are checking always equals the current cell value. Why is this happening? Here is the code: For Each rep In repNames() If rep <> vbNullString Then Worksheets(rep).Activate Set repComboRange = Range("A2", Range("A2").End(xlDown)) For Each rangeCell In repComboRange If rangeCell.Value <> rangeCell.Offset(-1, 0).Value And rangeCell.Offset(-1, 0).Value <> vbNullString Then rangeCell.EntireRow.Insert rangeCell.EntireRow.Insert End If Next rangeCell Else: Exit For End If Next rep The particular problem is at this line: rangeCell.EntireRow.Insert rangeCell.EntireRow.Insert This is what should happen: https://gyazo.com/c7f2bf238837fe2e3bca31a4505f6b4e However, this is what is happening:https://gyazo.com/28f8cc028887df565b542cdd7cb04cf2 Any help is hugely appreciated! Thanks guys! A: Is CutCopyMode ("marching ants frame") active? In this case, Excel tries to paste on insert. Use Application.CutCopyMode=0 before the Insert statement to be sure. Otherwise, it should work (works for me at least)... Also, you can speed it up by inserting both rows at once: rangeCell.Resize(2,1).EntireRow.Insert xlShiftDown
{ "pile_set_name": "StackExchange" }
Q: Panel-collapse começar fechado Estou com o seguinte código: https://jsfiddle.net/05913dg4/1/ Eu preciso fazer com que esse collapse, comece fechado. Ou seja, quando abrir a página ele começar fechado, e só depois de clicar ele abrir.... A: É só configurar o HTML como se ele estivesse "colapsado", ou seja. No heading você vai adicionar a classe panel-collapsed; Coloque o icone correspondente ao estado colapsed, fa-angle-down eu imagino; Adicione a propriedade display: none; a classe .panel-body. $(document).on('click', '.panel-heading', function(e){ var $this = $(this); if(!$this.hasClass('panel-collapsed')) { $this.parents('.panel').find('.panel-body').slideUp(); $this.addClass('panel-collapsed'); $this.find('i').removeClass('fa fa-angle-up').addClass('fa fa-angle-down'); } else { $this.parents('.panel').find('.panel-body').slideDown(); $this.removeClass('panel-collapsed'); $this.find('i').removeClass('fa fa-angle-down').addClass('fa fa-angle-up'); } }); .panel-heading { background-color: #6f5499; } .panel-body { background: #f5f5f5; padding: 25px; display: none; } <link href="https://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css" rel="stylesheet"/> <link href="https://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="panel panel-primary"> <div class="panel-heading panel-collapsed"> <h3 class="panel-title" style="padding: 15px;"><center> COMO CHEGAR?</center></h3> <span class="pull-right clickable"><i class="fa fa-angle-down"></i></span> </div> <div class="panel-body" style="padding:0;"> <p>content virá aqui....</p> </div> </div> Fiddle
{ "pile_set_name": "StackExchange" }
Q: Clarify faq on migration I noticed the faq on migration What is migration and how does it work?. Under things to consider when migrating it says Avoid migrating answered questions. The point of migration is to send the question to an on-topic place when it can get answered. If the OP already has an answer, then we've already defeated the purpose of migration and the destination site won't have anything to do with the question. Avoid migrating these questions unless they are of extremely good quality and risk deletion on the current site. Then I saw this question Is it worthwhile to migrate questions that already have accepted answers?. The accepted answer says Yes, absolutely! Those questions belong to the other site, accepted or not, because that's the place where they will be useful for other users in the future. These two are confusing me. Can the faq on migration be clarified more about this issue? A: The latter is better for two reasons: The question is moved to where it belongs. From a purely logical perspective, it makes sense to put the question where it's on-topic, even if it already has an answer. A signal is sent to any potential viewers that the question isn't on-topic here, but is on-topic elsewhere. It indicates to the reader that the sites have defined topics. I'm not going to personally edit the community wiki, though, unless the community agrees with the change. Do remember, though, that the faq posts are written by community-members, and are not official stances on issues. While most of the posts do reflect quorum very well, there is occasionally the sentence or two which does not reflect community consensus. So, while the faq is a very helpful resource, if something seems odd, take it with a grain of salt :]
{ "pile_set_name": "StackExchange" }
Q: How to ensure uniqueness when elasticsearch is inserted in multithreading? We have some documents of elasticsearch . The uniqueness of the document is determined by some fields together, how to ensure uniqueness when java multi-threading determines whether it exists and is inserted. I didn't know what good method I had before, so I wrote a method: I guess if it exists, if it doesn't exist, I insert it, and this method is modified by syncronized. But I found this to be a very inefficient practice. /** * @param document */ synchronized void selectAndInsert(Map<String, Object> document){ //Determine if it exists, insert it if it does not exist } My mapping is as follows: {"properties":{"pt_number":{ "type":"keyword" }, "pt_name":{"type":"keyword" },"pt_longitude":{ "type":"text"},"pt_latitude":{"type":"text" },"rd_code":{ "type":"text" }, "rd_name":{ "type":"keyword"}, "area_code":{ "type":"keyword"} ... and so on }} Uniqueness is determined by area_code, pt_longitude and pt_latitude. When the document is inserted, I will judge whether it exists according to area_code, pt-longitude, pt_latitude, and insert if it does not exist. How do I guarantee the uniqueness of a document when java multithreading is running? This question has plagued me for some time. Who can help me, I will be very grateful. A: There is no way to guarantee there isn't such document just by properties in index in any way. Even if you check it's presence in index and don't see it, there is some time between response for that operation was issued and your indexing request accepted by ES. So basically you have only two ways: Guarantee single execution of indexing operation (long and not-so-easy way because we don't have exactly-once systems) Convert document unique properties into document ID, so even if your indexing operations overlap, they will just write same values into same document (or the second one and following will fail, depending on request options). The latter one is quite easy, you have some options out of the box: Take all unique properties in determined order and concatenate their string representations (ugly) Take all unique properties in determined order, concatenate their byte values and encode using Base64 (less ugly) Take all unique properties in determined order, pass them through hashing function (md5, sha-X families, whatever you like) and use string representation of result.
{ "pile_set_name": "StackExchange" }
Q: "Doubling the variable" and differentiability Let's consider a domain $E \in \mathbb{R}^d$ and a function $f(x,y): E \times E \to \mathbb{R}$. Suppose $f \in C^2(E \times E)$. If we define a function $g$ on $E$ by $g(x):=f(x,x)$, is it true that $g \in C^2(E)$? Thank you very much! A: Yes, it's true. The derivatives of $g$ can be computed by the chain rule.
{ "pile_set_name": "StackExchange" }
Q: I can't 'flag' 'not constructive' when a question has a bounty A long-term bugbear of mine is the protection that a bounty affords from closing. Every so often, I find that someone's gone and posted a bounty on a question that deserves to be migrated or just terminated, but I can't vote. When I learned about the new feature of flags for the close reasons, I thought that my prayers were answered here. I could flag as non-constructive and leave it to a mod to decide. Sadly, the flag system seems to notice that I have rep enough to vote to close, and then rejects the vote due to the bounty. If it's going to work this way, I wish that the 'does not belong here' option were disabled for bountied questions altogether. Of course, what I really wish was for the protective field to be eliminated, and for questions with bounties to be closable, with the bounty refunded. A: To get around the protective field, flag the question with "other," and explain why the question deserves to be closed. The moderator can refund the bounty and close the question, if he agrees. There are two ways to build a UI with interlocking elements. The first way is to disable the elements that do not apply (in this case, the vote to close on a question with a bounty). The second way is to allow the user to use the UI element, perform a check for validity, and then notify the user if the action is invalid. The latter approach has the advantage of teaching people how the system works.
{ "pile_set_name": "StackExchange" }
Q: Given a list of strings, distribute into two 100 character fields I am not sure what's the best way to ask this question so please bear with me. I have a legacy platform that has 2x 100 varchar fields for holding delimited email addresses. I want to take a List<String> and distribute it into the two fields in such a way that I can add the maximum number of items. Obviously the email addresses are varying lengths, and a delimiter of ";MAPI:" has to be added between entries.The sequence does not matter and the only requirement for field2 is that field1 has at least a single entry. This new method would be called when a user tries to add a new address to the list, so it is entirely possible that the new item can not fit in any arrangement in which case I would simply tell the user that the field can not accept an address of that length. I tried ordering by length and adding items into field1 until it is full then adding the remainder to field2 but that is not "optimal" because if I left one or more of the short entries for field2 then a long entry could potentially better fill field1 A: It's a one-dimensional knapsack problem which is NP-hard, so you can only optimize solution by effective time for example using dynamic programming. https://en.wikipedia.org/wiki/Knapsack_problem
{ "pile_set_name": "StackExchange" }
Q: Get the titles and URLs of Yahoo result page in c# I want to get titles and URLs of Yahoo result page with htmlagility pack HtmlWeb w = new HtmlWeb(); string SearchResults = "https://en-maktoob.search.yahoo.com/search?p=" + query.querytxt; var hd = w.Load(SearchResults); var nodes = hd.DocumentNode.SelectNodes("//a[@cite and @href]"); if (nodes != null) { foreach (var node in nodes) { { string Text = node.Attributes["title"].Value; string Href = node.Attributes["href"].Value; } } It works but all links in search result are not Appropriate links how to omit ads link , Yahoo links and etc . I want to access the correct links A: What about this: HtmlWeb w = new HtmlWeb(); string search = "https://en-maktoob.search.yahoo.com/search?p=veverke"; //ac-algo ac-21th lh-15 var hd = w.Load(search); var titles = hd.DocumentNode.CssSelect(".title a").Select(n => n.InnerText); var links = hd.DocumentNode.CssSelect(".fz-15px.fw-m.fc-12th.wr-bw.lh-15").Select(n => n.InnerText); for (int i = 0; i < titles.Count() - 1; i++) { var title = titles.ElementAt(i); string link = string.Empty; if (links.Count() > i) link = links.ElementAt(i); Console.WriteLine("Title: {0}, Link: {1}", title, link); } Keep in mind that I am using the extension method CssSelect, from nuget package's ScrapySharp. Install it just like you installed HtmlAgilityPack, then add a using statement at the top of the code like using ScrapySharp.Extensions; and you are good to go. (I use it because its easier to refer to css selectors instead of xpath expressions...) Regarding skipping ads, I noticed ads in these yahoo search results will come at the last record only ? Assuming I am correct, simply skip the last one. Here's the output I get for running the code above:
{ "pile_set_name": "StackExchange" }
Q: Filter Object Array 1 on the basis on 2nd Object Array in Javascript(UnderscoreJS) I wanted to filter Object Array 1 if it's object value not exist in 2nd object Array. Non-Intersected values from 2nd array > aaa = [{id:1, name:"abc"}, {id:2, name:"xyz"}], > bbb = [{group:1}, {group:4}] > result should be [{id:2, name:"xyz"}] _.filter(aaa, function(a){ return _.find(bbb, function(b){ return b.id !== a.group; }); }); But the result is using this code is wrong. please help me here A: Here is a solution based on underscore. b.id !== a.group -> a.id !== b.group to match your objects' structure. Then, a.id !== b.group -> a.id === b.group and negate the find result, to filter your object properly ;) const aaa = [{id:1, name:"abc"}, {id:2, name:"xyz"}]; const bbb = [{group:1}, {group:4}]; const result = _.filter(aaa, function(a){ return !_.find(bbb, function(b){ return a.id === b.group; }); }); console.log(result); <script src="https://underscorejs.org/underscore-min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: Allow subclass instantiation only on the assembly of the superclass in C# Imagine the following scenario in a Xamarin solution: Assembly A (PCL): public abstract class MyBaseClass { public MyBaseClass() { [...] } [...] } Assembly B (3rd Party Library): public class SomeLibClass { [...] public void MethodThatCreatesClass(Type classType){ [...] //I want to allow this to work var obj = Activator.CreateInstance(classType); [...] } [...] } Assembly C (Main project): public class ClassImplA:MyBaseClass{ [...] } public class ClassImplA:MyBaseClass{ [...] } public class TheProblem{ public void AnExample(){ [...] //I want to block these instantiations for this Assembly and any other with subclasses of MyBaseClass var obj1 = new ClassImplA() var obj2 = new ClassImplB() [...] } } How can I prevent the subclasses from being instantiated on their own assembly and allow them only on the super class and the 3rd Party Library (using Activator.CreateInstance)? Attempt 1 I though I could make the base class with an internal constructor but then, I saw how silly that was because the subclasses wouldn't be able to inherit the constructor and so they wouldn't be able to inherit from the superclass. Attempt 2 I tried using Assembly.GetCallingAssembly on the base class, but that is not available on PCL projects. The solution I found was to call it through reflection but it also didn't work since the result of that on the base class would be the Assembly C for both cases (and I think that's because who calls the constructor of MyBaseClass is indeed the default constructors of ClassImplA and ClassImplB for both cases). Any other idea of how to do this? Or am I missing something here? Update The idea is to have the the PCL assembly abstract the main project (and some other projects) from offline synchronization. Given that, my PCL uses its own DB for caching and what I want is to provide only a single instance for each record of the DB (so that when a property changes, all assigned variables will have that value and I can ensure that since no one on the main project will be able to create those classes and they will be provided to the variables by a manager class which will handle the single instantions). Since I'm using SQLite-net for that and since it requires each instance to have an empty constructor, I need a way to only allow the SQLite and the PCL assemblies to create those subclasses declared on the main project(s) assembly(ies) Update 2 I have no problem if the solution to this can be bypassed with Reflection because my main focus is to prevent people of doing new ClassImplA on the main project by simple mistake. However if possible I would like to have that so that stuff like JsonConvert.DeserializeObject<ClassImplA> would in fact fail with an exception. A: I may be wrong but none of the access modifiers will allow you to express such constraints - they restrict what other entities can see, but once they see it, they can use it. You may try to use StackTrace class inside the base class's constructor to check who is calling it: public class Base { public Base() { Console.WriteLine( new StackTrace() .GetFrame(1) .GetMethod() .DeclaringType .Assembly .FullName); } } public class Derived : Base { public Derived() { } } With a bit of special cases handling it will probably work with Activator class , but isn't the best solution for obvious reasons (reflection, error-prone string/assembly handling). Or you may use some dependency that is required to do anything of substance, and that dependency can only be provided by your main assembly: public interface ICritical { // Required to do any real job IntPtr CriticalHandle { get; } } public class Base { public Base(ICritical critical) { if (!(critical is MyOnlyTrueImplementation)) throw ... } } public class Derived : Base { // They can't have a constructor without ICritical and you can check that you are getting you own ICritical implementation. public Derived(ICritical critical) : base(critical) { } } Well, other assemblies may provide their implementations of ICritical, but yours is the only one that will do any good. Don't try to prevent entity creation - make it impossible to use entities created in improper way. Assuming that you can control all classes that produce and consume such entities, you can make sure that only properly created entities can be used. It can be a primitive entity tracking mechanism, or even some dynamic proxy wrapping public class Context : IDisposable { private HashSet<Object> _entities; public TEntity Create<TEntity>() { var entity = ThirdPartyLib.Create(typeof(TEntity)); _entities.Add(entity); return entity; } public void Save<TEntity>(TEntity entity) { if (!_entities.Contains(entity)) throw new InvalidOperationException(); ...; } } It won't help to prevent all errors, but any attempt to persist "illegal" entities will blow up in the face, clearly indicating that one is doing something wrong. Just document it as a system particularity and leave it as it is. One can't always create a non-leaky abstraction (actually one basically never can). And in this case it seems that solving this problem is either nontrivial, or bad for performance, or both at the same time. So instead of brooding on those issues, we can just document that all entities should be created through the special classes. Directly instantiated objects are not guaranteed to work correctly with the rest of the system. It may look bad, but take, for example, Entity Framework with its gotchas in Lazy-Loading, proxy objects, detached entities and so on. And that is a well-known mature library. I don't argue that you shouldn't try something better, but that is still an option you can always resort to.
{ "pile_set_name": "StackExchange" }
Q: Why are ferries associated with "boat" and never "ship"? Even when a ferry is 150+ feet in length - clearly a ship, albeit a smallish one - why is it always referred to as a "boat" and not "ship" (As in "I'm going to catch the noon boat")? A: TL;DR: The characterization is based on history and tradition. There are many, many (some confusing) expressed differences between ship and boat, one of the pithier ones being When a ship sinks you get in a boat, when a boat sinks you get in the water. Submarines and ferries, as you noted, are boats. That would fit the above definition (most ferries don't have lifeboats) conveniently, but there has to be more. Some yachts, ferries, tug boats, fishing boats, police boats, etc. do carry small lifeboats or dinghies, but they usually don’t graduate to ship status because of that. (A tragic example being the Estonia [515.16 ft, 15,566 gross register tonnage]), a cruise ferry, which sank in the Baltic Sea. It is one of the worst maritime disasters of the 20th century, costing 852 lives. Anyone looking at it would not instinctively call it a boat. But it was built for coastal waterways, not deep, high seas. The coastal waterways puts it into the category of 'boat'. That it was used in high seas didn't make it high-seas-worthy, as history points out. It was not constructed[1] to be stable on taking on any water.) Per Mental Floss Another factor the Naval Institute considers is the vessel’s crew, command, and use. If it has a permanent crew with a commanding officer, it’s usually a ship. If it’s only crewed when actually in use and has no official CO, then you’re probably dealing with a boat. Ships are also usually intended and designed for deep-water use and are able to operate independently for long periods of time. Boats, meanwhile, lack the fuel and cargo capacity for extended, unassisted operation. The obvious exception to deep-water definition are the commercial fishing boats that go out for months in deep water. However, they don't have a fixed crew. Marine Insight lists seven differences, all of which must be taken into account. They are Size: The most important aspect that is considered while stating the difference between a ship and a boat is the size... “A ship can carry a boat, but a boat cannot carry a ship.” A mode of water transport that weighs at least 500 tonnes or above is categorised as a ship. In comparison, boats are stipulated to be quite compact in their structural size and displacement. (Submarines were once small enough to be carried on ships.) Operational Areas: Ships are vessels that are operated in oceanic areas and high seas. They are mainly built for cargo/passenger transportation across oceans. Boats are operable in smaller/restricted water areas and include ferrying and towing vessels... Boats are mainly used for smaller purposes and mainly ply in areas near to the coast. Navigation and Technology: Technologically, boats are simple vessels with less complicated equipment, systems and operational maintenance requirements. ...[Ships] are manned using advanced engineering, heavy machinery, and navigational systems. Crew: Ships... are operated by professionally trained navigators and engineers. A ship requires a captain to operate the ship and guide the crew....[T]he size of the crew on a boat depends on the size of the boat. It can be one person or a full-fledged crew depending on the size and purpose of the boat. Cargo Capacity: A boat is a small to mid-sized vessel, which has much lesser cargo carrying capability as compared to a ship. Construction and Design: [Ships] are complicated structures having a variety of machinery systems and designing aspects for safety and stability of the ship. A boat is much simple in construction and build, and has lesser machines and design complexities. Propulsion: A boat can be powered by sails, motor, or human force, whereas a ship has dedicated engines to propel them. Finally, the most reasonable explanation is provided by The Shipping Law Blog which states: Specifically, boats are small to medium-sized vessels with hulls, powered by sails, engines, or human force. Some types of vessel are always categorised as boats, regardless of their size or complexity. Their 'boat' status was designated when these types of vessel were small and has stuck despite their future growth. So, in the end, it comes down to tradition, as so many things do. [1] Causes of the disaster A: This is one of those ugly loose definition problems that English has from time to time. The answer is pretty much "because." A boat is a watercraft of any size designed to float or plane, to work or travel on water. Small boats are typically found on inland (lakes) or in protected coastal areas. A ship is a large buoyant watercraft. Ships are generally distinguished from boats based on size, shape and cargo or passenger capacity. A ferry (or ferryboat) is a boat or ship (a merchant vessel) used to carry (or ferry) primarily passengers, and sometimes vehicles and cargo as well, across a body of water. Ew. Ugly. There's no objective boundary between these two categories. The best I can give you is a subjective answer. Generally speaking, ferries historically referred to a non-seafaring (or possibly coastal) vessel or platform used to take people and goods across a body of water. They often did not resemble the classic concept of a "ship", that being a large, far-traveling, keeled vessel, often with sails or rows of oarsmen. Even though ferries these days can be ridiculously massive, I would wager that they were historically referred to as "boat" given their qualities, and the name has stuck. Edit: Hit-and-run downvoting doesn't help improve answers. If it's because I gave a subjective answer, two responses: This question, as has been demonstrated by both myself and others, has no objective answer. Sometimes English doesn't follow nice rules. The current highest-rated response is better than mine. Let's get that out of the way first so nobody feels the need to bring my motives into question. My guess is that my answer was downvoted due to not citing sources. However, all resources I found (and indeed the ones used by the best answer) use the very same vague language that probably led to this question in the first place. Using citations is often fantastic, but sometimes they just don't contribute. Regardless, if you downvote, please tell people why. A: The Royal Navy provides a modern definition: a ship is a vessel that leans towards the outside of a sharp turn and a boat is a vessel that leans towards the inside of a sharp turn. These characteristics arise from the pitch of the engines and the design the the hull. It is sadly not applicable to craft under sail. Source - a friend who is a naval officer. The first ferries were small rafts or boats with a rope used to pull the boat from one side of a river to another. This name has stuck. In the case of chain ferries, it is clear why.
{ "pile_set_name": "StackExchange" }
Q: Populate text box based on drop down selection I have this javascript function hoping to populate a textbox based on drop down selection. I am just using the first option (there are 7 more options, but this should illustrate the issue): <script> function TicketsQuantity(){ if (document.getElementByID("RaffleDollars").value == 25){ (document.getElementById("RaffleTickets").value = "1"); } } </script> Here is the drop down box code: <select size="1" name="RaffleDollars" id="RaffleDollars" onChange="javascript:TicketsQuantity();"> <option selected value="0.00">------Select $ Amount------</option> <option value="25">25.00</option> </select> Here is the text box code: <input name="RaffleTickets" size="5" id="RaffleTickets"> When I select 25.00 from the drop down box, it is not populating textbox with 1. Is my syntax incorrect? Any help would be appreciated. Thanks. A: You have an error: getElementByID is incorrect. Change it to: getElementById. Please correct your code to use the below. Remove javascript: here: onChange="TicketsQuantity();" Since you are using jquery, I would give you a jQuery based solution: $(function () { $("#RaffleDollars").change(function () { if ($(this).val() == "25") $("#RaffleTickets").val("1"); }); }); Working Snippet <select size="1" name="RaffleDollars" id="RaffleDollars" onChange="TicketsQuantity();"> <option selected value="0.00">------Select $ Amount------</option> <option value="25">25.00</option> </select> <input name="RaffleTickets" size="5" id="RaffleTickets"> <script> function TicketsQuantity() { if (document.getElementById("RaffleDollars").value == 25) { document.getElementById("RaffleTickets").value = "1"; } } </script>
{ "pile_set_name": "StackExchange" }
Q: Is the concept of an "interleaved homomorphism" a real thing? I am in need of the following class of functions: class InterleavedHomomorphic x where interleaveHomomorphism :: (forall a . f a -> g a) -> x f -> x g Obviously the name I invented for it is not in any way an official term for anything, and the type class above is not very elegant. Is this a concept that has a name, or even an implementation in some library? Is there some more reasonable way of doing this? The purpose of this function would be that I have some context f that annotates some data (Foo and Bar are just random example data structures for the sake of this question): data Foo f = One (f (Bar f)) | Product (f (Foo f)) (f (Foo f)) data Bar f = Zero | Succ (f (Bar f)) I would like to transform the context of the data in a polymorphic way; by only knowing the homomorphism between the contexts and not (necessarily) caring about the data itself. This would be done by providing instance InterleavedHomomorphic Foo and instance InterleavedHomomorphic Bar in the example above. A: So, assuming f and g are proper functors, forall a. f a -> g a is a natural transformation. We could make it a bit prettier: type f ~> g = forall a. f a -> g a Natural transformations like this let us form a category of Haskell Functors, so what you have is a functor from that to some other category. Following the steps of normal Haskell Functors, it would perhaps make sense to have x be an endofunctor, mapping Functors to other Functors. This is similar, but not identical, to what you have: class FFunctor x where ffmap :: (f ~> g) -> (x f ~> x g) However, in your case x f and x g are not functors, and x f -> x g is a normal function rather than a natural transformation. Still, the pattern is close enough to be intriguing. With this in mind, it seems that x is still an example of a functor, just between two different categories. It goes from the category of Functors to the category of xs with different structures. Each possible x, like Foo, forms a category with objects like Foo [] and Foo Maybe and transformations between them (Foo [] -> Foo Maybe). Your interleaveHomomorphism function "lifts" natural transformations into these x-morphisms, just like fmap "lifts" normal (a -> b) functions into functions in the image of the functor (f a -> f b). So yeah: your typeclass is a functor just like Functor, except between two different categories. I don't know of a specific name for it, largely because I don't know a specific name for constructs like x. More generally, I'm not even sure a specific name would make sense. At this point, we'd probably like a nice generic functor typeclass that go between any two categories. Maybe something like: class (Category catA, Category catB) => GFunctor f catA catB where gfmap :: catA a b -> catB (f a) (f b) This probably already exists in a library somewhere. Unfortunately, this particular approach to defining different functors would require a bunch of extra newtype noise since (->) is already a category. In fact, getting all the types to line up properly is going to be a bit of a pain. So it's probably easiest just to call it an XFunctor or something. Besides, just imagine the pun potential! EDIT: It looks like categories provides a CFunctor type like this, but a bit cleverer: class (Category r, Category s) => CFunctor f r s | f r -> s, f s -> r where cmap :: r a b -> s (f a) (f b) However, I'm not certain that even this is general enough! I think that we might want it to be more polymorphic over kinds too.
{ "pile_set_name": "StackExchange" }
Q: Android creating button programmatically issue i'm trying to create buttons programmatically on my android application depending on how many items I have on my sqlite database. The buttons are there, but my problem is to set onClick on every button because I want to show different content when user's click the buttons. I'm using this code for now : for(cursorCol.move(0); cursorCol.moveToNext(); cursorCol.isAfterLast()){ Id = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("id"))); Log.i("Id","Id : "+Id); titleButton = cursorCol.getString(cursorCol.getColumnIndex("title")); Log.i("titleButton","titleButton : " + titleButton); elemOrder1 = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("elemOrder"))); Log.i("elemOrder1 ","elemOrder1 : " + elemOrder1 ); btn = new Button(this); btn.setText(" " + titleButton + " "); btn.setId(Id); btn.setTextColor(Color.parseColor("#000000")); btn.setTextSize(12); btn.setPadding(10, 10, 10, 10); btn.setBackgroundResource(R.drawable.gray_button); btnlayout.addView(btn,params); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { infoCard.removeAllViews(); for(int i=0;i<=cursorCol.getCount();i++){ Log.i("","titleButton : "+titleButton); } } } But the problem is that when I click the button it's showing only the last titleButton. Actually I don't need to show titleButton, I just did it for testing purposes. Any ideas how can I create different onClick methods for every single button? A: I think the problem lies with this line of code: btn = new Button(this); You are editing the same button over and over again in your loop and not acutally creating a new one. To create a new one you will need to do this: Button new_btn = new Button(this); This will create a brand new one every time you iterate through your for loop.
{ "pile_set_name": "StackExchange" }
Q: Wanted: Examples of how black box optimizer works - step by step? I need to understend how black box optimizer work. I need a real life example of how it hlps. So what I need: What was the task, what were parameters, what was the function to minimize and how it all worked toogether. I need deteiled info on this topic, please - wiki does not give lot of help... A: Chapter 10 of Numerical Recipes has a good description of how the golden section search works in 1D, as well as description of multidimensional cases. You could see figure 10.1.1 in the obsolete C version (available free online)
{ "pile_set_name": "StackExchange" }
Q: How to insert a floating button on top right corner of screen in JS Using only plain javascript, how to insert a button that will always be floating in the top right corner of the window above other elements ? So far I got: var button = document.createElement("Button"); button.innerHTML = "Title"; button.style = "margin-top:0%;right:0%;position:absolute;" document.body.appendChild(button); A: Use top instead of margin-top and set a high z-index var button = document.createElement("Button"); button.innerHTML = "Title"; button.style = "top:0;right:0;position:absolute;z-index: 9999" document.body.appendChild(button);
{ "pile_set_name": "StackExchange" }
Q: Needs clarification on C# Flags i have this code: [Flags] public enum MyUriType { ForParse, ForDownload, Unknown } and then: MyUriType uriType = MyUriType.ForDownload; but, I was wondering why this returns true: if ((uriType & MyUriType.ForParse) == MyUriType.ForParse) When it is not set in the second code group. Please advise. A: By default, the first field for an enum type is given the ordinal value 0. So, if uriType does not contain the MyUriType.ForParse flag, then uriType & MyUriType.ForParse actually equals 0, which counterintuitively evaluates to true when you compare it to MyUriType.ForParse for equality (which is also 0). If you break it down to bitwise arithmetic then the expression you're evaluating is: ({something} & 0) == 0 ...which will always evaluate to true, no matter what the "something" is. Normally, when you define a Flags enum, you should actually specify values for each field: [Flags] public enum MyUriTypes { None = 0, ForParse = 1, ForDownload = 2, ForSomethingElse = 4, ForAnotherThing = 8 } Each value should be a power of 2 so that they don't conflict (every multiple of 2 is a binary shift-left). It's also customary to name it as a plural, so that people who use the enum know that it is a Flags enum and can/should hold multiple values. If you define your enum this way, your test code will now evaluate to false if uriType does not have the ForParse bit set.
{ "pile_set_name": "StackExchange" }
Q: Show two Google maps in one page The Google code works for one map but I manage to show two maps in one page. The problem is that the infowindow and marker isn't working for the second map. How do I set this correctly? HTML <div id="gmap_canvas" style="height:400px;width:100%;"></div> <div id="gmap_canvas2" style="height:400px;width:100%;"></div> JS function init_map() { var myOptions = { zoom: 16, styles: [{ stylers: [{ saturation: -50 }] }], center: new google.maps.LatLng(28.529627, 77.218068), mapTypeId: google.maps.MapTypeId.ROADMAP }; var myOptions2 = { zoom: 12, styles: [{ stylers: [{ saturation: -50 }] }], center: new google.maps.LatLng(23.529627, 72.218068), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions); map2 = new google.maps.Map(document.getElementById('gmap_canvas2'), myOptions2); //I don't know how to call this function below separately? marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(28.529627, 77.218068) }); infowindow = new google.maps.InfoWindow({ content: 'Welcome' }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); }); infowindow.open(map, marker); } google.maps.event.addDomListener(window, 'load', init_map); How do I differentiate the function into two maps so it loads the values of infowindow and marker separately? A: Just try the following way. function init_map() { var myOptions = { zoom: 16, styles: [{ stylers: [{ saturation: -50 }] }], center: new google.maps.LatLng(28.529627, 77.218068), mapTypeId: google.maps.MapTypeId.ROADMAP }; var myOptions2 = { zoom: 12, styles: [{ stylers: [{ saturation: -50 }] }], center: new google.maps.LatLng(23.529627, 72.218068), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions); map2 = new google.maps.Map(document.getElementById('gmap_canvas2'), myOptions2); //FIRST MARKER marker1 = new google.maps.Marker({ map: map, position: new google.maps.LatLng(28.529627, 77.218068) }); infowindow1 = new google.maps.InfoWindow({ content: 'Welcome' }); google.maps.event.addListener(marker1, 'click', function() { infowindow1.open(map, marker1); }); infowindow1.open(map, marker1); //SECOND MARKER marker2 = new google.maps.Marker({ map: map2, position: new google.maps.LatLng(23.529627, 72.218068) }); infowindow2 = new google.maps.InfoWindow({ content: 'Welcome' }); google.maps.event.addListener(marker2, 'click', function() { infowindow2.open(map2, marker2); }); infowindow2.open(map2, marker2); } google.maps.event.addDomListener(window, 'load', init_map);
{ "pile_set_name": "StackExchange" }
Q: Sqlcipher, Windows: encryption succeeds but produces strange results I used sqlcipher_export(), exactly as specified here, to encrypt an existing Sqlite database. It all went fine - no errors, the resulting database is created and has a reasonable size. However, I am not able to open the encrypted database, even though I specify the correct key using PRAGMA key. Unencrypted databases open without problems. Moreover, the encrypted database looks strange; the header seems to be encrypted, but not the data. See http://i.stack.imgur.com/HaBpS.png, it's an image showing binary comparison between encrypted (left) and unencrypted (right) databases. In the debugger I can see that, during the encryption, the program goes through sqlcipher_page_cipher(), but most of the time (every time except for 2 invocations) the following clause is executed, and the function returns early: /* just copy raw data from in to out when key size is 0 * i.e. during a rekey of a plaintext database */ if(c_ctx->key_sz == 0) { memcpy(out, in, size); return SQLITE_OK; } SQL issued during encryption: ATTACH DATABASE 'encrypted.db' AS encrypted KEY '12345'; SELECT sqlcipher_export('encrypted'); DETACH DATABASE encrypted; SQL issued during opening: // open database PRAGMA key = '12345'; // try to read database - "file is encrypted or not a database" CODEC_TRACE logs generated during encryption and decryption are here. (In case it is important how I compiled Sqlcipher: I created an Sqlcipher amalgamation on a Linux machine, copied the resulting C file to a Windows machine, compiled it in Visual C++ Express, and linked to a precompiled OpenSSL DLL.) A: Root cause: Calls to OpenSSL's HMAC_Init_ex() in sqlcipher_page_hmac() corrupted memory that belonged to c_ctx->key_sz, setting it to zero. c_ctx->key_sz was adjacent to a parameter passed to HMAC_Init_ex(). (Details can be found in one of the comments to the original post.) This caused sqlcipher_page_cipher() to write plaintext pages to the encrypted file, instead of encrypted pages. Which didn't make sense and made the resulting database unusable. Upgrading OpenSSL from 0.9.8k to 1.0.0i fixed the problem.
{ "pile_set_name": "StackExchange" }
Q: .htaccess reweite is preventing login I recently tried to implement URL Rewriting but ran into a problem when I attempted to login. .htaccess <IfModule mod_rewrite.c> Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / # To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1 [R,L,NC] ## To internally redirect /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME}.php -f [NC] RewriteRule ^ %{REQUEST_URI}.php [L] </IfModule> Login Form <form action="assets/php/process_login.php" method="post" name="login_form" id="loginform"> <input type="text" name="email" placeholder="Email" /><br /> <input type="password" name="p" placeholder="Password" id="password" /><br /> <input type="submit" value="Login" onclick="formhash(this.form, this.form.password);" /> </form> process_register.php <?php include 'db_connect.php'; include 'functions.php'; sec_session_start(); $return = 'http://192.168.1.2/blisscount/user/'; if (isset($_POST['email'], $_POST['p'])) { $email = $_POST['email']; $password = $_POST['p']; if (login($email, $password, $mysqli) == true) { header('Location:'.$return.'index.php'); die; } else { header('Location:'.$return.'login.php?error=2'); die; } } else { header('Location:'.$return.'login.php?error=1'); die; } Once I submit the form the page redirects to http://192.168.1.2/blisscount/user/login.php?error=1 Implying it failed in process_register.php where it checks if the parameters are set. Using firebug I am able to see that the parameters are in fact being sent. This is the response I am getting from the call Reload the page to get source for: http://192.168.1.2/blisscount/user/assets/php/process_login.php Whats going wrong? A: You need to skip POST request from external redirects. Use this modified code: <IfModule mod_rewrite.c> Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / # To externally redirect /dir/foo.php to /dir/foo RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1 [R,L,NE] ## To internally redirect /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME}.php -f [NC] RewriteRule ^ %{REQUEST_URI}.php [L] </IfModule>
{ "pile_set_name": "StackExchange" }
Q: List manipulation and end-cases I am attempting to learn scheme (for expansion of mind not homework), and am still wrestling with its differences compared to procedural languages. Consider the following: In procedural language terms I have two zero-based integer arrays a and b of lengths n>=1 and n+1 respectively and want to output an array c of length n+1 where: c[0] = b[0] + a[0]; c[n] = b[n] + a[n-1]; c[i] = b[i] + Max(a[i-1],a[i]) (1 <= i <= n-1) So, for example if a = [5,6,1] and b = [1,2,3,4], then c= [6,8,9,5] I can do this simply in a procedural language. For example in Pascal: function MaxAdd(a, b : array; n : integer) : array; var i : integer; begin c[0] = b[0] + a[0]; c[n] = b[n] + a[n-1]; for i = 1 to n-1 do c[i] = b[i] + Max(a[i-1],a[i]); result := c; end; I am trying to do the same with scheme where I usetwo lists of integers instead of arrays. The following works, but seems clumsy to me. Is there a tidier way to handle end-cases? (define (max a b) (if (> a b) a b)) (define (maxaddhelper l1 l2) (cond ((= 1 (length l1)) (list (+ (car l1) (car l2)))) (else (cons (+ (max (car l1) (car (cdr l1))) (car l2)) (maxaddhelper (cdr l1) (cdr l2)) )))) (define (maxadd l1 l2) (cond ((= 1 (length l1)) (list (+ (car l1) (car l2)) (+ (car l1) (car (cdr l2))))) (else (cons (+ (car l1) (car l2)) (maxaddhelper l1 (cdr l2)) )))) test output... Welcome to DrRacket, version 5.93 [3m]. Language: scheme; memory limit: 128 MB. > (maxadd (list 5 6 1) (list 1 2 3 4)) (6 8 9 5) > A: This problem makes heavy use of indexes, so is better suited for a Scheme vector - which offers the same efficient index-based operations as an array. For example, an idiomatic solution in Racket would be: (define (max-add a b) (let* ([n (vector-length a)] [c (make-vector (add1 n))]) (vector-set! c 0 (+ (vector-ref b 0) (vector-ref a 0))) (vector-set! c n (+ (vector-ref b n) (vector-ref a (sub1 n)))) (for ([i (in-range 1 n)]) (vector-set! c i (+ (vector-ref b i) (max (vector-ref a (sub1 i)) (vector-ref a i))))) c)) (max-add '#(5 6 1) '#(1 2 3 4)) => '#(6 8 9 5) Nobody said that all problems in Scheme must be solved using linked lists, this example in particular shows that sometimes you have to choose the data structure better suited for the job. If lists are a necessity, then list->vector and vector->list will allow you to switch back and forth between data structures. EDIT: As mentioned by @uselpa, it's also possible to solve this problem using only lists, more in the spirit of SICP and idiomatic for Scheme. For completeness sake here's my implementation, a bit simpler and easier to understand than the other answer: (define (max-add a b) (let loop ([a a] [b b] [prev (car a)]) (if (null? a) (list (+ (car b) prev)) (cons (+ (car b) (max prev (car a))) (loop (cdr a) (cdr b) (car a)))))) (max-add '(5 6 1) '(1 2 3 4)) => '(6 8 9 5)
{ "pile_set_name": "StackExchange" }
Q: iPhone 5 displaying single 1x icon instead of 2x? All of the icons on my iPhone 5 display at 2x, but for some reason, my SchoolsFirst eDeposit icon displays the 1x image. Any idea how I can fix this? I tried deleting/redownloading the app, and hiding it in the "Purchased Apps" section of iTunes, and nothing worked. A: The app probably doesn't have a 2x icon. Apple doesn't allow apps in the store with only 1x, so I assume this app has not been updated in a very long time? Contact the developer and ask them to fix it. Nothing else you can do, only the developer of an app can modify it (this is a security policy enforced on iOS to prevent malware attacks).
{ "pile_set_name": "StackExchange" }
Q: Flask-SQLAlchemy TimeoutError Flask Python 2.7 Postgres 9 Ubuntu 14.04 I'm using Flask and SQLAlchemy, after 15 consecutive HTTP requests I get: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30 Then server stops responding: Very similar as: Flask-SQLAlchemy TimeoutError I don't have session engine, per my understanding Flask-SQLAlchemy should take care of it. What do I need to configure to support more sessions and to clean existing ones periodically. app.py import models api_app = Flask(__name__) api_app.config.from_pyfile(settings.celery_config) db = SQLAlchemy(api_app) @api_app.teardown_appcontext def shutdown_session(exception=None): try: db.session.close() except AttributeError,e: print str(e) except Exception,e: print api_app.name print str(e) @api_app.route('/api/1.0/job/<string:ref>/') def get_job_by_id(ref): """ :param id: :return: """ try: if request.method == 'GET': job = models.Job.query.filter(models.Job.reference == ref) if job: job_ = job.all() if len(job_) == 1: return jsonify(job_[0].serialize()) resp = Response(status=404, mimetype='application/json') return resp else: resp = Response(status=405, mimetype='application/json') return resp except Exception,e: print str(e) resp = Response(status=500, mimetype='application/json') return resp models.py from api_app import db class Job(db.Model, AutoSerialize, Serializer): __tablename__ = 'job' __public__ = ('status','description','reference') id = Column(Integer, primary_key=True, server_default=text("nextval('job_id_seq'::regclass)")) status = Column(String(40), nullable=False) description = Column(String(200)) reference = Column(String(50)) def serialize(self): d = Serializer.serialize(self) del d['id'] return d A: based on @spicyramen comment: increase SQLALCHEMY_POOL_SIZE The size of the database pool.
{ "pile_set_name": "StackExchange" }
Q: Extracting text from the 1st and 4th column of a HTML table row with "grep" Can anyone see what I'm doing wrong in the grep statement? I think I'm just missing an escape character. for i in "${!PORTARR[@]}"; do grep \<td\>"${!PORTARR[i]}"\<\/td\> tmp/portlist >> databases/ports.db done *** UPDATE *** Well unfortunately that's not going to work. Here is ultimately what I am trying to do. From this string: <tr><td>4</td><td>TCP</td><td>UDP</td><td>Unassigned</td><td>Official</td></tr> I need to get this: 4,Unassigned A: I suspect that you meant to write ${PORTARR[i]} (the ith element of PORTARR) instead of ${!PORTARR[i]} (the value of the variable named by the ith element of PORTARR); so: for i in "${!PORTARR[@]}"; do grep \<td\>"${!PORTARR[i]}"\<\/td\> tmp/portlist >> databases/ports.db done But I'd recommend a few other tweaks as well: for elem in "${PORTARR[@]}"; do grep "<td>$elem</td>" tmp/portlist done > databases/ports.db Update: For your updated question, I think you're better off using a real programming language, like Perl: perl -we ' my @ports = @ARGV; @ARGV = (); my %ports = map +($_ => undef), @ports; while(<>) { my $fields = m/<td>([^<]*)<\/td>/g; if(exists $ports{$fields[0]}) { $ports{$fields[0]} = $fields[3]; } } foreach my $port (@ports) { if(defined $ports{$port}) { print "$port,$ports{$port}\n"; } } ' "${PORTARR[@]}" < tmp/portlist > databases/ports.db (Disclaimer: not tested.)
{ "pile_set_name": "StackExchange" }
Q: 'einfangen' meaning 'to stop'? I know that einfangen means various flavours of catching, eg, catching a fish, a thief, an infection, or a festive mood. But I have just come across this passage where it seems to mean to arrest a development: Ja, weil in den einzelnen Ländern seit Jahren jeder neue Fernsehvertrag 20 bis 100 Prozent mehr Geld bringt. Dieses wird von den Vereinen sofort in die Erhöhung der Wettbewerbsfähigkeit der Mannschaften investiert. Indem man Spieler verpflichtet, die man sich zuvor nicht leisten konnte. Und zwar über hohe Gehaltszahlungen. Diese Entwicklung gilt es einzufangen. Catch or capture doesn't make sense here. Is this a meaning that dictionaries don't list? A: Etwas einfangen in this context is mostly used for a process or a development that is starting to go, or already has gone, in the wrong direction. There is a strong sense of catching in the expression. You want to – so to speak – get a grip on the development to stop it from becoming any worse, to revert it, or to redirect it towards a more desirable outcome. There is a sense of making things better in the expression, too. To arrest doesn’t have that. I’d rather go for something like correcting/mitigating a development.
{ "pile_set_name": "StackExchange" }
Q: Drag n Drop using jQuery UI I am using jQuery UI for drag n drop. JsFiddle here <div id="draggable" class="ui-widget-content"> <div id="" class="draggables"> <label>Text Input</label> <input type="text" name="textinput" /> </div> <div id="" class="draggables"> <label>File Upload</label> <input type="file" name="fileinput" /> </div> <div id="" class="draggables"> <label>Textarea Input</label> <textarea rows="3" cols="20" name="textareainput" ></textarea> </div> </div> <div id="sortable" class="ui-widget-content"> <p></p> </div> Note that Here draggable and sortable are id of div I am using clone for drag from draggable and drop into sortable. now i want to when drag from sortable and drop into draggable that element destroy without any changes of draggable element means 3 div of draggable will be remain same but if draggable element drop in draggable than 3 div will not remain same I know this is happen because i m using drop event. how to solve this problem A: Got the solution In Droppable jQuery UI there is a method accept using that i solve this problem . $(function() { $( "#sortable" ).droppable({ drop: function( event, ui ) { ui.draggable.addClass( "droppables" ); //using this add class } }); $('#draggable').droppable({ accept: ".droppables", // using this which draggable elements are accepted by the droppable. drop: function(event, ui) { ui.draggable.remove(); } }); }); look at jsFiddle here
{ "pile_set_name": "StackExchange" }
Q: Why is a 3-way merge advantageous over a 2-way merge? Wikipedia says a 3-way merge is less error-prone than a 2-way merge, and often times doesn't need user intervention. Why is this the case? An example where a 3-way merge succeeds and a 2-way merge fails would be helpful. A: Say you and your friend both checked out a file, and made some changes to it. You removed a line at the beginning, and your friend added a line at the end. Then he committed his file, and you need to merge his changes into your copy. If you were doing a two-way merge (in other words, a diff), the tool could compare the two files, and see that the first and last lines are different. But how would it know what to do with the differences? Should the merged version include the first line? Should it include the last line? With a three-way merge, it can compare the two files, but it can also compare each of them against the original copy (before either of you changed it). So it can see that you removed the first line, and that your friend added the last line. And it can use that information to produce the merged version. A: This slide from a perforce presentation is interesting: The essential logic of a three-way merge tool is simple: Compare base, source, and target files Identify the "chunks" in the source and target files file: Chunks that don't match the base Chunks that do match the base Then, put together a merged result consisting of: The chunks that match one another in all 3 files The chunks that don't match the base in either the source or in the target but not in both The chunks that don't match the base but that do match each other (i.e., they've been changed the same way in both the source and the target) Placeholders for the chunks that conflict, to be resolved by the user. Note that the "chunks" in this illustration are purely symbolic. Each could represent lines in a file, or nodes in a hierarchy, or even files in a directory. It all depends on what a particular merge tool is capable of. You may be asking what advantage a 3-way merge offers over a 2-way merge. Actually, there is no such thing as a two-way merge, only tools that diff two files and allow you to "merge" by picking chunks from one file or the other. Only a 3-way merge gives you the ability to know whether or not a chunk is a change from the origin and whether or not changes conflict. A: A three way merge where two changesets to one base file are merged as they are applied, as opposed to applying one, then merging the result with the other. For example, having two changes where a line is added in the same place could be interpreded as two additions, not a change of one line. For example file a has been modified by two people, one adding moose, one adding mouse. #File a dog cat #diff b, a dog +++ mouse cat #diff c, a dog +++ moose cat Now, if we merge the changesets as we apply them, we will get (3-way merge) #diff b and c, a dog +++ mouse +++ moose cat But if we apply b, then look at the change from b to c it will look like we are just changing a 'u' to an 'o' (2-way merge) #diff b, c dog --- mouse +++ moose cat
{ "pile_set_name": "StackExchange" }
Q: Opening password-protected pdf file with iTextSharp I'm making an application that should display PDFs with password. This is my code: protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { try { string filePath = Request.QueryString["filePath"]; if (filePath.ToUpper().EndsWith("PDF")) { copyPDF(filePath); } } catch { string message = "<script language='Javascript'>alert('File Not Found! Call Records Department for verification. ')</script>"; ScriptManager.RegisterStartupScript(Page, this.GetType(), message, message, false); } } } public void copyPDF(string filePath) { iTextSharp.text.pdf.RandomAccessFileOrArray ra = new iTextSharp.text.pdf.RandomAccessFileOrArray(Server.MapPath(ResolveUrl(filePath))); if (ra != null) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] password = System.Text.ASCIIEncoding.ASCII.GetBytes("Secretinfo"); iTextSharp.text.pdf.PdfReader thepdfReader = new iTextSharp.text.pdf.PdfReader(ra, password); int pages = thepdfReader.NumberOfPages; iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(); iTextSharp.text.pdf.PdfCopy pdfCopy = new iTextSharp.text.pdf.PdfCopy(pdfDoc, ms); pdfDoc.Open(); int i = 0; while (i < pages) { pdfCopy.AddPage(pdfCopy.GetImportedPage(thepdfReader, i + 1)); i += 1; } pdfDoc.Close(); Byte[] byteInfo = ms.ToArray(); Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("content-length", byteInfo.Length.ToString()); Response.BinaryWrite(byteInfo); Response.Flush(); Response.End(); } } My code has no problem opening pdf files without password but it can't open pdfs with password even though the password is supplied. The application executes the catch instead. What seems to be wrong with my code? EDIT: I removed the Catch to see the exception thrown. Exception Details: System.ArgumentException: PdfReader not opened with owner password It says the source of the error is Line 51. Line 49: while (i < pages) Line 50: { Line 51: pdfCopy.AddPage(pdfCopy.GetImportedPage(thepdfReader, i + 1)); Line 52: i += 1; Line 53: } A: For certain operations on encrypted documents iText(Sharp) requires that the document not merely is opened with the user password but instead with the owner password. This corresponds to the definition of these passwords in the PDF specification: Whether additional operations shall be allowed on a decrypted document depends on which password (if any) was supplied when the document was opened and on any access restrictions that were specified when the document was created: Opening the document with the correct owner password should allow full (owner) access to the document. This unlimited access includes the ability to change the document’s passwords and access permissions. Opening the document with the correct user password (or opening a document with the default password) should allow additional operations to be performed according to the user access permissions specified in the document’s encryption dictionary. (section 7.6.3.1 in ISO 32000-1) iText(Sharp) currently does not check in detail the user access permissions specified in the document’s encryption dictionary but instead always requires the owner password for operations requiring certain permissions, and copying whole pages from a document definitively is one of them. This been said, the iText(Sharp) developers are very much aware (due to many such questions asked) that iText(Sharp) users may be entitled to execute such operations even without the owner password on account of the before mentioned user access permissions specified in the document’s encryption dictionary, that there are myriad PDFs to which their respective owners applied an owner password (to prevent misuse by others) and then forgot it (or by using a randomly generated one never knew it to start with), and that iText(Sharp) (being open source) can easily be patched by anyone not to respect the differences between user and owner password. To allow users to do what they are entitled to and to prevent the spreading of patched copies of the library, iText(Sharp) contains an override for this test in the PdfReader class: /** * The iText developers are not responsible if you decide to change the * value of this static parameter. * @since 5.0.2 */ public static bool unethicalreading = false; Thus, by setting PdfReader.unethicalreading = true; you globally override this permission checking mechanism. Please respect the rights of PDF authors and only use this override if you indeed are entitled to execute the operations in question.
{ "pile_set_name": "StackExchange" }
Q: Android Canvas Off Screen Drawing Performance I'm developing an Android game using Canvas element. I have many graphic elements (sprites) drawn on a large game map. These elements are drawn by standard graphics functions like drawLine, drawPath, drawArc etc. It's not hard to test if they are in screen or not. So, if they are out of the screen, i may skip their drawing routines completely. But even this has a CPU cost. I wonder if Android Graphics Library can do this faster than I can? In short, should I try to draw everything even if they are completely out of the screen coordinates believing Android Graphics Library would take care of them and not spend much CPU trying to draw them or should I check their drawing area rectangle myself and if they are completely out of screen, skip the drawing routines? Which is the proper way? Which one is supposed to be faster? p.s: I'm targeting Android v2.1 and above. A: From a not-entirely-scientific test I did drawing Bitmaps tiled across a greater area than the screen, I found that checking beforehand if the Bitmap was onscreen doesn't seem to make a considerable different. In one test I set a Rect to the screen size and set another Rect to the position of the Bitmap and checked Rect.intersects() before drawing. In the other test I just drew the Bitmap. After 300-ish draws there wasn't a visible trend - some went one way, others went another. I tried the 300-draw test every frame, and the variation from frame to frame was much greater than difference between checked and unchecked drawing. From that I think it's safe to say Android checks bounds in its native code, or you'd expect a considerable difference. I'd share the code of my test, but I think it makes sense for you to do your own test in the context of your situation. It's possible points behave differently than Bitmaps, or some other feature of your paint or canvas changes things. Hope that help you (or another to stumble across this thread as I did with the same question).
{ "pile_set_name": "StackExchange" }
Q: How was everyone so sure that Voldemort was dead the 2nd time? So the first time that Voldemort "died", the wizarding world was in full celebration mode because they thought him gone forever. But once Voldemort returned thanks to his secret Horcruxes, panic ensued again. So when Voldemort died a 2nd time, why was everyone so sure he was dead again? Only Harry and his friends (and maybe some Death Eaters) knew about the Horcruxes, therefore knowing that this death was the permanent one. But why didn't other people suspect that he'd just return like he did before? A: Well, technically he didn't die the 'first' time, he kind of diminished and became worse than a ghost who had to consume unicorn blood in order to survive. This happened due to ancient love magic which Voldemort is known to consider inferior to his brand of dark magic. Harry's mother Lily died protecting him and it was this act of selfless love that acted as a shield for infant Harry against Voldemort's death curse, which rebounded on him but couldn't kill him as he had Horcruxes. As for his actual death, the book states "And Harry, with the unerring skill of the Seeker, caught the wand in his free hand as Voldemort fell backward, arms splayed, the slit pupils of the scarlet eyes rolling upward. Tom Riddle hit the floor with a mundane finality, his body feeble and shrunken, the white hands empty, the snakelike face vacant and unknowing. Voldemort was dead, killed by his own rebounding curse, and Harry stood with two wands in his hand, staring down at his enemy’s shell. One shivering second of silence, the shock of the moment suspended: and then the tumult broke around Harry as the screams and the cheers and the roars of the watchers rent the air. " -Book 7 Page 744 In the films we see Voldemort burn up and vanish, while in the books it was interpreted that his body was left behind as proof that he was in fact dead. A: The only survivor of the killing curse was Harry. Nobody actually saw what happened in Godric's Hollow (besides Harry, and that was a green flash and a laugh), so nobody really knew what happened to Voldemort after that happened, and whether he actually died or not. There were rumours that he was still alive (which Dumbledore mentions to Professor McGonagall), and the celebrations of the people the first time round were in part due to someone surviving the killing curse. Professor McGonagall's voice trembled as she went on. "That's not all. They're saying he tried to kill the Potter's son, Harry. But - he couldn't. He couldn't kill that little boy. No one knows why, or how, but they're saying that when he couldn't kill Harry Potter, Voldemort's power somehow broke - and that's why he's gone. Harry Potter and the Philosopher's Stone, Chapter 1 Notice that Professor McGonagall doesn't say dead with reference to Voldemort, and Harry was clearly alive after the failed AK - which is proof that if someone does survive, they're definitely alive (which Voldemort isn't). There were lots of witnesses this time to see that Voldemort took the killing curse in the Battle at Hogwarts, and that he was dead. (When Harry took it, and survived, he was crying but still alive.) As others have said, the explanation of Horcruxes keeping him around previously, and the destruction of them would have confirmed that he was finally dead. There is also the point that the people wanted to believe that their hero had finally rid them of their nemesis. A: They weren’t completely sure he was dead the first time. Right after the Dark Lord loses his power at the Potters’ house, the prevalent rumor in the wizarding world was that he lost his power, not that he was actually dead. “Professor McGonagall’s voice trembled as she went on. ‘That’s not all. They’re saying he tried to kill the Potters’ son, Harry. But – he couldn’t. He couldn’t kill that little boy. No one knows why, or how, but they’re saying that when he couldn’t kill Harry Potter, Voldemort’s power somehow broke – and that’s why he’s gone.” - Harry Potter and the Philosopher's Stone, Chapter 1 (The Boy who Lived) Hagrid tells Harry something similar, that the majority of the wizarding world believed the Dark Lord lost his power, but was still alive somewhere. “Most of us reckon he’s still out there somewhere but lost his powers. Too weak to carry on. ’Cause somethin’ about you finished him, Harry. There was somethin’ goin’ on that night he hadn’t counted on – I dunno what it was, no one does – but somethin’ about you stumped him, all right.” - Harry Potter and the Philosopher's Stone, Chapter 4 (The Keeper of the Keys) They celebrated because they believed he’d lost his power and he wasn’t actively terrorizing them anymore. Some did believe he died, but very many didn’t. They saw his body - they didn’t the first time. What exactly happened surrounding the Dark Lord’s first downfall was fairly mysterious to the majority of the wizarding world. Though the Dark Lord was ripped from his body, there’s never any mention of a dead body left behind in the house - if there was, then more people would likely believe he was truly dead then since Horcruxes weren’t common knowledge. However, when Harry kills him permanently, there is a corpse left behind, and several witnesses who saw. “And Harry, with the unerring skill of the Seeker, caught the wand in his free hand as Voldemort fell backwards, arms splayed, the slit pupils of the scarlet eyes rolling upwards. Tom Riddle hit the floor with a mundane finality, his body feeble and shrunken, the white hands empty, the snake-like face vacant and unknowing. Voldemort was dead, killed by his own rebounding curse, and Harry stood with two wands in his hand, staring down at his enemy’s shell. One shivering second of silence, the shock of the moment suspended: and then the tumult broke around Harry as the screams and the cheers and the roars of the watchers rent the air.” - Harry Potter and the Deathly Hallows, Chapter 36 (The Flaw in the Plan) In addition, after that initial fall, the Dark Lord’s body stays dead and unmoving. “They moved Voldemort’s body and laid it in a chamber off the Hall, away from the bodies of Fred, Tonks, Lupin, Colin Creevey and fifty others who had died fighting him.” - Harry Potter and the Deathly Hallows, Chapter 36 (The Flaw in the Plan) His not getting up was likely enough proof for the majority of the wizarding world, though there very well may have been some who still weren’t sure and either feared or hoped he’d return again.
{ "pile_set_name": "StackExchange" }
Q: Where is file after create in android, where it is? I create a file in android emulator, after that I try it on phone but I don't have the same dir. Where can I find my file on PHONE? public void costam (String text) { try { FileOutputStream fOut = context.openFileOutput("samplefile.txt", context.MODE_WORLD_READABLE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(text); osw.flush(); osw.close(); }catch(Exception e){ } } A: It's here: /data/data/domain.package.AppName/samplefile.txt
{ "pile_set_name": "StackExchange" }
Q: python regular expression to check start and end of a word in a string I am working on a script to rename files. In this scenario there are three possibilities. 1.file does not exist: Create new file 2.File exists: create new file with filename '(number of occurence of file)'.eg filename(1) 3.Duplicate of file already exists: create new file with filename '(number of occurence of file)'.eg filename(2) I have the filename in a string. I can check the last character of filename using regex but how to check the last characters from '(' to ')' and get the number inside it? A: You just need something like this: (?<=\()(\d+)(?=\)[^()]*$) Demo Explanation: (?<=\() must be preceded by a literal ( (\d+) match and capture the digits (?=\)[^()]+$) must be followed by ) and then no more ( or ) until the end of the string. Example: if the file name is Foo (Bar) Baz (23).jpg, the regex above matches 23
{ "pile_set_name": "StackExchange" }
Q: Typedef of structs I am using structs in my project in this way: typedef struct { int str1_val1; int str1_val2; } struct1; and typedef struct { int str2_val1; int str2_val2; struct1* str2_val3; } struct2; Is it possible that I hack this definition in a way, that I would use only types with my code, like struct2* a; a = (struct2*) malloc(sizeof(struct2)); without using keyword struct? A: Yes, as follows: struct _struct1 { ... }; typedef struct _struct1 struct1; struct _struct2 { ... }; typedef struct _struct2 struct2; ... struct2 *a; a = (struct2*)malloc(sizeof(struct2));
{ "pile_set_name": "StackExchange" }
Q: How to submit a form with hidden fields from an action? Say I have the following form that's in classic asp: <form name="impdata" id="impdata" method="POST" action="http://www.bob.com/dologin.asp"> <input type="hidden" value="" id="txtName" name="txtName" /> </form> I need to simulate the action of submitting the form in asp.net mvc3, but I need to modify the hidden value before submitting. Is it possible to do this from the action or in another way? What I have so far... View: @using (Html.BeginForm("Impersonate", "Index", FormMethod.Post, new { id = "impersonateForm" })) { <input id="Impersonate" class="button" type="submit" value="Impersonate" action /> <input type="hidden" value="" id="txtName" name="txtName" /> } Controller: [HttpPost] public ActionResult Impersonate(string txtName) { txtName = txtName + "this string needs to be modified and then submitted as a hidden field"; //Redirect won't work needs the hidden field //return Redirect("http://www.bob.com/dologin.asp"); } Solution: Seems that it isn't easy to do this from the controller so I ended up using jQuery. The action returns a JsonResult. Something like: <button id="Impersonate" class="button" onclick="Impersonate()">Impersonate!</button> <form name="impdata" id="impersonateForm" action="http://www.bob.com/dologin.asp"> <input type="hidden" value="" id="txtName" name="txtName" /> </form> function Impersonate() { $.ajax({ type: 'POST', asynch: false, url: '@Url.Action("Impersonate", "Index")', data: { name: $('#txtName').val() }, success: function (data) { $('#txtName').val(data.Name); $('#impersonateForm').submit(); } }); Seems to work well... A: It is rather hard to redirect to a POST from a POST (relies on HTTP status codes without universal support), and it is impossible from a GET. The simplest solution is probably a little JavaScript on the result that posts the (new) form. Thus you action method returns a view with the necessary data in it (passed via the model from the controller) which will include the JavaScript.
{ "pile_set_name": "StackExchange" }
Q: Selenium doesn't read the second page By default page 1 will open. I am clicking on "next page" using mores.click(), which is opening properly in the browser. But when I try to read the html code, it is still the first page. How do I make sure that I read the second page. This is my code: driver = webdriver.Firefox() driver.get('https://colleges.niche.com/stanford-university/reviews/') mores = driver.find_element_by_class_name('icon-arrowright-thin--pagination') mores.click() vkl = driver.page_source print vkl A: You are probably doing it too quick. Add some wait after your click and make sure that the second page is actually appearing on the screen before you try to read the source html. Keep in mind that Selenium will not automatically wait for the second page to load completely or at all. It will perform the next command: driver.page_source immediately.
{ "pile_set_name": "StackExchange" }
Q: ReactiveUI Dialog Fragment with Xamarin I am using reactiveUI 7.4 with VS 2017. I want a Dialog Fragment where I can use Bind Method like ReactiveFragment. Are there any implementation on this. I was able to find following for java. But not for c#. Could someone guide me. Thanks! https://github.com/ReactiveX/RxAndroid/blob/8c196c59affe79d4015552751c820fe513de0bb7/rxandroid-framework/src/main/java/rx/android/observables/ReactiveDialog.java A: Didn't found one either, we created one, it's available on github if that can help you to create your own : https://github.com/Ideine/Xmf2/blob/cdbe0abd2f924f5668ac2791fbc7fba3b22ddf71/src/Xmf2.Rx.Droid/BaseView/XMFReactiveDialogFragment.cs
{ "pile_set_name": "StackExchange" }
Q: Cannot get service account authorization to work on GCS script using Python client lib APIs In attempting to write a python script to access GCS using service-based authorization, I have come up with the following. Note that 'key' is the contents of my p12 file. I am attempting to just read the list of buckets on my account. I have successfully created one bucket using the web interface to GCS, and can see that with gsutil. When I execute the code below I get a 403 error. At first I thought I was not authorized correctly, but I tried from this very useful web page (which uses web-based authorization), and it works correctly. https://developers.google.com/apis-explorer/#p/storage/v1beta1/storage.buckets.list?projectId=&_h=2& When I look at the headers and query string and compare them to the keaders and query of the website-generated request I see that there is no authorization header, and that there is no key= tag in the query string. I suppose I thought that the credential authorization would have taken care of this for me. What am I doing wrong? code: credentials = SignedJwtAssertionCredentials( '[email protected]', key, scope='https://www.googleapis.com/auth/devstorage.full_control') http = httplib2.Http() http = credentials.authorize(http) service = build("storage", "v1beta1", http=http) # Build the request request = service.buckets().list(projectId="159910083329") # Diagnostic pprint.pprint(request.headers) pprint.pprint(request.to_json()) # Do it! response = request.execute() When I try to execute I get the 403. A: I got this working, however, the code I used is not fundamentally different from the snippet you posted. Just in case you'd like to diff my version with yours, attached below is a complete copy of a Python program that worked for me. I initially got a 403, just like you, which was due to inheriting your project id :). After updating that value to use my project ID, I got a correct bucket listing. Two things to check: Make sure the project id you are using is correct and has the "Google Cloud Storage JSON API" enabled on the Google Developer Console "Services" tab (it's a different service from the other Google Cloud Storage API). Make sure you are loading the service accounts private key exactly as it came from the developer's console. I would recommend reading it into memory from the file you downloaded, as I've done here, rather than trying to copy it into a string literal in your code. #!/usr/bin/env python import pprint import oauth2client from oauth2client.client import SignedJwtAssertionCredentials import httplib2 from apiclient.discovery import build f = open('key.p12', 'r') key = f.read() f.close() credentials = SignedJwtAssertionCredentials( 'REDACTED', key, scope='https://www.googleapis.com/auth/devstorage.full_control') http = httplib2.Http() http = credentials.authorize(http) service = build("storage", "v1beta1", http=http) # Build the request request = service.buckets().list(projectId="REDACTED") # Diagnostic pprint.pprint(request.headers) pprint.pprint(request.to_json()) # Do it! response = request.execute() pprint.pprint(response)
{ "pile_set_name": "StackExchange" }