text
stringlengths
64
89.7k
meta
dict
Q: How to pass a function as props to a component of Material-UI for React? I wanted to make an Appbar which will contain a SearchBar. for this I was using Material-UI for React. I have a file in my component section which loads the Appbar Here is the appbar.js function SearchAppBar(props) { const { classes, placeholder, writeInput } = props; return ( <div className={classes.root}> <AppBar position="fixed"> <Toolbar> <IconButton className={classes.menuButton} color="inherit" aria-label="Open drawer" > <MenuIcon /> </IconButton> <Typography className={classes.title} variant="h6" color="inherit" noWrap > My Weather </Typography> <div className={classes.grow} /> <div className={classes.search}> <div className={classes.searchIcon}> <SearchIcon /> </div> <InputBase placeholder={placeholder} classes={{ root: classes.inputRoot, input: classes.inputInput }} onChange={this.writeInput} /> </div> </Toolbar> </AppBar> </div> ); } SearchAppBar.propTypes = { classes: PropTypes.object.isRequired, placeholder: PropTypes.string, writeInput: PropTypes.func }; export default withStyles(style_appbar)(SearchAppBar); After that, I imported this file to another file named searchbar.js. Why I did that? Well, so that I can control the input with the component state and the props Here is the searchcbar.js import React, { Component } from "react"; import AppBar from "./appbar"; export default class Search extends Component { constructor(props) { super(props); this.state = { term: "" }; this.onInputChange = this.onInputChange.bind(this); } onInputChange(event) { console.log(event.target.value); this.setState({ term: event.target.value }); } render() { return ( <AppBar placeholder="Search forecast for your favorite cities..." value={this.state.term} writeInput={this.onInputChange} /> ); } } And then I imported this file to my app.js. Before diving deep, I wanted to see if everything works, so I put a console log but I am not getting any console log. Rather I am having the error, Cannot read property 'writeInput' of undefined in appbar.js:46:29 writeInput is the function which I was sending to the Materila-UI's component as a props! The link of the sandbox of the code is here, you can check the output too.project's sandbox ps. It maye take some time for the sandbox to boot up! So, can I not send a function as props to the Material-UI's component? If not what's the alternate way to resolve this issue? A: You can send a function to functional component and access it. Don’t use this when calling writeInput. Since you are assigning const { writeInput} = props; you have to call writeInput or if you don’t assign like this then you can call props.writeInput PFB corrected code <InputBase placeholder={placeholder} classes={{ root: classes.inputRoot, input: classes.inputInput }} onChange={writeInput} />
{ "pile_set_name": "StackExchange" }
Q: Import Accumulo Libraries in Scala SBT project I want to know about, using Accumulo or any other java libraries in SBT projects. I used Intellij to automatically import libraries, and it imported but getting errors in Intellij and at runtime/project build like:- Cannot resolve _. In import org.apache.accumulo.core.client.__ I used these steps to include:- File > Project Structure > Libraries(In left Pan) > Clicked+icon located at top left in middle pan > Selected from Maven > Searched Accumulo and Selected org.apache.accumulo.core. A: When you look for Maven dependencies in Maven central it also gives you the syntax for adding the dependencies in several build tools - Including SBT for instance if you look up Apache Accumulo core you'd see the SBT usage as : libraryDependencies += "org.apache.accumulo" % "accumulo-core" % "1.8.1"
{ "pile_set_name": "StackExchange" }
Q: google maps : How to find if any markers inside map I have divided the my google map display in to numbers of parts, Now I want of find it out if any markers are positioned inside a/any particulate cell. Any Help ? Farther Explained : I have got the map bounds by map.getBounds(); method and then farther divide it into numbers of sub-bounds. also I have putted markers as map.addOverlay(markerObject); Now , I want find if of the cells (which I got by dividing the map by bounds) is containing any markers or not . I have divide the entire map bounds into numbers of sub bounds A: So keep all markers in array. Each marker has a method called get_position( ). After you have finished division of map bound into small sub bounds, you just need to iterate over the sub bounds and check whenever the marker within it. PS. Also take a look on it, in some cases could be useful. Suppose you on sub bound cell: var sub_bounds = new Array(); // here you've pushed into an array the sub bounds for ( var i = 0; i<sub_bounds.length; ++i) { for ( var j = 0; j < markers.length; ++j) { var lat = markers[j].get_position( ).lat; var lng = markers[j].get_position( ).lng; if ( sub_bounds[i].sw.lat<lat && lat<sub_bounds[i].ne.lat && sub_bounds[i].sw.lng<lng && lng<sub_bounds[i].ne.lng) // marker within cell, do whatever you need to do } }
{ "pile_set_name": "StackExchange" }
Q: Simple Facebook app, no permissions but add abuse protection/user tracking? Ok so I am developing my first facebook app, it is a very simple voting system everything is going to be on my db and in facebook using an iframe. I do not need to access user information or post to a wall for them or anything like that. I do however need to track users to prevent them from abusing the voting system. I am not sure but is there a unique identifier I can store from the user without requesting permissions? Ie. user token, or id or w.e. I read the basic information portion of the facebook permissions but I can't understand whether that is data given without permissions request or after the permissions request prompt. https://developers.facebook.com/docs/authentication/permissions/ (basic information section) A: Ok, these answers were not helpful. So through trial and error we found that even basic information like the facebook user id, as well as any other unique data are not accessible in any fashion without sending the user to a permissions request to accept the application.
{ "pile_set_name": "StackExchange" }
Q: Select from 2 tables in SQL server I have 2 tables in my database, tell and phone: Table tell: id int name varchar Table phone: number int name nvarchar I wanted to select id and name and number Please help me. A: You'll just need to join the two tables together on the name column: select t.id, t1.name, p.number from tell t inner join phone p on t.name = p.name A: SELECT t.id, t.name, p.number FROM tell t JOIN phone p ON t.name = p.name
{ "pile_set_name": "StackExchange" }
Q: Grouped Table in Monotouch with MvvmCross How do you implement a view with a grouped table in MonoTouch using MvvmCross, so you get something like this: http://www.yetanotherchris.me/storage/downloads/UITableViewController.png Right now I have this piece of code, but I cannot change the UITableViewStyle to Grouped: public partial class HomeView : MvxBindingTouchTableViewController<HomeViewModel> { public HomeView(MvxShowViewModelRequest request) : base(request) { } public override void ViewDidLoad() { base.ViewDidLoad(); NavigationItem.SetRightBarButtonItem(new UIBarButtonItem("History", UIBarButtonItemStyle.Bordered, (sender, e) => ViewModel.DoGoToHistory()), false); var source = new MvxActionBasedBindableTableViewSource( TableView, UITableViewCellStyle.Value1, new NSString("HomeView"), "{'TitleText':{'Path':'Date'},'DetailText':{'Path':'Location'},'SelectedCommand':{'Path':'ViewDetailCommand'}}", UITableViewCellAccessory.DisclosureIndicator); this.AddBindings( new Dictionary<object, string>() { { source, "{'ItemsSource':{'Path':'List'}}" }, { this, "{'Title':{'Path':'TestTitle'}}"} }); TableView.Source = source; TableView.ReloadData(); } } Does anyone knows how to do this? A: Your picture shows only one section.... assuming you are looking for just one section, but this grouped styling, then all you need to do is to introduce UITableViewStyle.Grouped somehow. I'm not sure that the current MvxTableViewController exposes this for you - so you might either need to edit the Mvx source to add the appropriate constructors: protected MvxTouchTableViewController(MvxShowViewModelRequest request, UITableViewStyle style = UITableViewStyle.Plain) : base(style) { ShowRequest = request; } and protected MvxBindingTouchTableViewController(MvxShowViewModelRequest request, UITableViewStyle style = UITableViewStyle.Plain) : base(request, style) { } Alternatively you could use a basic view controller (in which you add a Table as a subview) instead of a tableview derived view controller. If you want multiple Groups, then you'll need to do a bit more work - as you'll need to work out how the bound TableViewSource works out the number of sections and the number of items in each section.
{ "pile_set_name": "StackExchange" }
Q: Converting UTC to local time returns strange result I have a solution of three projects: Core Outlook Add-In ASP.NET Website Both, the Outlook Add-In and the Website use the same methods from Core project to get data from SQL Server. When I write my data into database, I convert all DateTime values of two tables into UTC time: POLL_START POLL_END 2013-07-31 12:00:00.000 2013-08-01 12:00:00.000 and PICK_DATE 2013-07-31 12:00:48.000 2013-07-31 13:00:12.000 When I get the data in my Outlook Add-In, this is the correct result: When opening the same in my website, the picks are fine: But my start and end time are "broken" - the offset is added, bute the wrong hours are used: Here's the code for my converting, that both, Outlook and the website, use: private static void ConvertToLocalTime(POLL item) { item.POLL_START = item.POLL_START.FromUTC(); item.POLL_END = item.POLL_END.FromUTC(); } private static void ConvertToLocalTime(PICK pick) { if (pick.PICK_DATE != null) pick.PICK_DATE = ((DateTime)pick.PICK_DATE).FromUTC(); } And the implementation of DateTime.FromUtc(): public static DateTime FromUTC(this DateTime value) { var local = TimeZoneInfo.Local; return TimeZoneInfo.ConvertTime(value, TimeZoneInfo.Utc, local); } I had the same result with DateTime.ToLocalTime(). Anyone an idea? EDIT 1: This is how the start and end gets displayed on the website (end with End instead of Start): var startCell = new TableCell { Text = String.Format( @"<a href='{0}' title='{2}' target='_blank'>{1:dd.MM.yyyy HH:mm \U\T\Czzz}</a>", Common.GetTimeAndDateHyperlink(_poll.Start, "Vote Start"), _poll.Start, ConvertToLocalTimeZone), CssClass = "InfoContent" }; And the picks: answerCell = new TableCell { Text = String.Format( @"<a href='{0}' title='{2}' target='_blank'>{1}</a>", Common.GetTimeAndDateHyperlink(ao.Time, ao.RealAnswer), ao.RealAnswer, ConvertToLocalTimeZone) }; ao.RealAnswer returns the formated DateTime string: return String.Format(WholeTime == true ? "{0:d}" : @"{0:dd.MM.yyyy HH:mm \U\T\Czzz}", Time); A: I solved the issue now. The DateTime values for start and end didn't get correctly converted: The values weren't casted to local time. The reason, why the website displayed the time as local time is, that the SQL server stores every DateTime value as DateTimeKind.Unspecified instead of keeping the specified data (e.g. DateTimeKind.Utc) during the insert. When reading the data from the server, all Kinds are DateTimeKind.Unspecified, so the .ToString() of DateTime uses the local kind. This results into the UTC time + local UTC offset.
{ "pile_set_name": "StackExchange" }
Q: sugarcrm filter orderby field I am trying to create a filter in SugarCRM 7.7. I am working in a custome module. My new filtername is 'Next Review Date'. I have created a file inside my src/modules/mynewfiltermodule/clients/base/filters/nextreviewdate/nextreviewsate.php $viewdefs[$module_name]['base']['filter']['nextreviewdate'] = array( 'create' => false, 'filters' => array( array( 'id' => 'nextreviewdate', 'name' => 'LBL_NEXT_REVIEW_DATE_ONLY_FILTER', 'filter_definition' => array( array( 'next_review_date' => 'orderby ASC', ), ), 'editable' => false, ), ), ); I want to orderby the field in next_review_date in ASC order, It is a date field. Can someone help me. How can i do it? A: http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.5/UI_Model/Views/Filters/index.html In this link there is no way of sorting in filter. But i Have an idea , you use your filter and apply the default filter there. in custom/modules/module_name/clients/base/views/list/list.php 'orderBy' => array ( 'field' => 'nextreviewdate', 'direction' => 'ASC', ), this will Set the default Sorting order.I found only this solution . I think This may help you.
{ "pile_set_name": "StackExchange" }
Q: How can I determine whether a cv::Mat is using internal or external data? I'm integrating OpenCV with a legacy codebase that has its own ref-counted image class. I'm adding a constructor for creating these images from cv::Mat. As an optimization, I'd like to exploit cv::Mat's refcounting mechanism & make a shallow copy, when it owns the data. However, when it's using external data, then I need to force a deep copy. The problem is that, from reading the docs, I don't see a way to determine whether a cv::Mat owns its data or not. Can this be done (without modifying OpenCV)? BTW, in case it matters, I'm using OpenCV 3.1. A: Use the member UMatData * u of cv::Mat. It should be 0 if cv::Mat uses external data, otherwise you can get the ref counter as follows img.u->refcount
{ "pile_set_name": "StackExchange" }
Q: c# using regex to parse string between quotes I'm fairly new and I couldn't get this to work properly. I have this string ["string1","string2","string3","string4","string5","string6","string7","string8","string9","string10"] And I want to get all values between the " I think regex would be best to do the task. Thanks for your help. A: This will capture between the quotes: (?<=")[\w]+(?!=") An expanded example: string s = "[\"string1\",\"string2\",\"string3\",\"string4\",\"string5\",\"string6\",\"string7\",\"string8\",\"string9\",\"string10\"]"; foreach (Match m in Regex.Matches(s, "(?<=\")[\\w]+(?!=\")")) { Console.WriteLine(m.Value); } A: Since this looks like JSON, try using the JavaScriptSerializer class string myString = "[\"string1\",\"string2\",\"string3\",\"string4\",\"string5\",\"string6\",\"string7\",\"string8\",\"string9\",\"string10\"]"; string[] strings = (new JavaScriptSerializer()).Deserialize<string[]>(myString); foreach (string str in strings) { Console.WriteLine(str); } Kinda seems overkill though.
{ "pile_set_name": "StackExchange" }
Q: process data with header in rows in python csv I have a csv file that has the product name in the first row and data headers in second row and from third row onwards contains the actual data with status of each user. And the csv file looks like this: adidas,, USER_ID,USER_NAME b012345,zaihan,Process b212345,nurhanani,Check b843432,nasirah,Call b712345,ibrahim,Check nike,, USER_ID,USER_NAME b842134,khalee,Call h123455,shabree,Process b777345,ibrahim,Process b012345,zaihan,Check b843432,nasirah,Call b312451,nurhanani,Process I would like to split the data product wise and rearrange the header and data like this: From header like this adidas,, USER_ID,USER_NAME b012345,zaihan,Process To header like this USER_ID,USER_NAME,adidas b012345,zaihan,Process And create DataFrame of each product and merge them like this: I had been writing the code for sometime and I think I've to hard-code the headers (for example, 'adidas' and 'nike') since what I understand from reading SO answers is, I need unique header names and the following code is not getting what I want: My python code is: import csvkit import sys import os from csvkit import convert with open('/tmp/csvdata.csv', 'rb') as q: reader = csvkit.reader(q) with open('/tmp/csvdata2.csv', 'wb') as s: data = csvkit.writer(s) data.writerow(['Name', 'Userid', 'adidas', 'nike']) for row in reader: row_data = [row[0], row[1], row[2], ''] data = csvkit.writer(s) data.writerow(row_data) EDIT So I got a solution from @piRSquared, which is correct if there are unique set of records for a product, but there could be multiple status for each user for the same product. And the solution gives ValueError: Index contains duplicate entries, cannot reshape An example for the input CSV data that having multiple status and will cause this problem: adidas,, USER_ID,USER_NAME b012345,zaihan,Process h003455,shabree,Check b212345,nurhanani,Check b843432,nasirah,Call b712345,ibrahim,Check b712345,ibrahim,Process nike,, USER_ID,USER_NAME b842134,khalee,Call h123455,shabree,Process b777345,ibrahim,Process b012345,zaihan,Check b843432,nasirah,Call b312451,nurhanani,Process I hope to achieve a result like this, seemingly that users in the same brand category can have the same id,name and both Process and Check. USER_ID,USER_NAME,adidas,nike b012345,zaihan,Process h003455,shabree,Check,Process b212345,nurhanani,Check,Process b843432,nasirah,Call,Call b712345,ibrahim,Check b712345,ibrahim,Process b777345,ibrahim,,Process b842134,khalee,,Call The end result should have an additional row like the above for users which has both Check and Process in the same brands (in this case the user ibrahim in nike brand) A: Ok, this is complicated. Solution from StringIO import StringIO import re import pandas as pd text = """adidas,, USER_ID,USER_NAME b012345,zaihan,Process b212345,nurhanani,Check b451234,nasirah,Call c234567,ibrahim,Check nike,, USER_ID,USER_NAME b842134,khalee,Call h123455,shabree,Process c234567,ibrahim,Process c143322,zaihan,Check b451234,nasirah,Call """ m = re.findall(r'(.*,,\n(.*([^,]|,[^,])\n)*)', text) dfs = range(len(m)) keys = range(len(m)) for i, f in enumerate(m): lines = f[0].split('\n') lines[1] += ',' keys[i] = lines[0].split(',')[0] dfs[i] = pd.read_csv(StringIO('\n'.join(lines[1:]))) df = pd.concat(dfs, keys=keys) df = df.set_index(['USER_ID', 'USER_NAME'], append=True).unstack(0) df.index = df.index.droplevel(0) df.columns = df.columns.droplevel(0) df = df.stack().unstack() Demonstration print df.to_csv() USER_ID,USER_NAME,adidas,nike b012345,zaihan,Process, b212345,nurhanani,Check, b451234,nasirah,Call,Call b842134,khalee,,Call c143322,zaihan,,Check c234567,ibrahim,Check,Process h123455,shabree,,Process Explanation # regular expression to match line with a single value identified # by having two commas at the end of the line. # This grabs nike and adidas. # It also grabs all lines after that until the next single valued line. m = re.findall(r'(.*,,\n(.*([^,]|,[^,])\n)*)', text) # place holder for list of sub dataframes dfs = range(len(m)) # place holder for list of keys. In this example this will be nike and adidas keys = range(len(m)) # Loop through each regex match. This example will only have 2. for i, f in enumerate(m): # split on new line so I can grab and fix stuff lines = f[0].split('\n') # Fix that header row only has 2 columns and data has 3 lines[1] += ',' # Grab nike or adidas or other single value keys[i] = lines[0].split(',')[0] # Create dataframe by reading in rest of lines dfs[i] = pd.read_csv(StringIO('\n'.join(lines[1:]))) # Concat dataframes with appropriate keys and pivot stuff df = pd.concat(dfs, keys=keys) df = df.set_index(['USER_ID', 'USER_NAME'], append=True).unstack(0) df.index = df.index.droplevel(0) df.columns = df.columns.droplevel(0) df = df.stack().unstack()
{ "pile_set_name": "StackExchange" }
Q: Best way to convert IEnumerable to string? Why isn't it possible to use fluent language on string? For example: var x = "asdf1234"; var y = new string(x.TakeWhile(char.IsLetter).ToArray()); Isn't there a better way to convert IEnumerable<char> to string? Here is a test I've made: class Program { static string input = "asdf1234"; static void Main() { Console.WriteLine("1000 times:"); RunTest(1000, input); Console.WriteLine("10000 times:"); RunTest(10000,input); Console.WriteLine("100000 times:"); RunTest(100000, input); Console.WriteLine("100000 times:"); RunTest(100000, "ffff57467"); Console.ReadKey(); } static void RunTest( int times, string input) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < times; i++) { string output = new string(input.TakeWhile(char.IsLetter).ToArray()); } sw.Stop(); var first = sw.ElapsedTicks; sw.Restart(); for (int i = 0; i < times; i++) { string output = Regex.Match(input, @"^[A-Z]+", RegexOptions.IgnoreCase).Value; } sw.Stop(); var second = sw.ElapsedTicks; var regex = new Regex(@"^[A-Z]+", RegexOptions.IgnoreCase); sw.Restart(); for (int i = 0; i < times; i++) { var output = regex.Match(input).Value; } sw.Stop(); var third = sw.ElapsedTicks; double percent = (first + second + third) / 100; double p1 = ( first / percent)/ 100; double p2 = (second / percent )/100; double p3 = (third / percent )/100; Console.WriteLine("TakeWhile took {0} ({1:P2}).,", first, p1); Console.WriteLine("Regex took {0}, ({1:P2})." , second,p2); Console.WriteLine("Preinstantiated Regex took {0}, ({1:P2}).", third,p3); Console.WriteLine(); } } Result: 1000 times: TakeWhile took 11217 (62.32%)., Regex took 5044, (28.02%). Preinstantiated Regex took 1741, (9.67%). 10000 times: TakeWhile took 9210 (14.78%)., Regex took 32461, (52.10%). Preinstantiated Regex took 20669, (33.18%). 100000 times: TakeWhile took 74945 (13.10%)., Regex took 324520, (56.70%). Preinstantiated Regex took 172913, (30.21%). 100000 times: TakeWhile took 74511 (13.77%)., Regex took 297760, (55.03%). Preinstantiated Regex took 168911, (31.22%). Conclusion: I'm doubting what's better to prefer, I think I'm gonna go on the TakeWhile which is the slowest only on first run. Anyway, my question is if there is any way to optimize the performance by restringing the result of the TakeWhile function. A: How about this to convert IEnumerable<char> to string: string.Concat(x.TakeWhile(char.IsLetter)); A: Edited for the release of .Net Core 2.1 Repeating the test for the release of .Net Core 2.1, I get results like this 1000000 iterations of "Concat" took 842ms. 1000000 iterations of "new String" took 1009ms. 1000000 iterations of "sb" took 902ms. In short, if you are using .Net Core 2.1 or later, Concat is king. See MS blog post for more details. I've made this the subject of another question but more and more, that is becoming a direct answer to this question. I've done some performance testing of 3 simple methods of converting an IEnumerable<char> to a string, those methods are new string return new string(charSequence.ToArray()); Concat return string.Concat(charSequence) StringBuilder var sb = new StringBuilder(); foreach (var c in charSequence) { sb.Append(c); } return sb.ToString(); In my testing, that is detailed in the linked question, for 1000000 iterations of "Some reasonably small test data" I get results like this, 1000000 iterations of "Concat" took 1597ms. 1000000 iterations of "new string" took 869ms. 1000000 iterations of "StringBuilder" took 748ms. This suggests to me that there is not good reason to use string.Concat for this task. If you want simplicity use the new string approach and if want performance use the StringBuilder. I would caveat my assertion, in practice all these methods work fine, and this could all be over optimization. A: Assuming that you're looking predominantly for performance, then something like this should be substantially faster than any of your examples: string x = "asdf1234"; string y = x.LeadingLettersOnly(); // ... public static class StringExtensions { public static string LeadingLettersOnly(this string source) { if (source == null) throw new ArgumentNullException("source"); if (source.Length == 0) return source; char[] buffer = new char[source.Length]; int bufferIndex = 0; for (int sourceIndex = 0; sourceIndex < source.Length; sourceIndex++) { char c = source[sourceIndex]; if (!char.IsLetter(c)) break; buffer[bufferIndex++] = c; } return new string(buffer, 0, bufferIndex); } }
{ "pile_set_name": "StackExchange" }
Q: Recursive Descent Parser with Indentation and Backtracking I have been trying to find an Recursive Descent Parser Algorithm that is also suited for indentation with backtracking. But I keep having myself finding troublesome solutions for this. Are there any resources out there that also deal with indentation? Thanks A: Based on your question I'm assuming that you're writing your own recursive descent parser for an indentation-sensitive language. I've experimented with indentation-based languages before, and I solved the problem by having a state that keeps track of the current indentation level and two different terminals that match indentation. Both of them match indentation units (say two spaces or a tab) and count them. Let's call the matched indentation level matched_indentation and the current indentation level expected_indentation. For the first one, let's call it indent: if matched_indentation < expected_indentation, this is a dedent, and the match is a failure. if matched_indentation == expected_indentation, the match is a success. The matcher consumes the indentation. if matched_indentation > expected_indentation, you have a syntax error (indentation out of nowhere) and should handle it as such (throw an exception or something). For the second one, let's call it dedent: if matched_indentation < expected_indentation, the match is successful. You reduce expected_indentation by one, but you don't consume the input. This is so that you can chain multiple dedent terminals to close multiple scopes. if matched_indentation == expected_indentation, the match is successful, and this time you do consume the input (this is the last dedent terminal, all scopes are closed). if matched_indentation > expected_indentation, the match simply fails, you don't have a dedent here. Those terminals and non-terminals after which you expect an increase in indentation should increase expected_indentation by one. Let's say that you want to implement a python-like if statement (I'll use EBNF-like notation), it would look something like this: indented_statement : indent statement newline; if_statement : 'if' condition ':' newline indented_statement+ dedent ; Now let's look at the following piece of code, and also assume that an if_statement is a part of your statement rule: 1|if cond1: <- expected_indentation = 0, matched_indentation = 0 2| if cond2: <- expected_indentation = 1, matched_indentation = 1 3| statement1 <- expected_indentation = 2, matched_indentation = 2 4| statement2 <- expected_indentation = 2, matched_indentation = 2 5| <- expected_indentation = 2, matched_indentation = 0 On the first four lines you'll successfully match an indent terminal On the last line, you'll match two dedent terminals, closing both the scopes, and resulting with expected_indentation = 0 One thing you should be careful of is where you put your indent and dedent terminals. In this case, we don't need one in the if_statement rule because it is a statement, and indented_statement already expects an indent. Also mind how you treat newlines. One choice is to consume them as a sort of statement terminator, another is to have them precede the indentation, so choose whichever suits you best.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to link WM_INPUT with WM_KEYDOWN message or just distinguish it (WM_KEYDOWNs) by devices? I've done some research (with single input device altrough) in this field and discovered that in most situations messages are sent by pair, first WM_INPUT and then WM_KEYDOWN. So it's merely possible to link them together for filtering, i.e. WM_INPUT flags that it's corresponding WM_KEYDOWN shoudn't be sent to reciever (in my case first i discard all WM_KEYDOWN and then decide whenever i need to send them back to their recipients). I just assume that all next WM_KEYDOWN are belong to last WM_INPUT. My question exactly: can i seriously rely on that principle? Won't those messages mix up if i use multiple input devices? There are some serious questions about its reliability already: 1. How do i distinguish repeating input from multiple devices (answer is obvious - i can't). 2. Would WM_INPUT-WM_KEYDOWN pairs mix up in case of input from multiple devices? i.e. form an cortege like WM_INPUT, WM_INPUT, WM_KEYDOWN, WM_KEYDOWN? Also maybe it is possible to just discard all WM_KEYDOWN and generate all keyboard events by myself? Altrough it would be technically quite difficult, because there may be multiple WM_KEYDOWNs from one WM_INPUT (key repeatence work that way, multiple WM_KEYDOWN, one WM_KEYUP). Just in case, here's what i need to achieve: I need to filter all messages by time between them. All user input gets filtered by time interval between keypresses. If two messages were sent with interval <50ms i discard first message and second awaits while its TTL exceeds and if so, it sent to its recipient. Difficulty is that there can be multiple input devices and those timings will mess up with each other. A: I figured out that keyboard hook (WH_KEYBOARD) actually occurs before WM_KEYDOWN message, can't check if simultanious input from several devices will mess up order of WM_INPUTS and KeyboardHook events (like sequence of events: Dev0_WM_INPUT Dev1_WM_INPUT Dev0_KBDHook Dev1_KBDHook - altrough that sequence of event will be handle, what i fear is if Dev1_KBDhook will appear before Dev0_KBDhook or worse). With WM_KEYDOWN such mess was possible, still don't know if it will be same with keyboad hook. Anyway it is possible solution. On WM_INPUT i create Message itself and partly fill, on next KeyboardHookEvent i just fill remaining part. Generally WM_INPUTs and KeyboardHook events occur by pairs, but as i mentioned before, i don't exactly know if it can mess up, but if even so, if it will maintain order of KeyboardHookEvents and WM_INPUTS (like Dev0_INPUT, Dev1_INPUT and then Dev0_KBDEvent, Dev1_KBDEvent) it will give no trouble to parse those sequences. For example one stack: WM_INPUT pushes new message struct, KBDEvent pops and fill remaining parts. Not generally good solution, but i guess it is good enough to use if no other exists, solves the problem, atleas partially. If i'll manage to test its behavious upon simultanious input from multiple devices, i will post info here. Altrough i really doubt there will be any mess that can't handled. Unless windows chooses time to send corresponding keyboard event by random... Forgot to mention, yes it's partially possible to discard all input and generate manually. I just PostMessage manually forged message (i get lparam from KeyboardHookEvent). But it will give some problems. Like hotkeys won't work and also anything that uses GetAsyncKeyState. In my case it is acceptable altrough.
{ "pile_set_name": "StackExchange" }
Q: Find and replace a jar file using Maven Suppose you are working on a big project, which is run on some application server (let's say Tomcat, but it may be also Jboss, or Jetty, or something else). The project consists of a several wars, while each war contains a lot of jar. The whole thing is built using Maven and it takes a lot of time to build it all. Now, suppose a developer makes a change in just one module that produces one small jar. To continue working and test the change, the developer needs to replace this jar in the relevant wars and restart server (sometimes it's sufficient to redeploy wars). It's much faster then rebuilding the whole application. I have seen a lot of developers (including myself) creating shell scripts for this task. However, it could be much nicer, if it could be done automatically using maven. Let's say when running "mvn install" the plugin will also go to some predefined location (e.g. ${tomcat}/webapps) and search for all appearances of myjar.jar and replace them with a new version (We have multiple jars, remember?) Does anyone know about such a plugin? Or may be about some other tool that can do the same task? Or some better idea how to do it? Updated: Btw, If I don't find a solution, I'll probably implement it myself. So please let me know if you are interested. I'll need some beta testers :) Updated: So I created the plugin myself. See http://code.google.com/p/replace-file-plugin/ Any feedback is appreciated. A: Well, any features I asked for in this question, I have implemented myself. See http://code.google.com/p/replace-file-plugin/ I'll appreciate any feedback.
{ "pile_set_name": "StackExchange" }
Q: Cassandra Query Failures: All host(s) tried for query failed (no host was tried) I am not able to do queries against the Cassandra Node. I am able to make the connection to the cluster and connect. However while doing the the query, it fails Caused by: com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (no host was tried) at com.datastax.driver.core.RequestHandler.reportNoMoreHosts(RequestHandler.java:217) at com.datastax.driver.core.RequestHandler.access$1000(RequestHandler.java:44) at com.datastax.driver.core.RequestHandler$SpeculativeExecution.sendRequest(RequestHandler.java:276) at com.datastax.driver.core.RequestHandler.startNewExecution(RequestHandler.java:117) at com.datastax.driver.core.RequestHandler.sendRequest(RequestHandler.java:93) at com.datastax.driver.core.SessionManager.executeAsync(SessionManager.java:127) ... 3 more This is how I am connecting to the cluster: List<String> servers = config.getCassandraServers(); Builder builder = Cluster.builder(); for (String server : servers) { builder.addContactPoints(server); } PoolingOptions opts = new PoolingOptions(); opts.setCoreConnectionsPerHost(HostDistance.LOCAL, opts.getCoreConnectionsPerHost(HostDistance.LOCAL)); // setup socket exceptions SocketOptions socketOpts = new SocketOptions(); socketOpts.setReceiveBufferSize(1048576); socketOpts.setSendBufferSize(1048576); socketOpts.setTcpNoDelay(false); cluster = builder.withSocketOptions(socketOpts) .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE) .withPoolingOptions(opts) .withReconnectionPolicy(new ConstantReconnectionPolicy(100L)) .withLoadBalancingPolicy(new DCAwareRoundRobinPolicy(getColo(config))) .build(); cluster.connect(); I am using latest stable version of Cassandra 2.2.3 with the Datastax driver: <dependency> <groupId>com.datastax.cassandra</groupId> <artifactId>cassandra-driver-core</artifactId> <version>2.1.8</version> </dependency> Any pointers are highly appreciated Thanks Masti A: Here is the solve: Issue was with .withLoadBalancingPolicy(new DCAwareRoundRobinPolicy(getColo(config))) Here I only have a single node in AWS cloud to test my adapter and it was throwing Cassandra off. Removing that solves the issue Thanks
{ "pile_set_name": "StackExchange" }
Q: Byte Buddy - HotSwap with ByteBuddyAgent I'm trying to use the HotSwap feature of byte buddy. Unfortunately I receive some errors. I have read the documentation on the official website, and I'm aware that it only works when the program use a Java agent. I have tried to put -javaagent parameter on the startup of the Java virtual machine which looks like this: -javaagent:C:\lib\byte-buddy-agent-0.5.6.jar This produces the following error when starting my application: java.lang.ClassNotFoundException: net.bytebuddy.agent.ByteBuddyAgent.Installer FATAL ERROR in native method: processing of -javaagent failed at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:304) at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401) Exception in thread "main" Java Result: 1 Nevertheless I tried use the ByteBuddyAgent.installOnOpenJDK() method instead of the -javaagent parameter in hope that will solve the problem. But this throws following error, which relies on the same problem I think: java.lang.ClassNotFoundException: net.bytebuddy.agent.ByteBuddyAgent$Installer at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:304) at sun.instrument.InstrumentationImpl.loadClassAndCallAgentmain(InstrumentationImpl.java:411) Apr 09, 2015 1:35:01 PM net.bytebuddy.agent.ByteBuddyAgent doInstall INFORMATION: Cannot delete temporary file: C:\Users\Flo\AppData\Local\Temp\byteBuddyAgent4745240427430305215.jar Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1770) at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1653) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) ... Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) ... Caused by: java.lang.IllegalStateException: The programmatic installation of the Byte Buddy agent is only possible on the OpenJDK and JDKs with a compatible 'tools.jar' at net.bytebuddy.agent.ByteBuddyAgent.installOnOpenJDK(ByteBuddyAgent.java:176) at hotswapping.FXMLDocumentController.handleByteBuddyButton(FXMLDocumentController.java:90) ... 60 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at net.bytebuddy.agent.ByteBuddyAgent.doInstall(ByteBuddyAgent.java:199) at net.bytebuddy.agent.ByteBuddyAgent.installOnOpenJDK(ByteBuddyAgent.java:174) ... 61 more Caused by: com.sun.tools.attach.AgentInitializationException: Agent JAR loaded but agent failed to initialize at sun.tools.attach.HotSpotVirtualMachine.loadAgent(HotSpotVirtualMachine.java:121) ... 67 more Does anyone know what is the problem or have I misunderstood something from the tutorial? Btw I tried it with jdk1.7.0_55 and jdk1.8.0_40 and use neatbeans as ide. Version of byte buddy which I am using is v0.5.6. Thanks for helping. EDIT: It seems that the error with the -javaagent parameter is a bug in the current version, thanks Rafael Winterhalter for the quick response. I also figured out what was problem with the ByteBuddyAgent.installOnOpenJDK() method. It was a really stupid mistake from my side. It seems my netbeans use an older java version as jdk1.8.0_40, so I changed the netbeans_jdkhome variable in the netbeans.conf file in the etc folder of netbeans. Now that my netbeans use the same java version as my projects it seems that it works like a charm even with JavaFX applications. The only strange thing is that this error occurred only in JavaFX applications, in normal Java applications I never had this problems. FYI: Here is the code sample of my JavaFX application: package testbytebuddy; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import net.bytebuddy.agent.ByteBuddyAgent; public class TestByteBuddy extends Application { @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Say 'Hello World'"); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("Hello World!"); } }); StackPane root = new StackPane(); root.getChildren().add(btn); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Start application"); ByteBuddyAgent.installOnOpenJDK(); launch(args); System.out.println("End application"); } } A: The problem with using the agent directly is a bug in Byte Buddy where I reference the agent's main class with net.bytebuddy.agent.ByteBuddyAgent.Installer and not with net.bytebuddy.agent.ByteBuddyAgent$Installer as it would be correct. This will be fixed for Byte Buddy 0.5.7 which should be released at the end of April / beginning of Mai. For the second error, it seems like you used a bundled JDK that does not allow the programmatic attachment of the agent. It was difficult to see as this resultet in a similar error message. The programmatic attachment is however something that can go wrong, therefore it is difficult to provide more detailed information on the actual cause. Good you figured it out. This answer was already solved in the comments, this should serve as an overview for potential future readers.
{ "pile_set_name": "StackExchange" }
Q: truncate table for all db in sql server 2000 i need a script that will go to every db in server and if exsistes a table named "table1" will do truncate table table1 A: First run this script to see which tables would be truncated. Then do the obvious modification. SET NOCOUNT ON declare @name sysname declare @sql varchar(255) declare @sql2 varchar(255) declare @rc int declare db_cursor cursor for select name from master..sysdatabases open db_cursor fetch next from db_cursor into @name while @@FETCH_STATUS = 0 begin Set @sql = 'select * into #t1 from ' + @name + '..sysobjects where name = ''table1'' and type = ''U''' EXEC(@sql) set @rc = @@rowcount if @rc > 0 begin set @sql2 = 'use ' + @name + '; ' + 'Truncate table table1' print @sql2 --Exec(@sql2) end fetch next from db_cursor into @name end close db_cursor deallocate db_cursor
{ "pile_set_name": "StackExchange" }
Q: Does radiation spread within a room or the entire vault? If I send a dweller into the wasteland and they come back with radiation poisoning, or there is a radroach infestation, will the radiation poisoning spread to other dwellers in the same room as the poisoned dwellers or to all dwellers within my vault? Also if it does spread, how is the rate of spread calculated? A: Neither. Dwellers in the vault take radiation damage where there isn't enough water. As long there is enough water, you don't have to worry about any radiation. Dwellers in the Wasteland with less than 10 END will take Radiation damage over time. There is no risk of them passing this radiation damage on to other dwellers. EDIT: As of 1.1, wasteland explorers with END up to 12 take Rad damage, but so little they will use 25 stimpacks and die before they need a single Radaway
{ "pile_set_name": "StackExchange" }
Q: Simple dropdown div I'm struggling with a simple dropdown link. I have a div with a text link and when clicking this text should appear another div with text information. So far the HTML is: <div id="about" class="fluid"> <a href="#">About & Contact</a> <div id="dropdown" class="fluid"><blockquote> We are a bla bla...</div> </div> I used CSS in order to hide the dropdown div: #dropdown {display: none;} And the jQuery function is: <script> $(function(){ $('#about').each(function(){ $(this).click(function(){ $(this).siblings('#dropdown').slideToggle(300); }); }); });​​ </script> Any help would be appreciated, thank you very much. A: Another way could be to use below code $("#about a").click(function() { $("#dropdown").toggle(); return false; }); https://jsfiddle.net/santoshjoshi/n0yeo9nb/
{ "pile_set_name": "StackExchange" }
Q: MVC4 Application Generates Empty with ambiguous tag in Google Chrome I have experienced 2 years in working with Microsoft MVC but today saw a strange tag and browser shows nothing on page load. That is after <html> and before <head> tags: <object type="{0C55C096-0F1D-4F28-AAA2-85EF591126E7}" cotype="cs" id="cosymantecbfw" style="width: 0px; height: 0px; display: block;"></object> While, The master layout is full of partial/static views. The <body> tag is completely null! Result viewed in Google Chrome. Edit: Alien Tag Produced by Norton(Symantec) in Google Chrome according to this page. A: The problem is not related to loading partial views and MVC works fine. JavaScript parts of page cause the problem. When we use our own scripts to employ called libraries to render elements, features and etc..., we have 2 choices to add scripts : Add by calling script file Add by writing scripts inside related page I have used both of 2 above concepts in my pages. I solved it by using second solution by collecting all of scripts in a file. And the ambiguous tag generated by Norton Internet Security In Google Chrome not in another Browsers.
{ "pile_set_name": "StackExchange" }
Q: How to save output of a generated text I am using the following code to generate a text: for i in xrange(300): sys.stdout.write(alphabet[bisect.bisect(f_list, random.random()) and I would like to know how to store the same text (in the variable text1) so that I can use it later in this code: for i in xrange(300): text1=sys.stdout.write(alphabet[bisect.bisect(f_list, random.random()) for word in text1: fd.inc(word) A: Something like this? text1 = [alphabet[bisect.bisect(f_list, random.random())] for i in xrange(300)]
{ "pile_set_name": "StackExchange" }
Q: Area of a lattice polygon in terms of its width Let $M$ be a lattice polygon on a plane (i.e. its vertices are integer points $(i,j)\in\mathbb Z^2$). Let us define lattice width in a direction $v=(m,n)\in\mathbb Z^2$ as $w_v(M)=\max\limits_{x,y\in M} v\cdot(x-y)$. Suppose the $minimal$ lattice width of $M$ equals $d$. It is clear that the area of $M$ should be proportional to $d^2$. One can prove an inequalities $area\geq d^2/4$ as is written in comments. But it seems far from the best one. So, the question is what is the best $\alpha$ such that $area(M)\geq \alpha d^2$ for each $M$ with minimal lattice width equals $d$. From my comment below one can extract that $\alpha\leq 3/8$ Added: F. Petrov gave a link to the proof of the fact, but there is no complete proof in the Internet so I rewrote it in the appendix in http://arxiv.org/abs/1306.4688 A: $\alpha=3/8$ is sharp according to, say this article, the authors refer to [L. Fejes-Toth and E. Makai, Jr., On the thinnest non-separable lattice of convex plates, Studia Sci. Math. Hungar. 9 (1974), 191–193.]
{ "pile_set_name": "StackExchange" }
Q: Sketching a discrete-time dynamical system with a repelling period-2 orbit Sketch the graph of a continuous function which has an attracting fixed point and a repelling period-2 orbit. I am having a hard time trying to come up with a graph with the above conditions. I know that to have an attracting fixed point, the magnitude of the slope of the tangent line has to be between 0 and 1. But how do you draw a repelling period-2 orbit? A: Suppose you want your orbit to be $x_1\to x_2\to x_1$. Draw the graph of your function $f$ so that it goes through the points $(x_1,x_2)$ and $(x_2,x_1)$. In addition, make sure that the absolute value of the slope of the graph as it goes through those points is larger than $1$. For, if $F=f \circ f$, then we have $$F'(x_1) = f'(f(x_1))f'(x_1) = f'(x_2)f'(x_1) = F'(x_2).$$ Thus, if $f'(x_2)$ and $f'(x_1)$ are both larger than one in absolute value, then the same will be true for $F$ and the orbit will be repelling. Finally, as you seem to know, make sure that the graph of $f$ intersects the graph of $y=x$ with small slope. If $x_1 = 0$ and $x_2 = 1$, then one such graph might look like so:
{ "pile_set_name": "StackExchange" }
Q: Dynamically add image to a slider in wordpress I am new to wordpress. Basically implemented a slider which works perfectly. Now Main thing is that I want the images that I used to be uploaded by admin user. I don't have idea to achieve this. Please help me. Amy help is heartly appreciated. Here is my code :- <aside class="portfolio-right"> <ul class="mybxslider"> <li><img src="<?php bloginfo('template_url'); ?>/images/acc-thumbnail-1.jpg" /></li> <li><img src="<?php bloginfo('template_url'); ?>/images/acc-thumbnail-2.jpg" /></li> <li><img src="<?php bloginfo('template_url'); ?>/images/acc-thumbnail-3.jpg" /></li> </ul> <script> $('.mybxslider').bxSlider({ adaptiveHeight: true, mode: 'fade' }); </script> </aside> A: Create custom post type Slider Images & add slider image as feature image in that post type.. for display that images in slider use <ul class="mybxslider"> <?php $args = array( 'post_type' => 'slider_post', //Post type 'posts_per_page' => 10 ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?> <li><img src="<?=$url?>" width="350" height="350" /></li> <?php } } ?> </ul>
{ "pile_set_name": "StackExchange" }
Q: Add new row with jQuery, calculation function not executed I have a table that has this function: function subtotal(){ var gt = 0; $('.itemlist tr').each(function (){ $(this).find('.ttl span').html($('.qty', this).val() * $('.price span', this).text()); }); $('.ttl').each(function(){ total += parseInt($(this).text(),10); }); $('.subtotal').html(total); } $(".qty").keyup(subtotal); But having added a new row with this function; $(".addrow a").click(function(event){ $(".itemlist").append('<tr><td><a href="#" class="delRow">x</a></td><td>000000</td><td><select class="fixed2"><option>---</option><option>Baju Kurung</option><option>Kebaya Pondan Shining</option></select></td><td><select class="fixed2"><option>---</option><option>Hijau</option><option>Purple</option></select></td><td>0</td><td><input type="number" class="qty" /></td><td class="price">RM<span>2.00</span></td><td class="ttl">0.00</td></tr>'); event.preventDefault(); }); The newly created row isn't functioning properly anymore. Here's http://jsfiddle.net/RtCdG/3/ Help and feedback appreciated. A: Here is the working code for you, $(document).on('keyup', ".qty", function (e) { var total = 0; $(this).closest('tr').find('.ttl span').html($(this).closest('tr').find('.qty').val() * $(this).closest('tr').find('.price span').text()); $('.ttl span').each(function () { total += parseInt($(this).text(), 10); }); $('.subtotal').html(total); }); and your new insertinf html should have <td class="ttl">RM<span>0.00</span></td> instead of <td class="ttl">0.00</td> http://jsfiddle.net/RtCdG/9/ Update, As you request following are the reasons, To apply any event to dynamic content, you have to use jQuery .on() API You are calling.find('.ttl span').html() in your subtotal but there is no span inside the .ttl for new row.
{ "pile_set_name": "StackExchange" }
Q: He dies when he is Teaching English for adults we were reading a story. In the story of a man appears this sentence " He dies when he is 102 years old" An ESL adult asked me: Shouldn't be that sentence in the past,... when he was 102? I said No, it's OK the way it is;but I struggled to give him the reason. Could somebody help? There are some questions about the use of would with the historical present on this site: "Paul would later transfer to McKinley High and join Kevin and Winnie." Using “would” when narrating a story in simple present [duplicate] But this question is about why it is possible to use the present simple in this particular example. It does not ask about the use of would with the present simple. I wasn't born here so English is my second language too!!! A: Narrative is most often in the past tense, but it is nevertheless quite common to use the historic (or narrative) present tense. When using the historic present, the viewpoint moves along with the events described, so is is the only choice here. You could say (in a present-tense narrative) He died when he was 102 years old, and that would locate the death in the past relative to the current narrative moment (eg perhaps the narrator is looking at a picture of his father); but to change the tense in the middle of that sentence would be incoherent.
{ "pile_set_name": "StackExchange" }
Q: What happened to my edit on "Molecular Gastronomy" question? Two days ago I edited the title of this question, What is Molecular Gastronomy? because it was written "What's is Molecular Gastronomy?" I see today it was updated, but by someone else, and I don't show up in the edit history. Did I imagine it, or was it rejected for some reason? I'm not sure where I can find rejected edit history. A: There's a page where you can see the status of your edits. You should start by checking that. To do that go to your account -> Activity -> Suggestions. I don't see you in the edit history though. I believe a question (or answer) may only have one suggested edit in queue at a time. So if you were second, your edit would not have been submitted. Sounds like that's what happened.
{ "pile_set_name": "StackExchange" }
Q: how to put condition check each group by value in mysql Here how my tables look like: CREATE TABLE my_table(id INT,emp_id INT,dept_id INT,salary INT,isapproved INT,isvalid INT); INSERT INTO my_table VALUES (1, e1, d1, 100, 1, 1), (2, e1, d2, 200, 0, 1), (3, e1, d1, 300, 0, 0), (4, e2, d1, 400, 1, 0), (5, e3, d2, 500, 1, 1), (6, e3, d1, 600, 1, 1), (7, e3, d1, 700, 1, 1), (8, e4, d3, 800, 1, 1); what i want first of all,i need to check the query group by emp_id , i got e1,e2,e3,e4 then check each emp_id with condition isapproved = 1 and isvalid = 1 finally i want this answer emp_id e3 e4 note: i need single query.please help me. A: You can do a self join onto the table then exclude any which have a matching record which isn't approved or isn't valid. SELECT mt.emp_id FROM my_table mt LEFT JOIN my_table mtx ON (mtx.emp_id = mt.emp_id AND (mtx.isapproved = 0 OR mtx.isvalid = 0)) WHERE mt.isapproved = 1 AND mt.isvalid = 1 AND mtx.id IS NULL GROUP BY mt.emp_id SQL Fiddle (note I changed the type of emp_id and dept_id as these were integers but had string values).
{ "pile_set_name": "StackExchange" }
Q: Rails : How to build statistics per day/month/year or How database agnostic SQL functions are missing (ex. : STRFTIME, DATE_FORMAT, DATE_TRUNC) I have been searching all over the web and I have no clue. Suppose you have to build a dashboard in the admin area of your Rails app and you want to have the number of subscriptions per day. Suppose that you are using SQLite3 for development, MySQL for production (pretty standard setup) Basically, there are two options : 1) Retrieve all rows from the database using Subscriber.all and aggregate by day in the Rails app using the Enumerable.group_by : @subscribers = Subscriber.all @subscriptions_per_day = @subscribers.group_by { |s| s.created_at.beginning_of_day } I think this is a really bad idea. Retrieving all rows from the database can be acceptable for a small application, but it will not scale at all. Database aggregate and date functions to the rescue ! 2) Run a SQL query in the database using aggregate and date functions : Subscriber.select('STRFTIME("%Y-%m-%d", created_at) AS day, COUNT(*) AS subscriptions').group('day') Which will run in this SQL query : SELECT STRFTIME("%Y-%m-%d", created_at) AS day, COUNT(*) AS subscriptions FROM subscribers GROUP BY day Much better. Now aggregates are done in the database which is optimized for this kind of task, and only one row per day is returned from the database to the Rails app. ... but wait... now the app has to go live in my production env which uses MySQL ! Replace STRFTIME() with DATE_FORMAT(). What if tomorrow I switch to PostgreSQL ? Replace DATE_FORMAT() with DATE_TRUNC(). I like to develop with SQLite. Simple and easy. I also like the idea that Rails is database agnostic. But why Rails doesn't provide a way to translate SQL functions that do the exact same thing, but have different syntax in each RDBMS (this difference is really stupid, but hey, it's too late to complain about it) ? I can't believe that I find so few answers on the Web for such a basic feature of a Rails app : count the subscriptions per day, month or year. Tell me I'm missing something :) EDIT It's been a few years since I posted this question. Experience has shown that I should use the same DB for dev and prod. So I now consider the database agnostic requirement irrelevant. Dev/prod parity FTW. A: I ended up writing my own gem. Check it out and feel free to contribute: https://github.com/lakim/sql_funk It allows you to make calls like: Subscriber.count_by("created_at", :group_by => "day") A: You speak of some pretty difficult problems that Rails, unfortunately, completely overlooks. The ActiveRecord::Calculations docs are written like they're all you ever need, but databases can do much more advanced things. As Donal Fellows mentioned in his comment, the problem is much trickier than it seems. I've developed a Rails application over the last two years that makes heavy use of aggregation, and I've tried a few different approaches to the problem. I unfortunately don't have the luxary of ignoring things like daylight savings because the statistics are "only trends". The calculations I generate are tested by my customers to exact specifications. To expand upon the problem a bit, I think you'll find that your current solution of grouping by dates is inadequate. It seems like a natural option to use STRFTIME. The primary problem is that it doesn't let you group by arbitrary time periods. If you want to do aggregation by year, month, day, hour, and/or minute, STRFTIME will work fine. If not, you'll find yourself looking for another solution. Another huge problem is that of aggregation upon aggregation. Say, for example, you want to group by month, but you want to do it starting from the 15th of every month. How would you do it using STRFTIME? You'd have to group by each day, and then by month, but then someone account for the starting offset of the 15th day of each month. The final straw is that grouping by STRFTIME necessitates grouping by a string value, which you'll find very slow when performing aggregation upon aggregation. The most performant and best designed solution I've come to is one based upon integer time periods. Here is an excerpt from one of my mysql queries: SELECT field1, field2, field3, CEIL((UNIX_TIMESTAMP(CONVERT_TZ(date, '+0:00', @@session.time_zone)) + :begin_offset) / :time_interval) AS time_period FROM some_table GROUP BY time_period In this case, :time_interval is the number of seconds in the grouping period (e.g. 86400 for daily) and :begin_offset is the number of seconds to offset the period start. The CONVERT_TZ() business accounts for the way mysql interprets dates. Mysql always assumes that the date field is in the mysql local time zone. But because I store times in UTC, I must convert it from UTC to the session time zone if I want the UNIX_TIMESTAMP() function to give me a correct response. The time period ends up being an integer that describes the number of time intervals since the start of unix time. This solution is much more flexible because it lets you group by arbitrary periods and doesn't require aggregation upon aggregation. Now, to get to my real point. For a robust solution, I'd recommend that you consider not using Rails at all to generate these queries. The biggest issue is that the performance characteristics and subtleties of aggregation are different across the databases. You might find one design that works well in your development environment but not in production, or vice-versa. You'll jump through a lot of hoops to get Rails to play nicely with both databases in query construction. Instead I'd recommend that you generate database-specific views in your chosen database and bring those along to the correct environment. Try to model the view as you would any other ActiveRecord table (id's and all), and of course make the fields in the view identical across databases. Because these statistics are read-only queries, you can use a model to back them and pretend like they're full-fledged tables. Just raise an exception if somebody tries to save, create, update, or destroy. Not only will you get simplified model management by doing things the Rails way, you'll also find that you can write units tests for your aggregation features in ways you wouldn't dream of in pure SQL. And if you decide to switch databases, you'll have to rewrite those views, but your tests will tell you where you're wrong, and make life so much easier. A: I just released a gem that allows you to do this easily with MySQL. https://github.com/ankane/groupdate You should really try to run MySQL in development, too. Your development and production environments should be as close as possible - less of a chance for something to work on development and totally break production.
{ "pile_set_name": "StackExchange" }
Q: Why is this CSS input border showing? I have two different styles for input boxes, one is dark and the other is white. https://jsfiddle.net/ttwjLynh/ On the dark one, there appears to be this ugly white boarder and I don't know where it is coming from. How can I get rid of this white boarder? It does not appear on a white version and I don't know why it only appears when adding a background color. (Check fiddle) .black{ padding: 12px 20px; margin : 0 auto; box-sizing: border-box; text-align: center; display: inline-block; background-color: black; color: white; } .white{ padding: 12px 20px; margin : 0 auto; box-sizing: border-box; text-align: center; display: inline-block; } <div id="bet-and-chance-input-boxes"> <input class="black" value="text" autocomplete="off"> <input readonly value="text" class="black" placeholder="" name="bet" autocomplete="off"> </div> <div id="bet-and-chance-input-boxes"> <input class="white" id="userbet"value="text" autocomplete="off"> <input readonly class="white" value="text" placeholder="" name="" autocomplete="off"> </div> A: If you inspect the element, it shows that it uses border-style: inset; for the input box which is the default value set by the User Agent stylesheet. So in-order to fix it, we need to override the border-style property for input. Hence, we set it to solid or you can set it as border: 1px solid red;, replace red with any desired color of yours. Also make sure, that if you want to target input which are of type=text, then use a selector like input[type=text] { /* override the defaults here*/ } .black { padding: 12px 20px; margin: 0 auto; box-sizing: border-box; text-align: center; display: inline-block; background-color: black; color: white; border-style: solid; } .white { padding: 12px 20px; margin: 0 auto; box-sizing: border-box; text-align: center; display: inline-block; } <div id="bet-and-chance-input-boxes"> <input class="black" value="text" autocomplete="off"> <input readonly value="text" class="black" placeholder="" name="bet" autocomplete="off"> </div> <div id="bet-and-chance-input-boxes"> <input class="white" id="userbet" value="text" autocomplete="off"> <input readonly class="white" value="text" placeholder="" name="" autocomplete="off"> </div>
{ "pile_set_name": "StackExchange" }
Q: How would I adjust my Python code for a nested .JSON tree (Python dictionary) to include multiple keys? In my current code, it seems to only take into account one value for my Subject key when there should be more (you can only see Economics in my JSON tree and not Maths). I've tried for hours and I can't get it to work. Here is my sample dataset - I have many more subjects in my full data set: ID,Name,Date,Subject,Start,Finish 0,Ladybridge High School,01/11/2019,Maths,05:28,06:45 0,Ladybridge High School,02/11/2019,Maths,05:30,06:45 0,Ladybridge High School,01/11/2019,Economics,11:58,12:40 0,Ladybridge High School,02/11/2019,Economics,11:58,12:40 1,Loreto Sixth Form,01/11/2019,Maths,05:28,06:45 1,Loreto Sixth Form,02/11/2019,Maths,05:30,06:45 1,Loreto Sixth Form,01/11/2019,Economics,11:58,12:40 1,Loreto Sixth Form,02/11/2019,Economics,11:58,12:40 Here is my Python code: timetable = {"Timetable": []} with open("C:/Users/kspv914/Downloads/Personal/Project Dawn/Timetable Sample.csv") as f: csv_data = [{k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True)] name_array = [] for name in [row["Name"] for row in csv_data]: name_array.append(name) name_set = set(name_array) for name in name_set: timetable["Timetable"].append({"Name": name, "Date": {}}) for row in csv_data: for entry in timetable["Timetable"]: if entry["Name"] == row["Name"]: entry["Date"][row["Date"]] = {} entry["Date"][row["Date"]][row["Subject"]] = { "Start": row["Start"], "Finish": row["Finish"] } Here is my JSON tree: A: You're making date dict empty and then adding a subject. Do something like this: timetable = {"Timetable": []} with open("a.csv") as f: csv_data = [{k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True)] name_array = [] for name in [row["Name"] for row in csv_data]: name_array.append(name) name_set = set(name_array) for name in name_set: timetable["Timetable"].append({"Name": name, "Date": {}}) for row in csv_data: for entry in timetable["Timetable"]: if entry["Name"] == row["Name"]: if row["Date"] not in entry["Date"]: entry["Date"][row["Date"]] = {} entry["Date"][row["Date"]][row["Subject"]] = { "Start": row["Start"], "Finish": row["Finish"] } I've just added if condition before assigning {} to entry["Date"][row["Date"]] It will give output like as shown in the below image:
{ "pile_set_name": "StackExchange" }
Q: Blocking an employer after they message you doesn't work According to a comment from Donna at Jobs: How to block an employer (before any contact)? I file this as a bug. Steve mentions in an answer to Is there a way to block an employer request after the fact? that there should be a big red button that says "Block Employer" near the top right in the inbox but there is none. Steve also mentions there in a comment That only applies if they message you but that doesn't apply either. There are only green/red I'm Interested/I'm Not Interested buttons at the bottom of a message. A: Thank you for your bug report. You should now be able to block an employer who has messaged you, even if you have not replied to the employer (or clicked Interested/Not Interested). Please let us know if you continue to have problems with this feature.
{ "pile_set_name": "StackExchange" }
Q: Can the Quran be considered authoritative when it references the life of Christ? There is a lot of debate on this question. Many historians believe Quran does give a picture to the life of Christ. Quran and Islam recognizes Christ as the mighty prophet and revere him in the six articles of faith of Islam. With this in mind, can the Quran be used as an authoritative source on the life of Christ in answers on this site? To further this, and ask the likewise question, should the Bible be considered authoritative on the life of Christ in this site? Or should secondary sources be used where history is concerned? and which secondary sources are considered to be authoritative about the life of Christ? A: It seems like the crux of the matter isn't whether or not a source is considered authoritative, but rather for whom. Nicene Christians (the vast majority of us) consider the 66 - 73 books of Scripture to be canonical, and nothing else. Gnostic Gospels, the Book of Mormon, and the Qu'ran just simply aren't for Nicene Christians. If the questioner wants a "mainstream" perspective, these sources wouldn't fit that bill. If the questioner wants a Mormon perspective, it will be called out as such, and identified as such. If the questioner wants a Gnostic perspective, ditto. And, if the questioner wants to know what Muslims think, it should be identified as Muslim. Grant you, I'd start thinking that it was off topic for Christianity and on topic for Islam.SE, but if we simply stick with IDENTIFY THE TRADITION YOU WANT TO KNOW ABOUT, the question answers itself. A: My first instinct is to say no since the Qu'ran is clearly derivative of the Christian account of Jesus. I would be very skeptical of an answer on History.SE that used the Qu'ran as a source for the life of Jesus. My second instinct is to say maybe. I'm sure there are Christians out there who consider the Qu'ran to be on equal footing with the New Testament. If an answer came from one of those viewpoints, I'd still be skeptical, but I might upvote it anyway. My third instinct is to ask "Why do you ask?" Frankly, you seem to have a very specific agenda to evangelize proselytize perform Da‘wah on the Stack Exchange network. If you plan on quoting the Qu'ran for that purpose and not so that you can learn about Christianity, then please reconsider. This is a site for learning about Christianity. If an answer (any answer) fails to support that goal, it ought to be deleted even if it "follows the rules". A: My inclination to use the Quran as a source for the historical life of Christ is to equate it with the Gnostic gospels. Most historians agree that the Gnostic gospels were written centuries after the events they claim to be about. I am not familiar with the Quran, but if it also says something about the historical life of Jesus (not just sayings or parables) then it is in the same category. It was written centuries after the events it claims to be about. Therefore, by general principles of historicity, it is less reliable than a book written nearer to the time frame of its reported events. So, because only a very small portion of historians consider any of Gnostic gospels for an accurate account of the life of Jesus, primarily because of their estimated written date, the Quran may be treated as a Gnostic gospel in regards to using it as an historical source for the life of Jesus. In contrast, the four gospels that are canonized (Matthew, Mark, Luke, and John) are generally accepted to be between 20 and 200 years of the events they claim happened. Some historians say more some less, but that is another argument, regardless, a manuscript from only 200 years after the events it claims is pretty good in terms of historicity, considering other manuscripts generally taken as fact. I don't know if this is discussed else where on the meta site here, but I have observed that the Gnostic gospels are only welcome in an answer if they were specifically requested by the asker. I would assume the same for the Quran in light of my reasoning above.
{ "pile_set_name": "StackExchange" }
Q: Can't separate columns when reading txt file Hi I managed to read txt files and printing them on the console window. I was given a task to select and sample a certain amount of data. Example of txt file: Voltage (V),Current (I),Power (W) 50,2,100, 51,2,102, 52,2,104, etc.. How can I display only the column of Voltage and Power? A: #include <stdio.h> int main(void) { int V, I, W;//float ? FILE *fp = fopen("data.txt", "r"); while(fgetc(fp) != '\n') ;//skip first line while(3==fscanf(fp, "%d,%d,%d,", &V, &I, &W)){ printf("V:%d, I:%d, W:%d\n", V, I, W); } fclose(fp); return 0; }
{ "pile_set_name": "StackExchange" }
Q: ggplot: Add legend and remove padding of graph I currently use following script to plot a graph with one common x and two distinct y-axes: library(ggplot2) library(scales) scaleFactor <- max(mtcars$cyl) / max(mtcars$hp) ggplot(mtcars, aes(x=disp)) + labs(title = "My Plot") + geom_smooth(aes(y=cyl), method="loess", col="blue") + geom_smooth(aes(y=hp * scaleFactor), method="loess", col="red") + scale_y_continuous(name="cyl", sec.axis=sec_axis(~./scaleFactor, name="hp")) Questions: How can I add a legend on the top left within the graph? How can I remove the spacing to the left and right of the x-axis? Note: + scale_x_continuous(expand = c(0, 0)) works perfectly in the example above, but in any other given time series, it returns *"Error in as.Date.numeric(value) : 'origin' must be supplied"`. Thank you! A: Please note that these are two very different questions, it would have been better to split them. You need to put both color inside the aes(), use then theme(legend.position = c(0.9, 0.2)) to move the legend. Note that the colors now won't correspond (they are just "labels"), you should to define your own color scale and legend with scale_color_manual(). ggplot(mtcars, aes(x=disp)) + labs(title = "My Plot") + geom_smooth(aes(y=cyl, col="blue"), method="loess") + geom_smooth(aes(y=hp * scaleFactor, col="red"), method="loess") + scale_y_continuous(name="cyl", sec.axis=sec_axis(~./scaleFactor, name="hp")) + theme(legend.position = c(0.9, 0.2)) + scale_x_continuous(expand = c(0, 0)) Error in as.Date.numeric(value) : 'origin' must be supplied" Is probably because x in that case is as.Date type, scale_x_date(expand = c(0, 0)) works. Here an example: set.seed(123) dat <- data.frame( dates = seq(from=as.Date("2018-01-01"), to=as.Date("2018-01-10"), by="day"), val1 = sample(10), val2 = sample(10) ) ggplot(dat, aes(x=dates)) + geom_line(aes(y=val1, color = "red")) + geom_line(aes(y=val2, color = "blue")) + theme(legend.position = c(0.9, 0.2)) + scale_x_date(expand = c(0,0)) + scale_y_continuous(name="val2", sec.axis=sec_axis(~./1, name="val2"))
{ "pile_set_name": "StackExchange" }
Q: Как работать с массивом в создании игры 3 в ряд Когда нажимаю на Кружочек (это как конфетка в Candy Crash), то он становится SetActive(true). Я хочу, чтобы все 4 стороны (верх, низ, правый, левый) тоже стали SetActive = true. Чтобы последующем, можно было их только двигать. Но, когда я нажимаю, то например, правый кружочек не становится SetActive, но зато True становится правый кружочек от самого первого созданного кружочка. ..... ..... ..... .*... <---- Вот этот Вот код класса для кружочка: public class CircleControl : MonoBehaviour { public int column; public int row; private Doska doska; private GameObject otherCircle; private Animator scaler; private Vector2 tempPos; public bool SetActive = false; public int nesw; //north = 1 east = 2 south = 3 west = 4 public int TargetX; public int TargetY; void Start () { scaler = GetComponent<Animator>(); scaler.SetInteger("ScalePlus", 1); doska = FindObjectOfType<Doska>(); } // Update is called once per frame void Update () { } private void OnMouseDown() { SetActive = true; scaler.SetInteger("ScalePlus", 2);//Анимация otherCircle = doska.allCircles[column + 1, row]; otherCircle.GetComponent<CircleControl>().SetActive = true; //doska.allCircles[column + 1, row].GetComponent<CircleControl>().SetActive = true; //doska.allCircles[column + 1, row].GetComponent<CircleControl>().nesw = 2; doska.allCircles[column, row + 1].GetComponent<CircleControl>().SetActive = true; doska.allCircles[column, row + 1].GetComponent<CircleControl>().nesw = 1; //doska.allCircles[column - 1, row].GetComponent<CircleControl>().SetActive = true; //doska.allCircles[column - 1, row].GetComponent<CircleControl>().nesw = 4; //doska.allCircles[column, row - 1].GetComponent<CircleControl>().SetActive = true; //doska.allCircles[column, row - 1].GetComponent<CircleControl>().nesw = 3; } void MoveCircles() { if(SetActive == true && nesw == 2 && column < doska.width) // направо { otherCircle = doska.allCircles[column + 1, row]; otherCircle.GetComponent<CircleControl>().column -= 1; column += 1; } else if (SetActive == true && nesw == 1 && row < doska.height)// вверх { if (SetActive) { otherCircle = doska.allCircles[column , row + 1]; otherCircle.GetComponent<CircleControl>().column -= 1; row += 1; } } else if (SetActive == true && nesw == 4 && column > 0)//влево { if (SetActive) { otherCircle = doska.allCircles[column - 1, row]; otherCircle.GetComponent<CircleControl>().column += 1; column -= 1; } } else if (SetActive == true && nesw == 2 && row > 0)// вниз { if (SetActive) { otherCircle = doska.allCircles[column, row - 1]; otherCircle.GetComponent<CircleControl>().row += 1; row -= 1; } } } } Код взаимодействия кружочка с его соседями в методе OnMouseDown() А вот код класса для доски: public class Doska : MonoBehaviour { public int width; public int height; public GameObject tilePref; public GameObject[] circles; private Tile [,] tiles; public GameObject[,] allCircles; void Start () { tiles = new Tile[width, height]; allCircles = new GameObject[width, height]; Nastroyka(); } // Update is called once per frame private void Nastroyka () { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Vector2 cleanPos = new Vector2 (i, j); GameObject bgTile = Instantiate(tilePref, cleanPos, Quaternion.identity) as GameObject; bgTile.transform.parent = this.transform; bgTile.name = "( " + i + ", " + j + " )"; int circlesUse = Random.Range(0, circles.Length); GameObject circle = Instantiate(circles[circlesUse], cleanPos, Quaternion.identity); circle.transform.parent = this.transform; circle.name = "( " + i + ", " + j + " )"; allCircles[i, j] = circle; } } } } A: Если все создание вашего поля происходит в методе Nastroyka() и нигде больше вы ничего не делаете - то проблема в том, что вы создаете все CircleControl правильно и в нужных местах, но не задаете ни одному из них значения row и column, что означает, что у всех ваших "кружочков" значения row и column равны 0. Если это так, то метод нужно поправить следующим образом: private void Nastroyka () { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Vector2 cleanPos = new Vector2 (i, j); GameObject bgTile = Instantiate(tilePref, cleanPos, Quaternion.identity) as GameObject; bgTile.transform.parent = this.transform; bgTile.name = "( " + i + ", " + j + " )"; int circlesUse = Random.Range(0, circles.Length); GameObject circle = Instantiate(circles[circlesUse], cleanPos, Quaternion.identity); circle.transform.parent = this.transform; circle.name = "( " + i + ", " + j + " )"; //получаем у объекта circle компонент CircleControl и //устанавливаем в переменные row и column нужные значения var circleControl = circle.GetComponent<CircleControl>(); circleControl.row = j; circleControl.column = i; allCircles[i, j] = circle; } } Таким образом, если у всех кружочков значения row и column равны 0, то какой бы вы кружочек не тыкнули, то SetActive(true) всегда будет становиться правый кружочек от самого первого созданного кружочка. А если вы еще где-то заполняете эти переменные, то вы не скинули весь необходимый код, чтобы понять вашу проблему.
{ "pile_set_name": "StackExchange" }
Q: angular2 route for notFound page I try to use children routs. My main routing-module(in root directory): import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { ProfileComponent } from './profile/profile.component'; import { NotFoundComponent } from './notfound/notfound.component'; import { LoggedInGuard } from './login-guard/login-guard.component'; const routes: Routes = [ {path: '', redirectTo: 'home', pathMatch: 'full'}, {path: 'home', component: HomeComponent, pathMatch: 'full'}, {path: 'profile', component: ProfileComponent, canActivate: [LoggedInGuard], canLoad: [LoggedInGuard]}, {path: '**', component: NotFoundComponent}, ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule {} and child routing-module(in sub-directory): import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { PPComponent } from './pp.component'; import { MembersComponent } from './members/members.component'; import { HistoryComponent } from './history/history.component'; @NgModule({ imports: [ RouterModule.forChild([ { path: 'partner-program', component: PPComponent, children: [ { path: '', redirectTo: 'members', pathMatch: 'full' }, { path: 'members', component: MembersComponent, }, { path: 'history', component: HistoryComponent, }, ] }, ]) ], exports: [ RouterModule ] }) export class PPRoutingModule { } I have a question about this route {path: '**', component: NotFoundComponent}. Angular2 sees this route before any children routes. And as a result url 'http://localhost:3000/partner-program' shows notFound component. If I remove notFound route, 'http://localhost:3000/partner-program' works fine. How can I declare notFound route and say Angular2 check it in last turn(after child routes)? Günter Zöchbauer, do you mean smth like this? RouterModule.forChild([ { path: '', children: [ { path: 'partner-program', component: PPComponent, children: [ { path: '', redirectTo: 'members', pathMatch: 'full' }, { path: 'members', component: MembersComponent, }, { path: 'history', component: HistoryComponent, }, ] } ] } ]) A: When you import these modules into the main module please make sure that AppRoutingModule is added on the end. It's all about the order of routes registration
{ "pile_set_name": "StackExchange" }
Q: Jquery passing the retrieved value to another id This is my first day using Jquery, I want to retrieve the id from the clicked element and pass the id to another element. So far I know that the id fetch is working fine according to my code, but I'm unable pass the value to another element! Idk where I'm going wrong.Here is the code. $(function() { $(".prs").click(function(e) { e.preventDefault(); var x= $(this).get(0).id); $("span #x").slideToggle("slow"); }); }); I want to pass the retrieved id to the id of span as in last line of code. A: This has nothing to do with jQuery, it's a JavaScript matter. You need to concatenate the string and your variable. Try this: $(function() { $(".prs").click(function(e) { e.preventDefault(); var x= $(this).get(0).id); $("span #" + x).slideToggle("slow"); }); }); However, just a side note. You don't need jQuery to get the id. Simply use JavaScript like this: var x= this.id; So your code can be simplified like this: $(function() { $(".prs").click(function(e) { e.preventDefault(); $("span #" + this.id).slideToggle("slow"); }); }); Finally, just a comment about the ids, it's not valid HTML to have two items with the same id. So you'll have to give them different ids, let say my_object for the clickable element and my_oject_box for the span. Then your code becomes: $(function() { $(".prs").click(function(e) { e.preventDefault(); $("#" + this.id + "_box").slideToggle("slow"); }); });
{ "pile_set_name": "StackExchange" }
Q: How to multiply two values and store the result atomically? Say I have the following global variables in my code: std::atomic<uint32_t> x(...); std::atomic<uint32_t> y(...); std::atomic<uint32_t> z(...); My task is to multiply x and y and then store the result in z: z = x * y I'm aware that the naive approach of calling store() and load() on each object is completely wrong: z.store(x.load() * y.load()); // wrong This way I'm performing three separate atomic instructions: another thread might slip through and change one of the values in the meantime. I could opt for a compare-and-swap (CAS) loop, but it would guarantee atomicity only for swapping the old value of z with the new one (x*y): I'm still not sure how to perform the whole operation in a single, atomic step. I'm also aware that wrapping x, y and z inside a struct and make it atomic is not feasible here, as the struct doesn't fit inside a single 64-bit register. The compiler would employ locks under the hood (please correct me if I'm wrong here). Is this problem solvable only with a mutex? A: I'm still not sure how to perform the whole operation in a single, atomic step. It will only be possible to do so if you architecture supports something like "32-bit atomic multiplication" (and you would have to do it outside the C++ standard's facilities) or an atomic that is wide enough to perform a RMW operation on 64-bits. I'm also aware that wrapping x, y and z inside a struct and make it atomic is not feasible here, as the struct doesn't fit inside a single 64-bit register. Even if they would fit, you would still need to do a RMW operation, since it is unlikely you have atomic multiplication anyway. Is this problem solvable only with a mutex? If your architecture supports a lock-free 64-bit atomic (check with is_always_lock_free), you can keep both x and y together and perform operations on it as needed. what if the variables were uint64_t instead, or the operation was way more complex like x * y * w * k / j? Assuming that your architecture does not have 128-bit lock-free atomics, then you cannot load that much data atomically. Either design your program so that it does not need the (complete) operation to be atomic to begin with, use locks or seek a way to avoid sharing the state. Note that even if you perceive some operations as atomic, you have to realize that in an SMP system you are putting pressure on the cache hierarchy anyway.
{ "pile_set_name": "StackExchange" }
Q: Synonym for 'place' which is not big Here are a few new sentences I have written in my diary: Our manager was asked to negotiate with the retailing shops' managers and signed the agreements with them. These retailing shops will have to keep our cakes in good condition in their window cabinets. Because the cakes will occupy some of the places in their window cabinets, we need to pay each shop more than a thousand dollars monthly. Because the word place sounds like it is very big in size, I want to replace it with some better word, but my vocabulary is weak. A: The first word that comes to my mind is "spot". A: Retail uses the phrase 'display spaces' for any type of area where a product is being displayed for promotional purposes. A: Baked goods are typically arranged inside glass display cases. The space is usually referred to as shelf space. This article might give you some vocabulary. And this one too.
{ "pile_set_name": "StackExchange" }
Q: How does $\bar{r}\times(\bar{\nabla}\times) - \bar{\nabla}\times(\bar{r}\times)$ relate to the orbital angular momentum operator? When I attempted to calculate the following by hand $$\bar{r}\times(\bar{\nabla}\times\bar{F}) - \bar{\nabla}\times(\bar{r}\times\bar{F}),$$ I noticed some of the terms I extracted looked similar to the terms that appear in the oribtal anglar momentum operator $$\bar{L} = -i\hbar(\bar{r}\times\bar{\nabla}).$$ Is there a condensed expression that uses $\bar{L}$? How does $$\bar{r}\times(\bar{\nabla}\times) - \bar{\nabla}\times(\bar{r}\times)$$ relate to the orbital angular momentum operator? A: In Einstein summation notation, we'd write $$\vec U = \vec r \times(\nabla\times\vec F) - \nabla\times(\vec r\times\vec F),$$ using a Levi-Civita symbol $\epsilon_{ijk}$ as: $$ U_a = \epsilon_{abc} ~r_b ~\epsilon_{cde} ~\partial_d ~F_e - \epsilon_{abc} ~\partial_b ~\epsilon_{cde} ~r_d ~F_e.$$Since $\epsilon$ is not varying with space we can commute it with $\partial_b$ on the right, leading to $$ U_a = \epsilon_{abc}~\epsilon_{cde}\left( r_b ~\partial_d ~F_e - \delta_{bd} F_e - r_d ~\partial_b ~ F_e\right),$$ and furthermore we have the "BAC-CAB" rule that $\epsilon_{abc}\epsilon_{cde}$ can only be nonzero when either $a = d$ and $b = e$ (with coefficient +1) or when $a = e$ and $b = d$ (with coefficient -1), so it can be rewritten as $\delta_{ad}\delta_{be} - \delta_{ae}\delta_{bd}.$ So then this expression is $$ U_a = (\delta_{ad}\delta_{be} - \delta_{ae}\delta_{bd}) \left(r_b ~\partial_d ~F_e - \delta_{bd} F_e - r_d ~\partial_b ~ F_e\right),$$whence the term $\delta_{bd} F_e$ will always vanish, as we get $\delta_{ae} F_e - \delta_{ae} F_e = 0.$ Similarly the other terms suffer from $\delta_{bd}$ forming $r_b \partial_b F_a - r_b \partial_b F_a = 0.$ So the only term left is the $\delta_{ad}\delta_{be}$ one, leading to $$U_a = r_b ~\partial_a ~F_b - r_a ~\partial_b ~ F_b.$$The first term can be rewritten as $\partial_a(r_b F_b) - F_a,$ so this can be written as,$$\vec U = \nabla(\vec r\cdot \vec F) - \vec r (\nabla \cdot \vec F) - \vec F.$$ This looks a little like a BAC-CAB rule too but it cannot be of the form $A \times (B \times C)$ because the $\nabla$ would probably not be acting on $F$, so let's instead target $(A \times B) \times C = B (A \cdot C) - A (B\cdot C)$ with $A = r$, $B = \nabla$. In other words, let's calculate $$\vec V = (\vec r \times \nabla) \times F,$$ which we do the same way but with $$V_a = \epsilon_{abc} \epsilon_{bde} r_d \partial_e F_c.$$The relevant $\epsilon \propto \delta\delta$ analysis yields:$$V_a = (\delta_{ae} \delta_{cd} - \delta_{ad} \delta_{ce}) r_d \partial_e F_c = r_c \partial_a F_c - r_a \partial_c F_c = U_a.$$ In other words, $$\Big[\big(\vec r \times\big),~ \big(\nabla \times\big)\Big] = \frac{i}{\hbar} \big(\hat L \times\big).$$
{ "pile_set_name": "StackExchange" }
Q: Why $\mathbb{Z}_m \times \mathbb{Z}_n, \, \text{gcd}(m,n) >1$ isn't cyclic? I'm aware of the theorem which states that $\mathbb{Z}_m \times \mathbb{Z}_n$ is isomorphic to $\mathbb{Z}_{mn}$ (and thus cyclic) if and only if $\text{gcd}(m,n)=1$. However, in $G=\mathbb{Z}_2 \times \mathbb{Z}_4$, where $\text{gcd}(2,4)=2$, it seems to me that if we take $(0,0)$ and add to it $(1,1)$ $4$ times (least common multiple of $2,4$) then we return to $(0,0)$. That's what misled me into thinking that $G$ is cyclic. Could you explain to me why this is a faulty syllogism and provide me with a more practical way to visualize cyclic direct products? A: Suppose that $m$ and $n$ are not coprime. Let $d=\text{gcd}(m,n)$ and $$ a=\frac{mn}{d} $$ Then $a$ is a multiple of both $m$ and $n$. Suppose that $(r,s) \in \mathbb{Z}_m \times \mathbb{Z}_n$. We have $$a(r,s)=(ar,as)=(0,0), $$ since $ar$ is a multiple of $m$ and $as$ is a multiple of $n$. Thus, every element of $\mathbb{Z}_m \times \mathbb{Z}_n$ has order at most $a$ which is less than $mn$ and so $\mathbb{Z}_m \times \mathbb{Z}_n$ is not cyclic.
{ "pile_set_name": "StackExchange" }
Q: Posting on user wall doesn't work if link is included I am trying to post to a user wall using the Graph API. I tested using my own wall, and I have authenticated my Facebook app to publish_stream. post_params = { access_token:FACEBOOK_APP_TOKEN, link:'http://example.com', picture:"http://example.com/images/logo.png", message:"dummy", description:'dummy' } get_facebook_client().client.post("#{user_fb_id}/feed", post_params) I can successfully post something to my wall if I don't have the link parameter (containing our company url). If I include the link param, Facebook would still return the ID of the status update like {"id": "4804827_871793267189"}, like a successful post request, but post won't appear on my wall. The above use the ruby gem rest-more, but this behavior happens when I hand code everything too. A: I realize that I can post any other link (even other subdomain my company url). So I think Facebook will ignore posting with a link which the user have shared before.
{ "pile_set_name": "StackExchange" }
Q: Separate a vector (or array) of strings separated by a "00" (C++) I have a vector of strings of different "categories". Each category is separated by a "00" string in the vector. So like: "Pizza" "IceCream" "Bread" "00" "Windows" "Mac" "Linux" "Unix" "00" "Raining" "Snowing" "00" "Hiking" "00" I am trying to figure out how to separate these categories into a vector of strings with all categories in one string like: "Pizza IceCream Bread" "Windows Mac Linux Unix" "Raining Snowing" "Hiking" EDIT: alldoubles is the vector name and its size is totalsize Attempt : Trying to add to a queue whenever the string is not 00 int loc = 0; //counter queue<string> tmp; string cur; while (loc<totalsize) { while (cur != "00") { tmp.push(cur); //add to queue when not 00 loc = loc + 1; cur = alldoubles[loc]; } while (tmp.empty()!=false) //unload the queue into a string res { // after an 00 was found and cout it string res; res = res + tmp.front(); tmp.pop(); cout << "RES " << res << endl; } } EDIT : now I get RES and the RES Pizza which is not all the food with this code int loc = 0; queue<string> tmp; string cur; while (loc<totalsize) { while (cur != "00") { tmp.push(cur); cur = alldoubles[loc]; loc = loc+1; } while (!tmp.empty()) { string res; res = res + tmp.front(); tmp.pop(); cout << "RES " << res << endl; } } A: // Example program #include <iostream> #include <string> #include <vector> #include <algorithm> int main() { std::vector<std::string> vv = { "one", "00", "two", "three", "00", "four" , "five", "six", "00", "seven" }; std::string const splitter("00"); // !!!! add 00 to the end vv.push_back(splitter); auto bb = vv.begin(); auto it = std::find(vv.begin(), vv.end(), splitter); // finds groups and prints them one by one while (it != vv.end()) { std::string accumulator; for(auto it2 = bb; it2 != it; ++it2) accumulator += *it2; bb = ++it; it = std::find(bb, vv.end(), splitter); std::cout << accumulator << std::endl; } } This prints: one twothree fourfivesix seven
{ "pile_set_name": "StackExchange" }
Q: Start two springboot apps in eclipse Is it possible to start two spring boot applications in eclipse, in the same workspace in the same time? How can i set two different ports for that two spring boot applications? A: Yes. It is possible to run two spring boot apps same time in the same workspace in eclipse. This is possible because each spring boot app comes with an embedded tomcat server and we have to make sure that each of them uses a different port number respectively. In each spring boot application, add application.properties file in src/main/resources folder. To override the default 8080 port, you have to use server.port property in the application.properties file. Make sure you set different port in each of the application. For example, set server.port=8888 in one application and server.port=9999 in another application, so that app1 will run on 8888 port and app2 will run on 9999 port. To scan for a free port (using OS natives to prevent clashes) use server.port=0.
{ "pile_set_name": "StackExchange" }
Q: Dynamically create a onClick event handler with jQuery I have following code which builds a table from array called 'data'. I would like to add javascript call into my other method called backend_getMovieData, but I dont know how to build a string from movie._id. I'm getting error "Uncaught SyntaxError: Unexpected token } " from my example code. data.forEach(function(movie) { $("#shows").find('tbody') .append($('<tr>') .append($('<td>' + movie._id + '</td>')) .append($('<td>' + movie.total + ' times</td>')) .append($('<td><button class=\'btn btn-success\' onClick=backend_getMovieData(' + movie._id + ');>Show times</button></td>'))); }); A: I think, your function is expecting a string. Do this: data.forEach(function(movie) { $("#shows").find('tbody') .append($('<tr>') <br /> .append($('<td>' + movie._id + '</td>'))<br /> .append($('<td>' + movie.total + ' times</td>'))<br /> .append($('<td><button class=\'btn btn-success\' onClick="backend_getMovieData(\'' + movie._id + '\')";>Show times</button></td>'))); }); You need to wrap it with quotes.
{ "pile_set_name": "StackExchange" }
Q: How can I create overlapping trapezoids or successive rhombus from array? I have been working on this for a while and would love some help. I have two sets of divs of different lengths offset by varying distances which are being created from an array. Fiddle 1: JSFiddle1 Between these sets of divs I would like to dynamically create a connecting shape (trapezoid/rhombus like shape). I was able to create the first one using CSS and borders. Fiddle 2: JSFiddle2 When I try to add successive divs I run into a problem. Fiddle 3: JSFiddle3 The goal would look something like this (but created dynamically from the array rather than my Photoshopping here): Any ideas? I am not concerned about crossbrowser (I am only using FF), though such might be nice if it is easy. A: I know you wanted an HTML and CSS based solution, but here is a JavaScript solution for generating a svg based solution: var correlationPoints = [ [0, 10, 50, 200, 600], [0, 200, 300, 400, 600] ], correlationHeight = 16, svg = document.getElementsByTagName('g')[0], patches = correlationPoints[0].length; for (var i = 0; i < correlationPoints[0].length - 1; i++) { var newElement = document.createElementNS("http://www.w3.org/2000/svg", 'path'), color = Math.round(((i + 1) / patches) * 255), path = [], c = 0; newElement.setAttribute('fill', 'RGB(' + color + ',' + color + ',' + color + ')'); path[c++] = 'M'; // start move path[c++] = correlationPoints[0][i]; // start at top left corner x path[c++] = '0'; //top left y path[c++] = 'L'; //top right path[c++] = correlationPoints[0][i + 1]; path[c++] = '0'; path[c++] = 'L'; // top of angle right path[c++] = correlationPoints[0][i + 1]; path[c++] = '20'; path[c++] = 'L'; // bottom of angle right path[c++] = correlationPoints[1][i + 1]; path[c++] = '40'; path[c++] = 'L'; // bottom right path[c++] = correlationPoints[1][i + 1]; path[c++] = '60'; path[c++] = 'L'; // bottom left path[c++] = correlationPoints[1][i]; path[c++] = '60'; path[c++] = 'L'; // bottom of angle left path[c++] = correlationPoints[1][i]; path[c++] = '40'; path[c++] = 'L'; // top of angle left path[c++] = correlationPoints[0][i]; path[c++] = '20'; newElement.setAttribute("d", path.join(' ')); svg.appendChild(newElement); } body { margin: 20px; background-color: lightblue; } path:hover { fill: red; } <h1>Title</h1> <p>Regular text.</p> <svg xmlns="http://www.w3.org/2000/svg" width="600px" height="60px"> <desc></desc> <g class="correlations" alignment-baseline="baseline"> </g> </svg> <p>Regular text.</p>
{ "pile_set_name": "StackExchange" }
Q: C++ object instance as a class member Sorry if the title is wrong, I don't know how else to name it. I have a class Name: class Name { char * name; public: Name(const char * n){ name = new char[strlen(n)+1]; strcpy(name,n); } Name& operator=(const Name& n){ name = new char[strlen(n.name)+1]; strcpy(name, n.name); return *this; } Name(const Name& n){ *this = n; } }; And another class Person which should have Name object as it's member. How can I do this? I was thinking something like this: class Person{ double height; Name name; public: Person(double h, const Name& n){ height = h; name = n; } }; But only this seems to work: class Person{ double height; Name * name; public: Person(double h, const Name & n){ height = h; name = new Name(n); } }; Is it the right way to do it, and why can't I do it like I thought in the first place? Thanks A: Make the constructor like this: Person(double h, const Name& n) : height(h), name(n) {} Then read about constructor initializer lists in your favorite C++ textbook. The reason your original code doesn't work is that Name doesn't have a default constructor (a constructor that can be called with no parameters).
{ "pile_set_name": "StackExchange" }
Q: Hamilton's principle with semiholonomic constraints in Goldstein I am studying from Goldstein's Classical Mechanics, 3rd edition. In section 2.4, he discussed Hamiltion's principle with semiholonomic constraints. The constraints can be written in the form $f_\alpha(q_1,...,q_n;\dot{q_1},...,\dot{q_n};t)=0$ where $\alpha=1,...,m$. Using variational priciple, we get $$\delta\int_{t_1}^{t_2}\left(L+\sum_{\alpha=1}^m \mu_\alpha f_\alpha\right)\mathrm dt=0 \tag{2.26}$$ where $\mu_\alpha=\mu_\alpha(t)$. But how can he get the formula $$\frac{d}{dt}\frac{\partial L}{\partial\dot{q_k}}-\frac{\partial L}{\partial q_k}=-\sum_{\alpha=1}^m \mu_\alpha \frac{\partial f_\alpha}{\partial\dot{q_k}} \tag{2.27}$$ for $k=1,...,n$ from the previous formula? When I go through the steps as in section 2.3, I get $$\frac{dI}{d\beta}=\int_{t_1}^{t_2}\sum_{k=1}^n\left(\frac{\partial L}{\partial q_k}-\frac{d}{dt}\frac{\partial L}{\partial\dot{q_k}}+\sum_{\alpha=1}^m \mu_\alpha\left(\frac{\partial f_\alpha}{\partial q_k}-\frac{d}{dt}\frac{\partial f_\alpha}{\partial\dot{q_k}}\right)\right)\frac{\partial q_k}{\partial\beta}\mathrm dt$$ where $\beta$ denotes the parameter of small change of path: \begin{align} q_1(t,\beta)&=q_1(t,0)+\beta\eta_1(t)\\ q_2(t,\beta)&=q_2(t,0)+\beta\eta_2(t)\\ &\ \,\,\vdots \end{align} Using the same argument as in the part of holonomic constraint in section 2.4, I get $$\frac{\partial L}{\partial q_k}-\frac{d}{dt}\frac{\partial L}{\partial\dot{q_k}}+\sum_{\alpha=1}^m \mu_\alpha \left(\frac{\partial f_\alpha}{\partial q_k}-\frac{d}{dt}\frac{\partial f_\alpha}{\partial\dot{q_k}}\right)=0$$ for $k=1,...,n$. What am I missing? A: Note that the treatment of Lagrange equations for non-holonomic constraints in Ref. 1 is inconsistent with Newton's laws, and has been retracted on the errata homepage for Ref. 1. See Ref. 2 for details. References: H. Goldstein, Classical Mechanics; 3rd ed; Section 2.4. Errata homepage. (Note that this criticism only concerns the treatment in the 3rd edition; the results in the 2nd edition are correct.) M.R. Flannery, The enigma of nonholonomic constraints, Am. J. Phys. 73 (2005) 265.
{ "pile_set_name": "StackExchange" }
Q: smarty fetch include on the fetched tpl page fails My ajax php located in maindirexample/actions is calling a tpl file one folder up in maindirexample/templates fetch('../templates/popupMyItems.tpl'); However this throws an error <br /> <b>Fatal error</b>: Uncaught exception 'SmartyException' with message 'Unable to load template file 'list-myItems.tpl' in '../templates/popupMyItems.tpl' popupMyitems.tpl seems to be called ok, however list-myItems.tpl fails (this is included in popupMyitems.tpl) .. {foreach from=$uniquecategories item=category name=cat} {if $smarty.foreach.cat.first} {include file="list-myItems.tpl" category="{$category|replace:' ':''}" active="true"} {else} {include file="list-myItems.tpl" category="{$category|replace:' ':''}" active="false"} {/if} {/foreach} Using {include file="../templates/list-myItems.tpl"} also fails : 'SmartyException' with message 'Unable to load template file 'list-myItems.tpl' in '../templates/popupMyItems.tpl'' in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\ex\libs\sysplugins\smarty_internal_templatebase.php:127 Stack trace: #0 C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\ex\libs\sysplugins\smarty_internal_template.php(286): Smarty_Internal_TemplateBase-&gt;fetch(NULL, NULL, NULL, NULL, false, false, true) #1 C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\ex\main\actions\templates_c\07c3452c9173e47b89ab427877861e26b839928c.file.popupMyItems.tpl.php(52): Smarty_Internal_Template-&gt;getSubTemplate('list-myItems.tp...', NULL, NULL, NULL, NULL, Array, 0) #2 C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\ex\libs\sysplugins\smarty_internal_templatebase.php(180): content_5236279826e113_69075833(Object(Smarty_Internal_Template)) #3 C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\ex\main\actions in <b>C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\ex\libs\sysplugins\smarty_internal_templatebase.php</b> on line Any ideas? Thanks A: You need to include it from ../templates/ as well. Smarty does not search the "current folder" for inclusions, but rather the include_dir specified in settings. So you should do something like this: {include file="../templates/list-myItems.tpl" category="{$category|replace:' ':''}" active="true"}
{ "pile_set_name": "StackExchange" }
Q: Aren't Legendre's conjecture and Andrica's conjecture same? If Legendre's conjecture is true, couldn't we easily obtain $\sqrt{p_{n+1}}-\sqrt{p_{n}}<1$ where $p_{n}$ is the $n$th prime? $$p_{n+1}<(\lfloor \sqrt{p_{n}} \rfloor + 1)^{2}<( \sqrt{p_{n}}+ 1)^{2}$$ $$\sqrt{p_{n+1}}<1+\sqrt{p_{n}}$$ $$\sqrt{p_{n+1}}-\sqrt{p_{n}}<1$$ which is Andrica's conjecture. A: Legendre's conjecture is reported by Wikipedia to be that for each $n$ there is a prime between $n^2$ and $(n+1)^2$. That would imply $$ \lfloor \sqrt{p_{n+1}} \rfloor - \lfloor \sqrt{p_n} \rfloor \le 1. $$ For example, $\lfloor\sqrt{173}\rfloor=13$ and $\lfloor\sqrt{167}\rfloor = 12$. Obviously in many cases the difference between integer parts of the square roots of consecutive primes is $0$. Notice, however, that $\sqrt{1021}\approx31.953\ldots$ and $\sqrt{953}\approx30.87\ldots$. Nothing in Legendre's conjecture says these cannot be consecutive primes, but Andrica's conjecture rules that out.
{ "pile_set_name": "StackExchange" }
Q: TypeScript Generic Function - "Argument not assignable error" when applying function for array Description I would like like to define a Generic function in TypeScript so that it would apply a transformation to the array argument and then return an array of same type. (TypeScript version used: v3.24) Simplified code snippet as follow: describe("generic functions", function () { it("should not give transpilation error", function () { // given function myFunction<T>(arr: T[]): T[] { // ...... apply some transformation to the array here return arr; // or return a copy of the array of same type } let arrays = [ ["a"], [1] ]; // Just for demonstration purpose, the actual input has more varieties of types // These can be transpiled without error myFunction(["b"]); myFunction([2]); arrays.map(myFunction); // This gives transpilation error, see following for the detailed message arrays.map(arr => myFunction(arr)); }); }); In particular I am not sure why the TS compiler would fail to recognize the type only when I am applying the function to an array of mixed type and calling it explicitly. The transpilation error message is: TS2345: Argument of type 'string[]| number[]' is not assignable to parameter of type 'string[]'. Type 'number[]' is not assignable to type 'string[]'. Type 'number' is not assignable to type 'string'. Similar question Assigning generics function to delegate in Typescript - But I would like to keep the generic signature as I want my function to be more flexible Typescript Generic type not assignable error - But my function is returning the generic type. (Apologies and please let me know if this duplicates with another question - I had tried to search but failed to find question that could answer this) A: The compiler is having trouble unwrapping the (string[] | number[]) type to infer the type argument. In this case, explicitly passing the type argument will work: arrays.map(arr => myFunction<string | number>(arr)); This is one of those cases where the compiler treats: (string | number)[][] Differently to: (string[] | number[])[] If you use the latter, it infers the type argument as string[], which then fails for number[]. You can help the compiler with a type guard, but this example is really thought exercise and I can't imagine wanting to use this in real life: function isStringArray(arr: any[]): arr is string[] { return (typeof arr[0] === 'string'); } arrays.map(arr => (isStringArray(arr)) ? myFunction(arr) : myFunction(arr)); Even though it calls myFunction either way, it can infer the type argument as string[] and number[] in each case.
{ "pile_set_name": "StackExchange" }
Q: Calculate sum of ascii values of email address in php I want to echo the sum of the lowercase ascii values of a email address. For example: [email protected] 97(a) + 64(@) + 98(b) + 46(.) + 110(n) + 108(l) = 523 Any idea how to calculate this in PHP? A: try to use ord() in PHP: ord() example $str = "[email protected]"; $sum = 0; $arr1 = str_split($str); foreach($arr1 as $item){ $sum += ord($item); }
{ "pile_set_name": "StackExchange" }
Q: Join Two tables having different number of columns I have a scenario like this in ssis - I have got two different inputs, out of which one is coming from a lookup nomatch output. The other input is actually a derived column that is takn from a single row single column result in an oledb source using sql query. The problem is that I need to join these two inputs and make it a single dataset to further push the data to the crm destination(Cozyroc). I know union all just cant do the work since it works on union of rows from different datasets. Also merge and merge join cannot be used since a common id or key need to be given inorder to join the two datasets, and i have got no such thing. For example, my first dataset looks like: usinessid userid name --------- ------ ---- ret678 435 john dfgt67 213 sam and my second dataset is like: systemid ------------------------ 6666-777-kjtyr-213t-ytui which is extracted using a single column single row query using the oledb source - sql command. Is there a way to combine these two dataset so that the end result will be something like: businessid userid name systemid ---------- ------ ---- ------------------------ ret678 435 john 6666-777-kjtyr-213t-ytui dfgt67 213 sam 6666-777-kjtyr-213t-ytui I want to do this without using a variable or using a derived column and hardcoding the systemid value. Pardon my editing... Any further inputs on this issue will be really helpful. A: To combine the two datasets the way you've shown, you could use a simple cross join: SELECT t1.businessid, t1.userid, t1.name, t2.systemid FROM table1 t1 CROSS JOIN table2 t2 ;
{ "pile_set_name": "StackExchange" }
Q: Partial Views using data grids I am trying to call in two partial views but my program is trying to populate my web grid before I pass it a search parameter. I can't figure out how to keep it from trying to render the webgrid before I pass it the text in the searchbox. This is in my partial view: <div class="webgrid-wrapper"> <div class="webgrid-title">Values</div> <div id="grid"> @grid.GetHtml( tableStyle: "webgrid", headerStyle: "webgrid-header", footerStyle: "webgrid-footer", alternatingRowStyle: "webgrid-alternating-rows", columns: grid.Columns( grid.Column("Id", "ID"), grid.Column("Name", "Name") ) ) </div> </div> </div> This is my Home view where I'm pulling both of the partial views into: <section class="featured"> <div class="content-wrapper"> <hgroup class="title"> <h1>@ViewBag.Title</h1> <h2>@ViewBag.Message</h2> </hgroup> </div> </section> @using (Html.BeginForm("Analysis", "Home", "POST")) { <div class="searchField"> <div class="searchbox"> Search: <input type="text" name="Search" /> <input type="submit" value="Submit"> </div> </div> } @Html.Partial("PartialChemAnalysis") @Html.Partial("PartialSlagView") A: you can do this by checking the search parameter if it has a value, if no, then you dont have to render the grid. in your controller public ViewResult Analysis(string search) { ViewBag.DisplayGrid = !string.IsNullOrEmpty(search); //do you logics then return } in your view @if (ViewBag.DisplayGrid != null && ViewBag.DisplayGrid) { //Render your partial since its true. @Html.Partial("PartialChemAnalysis") @Html.Partial("PartialSlagView") } upon initial load or if there are no search parameter. the viewbag will be set to false, and your partial will not be rendered. and will rendered if the search parameter has value.
{ "pile_set_name": "StackExchange" }
Q: how to count how many iterations it takes to get a random number equal to user input and calculate that average in C? Using nested loops, We have to create a program that takes a number in range of 0-99 from the user and use a seeded random number generator to try and guess the number. We have to keep track of how many numbers the RNG generates before it generates the user's number. We have to also do this process 50 times to then calculate the average number of tries it takes the RNG to guess our number. This is all i have so far and i'm stumped: #include<stdio.h> #include<stdlib.h> #include<time.h> int main() { srand(time(NULL)); int userInput; int randoms = rand() % 100; int numCalls; int i; float average = 0.0; printf("Please enter a number in between 0 and 99: "); scanf(" %d", &userInput); for( i = 0; i < 50; i++) { while (userInput != randoms); { numCalls = numCalls + 1; if (userInput = randoms) { float average = numCalls/50.0; } } printf("Number of iterations it took for a matching number: %d\n", numCalls); printf("Average number of iterations to find a match: %.2f\n", average); } return; } A: There are no update of randoms value if (userInput=randoms) is not a boolean function, it should be if (userInput==randoms) instead Here's what I suggest: int main() { srand(time(NULL)); int userInput; int randoms = rand() % 100; int numCalls; int i; float average = 0.0; int totalCalls=0; printf("Please enter a number in between 0 and 99: "); scanf(" %d", &userInput); for( i = 0; i < 50; i++) { numCalls = 0; //reset iteration number do{ randoms = rand()%100; numCalls++ } while (randoms!=userInput); totalCalls += numCalls; printf("Number of iterations it took for a matching number: %d\n", numCalls); average = (float)totalCalls/(float)i; printf("Average number of iterations to find a match: %.2f\n", average); } return; }
{ "pile_set_name": "StackExchange" }
Q: Java: Safe Animations with Swing I am creating a program that uses JFrame, JPanel, JLabel and all other sorts of swing components. What I want to do is create a 2D animation on a separate JPanel that is dedicated to this animation. So I will be overriding the paintComponent (Graphics g) method. I have experience making animations with for loops + Threads, but I am hearing that threads are not safe with swing. Due to this, is it safe for me to make an animation with the use of the Runnable interface? If not what shall I use (e.g. Timer) and please give a small example on how to best use it (or a link to a web page). EDIT: Thanks to Jeff, I will be using Timer to create the animation. For future viewers of this question, here is a quick program I coded in about 5 minutes, excuse the dirty code. I have also added some quick comments. import java.awt.*; import java.awt.event.*; import javax.swing.*; class JFrameAnimation extends JFrame implements ActionListener { JPanel panel; Timer timer; int x, y; public JFrameAnimation () { super (); setDefaultCloseOperation (EXIT_ON_CLOSE); timer = new Timer (15, this); //@ First param is the delay (in milliseconds) therefore this animation is updated every 15 ms. The shorter the delay, the faster the animation. //This class iplements ActionListener, and that is where the animation variables are updated. Timer passes an ActionEvent after each 15 ms. } public void run () { panel = new JPanel () { public void paintComponent (Graphics g) //The JPanel paint method we are overriding. { g.setColor (Color.white); g.fillRect (0, 0, 500, 500); //Setting panel background (white in this case); //g.fillRect (-1 + x, -1 + y, 50, 50); //This is to erase the black remains of the animation. (not used because the background is always redrawn. g.setColor (Color.black); g.fillRect (0 + x, 0 + y, 50, 50); //This is the animation. } } ; panel.setPreferredSize (new Dimension (500, 500)); //Setting the panel size getContentPane ().add (panel); //Adding panel to frame. pack (); setVisible (true); timer.start (); //This starts the animation. } public void actionPerformed (ActionEvent e) { x++; y++; if (x == 250) timer.stop (); //This stops the animation once it reaches a certain distance. panel.repaint (); //This is what paints the animation again (IMPORTANT: won't work without this). panel.revalidate (); //This isn't necessary, I like having it just in case. } public static void main (String[] args) { new JFrameAnimation ().run (); //Start our new application. } } A: Jimmy, I think you are misunderstanding how threads work in Swing. You must use a specific thread called the Event Dispatch Thread to do any updating on swing components (with a few specific exceptions I won't discuss here). You can use a swing timer to set a recurring task to run on the event dispatch thread. See this example of how to use Swing timers. http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html You should also read up on the Event Dispatch Thread so you understand its place in Swing http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html Java also provides a variety of methods for working with Swing in the SwingUtilities class, notably invokeLater and invokeAndWait which will run code on the event dispatch thread.
{ "pile_set_name": "StackExchange" }
Q: how to use wait in C How do i use wait ? It just baffles me to no end. I fork a tree of procs with recursion and now the children have to pause(wait/sleep) while I run pstree so I can print the proc tree. Should i use int status; wait(&status); or rather wait(NULL) and where should i put this? in the parent if(pid > 0) or in the children if(pid==0)? Maybe at the end of ifs, so I store all the pids in array and then run a for over them and use wait? my code template: void ProcRec(int index) { pid_t pid; int noChild = getNChild(index); int i= 0; for(i = 0; i < noChild; i++) { pid = fork(); if (pid > 0) { /* parent process */ } else if (pid == 0) { /* child process. */ createProc(index+1); } else { /* error */ exit(EXIT_FAILURE); } } if(getpid() == root) { sleep(1); pid = fork(); if(pid == 0) execl("/usr/bin/pstree", "pstree", getppid(), 0); } } A: The wait system-call puts the process to sleep and waits for a child-process to end. It then fills in the argument with the exit code of the child-process (if the argument is not NULL). So if in the parent process you have int status; if (wait(&status) >= 0) { if (WEXITED(status)) { /* Child process exited normally, through `return` or `exit` */ printf("Child process exited with %d status\n", WEXITSTATUS(status)); } } And in the child process you do e.g. exit(1), then the above code will print Child process exited with 1 status Also note that it's important to wait for all child processes. Child processes that you don't wait for will be in a so-called zombie state while the parent process is still running, and once the parent process exits the child processes will be orphaned and made children of process 1.
{ "pile_set_name": "StackExchange" }
Q: Is there a Naming Scheme for the Abyssal Ships? In Kantai Collection, the Ship Girls like Fusou and Bismark are named from real life ships. I am wondering if the Abyssal Ships like Wo and Ta are named with a particular scheme aswell or if it's just random? (I'm not Referring to Bosses like Southern War Demon or Anchorage Princess) A: There is definitely some pattern to the naming of these ships. The enemy ship classes are named in Iroha order corresponding to the first 18 characters of the Iroha, a classic Japanese poem which uses all 47 classical hiragana* (excluding ん but including ゑ and ゐ) once. This is an old-fashioned way of ordering hiragana (modern Japanese usually uses Gojūon ordering). It can be used to label things in order without resorting to numbers, similar to how one might use letters A, B, C, etc. For example, the series Sayonara Zetsubou Sensei uses the same ordering for classrooms, though in modern day Japan classrooms would usually be labelled by letters. The main difference between this and other ordering systems is that Iroha order feels more authentically Japanese and old-fashioned than the other options. A table illustrates the relationship between the numbers and the kana. From the wiki Ship Class Normal # Elite # Flagship # Destroyer I-class 501 514 564 Destroyer Ro-class 502 515 552 Destroyer Ha-class 503 516 553 Destroyer Ni-class 504 514 Light Cruiser Ho-class 505 515 554 ... You can see that the numbers are ascending, particularly in the leftmost column. I'm not sure the right columns are correct since there's some repetitions, but it would be a lot more work to check everything than it's worth doing here. Anyway, at least the normal numbers very clearly count up from 500, while the class kana progress in the Iroha. That still doesn't explain how the ships themselves are ordered, though it does say how they're named once you know the ordering. The ordering of types is pretty clear. All the Destroyers come before Light Cruisers, which are before the Torpedo Cruisers, etc. For the most part, it goes from smaller to larger ships. It's not exactly the same as the order here for your available ship types (for instance, battleships come after carriers, rather than before), but it's similar. How the ships are ordered within each type is a bit less clear. I think that most enemy vessel classes are based on a class of ship available to you. For example, Battleship Ru-class seems to be based on the Nagato-class, while the faster but less armored Battleship Ta-class has more similarities with the Kongou-class battleships, and the Aviation Battleship Re-class is based on the Fusou-class aviation battleships. The order there is compatible with the order in the Ship List, in that Nagato-class comes before Kongou-class, which comes before Fusou-class (at least prior to any remodeling). I suspect for the other types of ships, there's a similar relationship, but I don't actually know which enemy class corresponds to which of your classes, and some don't seem to match well at all. I'm not even sure the creators really put that much thought into it. If there is a nice correspondence, I suspect someone has compiled this somewhere before, if possibly only in Japanese. However, I didn't immediately find it while searching, and it's a tangential enough that I'm not sure it needs to be stated here. Even if there isn't an exact correspondence, it's clear that the enemy ships are numbered in a way that at least makes sense when you compare it to your ship list. Anyway, at the end of the day, there's no real meaning to the individual names. In terms of literal interpretation, they could have just as well used "A-class", "B-class", etc. (nevermind that those have a different meaning in English). The use of Iroha order here is consistent with the general mood of KanColle as a semi-historical game. It probably isn't worth reading much more into it than that. Note that the ship classes are actually written in Katakana, e.g. 駆逐イ級 rather than 駆逐い級. This doesn't really change anything significant, and one can just as well write the Iroha in Hiragana or Katakana. In this context, it's similar to writing in italics in English. There's a bit more to it than that, but the subtleties between Hiragana and Katakana use in this sort of context aren't really worth going into here.
{ "pile_set_name": "StackExchange" }
Q: node js http post request save cookie I am calling an http post request(login request from another 3rd party server) from node and want to save the cookie for future http requests. var options = { host: 'hostname.com', port: '80', path: '/login.php', method: 'POST' }; var data = qs.stringify({ uname: "validUsername", password: "validPassword" }); var req = http.request(options, function(response) { console.log(response.statusCode); console.log('HEADERS: ' + JSON.stringify(response.headers)); // console.log('Cookies: ' + response.getHeader("Set-Cookie")); response.setEncoding('utf8'); response.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); req.write(data); req.end(); How can i access and save the cookie from the response sent by the requested server? A: You should be able to get the header with response.headers['set-cookie'];. If you need to actually parse them, you could use a module like cookie (what Express uses) or cookiejar.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to include an external Params block in a Rails Grape resource? I'm using Ruby on Rails 4 and Grape. I'd like my Grape Resources to take up a little space so that they are more readable by other developers. In the last few days we have been integrating the Stripe API (as an example) and in the params do section of the Resources there are code blocks like this: desc 'Add bank account' do headers API::V1::Defaults.xxxxxxx success API::V1::Entities::xxxxxxx end params do requires :external_account, type: Hash, allow_blank: false, desc: 'Bank account nested data' do requires :bank_account, type: Hash, allow_blank: false, desc: 'Bank account nested data' do requires :id, type: String, desc: 'Stripe token for bank account' requires :account_holder_name, type: String, desc: 'Bank account holder name' requires :account_holder_type, type: String, desc: 'Bank account holder type [individual or company]' optional :bank_name, type: String, desc: 'Bank name' requires :country, type: String, desc: 'Bank account country' optional :currency, type: String, desc: 'Bank account currency' requires :routing_number, type: String, desc: 'Bank account routing number' requires :name, type: String, desc: 'Bank account holders name' requires :status, type: String, desc: 'Bank account status' requires :last4, type: Integer, desc: 'Account holder ID number.' end requires :client_ip, type: String, desc: 'IP address of user for Stripe service agreement' end requires :email, type: String, desc: 'Users email' requires :business_type, type: String, desc: 'Individual or Company' requires :tos_acceptance, type: Hash, allow_blank: false, desc: 'Type of Service' do requires :date, type: Integer, desc: 'ToS [date]' requires :ip, type: String, desc: 'ToS [ip]' end optional :individual, type: Hash do requires :first_name, type: String, desc: 'Individuals [first name]' requires :last_name, type: String, desc: 'Individuals [last name]' requires :ssn_last_4, type: String, desc: 'Individuals SSN number' optional :dob, type: Hash do requires :day, type: String, desc: 'Individuals date of birth [day]' requires :month, type: String, desc: 'Individuals date of birth [month]' requires :year, type: String, desc: 'Individuals date of birth [year]' end end optional :company, type: Hash do requires :name, type: String, desc: 'Company [first name]' requires :email, type: String, desc: 'Company [email]' requires :phone, type: String, desc: 'Company [phone]' end end # ... oauth2 post '/' do # ... end How can I make that params block go to another file (for example inside a file in the helpers folder) and the params block can be included? I tried to do this with include API::V1::Helpers::my_helper but I don't know how to insert the params block. Can someone help me, please? A: You might use shared params module SharedParams extend Grape::API::Helpers params :pagination do optional :page, type: Integer optional :per_page, type: Integer end end class API < Grape::API helpers SharedParams desc 'Get collection.' params do use :pagination end get do # your logic here end end
{ "pile_set_name": "StackExchange" }
Q: Removal of noise from vibration recordings Problem I am analyzing accelerometer recordings that are contaminated by 'spikes' caused by issues in the digital circuitry. The spikes are problematic, because I wish to determine the peak-amplitude from these signals using an automated procedure from a large number (hundreds, perhaps thousands) of these recordings. Hence, manually determining the amplitudes is possible, but not preferred. Background The acceleration recordings are oscillatory in nature and reach frequencies of ~200 Hz. I am planning on using a low-pass filter in Matlab to remove the contaminating spikes in the signal. Sample rate is around 730 Hz. An FFT-based filter may be complicated by the fact that the signal gradually increases and decreases in frequency over time. Here is a picture of an example recording including the pesky spikes (the noise) in the first 100 ms: Question I am using Matlab for signal processing and I am looking for advice on which digital filter for use as a high-pass filter? For example, Butterworth and Chebyshev filters are quite commonly applied if I am not mistaken, but why? Will wavelets do me any good? A: If you want to detect the peak value of the time-domain signal, it is important not to change phase of each frequency signals. Otherwise, the peak value will be affected by it and will slightly change. I think you already have recorded signal and you can process it after the recording. If so, it is better to use zero-phased filters, like this function in matlab. http://uk.mathworks.com/help/signal/ref/filtfilt.html In this case, the needed function is to reduce the spike, which contains so much frequencies. In the help page I have shown before, there is an example of filtering this kind of spikes from the relatively low-frequency signal. I think it's what you need. Edit I recommend Butterworth low pass filter for its flat gain characteristics. The gain ripple of the Chebtshev would affect badly. The phase change will be corrected by using the filter backward, which the filtfit does. As you imagine, the effect of the phase change would be very little in this case, but it cannot be guaranteed. Just for your information, Bessel would be a candidate when you do the filtering online. If you still doubt about the effect of the phase shift (not the time-shift) by the filter, you can imagine the time-streched pulse and impulse signal in the image and code below. These signals are almost the same but only the phase are different. Besides the amount of the effect, the phase shift does affect to the amplitude of the signal. I recomend you to use zero-phase filter if you want to measure the actual amplitude precisely. clear all; close all; % generate signal with the same phase N = 2^15; % number of samples for this signal for k = 1:N/2; S(k+1) = exp(0); end S(N/2+2: N) = conj(S(N/2: -1 :2)); signal1 = real(ifft(S)); % generate signal with different phase from above % this signal is called time-streched pulse. N = 2^15; for k = 1:N/2; S(k+1) = exp(-1j*2*pi*N/2*(k/N)^2); end S(N/2+2: N) = conj(S(N/2: -1 :2)); signal2 = real(ifft(S)); % and let's see them. subplot(211) plot(signal1) xlim([-1e4, length(signal1)]) xlabel('time') ylabel('all the same phase') subplot(212) plot(signal2) xlim([-1e4, length(signal1)]) xlabel('time') ylabel('only the phases are different form above')
{ "pile_set_name": "StackExchange" }
Q: do we really need a "software" tag? In the review queue, someone provided a definition for the "software" tag. Since the entire site is about software, what is the value of a "software" tag? And if there is value, can we think of a more suggestive term than "software" for that concept? A: If there was a use for it, I would say it would be for software we use to perform QA (as opposed to the QA of software). So bug-trackers, automated testing tools, etc. However, it's so generic that I don't know if it's useful. I'm going to recommend removing it. There's only 11 questions with it so it won't take long to burninate it. The only real hiccup is the question with this as its only tag. I might just have to delete that one...
{ "pile_set_name": "StackExchange" }
Q: white-space:pre does not work with contenteditable I am trying to prevent a contenteditable div from word wrapping. The white-space: pre property does not work for a contenteditable. This is the css: .preDiv{ border:1px solid blue; overflow:auto; width:100px; white-space:pre; } Here is a fiddle:contentEditable-fiddle I want it to work the way it does as if it wasn't a contenteditable. I need this because, in my real code the div has line numbers next to it and they are no longer correct when the div starts word-wrapping, when the width of the div changes. I have tried to use white-space:nowrap but then the entire text is set on one line. Does anyone have an idea how I can prevent this rearranging of the text when the width changes? A: Luckily the answer was out there on this fiddle:contenteditable with white-space pre This is the CSS this person used: #editor { border: 1px solid black; height: 200px; width: 300px; white-space: pre; word-wrap: normal; overflow-x: auto; } So it needed the extra: word-wrap: normal; Thank you Rick for your help, it boosts the morale!
{ "pile_set_name": "StackExchange" }
Q: Find all usages of DateTime.Now/Today/UtcNow with a Roslyn Analyzer I've implemented a TimeProvider within a large C# application, so that there is centralized control over the application time. I want to make sure in the future that no one is using DateTime.Now/Today/UtcNow as this would circumvent the previous mentioned implementation. Instead, I want an analyzer to suggest to use my TimeProviderService, so that it is not missed in e.g a code review. I want to solve this with an analyzer, so therefore my question is: How do I do this? Below is one of my attemps; however, this one seems to trigger some sort of legacy issue with FxCop: [DiagnosticAnalyzer(LanguageNames.CSharp)] public class Analyzer : DiagnosticAnalyzer { public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeSymbol, SyntaxKind.IdentifierName); } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public static string DiagnosticId = "1337"; private static void AnalyzeSymbol(SyntaxNodeAnalysisContext context) { var token = context.Node.GetFirstToken(); if (token.ToString().Equals("DateTime")) { var nextToken = token.GetNextToken(); if (nextToken.IsKind(SyntaxKind.DotToken)) { var dateTimeProperty = nextToken.GetNextToken(); var descripter = new DiagnosticDescriptor(DiagnosticId, "DateTime.Today: Use the TimeProvider.Today instead", "", "Noitso best practise", DiagnosticSeverity.Error, isEnabledByDefault: true); if (dateTimeProperty.ToString().Equals("Now")) { context.ReportDiagnostic(Diagnostic.Create(descripter, context.Node.GetLocation(), "DateTime.Now: Use the TimeProvider.Now instead")); } else if (dateTimeProperty.ToString().Equals("Today")) { context.ReportDiagnostic(Diagnostic.Create(descripter, context.Node.GetLocation())); } else if (dateTimeProperty.ToString().Equals("UtcNow")) { context.ReportDiagnostic(Diagnostic.Create(descripter, context.Node.GetLocation(), "DateTime.UtcNow: Use the TimeProvider.UtcNow instead")); } } } } } A: I recreated my project, which solved the legacy issue. I have no idea what I did wrong when I created it the first time :). The code almost worked, as it had one flaw var dateTimeProperty = token.GetNextToken(); is referencing the wrong token, it should be referencing nextToken.
{ "pile_set_name": "StackExchange" }
Q: Count not returning total count value in SQL I have a MySQL database and it has a signUp table. The table has a field called created which is a placeholder for signups date. Format is eg: [2014-10-12 17:48:24]. There are many user who signup in single day. I am trying to get a count of each day signups. My code below displays single date eg: [20141012000000] but the count is still 1. SELECT DISTINCT TRUNCATE(created,-6) as created, COUNT(*) as CountCreated FROM signUp WHERE created >= '20000101000000' AND created <= '30000101000000' GROUP BY created ---SQL RESULT--- |------------------------|-------------------------| |Created CountCreated |------------------------|-------------------------| |20141012000000 1 |------------------------|-------------------------| |20141015000000 1 |------------------------|-------------------------| There are more than 30 signup for that date. I used truncate so that the value is compared at the WHERE statement and its ommiting the TIME and only returning DATE. The time is zeroed. What I am trying to get: I simply want to get the total count of created field for that date. For example my signUp for [20141012000000] is 30 so I need it like this |------------------------|-------------------------| |Created CountCreated |------------------------|-------------------------| |20141012000000 30 |------------------------|-------------------------| |20141015000000 33 |------------------------|-------------------------| Please help me fix this... Thank You. A: Assuming created is datetime: SELECT date(created) as created, COUNT(*) as CountCreated FROM signUp GROUP BY date(created); If it is a string: SELECT left(created, 10) as created, COUNT(*) as CountCreated FROM signUp GROUP BY left(created, 10);
{ "pile_set_name": "StackExchange" }
Q: Fiddler gateway proxy username/password I'm trying to intercept a web application which uses a HTTP proxy (basic HTTP auth password protected) to access its resources. In Fiddler options, there is a setting for manual proxy configuration. But in that field, I can only define the proxy address and port. I need to define an username/password combination for upstream proxy. Is there any way to do this? A: Your scenario is a bit unclear. Clients should automatically prompt for proxy credentials when a HTTP/407 is received, although many don't. If your question is: "How can I add a Proxy-Authorization header to all requests that pass through Fiddler?" then it's pretty simple. Rules > Customize Rules > Scroll to OnBeforeRequest and add: if (!oSession.isHTTPS) { oSession.oRequest["Proxy-Authorization"] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="; } Where dXNlcm5hbWU6cGFzc3dvcmQ= is the base64-encoded version of the "username:password" string. You can use Fiddler's Tools > TextWizard to base64-encode a string.
{ "pile_set_name": "StackExchange" }
Q: What does "thrashing about" mean? In an ROBERT LOWELL's interview, in interviewer's question, I don't get the meaning of the part. Also in LOWELL's answer I dont get the part in italic, could any one help me to understand? INTERVIEWER But something of Crane does seem to have gotten into your work—or maybe it’s just that sence of power thrashing about. I thought it had come from a close admiring reading of Crane. LOWELL Yes, some kind of wildness and power that appeals to me, I guess. But when I wrote difficult poems they weren’t meant to be difficult, though I don’t know that Crane meant his to be. I wanted to be loaded and rich, but I thought the poems were all perfectly logical. You can have a wonderful time explaining a great poem like “Voyages II,” and it all can be explained, but in the end it’s just a love poem with a great confusion of images that are emotionally clear; a prose paraphrase wouldn’t give you any impression whatever of the poem. I couldn’t do that kind of poem, I don’t think; at least I’ve never been able to. Here is the link of interview: https://www.theparisreview.org/interviews/4664/robert-lowell-the-art-of-poetry-no-3-robert-lowell A: As @choster points out the phrasing is power thrashing about thrashing about means to move wildly The comment some kind of wildness and power that appeals to me appeals to me means the person finds it attractive, that they like it If someone says It is appealing to me. it means they like or are attracted to something. A cold beer sounds very appealing on a hot summer day.
{ "pile_set_name": "StackExchange" }
Q: How to make the TextView drag in LinearLayout smooth, in android? I have a situation which I am not able to fix, hopefully I will get some advises from you. The situation is simple: I have a LinearLayout in which I have a TextView with multiple lines of text. The user is able to drag the TextView around until he finds a position he likes. What is really important is that the TextView can be partially out of the LinearLayout (it will appear cut). Here are some code samples: <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top|center_horizontal" android:clipChildren="false" android:gravity="center_horizontal|center_vertical" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:textColor="@color/text_color" android:textSize="16sp" /> </LinearLayout> As you can see the LinearLayout has clipChildren = false to allow cutoff of text. For the textview I set a touch listener txt.setOnTouchListener(new View.OnTouchListener() { int initialX = 0; int initialY = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: initialX = (int) event.getX(); initialY = (int) event.getY(); break; case MotionEvent.ACTION_MOVE: int currentX = (int) event.getX(); int currentY = (int) event.getY(); LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) txt.getLayoutParams(); int left = lp.leftMargin + (currentX - initialX); int top = lp.topMargin + (currentY - initialY); int right = lp.rightMargin - (currentX - initialX); int bottom = lp.bottomMargin - (currentY - initialY); lp.rightMargin = right; lp.leftMargin = left; lp.bottomMargin = bottom; lp.topMargin = top; txt.setLayoutParams(lp); break; default: break; } return true; } }); And here is my problem: As you can see I've set all the layout parameters (right, left, bottom, top margins). Why is that ? 1) If I use only left/top the drag is smooth enought but text get's wrapped at the right border instead of getting cut. Probably due to right 0 margin value. 2) If I use all margins, the text gets cut as I want, but the movement is not smooth, it just jumps around for a few pixels. How can I fix this ? A: Well. this is weird. By inserting the TextView inside another LinearLayout with the same size as the initial one, makes everything smooth. I have no idea why.
{ "pile_set_name": "StackExchange" }
Q: Greedy algorithms in two pointer techniques(fast and slow runnner) I am learning the Two-Pointer Technique in Two-pointer Technique - Scenario II It introduced fast-runner pointer and slow-runner pointer to move elements and return the new length public int removeElement(int[] nums, int val) { int k = 0; for (int i = 0; i < nums.length; ++i) { if (nums[i] != val) { nums[k] = nums[i]; k++; } } return k; } A summary follows: This is a very common scenario of using the two-pointer technique when you need: One slow-runner and one fast-runner at the same time. The key to solving this kind of problems is to Determine the movement strategy for both pointers. Similar to the previous scenario, you might sometimes need to sort the array before using the two-pointer technique. And you might need a greedy thought to determine your movement strategy. Reference to And you might need a greedy thought to determine your movement strategy. The greedyhere is confusing since we take greedy as the fundamental greedy algorithms for granted. What kinds of greedy algorithms thought can be employed in two pointer? Could you please help an example? A: What kinds of greedy algorithms thought can be employed in two pointer? Consider this problem 3sum in LeetCode. This problem requires sorting the input array prior to applying two-pointers method. When you're sorting the input array in some order, this is pretty greedy way to attack a problem. Consider another problem Container With Most Water in LeetCode. I don't want to give you spoiler solution for this problem incase you didn't solve it yet. But to give you some idea how it relates to greedy approach, you need to advance left and right pointer based on some comparison between numbers which is actually kind of "Greedy".
{ "pile_set_name": "StackExchange" }
Q: Android 1.5: Asynctask doInBackground() not called when get() method is called I am running into an issue with the way my asynctasks are executed. Here's the problem code: firstTask = new background().new FirstTask(context); if (firstTask.execute().get().toString().equals("1")) { secondTask = new background().new SecondTask(context); } What I'm doing here is creating a new asynctask object, assigning it to firstTask and then executing it. I then want to fire off a separate asynctask when the first one is done and making sure it returns a success value (1 in this case). This works perfectly on Android 2.0 and up. However, I am testing with Android 1.5 and problems start popping up. The code above will run the first asynctask but doInBackground() is never called despite onPreExecute() being called. If I am to execute the first task without the get() method, doInBackground() is called and everything works as expected. Except now I do not have a way to determine if the first task completed successfully so that I can tell the second task to execute. Is it safe to assume that this is a bug with asynctask on Android 1.5? Especially since the API (https://developer.android.com/reference/android/os/AsyncTask.html#get%28%29) says that the get method has been implemented since API 3. Is there any way to fix this? Or another way to determine that the first task has finished? A: If you are going to block (via get()), why are you bothering with AsyncTask in the first place? The whole point of AsyncTask is to not block. If you want to have SecondTask execute when FirstTask is done, have FirstTask execute SecondTask in FirstTask's onPostExecute().
{ "pile_set_name": "StackExchange" }
Q: Custom ZoneIds / Time Zones in Java I'm attempting to model an iCalendar VTIMEZONE object using Java's ZoneId and ZoneOffsetTransitionRule. My VTIMEZONE object looks like BEGIN:VTIMEZONE TZID:Central European Standard Time BEGIN:STANDARD DTSTART:16010101T030000 TZOFFSETFROM:+0200 TZOFFSETTO:+0100 RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=10 END:STANDARD BEGIN:DAYLIGHT DTSTART:16010101T020000 TZOFFSETFROM:+0100 TZOFFSETTO:+0200 RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=1;BYDAY=MO END:DAYLIGHT END:VTIMEZONE I need to create my own ZoneId to model this because, as far as I know, there isn't a ZoneId available with these offsets and in which DST starts on the first Monday of January (as opposed to some Sunday of March). I have the following for creating a ZoneOffsetTransitionRule ZoneOffsetTransitionRule of = ZoneOffsetTransitionRule.of(Month.JANUARY, 1, DayOfWeek.MONDAY, LocalTime.of(2, 0), false, ZoneOffsetTransitionRule.TimeDefinition.STANDARD, ZoneOffset.ofHours(1), ZoneOffset.ofHours(1), ZoneOffset.ofHours(2)); But I'm not sure if it's correct or how to create a ZoneId from this. Is that transition rule accurate to model the DAYLIGHT component of my VTIMEZONE? How can I create a ZoneId from this so I can eventually create a ZonedDateTime? A: The only way to get a ZoneId (at least if we’re not very hacky) is through the factory methods of ZoneId and its subclass ZoneOffset. It might seem at first that this leaves of with the built-in ZoneIds. However, there’s a backdoor for specifying additional ZoneIds that ZoneId.of can then produce. It’s called ZoneRulesProvider. We need to specify an new and unique ID and we need to specify the zone rules (hence the name ZoneRulesProvider). So with your ZoneOffsetTransitionRule you are already on the way. We need two of them, though, yours for transitioning to DST (which would normally have happened in the spring) and one for going the other way in the fall. The following listing isn’t production code, of course, but is just to demonstrate that it is doable to develop and register your own ZoneRulesProvider. final String customZoneId = "Custom-CEST-1"; final ZoneOffset standardOffset = ZoneOffset.ofHours(1); final ZoneOffset summerTimeOffset = ZoneOffset.ofHours(2); // At least one transistion is required ZoneOffsetTransition initialTransition = ZoneOffsetTransition.of( LocalDateTime.of(1601, 1, 1, 3, 0), summerTimeOffset, standardOffset); List<ZoneOffsetTransition> transitionList = List.of(initialTransition); // Rules for going to and from summer time (DST) ZoneOffsetTransitionRule springRule = ZoneOffsetTransitionRule.of(Month.JANUARY, 1, DayOfWeek.MONDAY, LocalTime.of(2, 0), false, ZoneOffsetTransitionRule.TimeDefinition.STANDARD, standardOffset, standardOffset, summerTimeOffset); ZoneOffsetTransitionRule fallRule = ZoneOffsetTransitionRule.of(Month.OCTOBER, -1, DayOfWeek.SUNDAY, LocalTime.of(2, 0), false, ZoneOffsetTransitionRule.TimeDefinition.STANDARD, standardOffset, summerTimeOffset, standardOffset); ZoneRules rules = ZoneRules.of(standardOffset, standardOffset, transitionList, transitionList, List.of(springRule, fallRule)); // The heart of the magic: the ZoneRulesProvider ZoneRulesProvider customProvider = new ZoneRulesProvider() { @Override protected Set<String> provideZoneIds() { return Set.of(customZoneId); } @Override protected NavigableMap<String, ZoneRules> provideVersions(String zoneId) { return new TreeMap<>(Map.of(customZoneId, rules)); } @Override protected ZoneRules provideRules(String zoneId, boolean forCaching) { return rules; } }; // Registering the ZoneRulesProvider is the key to ZoneId using it ZoneRulesProvider.registerProvider(customProvider); // Get an instance of our custom ZoneId ZoneId customZone = ZoneId.of(customZoneId); // Transition to standard time was Sunday, October 29, 2017, // so try the day before and the day after System.out.println(LocalDate.of(2017, Month.OCTOBER, 28).atStartOfDay(customZone)); System.out.println(LocalDate.of(2017, Month.OCTOBER, 30).atStartOfDay(customZone)); // The special thing about our custom ZoneID is that transition to DST // happened on Monday, January 1. Try the day before and the day after. System.out.println(LocalDate.of(2017, Month.DECEMBER, 31).atStartOfDay(customZone)); System.out.println(LocalDate.of(2018, Month.JANUARY, 2).atStartOfDay(customZone)); The code prints: 2017-10-28T00:00+02:00[Custom-CEST-1] 2017-10-30T00:00+01:00[Custom-CEST-1] 2017-12-31T00:00+01:00[Custom-CEST-1] 2018-01-02T00:00+02:00[Custom-CEST-1] We see that we get the expected DST offset of +02:00 exactly before the transition to standard time and again after the transition to summer time.
{ "pile_set_name": "StackExchange" }
Q: "Tag attribute name has invalid character ' '. " Android Manifest I am getting the error "Tag attribute name has invalid character ' '. " in the Android Manifest, while there is no obviously invalid character. Here is the code: <activity android:name="Quiz 31" android:configChanges="orientation|keyboardHidden" android:label="Quiz 31" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar" > <intent-filter> <action android:name="com.SoulSlayerAbad.AMQ.QUIZ31" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> As you can see, no ' ' character in the code. Does anyone know why this is happening? One thing to note is that I generated this piece of code using a few lines of Java run inside of Eclipse console. The code for that is: int Begin = 0, End = 0; Scanner sc = new Scanner(System.in); String Text = " <activity "+ "android:name=\"Quiz "+Begin+"\" "+ "android:configChanges=\"orientation|keyboardHidden\" "+ "android:label=\"Quiz "+Begin+"\" "+ "android:screenOrientation=\"portrait\" "+ "android:theme=\"@android:style/Theme.NoTitleBar\" > "+ "<intent-filter> "+ "<action android:name=\"com.SoulSlayerAbad.AMQ.QUIZ"+Begin+"\" /> "+ "<category android:name=\"android.intent.category.DEFAULT\" /> "+ "</intent-filter> "+ "</activity> "; System.out.println("Begining:"); Begin = sc.nextInt(); System.out.println("End At:"); End = sc.nextInt(); while(Begin <= End){ System.out.println(Text); Begin++; } A: android:name is supposed to have reference of your class path which represents the activity. It must not contain any special characters or spaces. For example: android:name="com.json.test.MainActivity" Here, MainActivity is the class file which extends an Activity.
{ "pile_set_name": "StackExchange" }
Q: URL.Action() including route values I have an ASP.Net MVC 4 app and am using the Url.Action helper like this: @Url.Action("Information", "Admin") This page is used for both adding a new and edit an admin profile. The URLs are as follows: Adding a new: http://localhost:4935/Admin/Information Editing Existing: http://localhost:4935/Admin/Information/5 <==Admin ID When I'm in the Editing Existing section of the site and decide that I would like to add a new admin I click on the following link: <a href="@Url.Action("Information", "Admin")">Add an Admin</a> The problem however that the above link is actually going to http://localhost:4935/Admin/Information/5. This only happens when I'm in that page editing an existing admin. Anywhere else on the site it links correctly to http://localhost:4935/Admin/Information Has anyone else seen this? UPDATE: RouteConfig: routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); A: outgoing url in mvc generated based on the current routing schema. because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values. to solve this problem you should use UrlParameter.Optional: <a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
{ "pile_set_name": "StackExchange" }
Q: How to convert code AVFoundation objective c to Swift? I am using AVFoundation in swift for take pictures but I can't convert any func lines of code from objective c to Swift. My func code is: - (void) capImage { //method to capture image from AVCaptureSession video feed AVCaptureConnection *videoConnection = nil; for (AVCaptureConnection *connection in stillImageOutput.connections) { for (AVCaptureInputPort *port in [connection inputPorts]) { if ([[port mediaType] isEqual:AVMediaTypeVideo] ) { videoConnection = connection; break; } } if (videoConnection) { break; } } NSLog(@"about to request a capture from: %@", stillImageOutput); [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) { if (imageSampleBuffer != NULL) { NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; [self processImage:[UIImage imageWithData:imageData]]; } }]; } This line send me error AnyObject[]does not conform to protocol sequencfe..: for (AVCaptureInputPort *port in [connection inputPorts]) { In swift: for port:AnyObject in connection.inputPorts { And I don't know how convert this line: [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) { Can u help me to convert to swift? Thanks!! A: for (AVCaptureInputPort *port in [connection inputPorts]) { ) Arrays of AnyObject should be cast to arrays of your actual type before interating, like this: for (port in connection.inputPorts as AVCaptureInputPort[]) { } In terms of blocks to closures, you just have to get the syntax correct. stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) { (imageSampleBuffer, error) in // This line defines names the inputs //... } Note that this also uses Trailing Closure Syntax. Do read up on the docs more! EDIT: In terms of initializers, they now look like this: let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer) self.processImage(UIImage(data:imageData))
{ "pile_set_name": "StackExchange" }
Q: referring to specific parts of a python dictionary in javascript I made a program which parses data and then does a python json.dumps() with it. Next, in my javascript, I did a jQuery getJSON() with this data. Before I did the json.dumps() with my data, I split it into three list because I didn't know how to deal with the data in js. The data is structured like this: Key: (value1, value2) I simply need to refer to those individual 'columns' in my javascript separately. I feel like it might be more efficient to just do the dumps() with the python dictionary but I don't know how to refer to it as I want in the javascript. Obviously it's important that the data stay "grouped" How would I go about doing that? A: Here's a full example that I have used in a mapping project. Javascript loads data via Ajax from the flask application. The JQuery ajax method is very similar to the getJSON method. #ajax method to retreive well data for dynamic well values, x_pos, y_pos, substance concentration @app.route('/getWellData', methods=['GET', 'POST']) def getWellData(): #get all samples with that date date_collected = request.args.get('date_collected') site_id = request.args.get('site_id') site_map_id = request.args.get('site_map_id') substance_id = request.args.get('substance_id') well_results = wellSubstanceDataBySite( site_id=site_id, site_map_id=site_map_id, date_collected=date_collected, substance_id=substance_id) #return json to updateMarks ajax javascript function return json.dumps(well_results) Javascript: //call the ajax endpoint for getWellData to return position, values, etc $.ajax({ dataType: "json", url: '/getWellData', data: data, success: function(data){ //iterate over each value in the data array and append it as div element to the .landmarks div $.each(data, function(well_id, well){ //create the mark element, must be all mashed into one line, wont work with multiple lines //sutract depth_of_water (well.value) from well.top_of_casing var goundwater_elevation_val = well.top_of_casing - well.value var mark = '<div class="item mark" id="well-' + well_id + '" data-id="' + well_id + '" data-position="' + well.xpos + "," + well.ypos + '" data-value="' + goundwater_elevation_val.toFixed(4) + '" data-show-at-zoom="0"><div><div class="text"><input class="well-checkboxes" type="checkbox" name="enable-well-' + well_id + '" checked style="margin:3px;"><strong>' + goundwater_elevation_val.toFixed(4) + '</strong></div><img src="/static/jquery-image-viewer/example/images/mark.png" width="50px" height="50px" alt="Permanent Mark" /></div></div>'; if (well.value != 0) { //append the new mark to the .landmarks div $('.landmarks').append(mark); } }); //refresh all landmarks to plot the new landmarks on the map with the smoothZoom API $('#sitemap').smoothZoom('refreshAllLandmarks'); } });
{ "pile_set_name": "StackExchange" }
Q: Shiny "updateCheckboxGroupInput" inconsistency I don't know if this is a bug of just a feature, but the updateCheckboxGroupInput function in Shiny is not working consistently. When I update the group with selected=FALSE to deselect all the choices, the related reactive components (observer, UI elements) doesn't change anything. I know that there are many ways to do this task, my point here is to show the lack of consistency of the updateCheckboxGroupInput with the selected parameter. Here is simplified example that represents the problem using a couple of action buttons to select/deselect all the choices on the group. After updating with selected=FALSE, all the choices are deselected but the change does not affect the reactive components associated (in this case verbatimTextOutput) as is the case of selecting all. Can someone explain me why the updateCheckboxGroupInput is not working as expected? choices <- letters[1:5] runApp(list( ui = basicPage( checkboxGroupInput('chkGrp', 'Options', choices), actionButton("all","All"), actionButton("none","None"), verbatimTextOutput("value") ), server = function(input, output, session) { output$value <- renderPrint({ input$chkGrp }) observe({ if ( is.null(input$all) || input$all == 0) return() updateCheckboxGroupInput(session,"chkGrp",selected=choices ) }) observe({ if ( is.null(input$none) || input$none == 0) return() updateCheckboxGroupInput(session,"chkGrp",selected=FALSE) }) } )) A: When you use the updateCheckboxGroupInput you still have to provide what goes in there. rm(list = ls()) library(shiny) choices <- letters[1:5] runApp(list( ui = basicPage( checkboxGroupInput('chkGrp', 'Options', choices), actionButton("all","All"), actionButton("none","None"), verbatimTextOutput("value") ), server = function(input, output, session) { output$value <- renderPrint({ input$chkGrp }) observe({ if ( is.null(input$all) || input$all == 0) return() updateCheckboxGroupInput(session,"chkGrp",selected=choices ) }) observe({ if ( is.null(input$none) || input$none == 0) return() updateCheckboxGroupInput(session,"chkGrp",choices = choices,selected=NULL) }) } ))
{ "pile_set_name": "StackExchange" }
Q: How to display superscript in QComboBox item? I want to display 10-8 in QComboBox item. But it displays "sup" tags. A: the easiest way is to use special Unicode characters and use them in translation file (direct usage in code may be problematic): 10⁻⁸ If you don't like use translation file try this code: ui->comboBox->addItem(QString::fromWCharArray(L"10\x207B\x2078")); ui->comboBox->addItem(QString::fromWCharArray(L"10⁻⁸")); On my Qt.5.2.1 (Linux) it works. Also pasting above string in designer also works.
{ "pile_set_name": "StackExchange" }
Q: mysql: how to delete then insert all records of certain type? Here's the situation: I have a main admin whose id, in the table person is 478. this admin is supposed to handle partners, in the table partners. there's a table that "joins" them: person_partners. Sometimes, some people add new partners, and I'd like to run a query that: either: remove all links between this admin and partners, some kind of DELETE * FROM person_partners where id_person=478 re-insert all links between this admin and partners (= new partners will be inserted too), some kind of INSERT INTO person_partners (id_person,id_partner) VALUES (478, SELECT id FROM partners) (but this query give me this error: ERROR 1242 (21000): Subquery returns more than 1 row) or simply insert all partners that are not yet in person_partners with id_person=478 Any idea? A: Like BugFinder said, "You seem to have your own answers in the question" To fix the ERROR 1242 you have to write it like this: INSERT INTO person_partners (id_person,id_partner) SELECT '478', id FROM partners; Alternatively to "simply insert all partners that are not yet in person_partners with id_person=478" you can INSERT IGNORE INTO person_partners (id_person,id_partner) SELECT '478', id FROM partners; Read more about it here.
{ "pile_set_name": "StackExchange" }
Q: Kafka Topic Lag is keep increasing gradually when Message Size is huge I am using the Kafka Streams Processor API to construct a Kafka Streams application to retrieve messages from a Kafka topic. I have two consumer applications with the same Kafka Streams configuration. The difference is only in the message size. The 1st one has messages with 2000 characters (3KB) while 2nd one has messages with 34000 characters (60KB). Now in my second consumer application I am getting too much lag which increases gradually with the traffic while my first application is able to process the messages at the same time without any lag. My Stream configuration parameters are as below, application.id=Application1 default.key.serde=org.apache.kafka.common.serialization.Serdes$StringSerde default.value.serde=org.apache.kafka.common.serialization.Serdes$StringSerde num.stream.threads=1 commit.interval.ms=10 topology.optimization=all Thanks A: In order to consume messages faster, you need to increase the number of partitions (if it's not yet done, depending on the current value), and do one of the following two options: 1) increase the value for the config num.stream.threads within your application or 2) start several applications with the same consumer group (the same application.id). as for me, increasing num.stream.threads is preferable (until you reach the number of CPUs of the machine your app runs on). Try gradually increasing this value, e.g go from 4 over 6 to 8, and monitor the consumer lag of your application. By increasing num.stream.threads your app will be able to consume messages in parallel, assuming you have enough partitions.
{ "pile_set_name": "StackExchange" }
Q: Convert data from URL into Image in iPhone Here I'm working for static URL. My Code : NSURL *url = [[NSURL alloc] initWithString:@"http://cns.bu.edu/~lgrady/diagonal_line_nobreak_seg.jpg"]; NSData *myData = [NSData dataWithContentsOfURL:url]; img.image = [UIImage imageWithData:myData]; So, I can see image in ImageView. But, While passing internal web-service URL. And I'm getting data for Image in bytes from url instead of Image like below: {"AppBanner":"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUg.....VORK5CYII="} But with help of above code, I can't convert this data into Image. So how can I convert this data into image ? Any Solution ? Thanks in advance. A: Use NSData-Base64 to convert base64 into NSData and then into UIImage NSString *strBase64 = [yourResposeDict objectForKey:@"AppBanner"]; //decode strBase64 using NSData-Base64 library
{ "pile_set_name": "StackExchange" }
Q: How to color the entire row using xlwt util of pyexcelerator The util talks about a function called this style0 = xlwt.easyxf( 'font: name Times New Roman, colour_index red' ) there is color red instead of color_index too . Is there any provision to color the entire row? A: pattern: pattern solid This can be used to add color to row... then u can add the color u want.. pattern: pattern solid,fore-color "COLOR NAME"
{ "pile_set_name": "StackExchange" }
Q: Filipino transferring between Narita and Haneda, do I need a transit visa? My flight is LAX to Narita and to Haneda for my connecting flight going to the Philippines My questions are: Do I need a transit visa? Do I need to claim my luggages before proceeding to my connecting flight A: Filipino citizens are not visa-exempt nationals according to the Japanese regulations. In addition, you need a visa if you leave the airport. This means that, for the purpose of transferring from Narita to Haneda, you will need a Transit Visa. The Japanese embassy in the US lists the documents required to apply for such a visa: Required Documents Applicant's valid passport, properly signed by bearer. VISA APPLICATION FORM TO ENTER JAPAN (available here), completely filled out and signed by the applicant. One photograph (2" x 2") attached to application form Flight itinerary issued by travel agency or airline company (We advise you not to purchase your airline ticket until the visa is approved.) [...] Visa for the next destination (if required) to be visited after Japan must already be in the passport at the time of application. If stay in Japan exceeds one night: Proof of sufficient funds (e.g. most recent U.S. bank statement, travelers' checks or letter of guarantee from friend/relative in Japan) A: As of October 15, 2018, Filipino passport holders must meet 5 conditions for a Shore Pass when transiting airports in Japan. This information comes from a representative at ANA over the phone. She read the rules. transit less than 72 hrs. arrival at certain airports (Narita/Haneda for eg.) must have boarding pass of onward flight to 3rd country must have visa for 3rd country must stay in city. No hotels are provided as a general policy for long layovers. A: As stated by Timatic, the database used by airlines: Visa required, except for Holders of onward tickets transiting to a third country can obtain a Shore Pass on arrival for a max. stay of 72 hours only if there are no connecting flights on the same calendar day. Which means, if you're making an overnight connection, you do not need a visa, and will get an entry stamp for 72 hours. Otherwise, you do need a transit visa
{ "pile_set_name": "StackExchange" }
Q: Do these plastic molds exist? I want to make a few concrete pavers, so I started looking for a few tutorials, and found this youtube video. In the tutorial, he uses a plastic mold where he pours the concrete. Something like this: Do these plastic molds exist? I searched amazon and home depot, but didn’t find anything. A: On the recommendation of a neighbor, I purchased a set of five molds for US$99 with free shipping. The size for my bundle was 10" x 18" x 1.5" but they have many different sizes available. The web site has been upgraded since I purchased. The molds appear to be high quality and my neighbor has nearly paved his entire yard with the casting he's done.
{ "pile_set_name": "StackExchange" }
Q: Peer discovery not working on private network I'm running 3 nodes with the following command: geth --verbosity 4 --autodag --nat any --genesis /opt/blockchain/genesis.json \ --datadir /opt/blockchain/data --networkid 4828 --port 30303 --rpc \ --rpcaddr 10.48.247.25 --rpcport 8545 --rpcapi db,eth,net,web3,admin \ --rpccorsdomain '*' --fast --mine --ipcdisable The genesis.json file is the same for every node (I've checksumed them to be sure). What happens is the nodes can't find each other alone, I have to manually connect them throw admin.addPeer. To test it, I've created a interval loop in the console to print admin.peers every 1 sec.: var interval = setInterval(function(){console.log(admin.peers)}, 1000); If if connect node 1 to node 2 (1--2), they keep connecting to and disconnecting from each other. But node 3 is not able to connect to any of them. Why is this happening? A: Each of the geth instances will need to discover at least one other instance with a connection to the rest of your private network. You could nominate one (or more) of your geth instances as a bootnode that all the other instances first connect to in order to find other peers in your private network. To specify the bootnode that the non-bootnode instances should connect to initially, use the following command line parameter (from https://github.com/ethereum/go-ethereum/wiki/Connecting-to-the-network#connecting-to-the-network) : geth --bootnodes "enode://pubkey1@ip1:port1 [enode://pubkey2@ip2:port2 [enode://pubkey3@ip3:port3]]" You could alternatively nominate one (or more) of the nodes as a static node that other peers will always connect to (from https://github.com/ethereum/go-ethereum/wiki/Connecting-to-the-network#static-nodes) by adding the file /static-nodes.json for each geth instance with the following content: [ "enode://f4642fa65af50cfdea8fa7414a5def7bb7991478b768e296f5e4a54e8b995de102e0ceae2e826f293c481b5325f89be6d207b003382e18a8ecba66fbaf6416c0@33.4.2.1:30303", "enode://pubkey@ip:port" ] Remember to remove the comma ',' if you only have one geth instance in your static-nodes.json file (Can anyone help guide on running two geth clients on the same box and same network?).
{ "pile_set_name": "StackExchange" }
Q: How do i connect a 'unity' web-based game to a 'ruby on rails' website's database? A game my friends and I are developing requires being connected to a website's database, because players need to log in with their accounts which are saved in the website's database, and we need to save players' game records and stats in the same database. We haven't decided the database type(whether to use SQLite3 or PG or NoSQL) and we are open to any suggestions that will solve our problem. We can use a different game engine instead if it is easier to connect to the database. A: Don't base your game engine choice solely on the backend database you are going to implement. Unity is a very powerful engine and there are a lot of assets over there that can be used to connect to the backend. My recommendation would be to design a solid game and a solid backend separately and then connect them via REST services. This way your game and your backend will be decoupled. It's hard to choose a database engine without knowing more details, like number of users, what kind of data you want to store, concurrency, etc... But I have implemented a reliable backend for a multiplayer game using Django, Tastypie and a Postgres database.
{ "pile_set_name": "StackExchange" }
Q: Many-To-Many LINQ "IN" Query Edit: Both the answers below work. My problem was due to using the NHibernate LINQ provider like this: from parks in Session.Linq<Park>() instead of like this: from parks in Session.Linq<Park().AsEnumerable() I have a class called Park which has an of Amenities. I want to create a LINQ query that returns all Park objects which contain every Amenity in a list. So given: List<Park> Parks(IList<Amenity> amenities) { // I want a query that would look like this (if this worked) // return all Park objects that have all of the given amenities var query = from parks in db.Parks where parks.Amenities.Contains(amenities) select parks; } This query: var query = from parks in Session.Linq<Park>() where amenities.All(a => parks.Amenities.Contains(a)) select parks; doesn't work. Here's more of my code for context: Mapping classes(I"m using Fluent NHibernate) public ParkDBMap() { Id(x => x.ParkId).Column("ParkId").GeneratedBy.HiLo("0").UnsavedValue(0); Map(x => x.Name, "Name"); this.HasManyToMany<Amenity>(x => x.Amenities) .Table("ParksMaps_ParkAmenities") .Cascade.SaveUpdate(); } public AmenityDBMap() { Id(x => x.AmenityId).Column("AmenityId").GeneratedBy.HiLo("0").UnsavedValue(0); Map(x => x.Name, "Name"); } Test method: public void ListParksByAmenity() { // Create Parks int parkCount = 10; CreateParks(parkCount); // Create Amenities Amenity restrooms = new Amenity(); restrooms.Name = "Restrooms"; ParksRepos.SaveAmenity(restrooms); Amenity tennis = new Amenity(); tennis.Name = "Tennis Courts"; ParksRepos.SaveAmenity(tennis); Amenity dogs = new Amenity(); dogs.Name = "Dogs Allowed"; ParksRepos.SaveAmenity(dogs); // Add amenities to parks IList<Park> parks = ParksRepos.Parks(); parks[0].AddAmenity(dogs); parks[0].AddAmenity(tennis); parks[0].AddAmenity(restrooms); ParksRepos.SavePark(parks[0]); parks[4].AddAmenity(tennis); parks[4].AddAmenity(restrooms); ParksRepos.SavePark(parks[4]); parks[9].AddAmenity(restrooms); ParksRepos.SavePark(parks[4]); IList<Amenity> amenityList = new List<Amenity>() { restrooms}; List<Park> restroomsParks = ParksRepos.Parks(amenityList); // three parks have restrooms Assert.AreEqual(1, restroomsParks.Count); Assert.AreEqual(parks[0].Name, restroomsParks[0].Name); amenityList = new List<Amenity>() { dogs, tennis, restrooms }; List<Park> allAmenities = ParksRepos.Parks(amenityList); // only one park has all three amenities Assert.AreEqual(3, allAmenities.Count); } I have three tables. A "Parks" table, an "Amenities" table, and a many-to-many table that has two columns, a park id and an amenity id. I'm having trouble wrapping my head around this. Anyone have any suggestions? A: List<Park> Parks(IList<Amenity> amenities) { var query = from parks in db.Parks where amenities.All(a => parks.Amenities.Where(sa => sa.ID == a.ID).Count() == 1) select parks; }
{ "pile_set_name": "StackExchange" }
Q: An error occurred while processing this request wcf Data service This is my web.config code. <?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </assemblies> </compilation> </system.web> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> </system.serviceModel> <connectionStrings> <add name="SupplierProjectEntities" connectionString="metadata=res://*/SupplierDatabase.csdl|res://*/SupplierDatabase.ssdl|res://*/SupplierDatabase.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=127.0.0.1;User Id=root;password=sa_12345;database=supplier&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> </configuration> This is my WCF data service Code. using System; using System.Collections.Generic; using System.Data.Services; using System.Data.Services.Common; using System.Linq; using System.ServiceModel.Web; using System.Web; namespace SupplierService { public class SupplierProjectService : DataService<SupplierProjectEntities > { // This method is called only once to initialize service-wide policies. public static void InitializeService(DataServiceConfiguration config) { // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc. // Examples: config.UseVerboseErrors = true; config.SetEntitySetAccessRule("*", EntitySetRights.All); config.SetServiceOperationAccessRule("*", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } } } Error description. When i am running this wcf data service then i am getting error as below. <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> <code/> <message xml:lang="en-US">An error occurred while processing this request.</message> <innererror> <message> Object reference not set to an instance of an object. </message> <type>System.NullReferenceException</type> <stacktrace> at MySql.Data.MySqlClient.MySqlClientFactory.get_MySqlDbProviderServicesInstance() at MySql.Data.MySqlClient.MySqlClientFactory.System.IServiceProvider.GetService(Type serviceType) at System.Data.Common.DbProviderServices.GetProviderServices(DbProviderFactory factory) at System.Data.Metadata.Edm.StoreItemCollection.Loader.InitializeProviderManifest(Action`3 addError) at System.Data.Metadata.Edm.StoreItemCollection.Loader.OnProviderManifestTokenNotification(String token, Action`3 addError) at System.Data.EntityModel.SchemaObjectModel.Schema.HandleProviderManifestTokenAttribute(XmlReader reader) at System.Data.EntityModel.SchemaObjectModel.Schema.HandleAttribute(XmlReader reader) at System.Data.EntityModel.SchemaObjectModel.SchemaElement.ParseAttribute(XmlReader reader) at System.Data.EntityModel.SchemaObjectModel.SchemaElement.Parse(XmlReader reader) at System.Data.EntityModel.SchemaObjectModel.Schema.HandleTopLevelSchemaElement(XmlReader reader) at System.Data.EntityModel.SchemaObjectModel.Schema.InternalParse(XmlReader sourceReader, String sourceLocation) at System.Data.EntityModel.SchemaObjectModel.Schema.Parse(XmlReader sourceReader, String sourceLocation) at System.Data.EntityModel.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, AttributeValueNotification providerNotification, AttributeValueNotification providerManifestTokenNotification, ProviderManifestNeeded providerManifestNeeded, IList`1& schemaCollection) at System.Data.Metadata.Edm.StoreItemCollection.Loader.LoadItems(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths) at System.Data.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerManifestToken, Memoizer`2& cachedCTypeFunction) at System.Data.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths) at System.Data.Metadata.Edm.MetadataCache.StoreMetadataEntry.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader) at System.Data.Metadata.Edm.MetadataCache.StoreItemCollectionLoader.LoadItemCollection(StoreMetadataEntry entry) at System.Data.Metadata.Edm.MetadataCache.LoadItemCollection[T](IItemCollectionLoader`1 itemCollectionLoader, T entry) at System.Data.Metadata.Edm.MetadataCache.GetOrCreateStoreAndMappingItemCollections(String cacheKey, MetadataArtifactLoader loader, EdmItemCollection edmItemCollection, Object& entryToken) at System.Data.EntityClient.EntityConnection.LoadStoreItemCollections(MetadataWorkspace workspace, DbConnection storeConnection, DbProviderFactory factory, DbConnectionOptions connectionOptions, EdmItemCollection edmItemCollection, MetadataArtifactLoader artifactLoader) at System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections) at System.Data.EntityClient.EntityConnection.InitializeMetadata(DbConnection newConnection, DbConnection originalConnection, Boolean closeOriginalConnectionOnFailure) at System.Data.EntityClient.EntityConnection.Open() at System.Data.Objects.ObjectContext.EnsureConnection() at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() at System.Data.Objects.ObjectQuery`1.GetEnumeratorInternal() at System.Data.Objects.ObjectQuery.System.Collections.IEnumerable.GetEnumerator() at System.Data.Services.WebUtil.GetRequestEnumerator(IEnumerable enumerable) at System.Data.Services.DataService`1.SerializeResponseBody(RequestDescription description, IDataService dataService) at System.Data.Services.DataService`1.HandleNonBatchRequest(RequestDescription description) at System.Data.Services.DataService`1.HandleRequest() </stacktrace> </innererror> </error> Explanation of Error. This database i had first made in sql server.and when i had made wcf data service for sql server then it was working properly.and that database was as same as mysql database. but now have made WCF data service for mysql database then i am getting this error. as shown above.so please help me for this error it's argent to solve this error. I am asking this question to retrieve data from mysql database it's version is 6.7.4.0 A: I could get the answer of my question. The answer is that i had just forgot to add Mysql.data.dll and mysql.data.entity.dll in reference folder. so after adding this dll in reference folder i could solved above error so you can also try. i hope it will be helpful.
{ "pile_set_name": "StackExchange" }
Q: How to handle a shying horse mount as GM? The party of my players who ride on horses (given to them from a nice NPC) through a valley will get into a heavy thunderstorm soon. Some of the horses will get nervous or even start running and jumping around because of thunder and lightning (I'll roll some dice for which horse and what it will do) Now I don't know how to handle a panicking horse mount with PCs who do not have special animal feats. I just found the hoof attack, in case the character fell from the horse: large horse 2 hooves +0 (1d6+2) and light horse: 2 hooves –2 (1d4+1) which looks good to me. Which rolls should I make according to the rules e.g. for a player to calm down his panicking or fleeing horse? What to roll to decide whether a player falls off the horse? I'd like to create an intense scene without the need of using some evil monsters, so if someone has additional ideas for the situation, I'd also love to read them. One last thing: Since I'm new to game mastering, I wonder what kinds of XP should come out of this encounter (if any). Or maybe I just should reward the players in a different way, although I can't think of anything right now. A: By the rules If you want to use mechanics as much as possible, you could start by having the horses frightened or even panicked (not much difference for NPCs). The storm being what scares them, "fleeing away from the source" is technically impossible so it turns into random fleeing. In such situations, horses tend to scatter. To deal with the situations, PCs would have a few solutions: If anyone has Handle Animal trained, they could use it to Handle the horses, ordering them to Stay or Come. It's usually a DC 10 check but considering the unusual situation, it wouldn't be strange to raise the DC as if the animals were wounded (+2 to DC, or more if you think it's appropriate). This may have to be done for as long as the horses remain within the storm. Finding a shelter is paramount. They could try to Grapple with them or use Lassos to direct them to a safer place. You may consider the Ride skill use to Control mount in battle, a DC 20 check, as appropriate to control the horses in spite of their fear They may use various spells creatively to hinder the horses movement or block out the source of their fear. You may be able to push the horses into a Secure Shelter until the storm subsides. You could deafen the horses and/or blind them to stop them from perceiving the source of their fear. Being deaf or blind might freak them out differently though... You could use Grease or Entangle to slow them down, if not stop them outright As for staying the saddle when they rear, this is a DC 5 Ride check, along with a DC 15 Ride check to soften the fall in case they fail that first one. As a skill challenge If you want to go for something less strict and more drama-oriented, you could ask the players how they plan to solve the situation and come up with appropriate ability and skill checks as rulings. They may need a given number of successes to get all the horses to safety before getting a number of failures. The total tally would give a sense of how they did, possibly letting one or more mounts escape, to be retrieved later or lost forever, depending on how long-lasting you want the results to be. You could also rely on your sense of drama to decide what happens on each success and failure, depending on the actions being attempted, and to find the right moment to consider the scene over. XP Rewards It's not unusual to reward a creature's XP, as if it had been defeated in combat, whenever it's involved in such challenges. You could give them XP for each horse they managed to secure for example. Another way to do it is to consider the challenge as a whole and establish the goal you expect them to accomplish. You could say you expect them to keep all the horses safe for this to be a success. Or maybe you think this is rather difficult (especially if the party does not have the right skills, spells, etc...) so securing at least half the mounts would be quite the success. You will have to use gut feeling or your experience GMing for this group to get a sense of this. Whichever goal you use, if it's accomplished, give them XP for an encounter of a CR equal to their APL (Average Party Level). You can adjust that from CR-2 to CR+2 if you think this challenge is easy or hard compared to a regular CR=APL fight. I'd also suggest remaining open to unexpected developments. If you realize the challenge is much harder than you imagined for this party (and the players are genuinely having trouble), give more XP than you had planned. On the other hand, if they make it seem like a cakewalk without even trying (no clever solutions nor luck of the dice), then maybe you overestimated the challenge and it's worth less XP. In that last case, you could also savor some humble pie and award them the initial XP amount and remember it as a lesson for your next XP estimations. Finally, if the players come up with extremely clever solutions or really go out of their way to solve the challenge, you may decide it's worth some extra XP, if only as incentive for them to keep playing that way :)
{ "pile_set_name": "StackExchange" }
Q: Android - Memory Allocation Tracker not tracking my test allocation I'm currently playing around with the memory allocation tracker of the DDMS tool. In my project i insert the following line in a button's onClickListener: memTrackerTest = new byte[1024*1024]; memTrackerTest is a private variable of the Activity. I would expect to see the allocation in the tracker but unfortunately it doesn't appear. Other parts of my code, like the creation of a ProgressDialog show up fine. Any idea why my big allocation is not displayed in the allocation tracker? A: I'm not sure what the exact problem was. I tried the same code in a different class and it worked fine there.
{ "pile_set_name": "StackExchange" }
Q: Application of Bayes theorem and Partition Law, total probability Hi guys, preparing for my finals and trying to get this question out for practice. The exam is in a couple of hours so apologies for being brief. I think I have computed parts 1 and 2 fine. $$0.3*0.1 + 0.7*0.3 = 0.24$$ for the first part, and $$P(\text{parasite} \mid A) = \frac{P(A \mid \text{parasite})P(\text{parasite})}{P(A)}$$ $$= \frac{0.7*0.3}{0.3*0.7 + 0.7*0.2} = 0.6$$ Hopefully these parts are both correct so far. Now for part iii), I started out $$P(A_2 \mid A_1) = \frac{P(A_1 \mid A_2)P(A_2)}{P(A_1)}$$ but this doesn't really make any sense. So then I tried $$P(A_2 \mid A_1)= P(A_2 \mid A_1, \text{parasite}) + P(A_2 \mid A_1, \text{no parasite}) $$ I'm not sure where to go with it after this or if that approach is correct at all. I know I ought to look for a hint and then work through the rest myself but as the exam is so soon I would really appreciate someone pointing out the next couple of steps, and maybe even a hint/setup for part iv). A: Your second approach is the right idea, but what you were after is: $$\mathsf P(A_2\mid A_1) ~=~ \mathsf P(A_2\mid P_{\rm arasite})~\mathsf P(P_{\rm arasite}\mid A_1)+\mathsf P(A_2\mid P_{\rm arasite}^\complement)~\mathsf P(P_{\rm arasite}^\complement\mid A_1)$$ Now you are looking for $\mathsf P(P_{\rm arasite}\mid A_1,A_2)$ using Bayes' Rule, and the fact that the events of the two butterflies both being type A are conditionally independent given the presence/absence of the parasite.
{ "pile_set_name": "StackExchange" }
Q: Modification in the SQL script I want sysadmin logins which are not listed in the exceptionssysadmin table. I'm receiving empty columns with the below script. can someone suggest where am i going wrong ? The below is the script SELECT DISTINCT p.name AS [loginname] ,p.type_desc ,p.is_disabled ,s.sysadmin ,CONVERT(VARCHAR(10), p.create_date, 101) AS [created] ,CONVERT(VARCHAR(10), p.modify_date, 101) AS [update] FROM sys.server_principals p JOIN sys.syslogins s ON p.sid = s.sid JOIN sys.server_permissions sp ON p.principal_id = sp.grantee_principal_id CROSS JOIN test..ExceptionsSysadmin ES WHERE ES.AccountName NOT IN ( SELECT AccountName FROM ExceptionsSysAdmin ) AND p.type_desc IN ( 'SQL_LOGIN' ,'WINDOWS_LOGIN' ,'WINDOWS_GROUP' ) -- Logins that are not process logins AND p.name NOT LIKE '##%' -- Logins that are sysadmins or have GRANT CONTROL SERVER AND ( s.sysadmin = 1 OR sp.permission_name = 'CONTROL SERVER' ) ORDER BY p.name A: I want sysadmin logins which are not listed in the exceptionssysadmin table The cross join & IN() look like they are not needed. You could use NOT EXISTS() for checks if a value is not in a certain table This could be a solution: SELECT DISTINCT p.name AS [loginname] ,p.type_desc ,p.is_disabled ,s.sysadmin ,CONVERT(VARCHAR(10), p.create_date, 101) AS [created] ,CONVERT(VARCHAR(10), p.modify_date, 101) AS [update] FROM sys.server_principals p JOIN sys.syslogins s ON p.sid = s.sid JOIN sys.server_permissions sp ON p.principal_id = sp.grantee_principal_id WHERE NOT EXISTS ( SELECT AccountName FROM Test..ExceptionsSysAdmin WHERE p.[name] = AccountName ) AND p.type_desc IN ( 'SQL_LOGIN' ,'WINDOWS_LOGIN' ,'WINDOWS_GROUP' ) -- Logins that are not process logins AND p.name NOT LIKE '##%' -- Logins that are sysadmins or have GRANT CONTROL SERVER AND ( s.sysadmin = 1 OR sp.permission_name = 'CONTROL SERVER' ) ORDER BY p.name; Tested with: CREATE TABLE ExceptionsSysAdmin(accountname varchar(255)) INSERT INTO ExceptionsSysAdmin(accountname) VALUES('NT SERVICE\SQLSERVERAGENT') And this login was excluded as a result
{ "pile_set_name": "StackExchange" }
Q: RenderMonkey - GLSL light I am making a shader in witch i am using a spot light, I am trying some shaders that I´ve found in the Internet before I make my own. I found this GLSL code: vec4 final_color = (gl_FrontLightModelProduct.sceneColor * gl_FrontMaterial.ambient) + (gl_LightSource[0].ambient * gl_FrontMaterial.ambient); Does anyone know how can i make this in the RenderMonkey? i know that i cannot use gl_LightSource[0], how can i make it? A: In rendermonkey you would need to set variables for the light properties which your shader would use. such a a vec4 for the light's ambient, diffuse, and specular colors. Then some vec3 for the vector to the light / position of the light, etc. Then you can set these variables to be artist variables, and you can edit them 'live' in the artist Editor on the right. It's a bit awkward, meaning that you either need to adjust your usage of your shader such that you don't rely on the built in gl_ constructs (so you don't need to edit a shader for it to run both in your program and in RM. Or you need to edit the shaders when you go inbetween. I prefer the former.
{ "pile_set_name": "StackExchange" }
Q: In which cases can I use indentations in python? I was reading Python Language reference. On lexical analysis page Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. Here, it says that adding indent on a line will just add the value associated with INDENT to the indent tracking stack. So I tried to do python equivalent of the C++ snippet int x = 23; { int y = 13; } int z = 2*x; with this python snippet x = 23 y = 13 z = 2*x But making python run this code generated following error: y = 13 IndentationError: unexpected indent So the above rule doesn't apply all the time, I wanted to know Is there a python equivalent to the above C++ code snippet What exactly are the cases in python, when I can use the indentation, other than the general cases like function and class definitions. A: "At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated." So here it tells you all about when indent token are generated. Now you also need to know that only the key words class, def, if, for, while, etc. allows you to have an additionnal current indent token. "when I can use the indentation, other than the general cases like function and class definitions". -> Never. Note : breaking line doesn't count as indent token. So : >>> a = [1, 2, \ # \ is breaking line. 3] is possible, it doesn't technically count as indentation because it's the same python line. Same for function arguments : >>> a = np.array([0,1], dtype=float)
{ "pile_set_name": "StackExchange" }
Q: T-SQL Select accounts with no activity I have this table ID InvoiceNo Created_date -- --------- ------------ 1 123 1/1/2009 1 234 1/1/2010 1 2304 2/1/2010 1 av245 3/1/2011 1 45wd3 4/1/2011 2 345 1/1/2010 2 4w5 2/1/2010 I am trying to select the ID where there has been no activity since 11/1/2010. so my results should only show ID 2. I used EXISTS, NOT EXIST but it still shows ID 1. Any help is appreciated. A: Not optimized for performance, but I would just do something like this: quick and dirty alert select distinct q.id from (select id, max(created_date) as latestdate from TABLENAME group by id) q where q.latestdate <= '2010-11-01'
{ "pile_set_name": "StackExchange" }
Q: Using range of dates to iterate through series of date stamped XHR requests I am using Python.org version 2.7 64 bit on Windows Vista 64 bit. I have some code that is a development of the answer I got to the question I asked here: Cannot locate displayed data in source code when Scraping with Scrapy My development of this answer is to iterate through a series of dates in a range and obtain the data I am after for each of these dates (idea being that if there is no data for that date, I will get blank returned). The code is like so: from datetime import date, timedelta as td from ast import literal_eval from datetime import datetime import requests d1 = date(2013,11,01) d2 = date(2014,5,31) delta = d2 - d1 for i in range(delta.days + 1): time1 = str(d1 + td(days=i)) time2 = time1.split("-", 1)[0] time3 = time1.split("-", -1)[1] time4 = time1.rsplit("-", 1)[-1] time2 = int(time2) time3 = int(time3) time4 = int(time4) date = datetime(year=time2, month=time3, day=time4) print date url = 'http://www.whoscored.com/tournamentsfeed/8273/Fixtures/' params = {'d': date.strftime('%Y%m'), 'isAggregate': 'false'} headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'} response = requests.get(url, params=params, headers=headers) fixtures = literal_eval(response.content) print fixtures Rather than giving me the fixtures just for any given day, this code is giving me the fixtures for the whole of the month in which that date falls. The code then proceeds to fall over a random points during the iteration process and throws up the following error: Traceback (most recent call last): File "C:\Python27\newtets\newtets\spiders\test3.py", line 32, in <module> fixtures = literal_eval(response.content) File "C:\Python27\lib\ast.py", line 49, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "C:\Python27\lib\ast.py", line 37, in parse return compile(expr, filename, mode, PyCF_ONLY_AST) File "<unknown>", line 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> ^ SyntaxError: invalid syntax What I would like to know is: 1) Why is this code structure not returning either/or fixtures from that day/null if there are no fixtures? 2) What is the cause of this error and why does it keep occurring at random points during the execution? Thanks A: You could check if <!DOCTYPE is in the line before your use literal_eval fixtures = (response.content) if not "<!DOCTYPE " in fixtures: fixtures = literal_eval(response.content) Probably better to use a try/except catching the specific exception. Your code completes successfully the only lines the cause the error were the ones containing <!DOCTYPE which I imagine are not relevant for what you are trying to do, when printed it is html. Something like the following should work: try: fixtures = literal_eval(response.content) except SyntaxError: pass print fixtures There is an interesting part of the output: <h2>403 - Forbidden: Access is denied.</h2> <h3>You do not have permission to view this directory or page using the credentials that you supplied. There must be some part you are scraping the requires some sort of autorisation. You may need to pass the day also %d: params = {'d': date.strftime('%Y%m%d'), 'isAggregate': 'false'} If you print params before the change date is just year and month, I imagine you want the days to get different fixtures over the month.
{ "pile_set_name": "StackExchange" }
Q: OpenLayers.Format.GML.parseFeature() with GML v3 data I have a partial GML object with the geometry type polygon. The GML version must be 3+ since the coordinates are wrapped in the gml:posList tag: <gml:Polygon srsName="EPSG:25832" xmlns:gml="http://www.opengis.net/gml"> <gml:exterior> <gml:LinearRing srsName="EPSG:25832"> <gml:posList> N points where N is an even integer. </gml:posList> </gml:LinearRing> </gml:exterior> </gml:Polygon> I am using OpenLayers 2.10 and I am trying to convert the GML object into an OpenLayers feature using the OpenLayers.Format.GML class. When executing the parseFeature method, which later calls the parseGeometry.linestring I encounter this comment: /** * Two coordinate variations to consider: * 1) <gml:posList dimension="d">x0 y0 z0 x1 y1 z1</gml:posList> * 2) <gml:coordinates>x0, y0, z0 x1, y1, z1</gml:coordinates> */ And this line of code which assumes the dimension attribute to be present: var dim = parseInt(nodeList[0].getAttribute("dimension")); In OpenLayers.Format.GML.v3 the same line of code looks like this: var dim = parseInt(node.getAttribute("dimension")) || 2; The problematic difference for me is the || 2 part which assumes that a missing dimension means 2 dimensional - which is what I want. Then why not use the v3 edition, but the OpenLayers.Format.GML.v3 does not implement the parseFeature method. I am recieving GML features from various services and I do not control them. What is the best approach to handle this problem? A: After a quick glance it looks like the v2 and v3 JS files derive from base (definitely makes sense too) which offers a read method. Try checking that out. See: http://github.com/openlayers/openlayers/blob/2.x/lib/OpenLayers/Format/GML/Base.js#L151 If that is not complete or does not meet your needs you can just modify the source. Given the generous licensing and the nature of JavaScript you could just add it in yourself or better yet create a pull request for that change. See: http://github.com/openlayers/openlayers/blob/2.x/lib/OpenLayers/Format/GML.js#L348 If you feel the need to hack something messy together you can also add that attribute to the nodes: setMissingDefaults = function(node){ /* magic stuff */ } OpenLayers.Format.GML.parseFeature(setMissingDefaults(node));
{ "pile_set_name": "StackExchange" }
Q: Issue in calculation of values in all text fields I am implementing MVC application in which I am trying to dynamically calculate and display the calculation of all tr element whenever a user enters the value of Count field. I have static values coming from- public class Adjustment { public int Id { get; set; } public int Size { get; set; } public int Pieces { get; set; } public int Count{ get; set; } } public ActionResult Create() { var adjustments = from adjustment in AddAdjustment() select adjustment; ViewBag.AdjustmentList = adjustments; return View(); } private List<Adjustment> AddAdjustment() { List<Adjustment> AdjustmentList = new List<Adjustment>(); Adjustment oAdjustment = new Adjustment(); oAdjustment.Id = 1; oAdjustment.Size = 10; oAdjustment.Pieces = 12; oAdjustment.Count = 2; AdjustmentList.Add(oAdjustment); oAdjustment = new Adjustment(); oAdjustment.Id = 2; oAdjustment.Size = 20; oAdjustment.Pieces = 11; oAdjustment.Count = 1; AdjustmentList.Add(oAdjustment); return AdjustmentList; } My jQuery code is- <script type="text/javascript"> $(document).ready(function () { $('#Count').blur(function() { var count = $('#Count').val(); var bundalSize = $('#BundalSize').text(); var totalPieces = count*bundalSize; $('#Pieces').val(totalPieces); }); }); </script> and here is my table- <table class="table table-striped table-hover"> <thead> <tr> <th> Bundal Size </th> <th> Count </th> <th style="border-right:solid #e8eef4 thick;"> Pieces </th> <th> Count </th> <th> Pieces </th> </tr> </thead> <tbody> @foreach (var item in ViewBag.AdjustmentList) { <tr> <td style="width:100px;" id="BundalSize"> @item.Size </td> <td style="width:90px;"> @item.Count </td> <td style="width:180px; border-right:solid #e8eef4 thick;"> @item.Pieces </td> <td> <input id="Count" type="text" style="width:100px ;height:15px ;margin:1px" /> </td> <td> <input id="Pieces" type="text" style="width:100px ;height:15px ;margin:1px" disabled /> </td> </tr> } </tbody> </table> When I am trying to calculate multiplication on blur event ,it results only for first record in table. I want to calculate it on each id="Count" for each record. Is there any solution for it? A: Use class instead of id like, <td style="width:100px;" class="BundalSize"> @item.Size </td> <td> <input class="Count" type="text" style="width:100px ;height:15px ;margin:1px" /> </td> <td> <input class="Pieces" type="text" style="width:100px ;height:15px ;margin:1px" disabled /> </td> Change your jquery code like, $(document).ready(function () { $('.Count').blur(function() { var $parent = $(this).closest('tr');// for current row var count = parseFloat($(this).val()); // use parseInt if integer var bundalSize = parseFloat($parent.find('.BundalSize').text()); var totalPieces = count*bundalSize; $parent.find('.Pieces').val(totalPieces); }); });
{ "pile_set_name": "StackExchange" }
Q: Event for textarea changes I have a JavaScript library that updates a hidden <textarea> HTML element with some data based on some things. In my (JavaScript) application I'd like to know when these updates occur without having to go through the existing library code. I was hoping there was an event for this, but apparently not. How would I listen for changes of the textarea? Changes can be as simple as document.getElementById("myTextarea").value = "hello"; EDIT I will be using FireFox only, since this code will only be part of a test suite I'm building. A: If you control the Javascript library you mention, I would say the easiest way would be to manually trigger the change event every time you change a field's value. I think this is how it's done in JQuery: Events/change Otherwise, a simple document.getElementById('myTextarea').onchange() might work as well. If you have many calls, you could wrap the changing of the value, and the triggering of the event into a changeFormElement(id, value) function. This requires, of course, that you can modify every instance of when a textarea is changed. If that is given, this is probably the most elegant way.
{ "pile_set_name": "StackExchange" }