date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/18
1,572
5,183
<issue_start>username_0: Is it possible to use a stem part of multiple xpaths to create a program to randomly selects one? Say for example we are given these multiple xpaths: ``` //a[@href='/colour/red/yellow'] //a[@href='/colour/red/blue'] //a[@href='/colour/blue/ornage'] //a[@href='/colour/yellow/green'] ``` Is it possible to randomly select one of the xpaths by using part of the xpath in a code, e.g: ``` option1 = browser.find_element_by_xpath("part of xpath") ``` I know this line of code wont work, but is there a specific function to use instead of **`browser.find_element_by_xpath`** I am a beginner at programming pls help. **[EDIT]: I have found this function instead:** ``` find_element_by_partial_link_text('') ``` **I'm not sure how this function works, but would i be able to use this instead on links of each example, e.g:** * we are given the site: <http://www.colour.com/colour/> (Not real site) * and a link to part of the website is: <http://www.colour.com/colour/red/yellow> * and a link to another part of the website is: <http://www.colour.com/colour/red/blue> I want a code that randomly picks between both parts of site, could i use something similar to: ``` option1 = find_element_by_partial_link_text('http://www.colour.com/colour/red') ``` * My point more specifically is to use part of link, and let program search the website for possible full links, and randomly select one. Is this even possible? **[UPDATE]:** **Breaks Software's solution worked**; it has allowed me to use part of link, e.g. <http://www.colour.com/colour/red> The program its self would then make a decision between: <http://www.colour.com/colour/red/yellow> and <http://www.colour.com/colour/red/blue> Code: ``` #open website browser = webdriver.Chrome() browser.get(('http://www.colour.com/colour')) from random import randint #generating program to select random link target_links = browser.find_elements_by_css_selector("a[href^='/colour/red") random_index = randint(0, len(target_links) - 1) target_links[random_index].click() ``` Thank you for everyone's help, I hope this question can help others facing similar problem.<issue_comment>username_1: Try this : ``` from random import randint color_list = ('yellow', 'blue', 'orange', 'green') list_len = len(color_list) myrandint = randint(0, list_len -1) browser.find_element_by_xpath("//a[@href='/colour/"+color_list[myrandint]+"/"+color_list[myrandint]+"']") print(test) ``` Or ``` from random import randint my_list = ( "//a[@href='/colour/red/yellow']", "//a[@href='/colour/red/blue']", "//a[@href='/colour/blue/ornage']", "'//a[@href='/colour/yellow/green']" ) list_len = len(color_list) myrandint = randint(0, list_len -1) browser.find_element_by_xpath(my_list[myrandint]) ``` Upvotes: 1 <issue_comment>username_2: You can try to use below code: ``` import random list_of_xpath = ["//a[@href='/colour/red/yellow']", "//a[@href='/colour/red/blue']", "//a[@href='/colour/blue/ornage']", "//a[@href='/colour/yellow/green']"] option1 = browser.find_element_by_xpath(random.choice(list_of_xpath)) ``` Or if you need just some random combination of colors in your XPath: ``` colors = ['yellow', 'blue', 'orange', 'green'] xpath = "//a[@href='/colour/{0}/{1}']".format(random.choice(colors), random.choice(colors)) option1 = browser.find_element_by_xpath(xpath) ``` Upvotes: 1 <issue_comment>username_3: As per your question, * The first question *Is it possible to use a stem part of multiple xpaths to create a program to randomly selects one?* Answer is **Yes** * The second question *Is it possible to randomly select one of the xpaths?* Doesn't seems to me a valid usecase because if you select a random `xpath` you won't be able to `Assert`/`validate` further. * As per the first question a solution would be to pass the intended choice of colour to navigate and you can write a function as follows : ``` def test_url(choiceColour): option1 = browser.find_element_by_xpath("//a[contains(@href, '" + choiceColour + "')]") ``` * Incase you want to pass two colours of your choice you can write a function as follows : ``` def test_url(firstColour, secondColour): option1 = browser.find_element_by_xpath("//a[contains(@href, '" + firstColour + "') and contains(@href, '" + secondColour + "')]") ``` * Now you can call either of these functions from your `main()`/`@Test` method as per your requirement. > > **Note** : Incase of the function def `test_url(firstColour, secondColour)` passing **/colour/red/yellow** or **/colour/yellow/red** may identify the same element. > > > Upvotes: 0 <issue_comment>username_4: I think that you are asking to find all of the links that start with a particular URL, then randomly choose one of them to follow. ``` target_links = browser.find_elements_by_css_selector("a[href^='http://www.colour.com']") random_index = randint(0, len(target_links) - 1) target_links[random_index].click() ``` alternatively, you could look for the links that contain the partial path "colour" with the CSS selector: ``` a[href*='/colour/'] ``` Upvotes: 1 [selected_answer]
2018/03/18
1,078
3,702
<issue_start>username_0: This code to append to a to-do list works in the editor in a Codecademy tutorial, but using the same code in CodePen, nothing happens when I type text into the form box and hit submit (whereas in Codecademy, the entered text is added below the form box). It's not just an issue with CodePen, either; the same thing happened after entering it into Atom. To see how it works you can [view my CodePen](https://codepen.io/nataliecardot/pen/VXmPrO), but I'll also enter the code used below for convenience. Here's the HTML: ``` To Do To Do ----- Add ``` And the JavaScript: ``` $(function() { $('.button').click(function() { let toAdd = $('input[name=checkListItem]').val(); // inserts specified element as last child of target element $('.list').append('' + toAdd + ''); }); $(document).on('click', '.item', function() { $(this).remove(); }); }); ``` Why the discrepancy? Is something wrong with the code?<issue_comment>username_1: You have to add jQuery support to your CodePen snippet. Click on "settings" in JavaScript window, then pick "jQuery" from "Quick-add" dropdown in the bottom of "Pen Settings" window. You will have to link to jQuery dependency manually so your code can work flawless outside sandboxes like Codeacademy, CodePen, JSFiddle etc. Here is how to use jQuery from CDN: <http://jquery.com/download/#using-jquery-with-a-cdn> Basically, you will end up adding something like this: before the line. Upvotes: 0 <issue_comment>username_2: You need to enable jQuery. Also, if you want to clear the input field after adding a new item you can do this: ``` $('input[name=checkListItem]').val(''); ``` Here's a working solution! ```js $(function() { $('.button').click(function() { let toAdd = $('input[name=checkListItem]').val(); console.log(toAdd); // inserts specified element as last child of target element $('.list').append('' + toAdd + ''); $('input[name=checkListItem]').val(''); }); $(document).on('click', '.item', function() { $(this).remove(); }); }); ``` ```css h2 { font-family: Helvetica; color: grey; } form { /* needed for the same property/value to work to display the button next to form */ display: inline-block; } input[type=text] { border: 1px solid #ccc; height: 1.6em; width: 15em; } .button { /* makes button display next to form */ display: inline-block; vertical-align: middle; box-shadow: inset 0px 1px 0 0 #fff; /* starts at top, transitions from left to right */ background: linear-gradient(#f9f9f9 5%, #e9e9e9 100%); border: 1px solid #ccc; color: #666; background-color: #c00; font-size: 0.7em; font-family: Arial; font-weight: bold; border-radius: 0.33em; /* padding is space between element's content and border. First value sets top and bottom padding; second value sets right and left */ padding: 0.5em 0.9em; text-shadow: 0 1px #fff; text-align: center; cursor: pointer; } ``` ```html To Do ----- Add ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: > > Uncaught ReferenceError: $ is not defined > at pen.js:1 > Blockquote > > > Hey, Its always advisable to look at browser console to check what the error is. 60% of your problems will be solved by just looking at console. and next 40 % be be solved by debugging the javascript code using chrome browser. This is the error that is thrown along with other few errors. It means that you have not included Jquery library in your html. Please import it using this cdn link <https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js> or as mention by username_1 Upvotes: 0
2018/03/18
471
1,747
<issue_start>username_0: `godoc -html` generates documents for only one package. However, I want to ship the project with all documents for all packages, just like when I run `godoc -http`. With that, I could find all packages and navigate through them from the browser. Is it possible to generate HTML pages for all packages **linked together** through `godoc -html`?<issue_comment>username_1: You have two questions here: > > Is it possible to generate HTML pages for all packages linked together through godoc -html? > > > No. Because it is not implemented into godoc (<https://godoc.org/golang.org/x/tools/cmd/godoc>). The other question: > > How can I generate HTML documents for all packages inside a folder > using godoc > > > I think the simplest way is to start godoc with the http flag: `godoc -http=:6060` Then you navigate to the folder you want to get the docs. For that url you can use a webcrawler for getting the html documentation. There are already some crawler in Go (<https://godoc.org/?q=crawler>), if you don't want to write a crawler by your own. Upvotes: 3 [selected_answer]<issue_comment>username_2: I developed [Golds](https://github.com/go101/golds), which is an alternate Go docs generation tool (and a local docs server / code reader). Hope you this tool would satisfy your need. Under your project directory, you can run any of the following commands to generate HTML docs for your Go project: * golds -gen -nouses -plainsrc -wdpkgs-listing=promoted ./... * golds -gen -nouses -wdpkgs-listing=promoted ./... * golds -gen -wdpkgs-listing=promoted ./... The first command generates the most compact docs and the last one generates the full docs, which size is 6 times of the compact docs. Upvotes: 1
2018/03/18
1,622
5,373
<issue_start>username_0: I'm learning about Bash scripting, and need some help understanding regex's. I have a variable that is basically the html of a webpage (exported using wget): ``` currentURL = "https://www.example.com" currentPage=$(wget -q -O - $currentURL) ``` I want to get the id's of all linked photos in this page. I just need help figuring out what the RegEx should be. [I started with this](https://unix.stackexchange.com/a/167656), but I need to modify the regex: Test string (this is what `currentURL` contains, there can be zero to many instances of this): ``` [![](./download/file.php?id=123456&t=1)](./download/file.php?id=123456&mode=view) ``` Current Regex: ``` .\/download\/file.php\?id=[0-9]{6}\&mode=view ``` [Here's the regex I created](https://regex101.com/r/yE3tO8/105), but it doesn't seem to work in bash. The best solution would be to have the ID of each file. In this case, simply `123456`. But if we can start with getting the `/download/file.php?id=123456`, that'd be a good start.<issue_comment>username_1: Don't parse XML/HTML with regex, use a proper XML/HTML parser. ### theory : According to the compiling theory, HTML can't be parsed using regex based on [finite state machine](http://en.wikipedia.org/wiki/Finite-state_machine). Due to hierarchical construction of HTML you need to use a [pushdown automaton](http://en.wikipedia.org/wiki/Pushdown_automaton) and manipulate [LALR](http://en.wikipedia.org/wiki/LR_parser) grammar using tool like [YACC](http://en.wikipedia.org/wiki/Yacc). ### realLife©®™ everyday tool in a [shell](/questions/tagged/shell "show questions tagged 'shell'") : You can use one of the following : [xmllint](http://xmlsoft.org/xmllint.html) often installed by default with libxml2, xpath1 [xmlstarlet](http://xmlstar.sourceforge.net/docs.php) can edit, select, transform... Not installed by default, xpath1 [xpath](https://metacpan.org/pod/XML::XPath) installed via perl's module XML::XPath, xpath1 [xidel](http://videlibri.sourceforge.net/xidel.html) xpath3 [saxon-lint](https://github.com/sputnick-dev/saxon-lint) my own project, wrapper over @Michael Kay's Saxon-HE Java library, xpath3 ### or you can use high level languages and proper libs, I think of : [python](/questions/tagged/python "show questions tagged 'python'")'s [`lxml`](http://lxml.de/) (`from lxml import etree`) [perl](/questions/tagged/perl "show questions tagged 'perl'")'s [`XML::LibXML`](https://metacpan.org/pod/distribution/XML-LibXML/LibXML.pod), [`XML::XPath`](https://metacpan.org/pod/XML::XPath), [`XML::Twig::XPath`](https://metacpan.org/pod/XML::Twig), [`HTML::TreeBuilder::XPath`](https://metacpan.org/pod/HTML::TreeBuilder::XPath) [php](/questions/tagged/php "show questions tagged 'php'")'s [`DOMXpath`](https://sputnick.fr/scripts/parsing-HTML-with-DOMXpath.php.html) --- Check: [Using regular expressions with HTML tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) --- Example using [xidel](/questions/tagged/xidel "show questions tagged 'xidel'"): ``` xidel -s "$currentURL" -e '//a/extract(@href,"id=(\d+)",1)' ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Let's first clarify a couple of misunderstandings. > > I'm learning about Bash scripting, and need some help understanding regex's. > > > You seem to be implying some sort of relation between Bash and regex. As if Bash was some sort of regex engine. It isn't. The `[[` builtin is the only thing I recall in Bash that supports regular expressions, but I think you mean something else. There are some common commands executed in Bash that support some implementation of regular expressions such as `grep` or `sed` and others. Maybe that's what you meant. It's good to be specific and accurate. > > I want to get the id's of all linked photos in this page. I just need help figuring out what the RegEx should be. > > > This suggests an underlying assumption that if you want to extract content from an HTML, then regex is the way to go. [That assumption is incorrect.](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) --- Although it's best to extract content from HTML using an XML parser (using one of the suggestions in Gilles' answer), and trying to use regex for it is not a good reflect, for simple cases like yours it might just be good enough: ``` grep -oP '\./download/file\.php\?id=\K\d+(?=&mode=view)' file.html ``` Take note that you escaped the wrong characters in the regex: * `/` and `&` don't have a special meaning and don't need to be escaped * `.` and `?` have special meaning and need to be escaped Some extra tricks in the above regex are good to explain: * The `-P` flag of `grep` enables Perl style (powerful) regular expressions * `\K` is a Perl specific symbol, it means to not include in the match the content before the `\K` * The `(?=...)` is a zero-width positive lookahead assertion. For example, `/\w+(?=\t)/` matches a word followed by a tab, without including the tab in the match. * The `\K` and the lookahead trickery is to work with `grep -o`, which outputs only the matched part. But without these trickeries the matched part would be for example `./download/file.php?id=123456&mode=view`, which is more than what you want. Upvotes: 2
2018/03/18
444
1,579
<issue_start>username_0: I'm learning SQL, for an exercise I have to several things. I'm making a query to compare the most recent orderdate with the orderdate before. I want to use a correlated subquery for this. I have already made it using a Cross Apply and Window functions. At the moment I have this: ``` select b1.klantnr, DATEDIFF(D, (Select MAX(b1.Besteldatum)), (Select MAX(b1.Besteldatum) where besteldatum not in (Select MAX(b1.besteldatum)))) as verschil from bestelling b1 group by b1.klantnr, b1.besteldatum ``` I only get `null` values in the datediff column. It should return this: [Results](https://i.stack.imgur.com/sPvBB.png) I'm using SQL Server 2014 Management Studio. Any help appreciated.<issue_comment>username_1: Here is one simple way: ``` select datediff(day, min(bs.Besteldatum), max(bs.Besteldatum)) as most_recent_diff from (select top (2) bs.* from bestelling bs order by bs.Besteldatum ) bs; ``` This uses a subquery, but not a correlated subquery. Should have really good performance, if you have an index on `bestselling(Besteldatum)`. Upvotes: 1 <issue_comment>username_2: A correlated subquery way. ``` select top 1 bs.*,datediff(day, (select max(bs1.Besteldatum) from bestelling bs1 where bs1.Besteldatum ``` This gives only the difference between latest date and the date preceding it. If you need all records remove `top 1` from the query. Upvotes: 1 [selected_answer]
2018/03/18
2,693
5,050
<issue_start>username_0: I have a dataframe as show below: ``` index value 2003-01-01 00:00:00 14.5 2003-01-01 01:00:00 15.8 2003-01-01 02:00:00 0 2003-01-01 03:00:00 0 2003-01-01 04:00:00 13.6 2003-01-01 05:00:00 4.3 2003-01-01 06:00:00 13.7 2003-01-01 07:00:00 14.4 2003-01-01 08:00:00 0 2003-01-01 09:00:00 0 2003-01-01 10:00:00 0 2003-01-01 11:00:00 17.2 2003-01-01 12:00:00 0 2003-01-01 13:00:00 5.3 2003-01-01 14:00:00 0 2003-01-01 15:00:00 2.0 2003-01-01 16:00:00 4.0 2003-01-01 17:00:00 0 2003-01-01 18:00:00 0 2003-01-01 19:00:00 3.9 2003-01-01 20:00:00 7.2 2003-01-01 21:00:00 1.0 2003-01-01 22:00:00 1.0 2003-01-01 23:00:00 10.0 ``` The index is datetime and have column record the rainfall value(unit:mm) in each hour,I would like to calculate the "Average wet spell duration", which means the average of continuous hours that exist values (not zero) in a day, so the calculation is ``` 2 + 4 + 1 + 1 + 2 + 5 / 6 (events) = 2.5 (hr) ``` and the "average wet spell amount", which means the average of sum of the values in continuous hours in a day. ``` { (14.5 + 15.8) + ( 13.6 + 4.3 + 13.7 + 14.4 ) + (17.2) + (5.3) + (2 + 4)+ (3.9 + 7.2 + 1 + 1 + 10) } / 6 (events) = 21.32 (mm) ``` The datafame above is just a example, the dataframe which I have have more longer time series (more than one year for example), how can I write a function so it could calculate the two value mentioned above in a better way? thanks in advance! P.S. the values may be NaN, and I would like to just ignore it.<issue_comment>username_1: I am not exactly sure what you are asking for. But, I think what you are asking for is `resample()`. If I misunderstood your question, correct me, please. From [Creating pandas dataframe with datetime index and random values in column](https://stackoverflow.com/questions/42941310/creating-pandas-dataframe-with-datetime-index-and-random-values-in-column), I have created a random time series dataframe. ``` import pandas as pd import numpy as np from datetime import datetime, timedelta date_today = datetime.now() days = pd.date_range(date_today, date_today + timedelta(1), freq='H') np.random.seed(seed=1111) data = np.random.randint(1, high=100, size=len(days)) df = pd.DataFrame({'Day': days, 'Value': data}) df = df.set_index('Day') ``` *View the dataframe* ``` Day Value 2018-03-18 20:18:08.205546 29 2018-03-18 21:18:08.205546 56 2018-03-18 22:18:08.205546 82 2018-03-18 23:18:08.205546 13 2018-03-19 00:18:08.205546 35 2018-03-19 01:18:08.205546 53 2018-03-19 02:18:08.205546 25 2018-03-19 03:18:08.205546 23 2018-03-19 04:18:08.205546 21 2018-03-19 05:18:08.205546 12 2018-03-19 06:18:08.205546 15 2018-03-19 07:18:08.205546 9 2018-03-19 08:18:08.205546 13 2018-03-19 09:18:08.205546 87 2018-03-19 10:18:08.205546 9 2018-03-19 11:18:08.205546 63 2018-03-19 12:18:08.205546 62 2018-03-19 13:18:08.205546 52 2018-03-19 14:18:08.205546 43 2018-03-19 15:18:08.205546 77 2018-03-19 16:18:08.205546 95 2018-03-19 17:18:08.205546 79 2018-03-19 18:18:08.205546 77 2018-03-19 19:18:08.205546 5 2018-03-19 20:18:08.205546 78 ``` --- Now, re-sampling your dataframe ``` # resample into 2 hours and drop the NaNs df.resample('2H').mean().dropna() ``` It gives you, ``` Day Value 2018-03-18 20:00:00 42.5 2018-03-18 22:00:00 47.5 2018-03-19 00:00:00 44.0 2018-03-19 02:00:00 24.0 2018-03-19 04:00:00 16.5 2018-03-19 06:00:00 12.0 2018-03-19 08:00:00 50.0 2018-03-19 10:00:00 36.0 2018-03-19 12:00:00 57.0 2018-03-19 14:00:00 60.0 2018-03-19 16:00:00 87.0 2018-03-19 18:00:00 41.0 2018-03-19 20:00:00 78.0 ``` Similarly, you can resample into days, hours, minutes etc which I leave upto you. You might need to take a look at * [Where is the documentation on Pandas 'Freq' tags?](https://stackoverflow.com/questions/35339139/where-is-the-documentation-on-pandas-freq-tags) * <https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html> Upvotes: 2 <issue_comment>username_2: I believe this is what you are looking for. I have added explanations to the code for each step. ``` # create helper columns defining contiguous blocks and day df['block'] = (df['value'].astype(bool).shift() != df['value'].astype(bool)).cumsum() df['day'] = df['index'].dt.normalize() # group by day to get unique block count and value count session_map = df[df['value'].astype(bool)].groupby('day')['block'].nunique() hour_map = df[df['value'].astype(bool)].groupby('day')['value'].count() # map to original dataframe df['sessions'] = df['day'].map(session_map) df['hours'] = df['day'].map(hour_map) # calculate result res = df.groupby(['day', 'hours', 'sessions'], as_index=False)['value'].sum() res['duration'] = res['hours'] / res['sessions'] res['amount'] = res['value'] / res['sessions'] ``` **Result** ``` day sessions duration value amount 0 2003-01-01 6 2.5 127.9 21.316667 ``` Upvotes: 4 [selected_answer]
2018/03/18
1,926
3,857
<issue_start>username_0: I am a beginner at Python and I'm trying to use a `while loop` to sum up all of the squared `n` values in a given `n` value range. Code: ``` def problem2(n): x = 0 y = 0 while x < n: y = (n**2)+y x+=1 return y ``` For some reason, this equation returns the input number cubed. Can someone explain why this happens and how to fix it?<issue_comment>username_1: I am not exactly sure what you are asking for. But, I think what you are asking for is `resample()`. If I misunderstood your question, correct me, please. From [Creating pandas dataframe with datetime index and random values in column](https://stackoverflow.com/questions/42941310/creating-pandas-dataframe-with-datetime-index-and-random-values-in-column), I have created a random time series dataframe. ``` import pandas as pd import numpy as np from datetime import datetime, timedelta date_today = datetime.now() days = pd.date_range(date_today, date_today + timedelta(1), freq='H') np.random.seed(seed=1111) data = np.random.randint(1, high=100, size=len(days)) df = pd.DataFrame({'Day': days, 'Value': data}) df = df.set_index('Day') ``` *View the dataframe* ``` Day Value 2018-03-18 20:18:08.205546 29 2018-03-18 21:18:08.205546 56 2018-03-18 22:18:08.205546 82 2018-03-18 23:18:08.205546 13 2018-03-19 00:18:08.205546 35 2018-03-19 01:18:08.205546 53 2018-03-19 02:18:08.205546 25 2018-03-19 03:18:08.205546 23 2018-03-19 04:18:08.205546 21 2018-03-19 05:18:08.205546 12 2018-03-19 06:18:08.205546 15 2018-03-19 07:18:08.205546 9 2018-03-19 08:18:08.205546 13 2018-03-19 09:18:08.205546 87 2018-03-19 10:18:08.205546 9 2018-03-19 11:18:08.205546 63 2018-03-19 12:18:08.205546 62 2018-03-19 13:18:08.205546 52 2018-03-19 14:18:08.205546 43 2018-03-19 15:18:08.205546 77 2018-03-19 16:18:08.205546 95 2018-03-19 17:18:08.205546 79 2018-03-19 18:18:08.205546 77 2018-03-19 19:18:08.205546 5 2018-03-19 20:18:08.205546 78 ``` --- Now, re-sampling your dataframe ``` # resample into 2 hours and drop the NaNs df.resample('2H').mean().dropna() ``` It gives you, ``` Day Value 2018-03-18 20:00:00 42.5 2018-03-18 22:00:00 47.5 2018-03-19 00:00:00 44.0 2018-03-19 02:00:00 24.0 2018-03-19 04:00:00 16.5 2018-03-19 06:00:00 12.0 2018-03-19 08:00:00 50.0 2018-03-19 10:00:00 36.0 2018-03-19 12:00:00 57.0 2018-03-19 14:00:00 60.0 2018-03-19 16:00:00 87.0 2018-03-19 18:00:00 41.0 2018-03-19 20:00:00 78.0 ``` Similarly, you can resample into days, hours, minutes etc which I leave upto you. You might need to take a look at * [Where is the documentation on Pandas 'Freq' tags?](https://stackoverflow.com/questions/35339139/where-is-the-documentation-on-pandas-freq-tags) * <https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html> Upvotes: 2 <issue_comment>username_2: I believe this is what you are looking for. I have added explanations to the code for each step. ``` # create helper columns defining contiguous blocks and day df['block'] = (df['value'].astype(bool).shift() != df['value'].astype(bool)).cumsum() df['day'] = df['index'].dt.normalize() # group by day to get unique block count and value count session_map = df[df['value'].astype(bool)].groupby('day')['block'].nunique() hour_map = df[df['value'].astype(bool)].groupby('day')['value'].count() # map to original dataframe df['sessions'] = df['day'].map(session_map) df['hours'] = df['day'].map(hour_map) # calculate result res = df.groupby(['day', 'hours', 'sessions'], as_index=False)['value'].sum() res['duration'] = res['hours'] / res['sessions'] res['amount'] = res['value'] / res['sessions'] ``` **Result** ``` day sessions duration value amount 0 2003-01-01 6 2.5 127.9 21.316667 ``` Upvotes: 4 [selected_answer]
2018/03/18
457
1,687
<issue_start>username_0: I'm trying to insert values into a struct so I can display them again later on. ``` typedef struct { char* displayname; char* name; } objectHolder; void registerObject(char* displayname, char* name) { objectHolder->displayname = displayname; objectHolder->name = name; char buffer[70]; sprintf(buffer, "%s spawned", displayname); menu.drawFeedNotification(buffer, "Object Spawner"); } ``` But this returns me: ``` source/main.cpp:82:17: error: expected unqualified-id before ‘->’ token objectHolder->displayname = displayname; ^ source/main.cpp:83:17: error: expected unqualified-id before ‘->’ token objectHolder->name = name; ``` I have tried to replace the `->` but that didn't do the job either. I can't find results on Google about how to perform this properly. Any help is appreciated.<issue_comment>username_1: You have *two* problems. The first is the syntax, where the "arrow" `->` is used for *pointers* to structures. The other problem is that `objectHolder` is not an actual structure instance, it's not a variable. It is a *type-name*. An alias of the structure type. You use `objectHolder` to declare and define variables of the structure. Upvotes: 1 <issue_comment>username_2: In your program, `objectHolder` denotes a type, not a variable/an object. You cannot apply operator `->` to types, only to a pointer to an object. If you want to introduce a global variable, then you'd need to write: ``` typedef struct { char* displayname; char* name; } objectHolderType; objectHolderType objectHolderObj; objectHolderType *objectHolder = &objectHolderObj ... ``` Upvotes: 0
2018/03/18
387
1,179
<issue_start>username_0: Currently, I am trying to get all the steam reviews from a particular game, using the method described in the Steamworks documentation: <https://partner.steamgames.com/doc/store/getreviews> However, when I try to get reviews for a game like Dota 2 for example using the method: <http://store.steampowered.com/appreviews/570?json=1&start_offset=9200> <http://store.steampowered.com/appreviews/570?json=1&start_offset=9220> I always got the same return after a small offset. There should be more than 878,134 reviews for Dota 2. Why I got the same return before reaching the end? Thanks.<issue_comment>username_1: Not all reviews can be accessed with the method described in <https://partner.steamgames.com/doc/store/getreviews> . For example, for now, there are 18 reviews in <http://store.steampowered.com/app/794820/Knights_of_Pen_and_Paper_2_Free_Edition/>. But there is nothing in <http://store.steampowered.com/appreviews/794820?json=1>. Upvotes: 1 <issue_comment>username_2: You need to specify day\_range. Try set day\_range=9223372036854775807 source <https://www.reddit.com/r/devsteam/comments/7qxjho/steam_api_user_reviews_query/> Upvotes: 0
2018/03/18
874
2,924
<issue_start>username_0: So i am using the Google maps API for my website and I want the markers text to be equal to the value of another html element. Anyone here knows how to update the value of the text property of a marker in the google maps API? Here is my code regarding the problem. ``` var map, marker; var input = document.getElementById('inputField'); input.onkeyup = function() { //want to set the marker.text property to input.value and update the markers text } function myMap() { var long = 59.614503; var lat = 16.539939; var myLatlng = new google.maps.LatLng(lat, long); var mapProp = { center: new google.maps.LatLng(long, lat), zoom: 16, styles: [......] } } map = new google.maps.Map(document.getElementById("googleMap"), mapProp); marker = new google.maps.Marker({ position: new google.maps.LatLng(long, lat), label: { color: 'white', fontWeight: 'bold', fontSize: '10px', text: arena }, optimized: false, visible: true, draggable: true, }); marker.setMap(map); ```<issue_comment>username_1: You coul try using ``` marker.label.text = 'my_new_text'; // set the new text marker.label..setStyles(); // Force label to redraw (makes update visible) ``` Upvotes: 1 <issue_comment>username_2: Get the existing label object, set its `text` property to the desired value, then set it on the marker (unless you want to change other formatting). ``` input.onkeyup = function() { var label = marker.getLabel(); label.text = input.value; marker.setLabel(label); } ``` [proof of concept fiddle](http://jsfiddle.net/username_2/ueLpd6j9/) [![screenshot of resulting map](https://i.stack.imgur.com/Z5cad.png)](https://i.stack.imgur.com/Z5cad.png) **code snippet:** ```js var map, marker; function initialize() { var input = document.getElementById('inputField'); input.onkeyup = function() { var label = marker.getLabel(); console.log(label); label.text = input.value; marker.setLabel(label); } function myMap() { var lat = 59.614503; var lng = 16.539939; var myLatlng = new google.maps.LatLng(lat, lng); var mapProp = { center: new google.maps.LatLng(lat, lng), zoom: 16 } map = new google.maps.Map(document.getElementById("googleMap"), mapProp); marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), label: { color: 'white', fontWeight: 'bold', fontSize: '10px', text: "arena" }, optimized: false, visible: true, draggable: true, }); marker.setMap(map); } myMap(); } google.maps.event.addDomListener(window, "load", initialize); ``` ```css html, body, #googleMap { height: 100%; width: 100%; margin: 0px; padding: 0px } ``` ```html ``` Upvotes: 3 [selected_answer]
2018/03/18
2,596
9,072
<issue_start>username_0: I am trying to pass data through pojo class in cucumber but i am getting Null pointer Exception My feature file is as follows -: ``` Feature: Registeration in Mercuryflight site Background: Given I've a valid set of data and access pojo @Registrationpojo Scenario: Multiple user Registration process using pojo When Registeration page Display for pojo Then Enter valid data for successful registration pojo | username | password | confirmpassword | | aditya91p | test123 | test123 | | rakesh90p | test123 | test123 | | preety18p | test123 | test123 | And close ``` My pojo class is as follows -: ``` package com.Cucumber_Maven.test; public class UserData { private String username; private String password; private String confirmpassword; public UserData(String username, String password, String confirmpassword) { this.username = username; this.password = <PASSWORD>; this.confirmpassword = <PASSWORD>; } public String getUserName() { return username; } public String getPassword() { return <PASSWORD>; } public String getConfirmPassword() { return <PASSWORD>; } } ``` My Step definition is as follows -: ``` package com.Cucumber_Maven.test; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import cucumber.api.DataTable; import cucumber.api.PendingException; import cucumber.api.Scenario; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import junit.framework.Assert; public class StepPojo { WebDriver driver; Scenario scenario; @Given("^I've a valid set of data and access pojo$") public void i_ve_a_valid_set_of_data_and_access_pojo() throws Throwable { System.out.println("Pojo class demo "); System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"/src/test/resource/driver/chromedriver.exe"); driver = new ChromeDriver(); this.scenario= scenario; } @When("^Registeration page Display for pojo$") public void registeration_page_Display_for_pojo() throws Throwable { driver.manage().window().maximize(); driver.navigate().to("http://newtours.demoaut.com/"); Thread.sleep(5000); WebElement register=driver.findElement(By.linkText("REGISTER")); register.click(); } /*@Then("^Enter valid data for successful registration pojo$") public void enter_valid_data_for_successful_registration_pojo(List pojolist) throws Throwable { scenario.write("entering user registeration details..."); System.out.println("Total user..."+pojolist.size()); for(UserData data :pojolist) { System.out.println(data.getUserName() +" with pswd is "+data.getPassword()); driver.findElement(By.xpath(".//\*[@id='email']")).sendKeys(data.getUserName()); driver.findElement(By.xpath(".//\*[@name='password']")).sendKeys(data.getPassword()); driver.findElement(By.xpath("")).sendKeys(data.getConfirmPassword()); driver.findElement(By.xpath(".//\*[@name='register']")).click(); //assertion Thread.sleep(3000); String msg=driver.findElement(By.xpath(".//\*[contains(text(),'Dear')]")).getText(); System.out.println(msg); Assert.assertTrue("text is getting displayed", msg.contains("Dear")); //clicking on register WebElement register=driver.findElement(By.linkText("REGISTER")); JavascriptExecutor js=(JavascriptExecutor) driver; js.executeScript("arguments[0].setAttribute('target','\_self');", register); register.click(); } }\*/ @Then("^Enter valid data for successful registration pojo$") public void enter\_valid\_data\_for\_successful\_registration\_pojo(List pojolist) throws Throwable { scenario.write("entering user registeration details..."); System.out.println("Total user..."+pojolist.size()); for(UserData data :pojolist) { System.out.println(data.getUserName() +" with pswd is "+data.getPassword()); driver.findElement(By.xpath(".//\*[@id='email']")).sendKeys(data.getUserName()); driver.findElement(By.xpath(".//\*[@name='password']")).sendKeys(data.getPassword()); driver.findElement(By.xpath("")).sendKeys(data.getConfirmPassword()); driver.findElement(By.xpath(".//\*[@name='register']")).click(); //assertion Thread.sleep(3000); String msg=driver.findElement(By.xpath(".//\*[contains(text(),'Dear')]")).getText(); System.out.println(msg); Assert.assertTrue("text is getting displayed", msg.contains("Dear")); //clicking on register WebElement register=driver.findElement(By.linkText("REGISTER")); JavascriptExecutor js=(JavascriptExecutor) driver; js.executeScript("arguments[0].setAttribute('target','\_self');", register); register.click(); } } } ``` My error Trace is -: ``` Background: # C:/Users/krsna/eclipse-workspace/Cucumber_Maven/src/test/resource/mercuryflight.feature:3 Given I've a valid set of data and access pojo # StepPojo.i_ve_a_valid_set_of_data_and_access_pojo() @Registrationpojo Scenario: Multiple user Registration process using pojo # C:/Users/krsna/eclipse-workspace/Cucumber_Maven/src/test/resource/mercuryflight.feature:7 When Registeration page Display for pojo # StepPojo.registeration_page_Display_for_pojo() Then Enter valid data for successful registration pojo # StepPojo.enter_valid_data_for_successful_registration_pojo(UserData>) java.lang.NullPointerException at com.Cucumber_Maven.test.StepPojo.enter_valid_data_for_successful_registration_pojo(StepPojo.java:79) at ✽.Then Enter valid data for successful registration pojo(C:/Users/krsna/eclipse-workspace/Cucumber_Maven/src/test/resource/mercuryflight.feature:9) And close # StepDefinitionDemo.close() Failed scenarios: C:/Users/krsna/eclipse-workspace/Cucumber_Maven/src/test/resource/mercuryflight.feature:7 # Scenario: Multiple user Registration process using pojo 1 Scenarios (1 failed) 4 Steps (1 failed, 1 skipped, 2 passed) 0m40.507s ``` my folder structure is as follows -: [![enter image description here](https://i.stack.imgur.com/suqL7.png)](https://i.stack.imgur.com/suqL7.png) Any help to solve this would be appreciated. Also my pom file is as -: ``` 4.0.0 com Cucumber\_Maven 0.0.1-SNAPSHOT jar Cucumber\_Maven http://maven.apache.org UTF-8 junit junit 4.12 test info.cukes cucumber-core 1.2.5 info.cukes cucumber-java 1.2.0 info.cukes cucumber-junit 1.2.0 info.cukes cucumber-jvm 1.2.5 pom info.cukes cucumber-jvm-deps 1.0.5 org.seleniumhq.selenium selenium-java 3.9.1 ``` I am getting error for this line in -: ``` @Then("^Enter valid data for successful registration pojo$") public void enter_valid_data_for_successful_registration_pojo(List pojolist) throws Throwable { scenario.write("entering user registeration details..."); System.out.println("Total user..."+pojolist.size()); ```<issue_comment>username_1: You coul try using ``` marker.label.text = 'my_new_text'; // set the new text marker.label..setStyles(); // Force label to redraw (makes update visible) ``` Upvotes: 1 <issue_comment>username_2: Get the existing label object, set its `text` property to the desired value, then set it on the marker (unless you want to change other formatting). ``` input.onkeyup = function() { var label = marker.getLabel(); label.text = input.value; marker.setLabel(label); } ``` [proof of concept fiddle](http://jsfiddle.net/username_2/ueLpd6j9/) [![screenshot of resulting map](https://i.stack.imgur.com/Z5cad.png)](https://i.stack.imgur.com/Z5cad.png) **code snippet:** ```js var map, marker; function initialize() { var input = document.getElementById('inputField'); input.onkeyup = function() { var label = marker.getLabel(); console.log(label); label.text = input.value; marker.setLabel(label); } function myMap() { var lat = 59.614503; var lng = 16.539939; var myLatlng = new google.maps.LatLng(lat, lng); var mapProp = { center: new google.maps.LatLng(lat, lng), zoom: 16 } map = new google.maps.Map(document.getElementById("googleMap"), mapProp); marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), label: { color: 'white', fontWeight: 'bold', fontSize: '10px', text: "arena" }, optimized: false, visible: true, draggable: true, }); marker.setMap(map); } myMap(); } google.maps.event.addDomListener(window, "load", initialize); ``` ```css html, body, #googleMap { height: 100%; width: 100%; margin: 0px; padding: 0px } ``` ```html ``` Upvotes: 3 [selected_answer]
2018/03/18
315
1,209
<issue_start>username_0: I need the bot to delete the message from the command author, and leave the bot message. Any help will be appreciated! thank you. I have already tried looking for a answer on google but nothing has worked<issue_comment>username_1: You can obtain the message that called the command by passing the context with the command using the `pass_context` option. You can use the [`Client.delete_message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.delete_message) coroutine to delete messages. ``` from discord.ext import commands bot = commands.Bot(command_prefix='!') @bot.command(pass_context=True) async def deletethis(ctx): await bot.say('Command received') await bot.delete_message(ctx.message) await bot.say('Message deleted') bot.run('token') ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: I'm kinda late here. I tried implementing this with the new 1.0 terms but couldn't make it work. If anyone has an updated version, please do tell Edit: I found that the new best way of doing it is to just add this at the end of the function: ``` await ctx.message.delete() ``` No need for a separate delete function anymore. Upvotes: 2
2018/03/18
1,398
5,144
<issue_start>username_0: I am trying filter this array with .filter. ```js var objList = [ { "name": "Object0Name", "id": "Object0ID", "Object1List": [ { "id": "Object1id_A1", "name": "Object1Name_A1", "Object2List": [ { "id": 187, "name": "Object2Name_A1", "Object3List": [ { "id": "mammal", "name": "mammal", "Object4List": [ { "id_client": "rabbit", "Currency": "EUR" }, { "id_client": "cat", "Currency": "EUR", }, { "id_client": "tiger", "Currency": "EUR", } ] } ] } ] }, { "id": "Object1id_B1", "name": "Object1Name_B1", "Object2List": [ { "id": 189, "name": "Object2Name_B1", "Object3List": [ { "id": "fish", "name": "fish", "Object4List": [ { "id_client": "tiger shark", "Currency": "EUR", }, { "id_client": "tuna", "currency": "GBP", }, ] } ] } ] } ] } ] var response= objList.filter(function(Object0List){ return Object0List.Object1List.filter(function(Object1List){ return Object1List.Object2List.filter(function(Object2List){ return Object2List.Object3List.filter(function(Object3List){ return Object3List.Object4List.filter(function(Object4List){ return Object4List.id_client==="tiger shark"; }); }); }); }); }); var myJSON = JSON.stringify(response); console.log('The animal is:'); console.log(myJSON); ``` But the filter doesn't work. I am receiving all objects. I must receive: [ { "name": "Object0Name", "id": "Object0ID", "Object1List": [ ``` { "id": "Object1id_B1", "name": "Object1Name_B1", "Object2List": [ { "id": 189, "name": "Object2Name_B1", "Object3List": [ { "id": "fish", "name": "fish", "Object4List": [ { "id_client": "tiger shark", "Currency": "EUR", } ] } ] } ] } ] ``` } ] Could someone help me find out what I'm doing wrong? I'm sure the problem is that I'm using the .filter function badly but it took several hours and I'm not capable of fixing it. I think that I do not understand this function for nested objects, I tried to filter the array of nested objects with lambda expressions but I'm also not able. Thanks you very much.<issue_comment>username_1: I assume that every of your objects has this structure: ``` { id: "sth", name: "whatever" children: [ /***/ ] } ``` So then it is quite easy to filter recursively: ``` function filter(arr, search){ const result = []; for(const {name, id, children} of arr){ children = filter(children, search); if(children.length || id === search) result.push({id, name, children }); } return result; } ``` Usable as: ``` var response = filter(objList, "tiger shark"); ``` Upvotes: 0 <issue_comment>username_2: You could check each property which is an array and take only filtered values. This approach mutates the original array. ```js function filter(array, value) { var temp = array.filter(o => Object.keys(o).some(k => { var t = filter(Array.isArray(o[k]) ? o[k] : [], value); if (o[k] === value) { return true; } if (t && Array.isArray(t) && t.length) { o[k] = t; return true; } }) ); if (temp.length) { return temp; } } var array = [{ name: "Object0Name", id: "Object0ID", Object1List: [{ id: "Object1id_A1", name: "Object1Name_A1", Object2List: [{ id: 187, name: "Object2Name_A1", Object3List: [{ id: "mammal", name: "mammal", Object4List: [{ id: "rabbit", Currency: "EUR" }, { id: "cat", Currency: "EUR" }, { id: "tiger", Currency: "EUR" }] }] }] }, { id: "Object1id_B1", name: "Object1Name_B1", Object2List: [{ id: 189, name: "Object2Name_B1", Object3List: [{ id: "fish", name: "fish", Object4List: [{ id: "tiger shark", Currency: "EUR" }, { id: "tuna", currency: "GBP" }] }] }] }] }], result = filter(array, 'tiger shark'); console.log(result); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` Upvotes: 2 [selected_answer]
2018/03/18
859
1,759
<issue_start>username_0: I have a data.frame which has two column. However, I need to convert the format of `psw` column in 5 digit integer from the current format. How can I automatically change 1 digit to 5 in `psw` column? How can I get this done in R easily? Thanks Here is reproducible data.frame ``` mydat <- data.frame(ID=LETTERS[seq( from = 1, to = 6)], psw=c(10501,3,80310,8930,234,1)) > mydat ID psw 1 A 10501 2 B 3 3 C 80310 4 D 8930 5 E 234 6 F 1 ``` This is my desired output: ``` > mydat ID psw 1 A 10501 2 B 00003 3 C 80310 4 D 08930 5 E 00234 6 F 00001 ```<issue_comment>username_1: You can't do that while keeping the `psw` column numeric, but you can format it to be a certain width as a character vector. Here are two methods for this: In base R you can use `formatC()`: ``` mydat <- data.frame(ID=LETTERS[seq( from = 1, to = 6)], psw=c(10501,3,80310,8930,234,1)) mydat$psw <- formatC(mydat$psw, width = 5, format = "d", flag = "0") mydat # ID psw # 1 A 10501 # 2 B 00003 # 3 C 80310 # 4 D 08930 # 5 E 00234 # 6 F 00001 ``` In `stringr`, you can use `str_pad()`: ``` install.packages("stringr") library(stringr) mydat <- data.frame(ID=LETTERS[seq( from = 1, to = 6)], psw=c(10501,3,80310,8930,234,1)) mydat$psw <- str_pad(mydat$psw, width = 5, pad = "0") mydat # ID psw # 1 A 10501 # 2 B 00003 # 3 C 80310 # 4 D 08930 # 5 E 00234 # 6 F 00001 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: One can even use `sprintf` in `base-R`. ``` mydat$psw <- sprintf("%05d",mydat$psw) mydat # ID psw # 1 A 10501 # 2 B 00003 # 3 C 80310 # 4 D 08930 # 5 E 00234 # 6 F 00001 ``` Upvotes: 1
2018/03/18
970
3,174
<issue_start>username_0: I am working with a third party device which has some implementation of Lua, and communicates in BACnet. The documentation is pretty janky, not providing any sort of help for any more advanced programming ideas. It's simply, "This is how you set variables...". So, I am trying to just figure it out, and hoping you all can help. I need to set a long list of variables to certain values. I have a userdata 'ME', with a bunch of variables named MVXX (e.g. - MV21, MV98, MV56, etc). (This is all kind of background for BACnet.) Variables in BACnet all have 17 'priorities', i.e., every BACnet variable is actually a sort of list of 17 values, with priority 16 being the default. So, typically, if I were to say `ME.MV12 = 23`, that would set MV12's priority-16 to the desired value of 23. However, I need to set priority 17. I can do this in the provided Lua implementation, by saying `ME.MV12_PV[17] = 23`. I can set any of the priorities I want by indexing that PV. (Corollaries - what is PV? What is the underscore? How do I get to these objects? Or are they just interpreted from Lua to some function in C on the backend?) All this being said, I need to make that variable name dynamic, so that i can set whichever value I need to set, based on some other code. I have made several attempts. This tells me the object(`MV12_PV[17]`) does not exist: ``` x = 12 ME["MV" .. x .. "_PV[17]"] = 23 ``` But this works fine, setting priority 16 to 23: ``` x = 12 ME["MV" .. x] = 23 ``` I was trying to attempt some sort of what I think is called an evaluation, or eval. But, this just prints out `function` followed by some random 8 digit number: ``` x = 12 test = assert(loadstring("MV" .. x .. "_PV[17] = 23")) print(test) ``` Any help? Apologies if I am unclear - tbh, I am so far behind the 8-ball I am pretty much grabbing at straws.<issue_comment>username_1: Underscores can be part of Lua identifiers (variable and function names). They are just part of the variable name (like letters are) and aren't a special Lua operator like `[` and `]` are. In the expression `ME.MV12_PV[17]` we have `ME` being an object with a bunch of fields, `ME.MV12_PV` being an array stored in the `"MV12_PV"` field of that object and `ME.MV12_PV[17]` is the 17th slot in that array. If you want to access fields dynamically, the thing to know is that accessing a field with dot notation in Lua is equivalent to using bracket notation and passing in the field name as a string: ``` -- The following are all equivalent: x.foo x["foo"] local fieldname = "foo" x[fieldname] ``` So in your case you might want to try doing something like this: ``` local n = 12 ME["MV"..n.."_PV"][17] = 23 ``` Upvotes: 1 <issue_comment>username_2: BACnet "Commmandable" Objects (e.g. Binary Output, Analog Output, and o[tionally Binary Value, Analog Value and a handful of others) actually have 16 priorities (1-16). The "17th" you are referring to may be the "Relinquish Default", a value that is used if all 16 priorities are set to NULL or "Relinquished". Perhaps your system will allow you to write to a BACnet Property called "Relinquish Default". Upvotes: 0
2018/03/18
401
1,371
<issue_start>username_0: We have `parquet` data saved on a server and I am trying to use `SparkR` `sql()` function in the following ways ``` df <- sql("SELECT * FROM parquet.` SELECT \* FROM parquet.` ``` and ``` createOrReplaceTempView(df, "table") df2 <- sql("SELECT * FROM table") show(df2) # returns " SELECT \* FROM table" ``` In both cases what I get is the sql query in a string format instead of the spark dataframe. Does anyone have any idea why this happens and why I don't get the dataframe? Thank you<issue_comment>username_1: Don't use the `show` statement use `showDF()`...or, `View(head(df2, num=20L))` Upvotes: 2 <issue_comment>username_2: This was a very silly problem. The solution is to just use the full name of the method ``` SparkR::sql(...) ``` instead of the short name. Apparently the function `sql` is masked. Upvotes: 2 <issue_comment>username_3: [show](https://spark.apache.org/docs/latest/api/R/show.html) method documentation in sparkR states that if eager evaluation is not enabled it returns the class and type information of the Spark object. so you should use [showDF](https://spark.apache.org/docs/latest/api/R/showDF.html) instead. besides that, apparently, the `sql` method is masked in `R` and you should call it with explicit package deceleration. like this: ``` df <- SparkR::sql("select 1") showDF(df) ``` Upvotes: 0
2018/03/18
711
2,155
<issue_start>username_0: I want to sort a list of strings alphabetically. Here is my code: `lis =list( input("list")) print (sorted (lis, key=str.lower))` input:`['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim']` output:`[' ', ' ', ' ', ' ', ' ', "'", "'", "'", "'", "'", "'", "'", "'", "'", "'", "'", "'", ',', ',', ',', ',', ',', 'E', 'I', 'S', 'S', 'W', '[', ']', 'c', 'd', 'e', 'e', 'e', 'e', 'e', 'f', 'g', 'g', 'h', 'i', 'i', 'i', 'l', 'm', 'm', 'n', 'n', 'o', 'r', 's', 't', 't', 't', 't', 't', 'u', 'u', 'u', 'x']` I have no idea why.<issue_comment>username_1: As opposed to what python 2 `input` does, python 3 `input` doesn't evaluate the input anymore (acts like `raw_input` did), for safety reasons (`input` was a hidden `eval` function) The code you showed worked fine in python 2, but needs some adaptations for python 3. In your case, you need to `ast.literal_eval` the list first, which parses and performs a safe evaluation of literals only (just what you need) or you're sorting the characters of the inputted string. Like this: ``` import ast lis = ast.literal_eval(input("list").lstrip()) print (sorted (lis, key=str.lower)) ``` (adding `lstrip()` so leading spaces are trimmed if any, `ast.literal_eval` cares about indentation) Upvotes: 2 [selected_answer]<issue_comment>username_2: input() function returns **one string** at once, not a regular list as you entered. so you need to feed it with a string of the items in the list like so: ``` lis = input('Enter your list items seperated by a space: ') lis = lis.split() lis.sort(key=str.lower) print(lis) ``` there are many other ways to do it but this is the most preferred one. Upvotes: -1 <issue_comment>username_3: This is how I have done it: ``` string=['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim'] for i in range(len(string)): string[i]=string[i].lower() s=sorted(string) print(s) ``` This way, all the **list elements** are converted into *lower case* and then `sorted() function` sorts all the list elements. The output: ``` ['constitute', 'eflux', 'intrigue', 'sedge', 'stem', 'whim'] ``` Hope this was useful! Upvotes: 0
2018/03/18
780
2,648
<issue_start>username_0: ``` #include using namespace std; // prototype functions void DisplayResult(float MaxOrMin); float FindMinimum(float Array[5]); float FindMaximum(float Array[5]); //Global Variables float Array[5]; float MaxOrMin = 3; float FindMin; float FindMax; //Main Function int main() { cout << "Please enter 5 numbers: " << endl; for (int i=0; i<5; i++) { cin >> Array[i]; // input for array } cout << "Please enter '0' for minimum or '9' for maximum:" << endl; cin >> MaxOrMin; // input 0 or 9 for min or max //Calling Functions FindMinimum(Array); FindMaximum(Array); DisplayResult(MaxOrMin); return 0; } //Function to find Minimum float FindMinimum(float Array[5]) { float FindMin = Array[0]; for (int y=1;y<5;y++) { if(Array[y] < FindMin) FindMin = Array[y]; } return FindMin; } //Function to find Maximum float FindMaximum(float Array[5]) { float FindMax = Array[0]; for (int x=1;x<5;x++) { if(Array[x] > FindMax) FindMax = Array[x]; } return FindMax; } ``` This last part is my if, else if, else funtion: ``` //Function to display minimum or maximum result void DisplayResult(float MaxOrMin) { if (MaxOrMin == 0) cout << "Minimum is: " << FindMin << endl; else if (MaxOrMin == 9) cout << "Maximum is: " << FindMax << endl; else cout << "Invalid Input" << endl; } ``` My project is to create a program using functions to take user input on a 5 float array. Then find the max and min and display whichever the user asks for. Here is where my problem comes in. For both max(input 9) and min(input 0) I am getting "0". However any other input correctly returns my "Invalid Input" message. I'm not getting any errors or warnings or errors at all on eclipse. My professor has told me that my problem was likely with my void function for displaying results. I am hoping someone could point me in the right direction here. Apologies for my formatting and/or if this question is too basic for this site.<issue_comment>username_1: You misunderstand how local and global variables work. Your Find\* functions shadow the globals with locals and thus they don't appear to do anything. Upvotes: 2 <issue_comment>username_2: The problem is that your `FindMinimum()` (and the same with `FindMaximum()`) function compute the minimum (maximum) in a local variable and return it but you, in `main()` don't receive they in correct variables So the computed value is lost. I mean... instead of ``` FindMinimum(Array); FindMaximum(Array); ``` you should write ``` FindMin = FindMinimum(Array); FindMax = FindMaximum(Array); ``` Upvotes: 1 [selected_answer]
2018/03/18
1,095
4,135
<issue_start>username_0: In my app I want to download images from url and show them in recyclerView. And basically everything is ok - when I download images, turn off wifi and mobile data - cached images are being displayed. Tried several times - it works perfectly. However ... after for example 3-4 hrs I tried again to launch app in offline mode and images were not displayed. Any idea what I'm doing wrong ? Here's my code in basic activity (onCreate) : ``` Picasso.Builder builder = new Picasso.Builder(getContext()); builder.downloader(new OkHttp3Downloader(getContext(),Integer.MAX_VALUE)); Picasso built = builder.build(); built.setIndicatorsEnabled(true); built.setLoggingEnabled(true); ``` Then I download and cache images like this : ``` public void onResponse(Call call, Response response) { CallbackListPost resp = response.body(); if (resp != null && resp.status.equals("ok")) { post\_total = resp.count\_total; displayApiResult(resp.posts); controller = new RealmController(getActivity().getApplication()); controller.savePost(resp.posts); for(Post post : resp.posts) { for (final Attachment att : post.attachments) { Picasso.with(getActivity()) .load(att.url) .fetch(new com.squareup.picasso.Callback() { @Override public void onSuccess() { Log.e(TAG, "onSuccess: " + att.url ); } @Override public void onError() { } }); } } ``` Then in second activity I display images like this : ``` public View getView(int position, View convertView, ViewGroup parent) { ImageView iv; if(convertView == null) { iv = new ImageView(mContext); } else { iv = (ImageView) convertView; } Picasso.with(mContext) .load(att.get(position).url) .noFade() .resize(150,150) .centerCrop() .into(iv); return iv; } ```<issue_comment>username_1: Hello you can try this: ``` Picasso.with(mContext) .load(att.get(position).url) .noFade() .resize(150,150) .centerCrop() .memoryPolicy(MemoryPolicy.NO_CACHE) .networkPolicy(NetworkPolicy.NO_CACHE) .into(iv); ``` Upvotes: 2 <issue_comment>username_2: I don't have much knowledge about Picasso. I have a suggestion that you must go with Glide, an image caching tool. Its very small library and very fast. Simple use cases with Glide's generated API will look something like this: // For a simple view: ``` @Override public void onCreate(Bundle savedInstanceState) { ... ImageView imageView = (ImageView) findViewById(R.id.my_image_view); GlideApp.with(this).load("goo.gl/gEgYUd").into(imageView); } // For a simple image list: @Override public View getView(int position, View recycled, ViewGroup container) { final ImageView myImageView; if (recycled == null) { myImageView = (ImageView) inflater.inflate(R.layout.my_image_view, container, false); } else { myImageView = (ImageView) recycled; } String url = myUrls.get(position); GlideApp .with(myFragment) .load(url) .centerCrop() .placeholder(R.drawable.loading_spinner) .into(myImageView); return myImageView; } ``` It has auto cache config, which means we don't need to bother about the image cache.It loads perfectly after first use. In Glide V4 ----------- ``` Glide.with(context) .load(“/user/profile/photo/path”) .asBitmap() .toBytes() .centerCrop() .into(new SimpleTarget(250, 250) { @Override public void onResourceReady(byte[] data, GlideAnimation anim) { // Post your bytes to a background thread and upload them here. } }); ``` Upvotes: 1 <issue_comment>username_3: If you refer to the documentation of the latest version of Picasso (2.71828) and figure out how Picasso handles it internally, you will understand why your images are NOT getting loaded from Disk/Cache. Well explained answer is here <https://stackoverflow.com/a/57114949/1508631>. Upvotes: 0
2018/03/18
1,012
3,304
<issue_start>username_0: I'm reversing engineering a old flash game and on login process a POST request is send to server. ActionScript2: ``` req.username = inicial.login_mc.username_txt.text; req.password = inicial.login_mc.password_txt.text; xmlResponse = new LoadVars(); xmlResponse.onLoad = function() { xml = new XML(xmlResponse.xml); trace("login xml: " + xml); user = xml.childNodes[0]; }; url_login = "api/auth/user"; req.sendAndLoad(url_login, xmlResponse, "POST"); ``` Request: ```none Request URL: http://localhost:3000/api/auth/user Request Method: POST Status Code: 200 OK Remote Address: [::1]:3000 Referrer Policy: no-referrer-when-downgrade username: aaaa password: <PASSWORD> ``` My response: ```none Connection: keep-alive Content-Length: 58 Content-Type: application/xml; charset=utf-8 Date: Sun, 18 Mar 2018 20:19:50 GMT ETag: W/"3a-G4M/BpWRvMgDdvlmOtNMapl/lLw" X-Powered-By: Express howdoing ``` The issue: the flash don't get any response, and xml is always empty. flashlog.txt: ```none Warning: getClassStyleDeclaration is not a function login xml: ``` Content-Type: text/xml don't work too. What it could be?<issue_comment>username_1: Hello you can try this: ``` Picasso.with(mContext) .load(att.get(position).url) .noFade() .resize(150,150) .centerCrop() .memoryPolicy(MemoryPolicy.NO_CACHE) .networkPolicy(NetworkPolicy.NO_CACHE) .into(iv); ``` Upvotes: 2 <issue_comment>username_2: I don't have much knowledge about Picasso. I have a suggestion that you must go with Glide, an image caching tool. Its very small library and very fast. Simple use cases with Glide's generated API will look something like this: // For a simple view: ``` @Override public void onCreate(Bundle savedInstanceState) { ... ImageView imageView = (ImageView) findViewById(R.id.my_image_view); GlideApp.with(this).load("goo.gl/gEgYUd").into(imageView); } // For a simple image list: @Override public View getView(int position, View recycled, ViewGroup container) { final ImageView myImageView; if (recycled == null) { myImageView = (ImageView) inflater.inflate(R.layout.my_image_view, container, false); } else { myImageView = (ImageView) recycled; } String url = myUrls.get(position); GlideApp .with(myFragment) .load(url) .centerCrop() .placeholder(R.drawable.loading_spinner) .into(myImageView); return myImageView; } ``` It has auto cache config, which means we don't need to bother about the image cache.It loads perfectly after first use. In Glide V4 ----------- ``` Glide.with(context) .load(“/user/profile/photo/path”) .asBitmap() .toBytes() .centerCrop() .into(new SimpleTarget(250, 250) { @Override public void onResourceReady(byte[] data, GlideAnimation anim) { // Post your bytes to a background thread and upload them here. } }); ``` Upvotes: 1 <issue_comment>username_3: If you refer to the documentation of the latest version of Picasso (2.71828) and figure out how Picasso handles it internally, you will understand why your images are NOT getting loaded from Disk/Cache. Well explained answer is here <https://stackoverflow.com/a/57114949/1508631>. Upvotes: 0
2018/03/18
1,183
3,493
<issue_start>username_0: I need help, this is my code. I've done what I need for the landing page, but can not make navigation bar stick to the top it is just hanging just above the middle of the screen. Don't know what to do with flex, or is in this example flex the problem, or what? I have tried position relative, absolute, flex start end, everything, I am pretty much exhausted from looking at this. Can not find the solution. AND THIS IS THE Snipt View ```css * { margin: 0; padding: 0; } body { margin: 0; font-family: Arial; font-size: 17px; color: #99b525; line-height: 1.6; } #showcase { background-image: url('img/lap-top.jpeg'); background-size: cover; background-position: center; background-attachment: fixed; height: 100vh; display: flex; flex-direction: column; justify-content: center; align-items: center; opacity: 0.9; padding: 0 20px; text-shadow: -2px 3px 2px #666; text-align: center; } #showcase h1 { font-size: 50px; line-height: 1.2; } #showcase p { font-size: 20px; } #showcase .header .button { font-size: 18px; text-decoration: none; padding: 10px 20px; margin-top: 20px; border: 1px solid #777; border-radius: 15px; color: #a3bd3b; -webkit-transition: background-color 0.8s ease-out; -moz-transition: background-color 0.8s ease-out; -o-transition: background-color 0.8s ease-out; transition: background-color 0.8s ease-out; } #showcase .header .button:hover { background: #a3bd3b; color: #fff; text-shadow: none; } .header { border: 3px solid #7c9c28; border-radius: 50px 25px 50px 25px; padding: 25px; background: #232323ad; display: flex; flex-direction: column; justify-content: center; align-items: center; } /*---------------------------------------------------*/ nav { width: 100%; height: 60px; background-color: transparent; } nav ul { float: left; } nav ul li { float: left; list-style: none; padding: 0px 4em; } nav ul li a { font-family: Arial; color: #222; font-size: 20px; padding: 24px 14px; text-decoration: none; } ``` ```html * [Home](index.html) * [Portfolio](#) * [About Me](#) * [Contact](#) Welcome to the beach ==================== Lorem ipsum dolar sit anet, amat der is tlen af serf nsajs jsiqo msnf kaiwks. [Read More](#) ``` What to do to make this right?<issue_comment>username_1: try removing #showcase height . if you want sticky menu try ``` position:fixed; ``` Upvotes: 0 <issue_comment>username_2: Your justify-content 'center' is causing the issue as it's attempting to push everything into the middle. If you're insistent on using the flexbox method (and depending on where you want the rest of your webpage), you can alter this to flex-start (so that everything moves to the top of the page). ``` #showcase { background-image: url('img/lap-top.jpeg'); background-size: cover; background-position: center; background-attachment: fixed; height: 100vh; display: flex; flex-direction: column; justify-content: flex-start; align-items: center; /* change to flex-start */ opacity: 0.9; padding: 0 20px; text-shadow: -2px 3px 2px #666; text-align: center; } ``` However, assuming you want your content "Welcome to the beach" in the middle, my personal solution would be to add this to your nav style: ``` nav { position:fixed; top:0; } ``` Upvotes: -1 [selected_answer]
2018/03/18
1,799
4,588
<issue_start>username_0: I'm trying to create my own indicator for the (forex) metatrader4 platform (C++), but I'm stuck on a logical problem using `for` function. This is part of my code ``` for(int i = limit - 1; i >= 0; i--) { CCI_buffer[i] = iCCI(NULL,0,CCI_period,PRICE_WEIGHTED,i); } ``` This code will return the value for each bar (array). This is fine. But I am trying to calculate the average value for the last 3 (for example) bars. A practical example of what I want to achieve. ``` (input values) CCI_buffer[0] = 100 CCI_buffer[1] = 50 CCI_buffer[2] = 0 CCI_buffer[3] = 50 CCI_buffer[4] = 100 CCI_average[0] = (CCI_buffer[0] + CCI_buffer[1] + CCI_buffer[2]) / 3 ([0]= 50) CCI_average[1] = (CCI_buffer[1] + CCI_buffer[2] + CCI_buffer[3]) / 3 ([1]= 33.33) CCI_average[2] = (CCI_buffer[2] + CCI_buffer[3] + CCI_buffer[4]) / 3 ([2]= 50) ``` How can I do that? In this case, my logic fails (I'm probably a fool) and I need to push forward. Should I use the "FOR" function twice? ``` for{ for{ } } ``` Or do I have the "FOR" function inside the formula to calculate? ``` for { CCI_average[i] = .... } ```<issue_comment>username_1: Example with two ways to solve the task: ``` #include #include #include // Method 1 float cci\_avg(int cci\_buffer[], int index\_start, int num\_values, int size) { assert(index\_start+num\_values <= size); assert(index\_start >= 0); assert(num\_values > 0); float sum = 0; for(int i=index\_start; i < index\_start+num\_values; ++i) { sum += cci\_buffer[i]; } return sum/num\_values; } int main() { const int SIZE = 5; int CCI\_buffer[SIZE] = {100, 50, 0, 50, 100}; // Call method 1 std::cout << "0, 3: " << cci\_avg(CCI\_buffer, 0, 3, SIZE) << std::endl; std::cout << "1, 3: " << cci\_avg(CCI\_buffer, 1, 3, SIZE) << std::endl; std::cout << "2, 3: " << cci\_avg(CCI\_buffer, 2, 3, SIZE) << std::endl; // fails // std::cout << "3, 3: " << cci\_avg(CCI\_buffer, 3, 3, SIZE) << std::endl; // Method 2 with std::accumulate int num\_values = 3; std::cout << "0, 3 with accumulate: " << std::accumulate(&CCI\_buffer[0], &CCI\_buffer[0+num\_values], 0)/ static\_cast(num\_values) << std::endl; std::cout << "1, 3 with accumulate: " << std::accumulate(&CCI\_buffer[1], &CCI\_buffer[1+num\_values], 0)/ static\_cast(num\_values) << std::endl; std::cout << "2, 3 with accumulate: " << std::accumulate(&CCI\_buffer[2], &CCI\_buffer[2+num\_values], 0)/ static\_cast(num\_values) << std::endl; return 0; } ``` Output: ``` 0, 3: 50 1, 3: 33.3333 2, 3: 50 0, 3 with accumulate: 50 1, 3 with accumulate: 33.3333 2, 3 with accumulate: 50 ``` The assert calls just give you a warning when you call it with invalid parameters. You could of course achieve this without a function, too. Docs for std::accumulate: <http://en.cppreference.com/w/cpp/algorithm/accumulate> Upvotes: 0 <issue_comment>username_2: You don't need nested for loop. Just calculate the prefix sums (<https://en.m.wikipedia.org/wiki/Prefix_sum>), And then you have access to sum of consecutive subsequence by `sums[last] - sums[first - 1]`. This will give you O(n) time instead of O(n\*m) (where n is number of elements, and m is number of elements to calculate average(in your example it's 3)). If you have m=3, it's okay to use O(n\*m) solution but if n=1000 and m=1000, you will give time compexity of 10^6 instead of 10^3, which is big difference. Upvotes: 0 <issue_comment>username_3: The last call to `cci_avg` properly throws the assert exception. The call asks to average 3 numbers beginning at index 3, i.e. at 3,4, and 5. But there is no index 5. They only go to 4. Bonus: Use std::accumulate. It will get the for-loop right every time. ``` #include #include #include float cci\_avg(int cci\_buffer[], int index\_start, int num\_values, int size) { assert(index\_start+num\_values <= size); assert(index\_start >= 0); assert(num\_values > 0); auto begin = cci\_buffer+index\_start; auto end = begin + num\_values; return std::accumulate(begin, end, 0.0f) / num\_values; } int main() { const int SIZE = 5; int CCI\_buffer[SIZE]; CCI\_buffer[0] = 100; CCI\_buffer[1] = 50; CCI\_buffer[2] = 0; CCI\_buffer[3] = 50; CCI\_buffer[4] = 100; std::cout << "0, 3: " << cci\_avg(CCI\_buffer, 0, 3, SIZE) << std::endl; std::cout << "1, 3: " << cci\_avg(CCI\_buffer, 1, 3, SIZE) << std::endl; std::cout << "2, 3: " << cci\_avg(CCI\_buffer, 2, 3, SIZE) << std::endl; // The next is no good // std::cout << "3, 3: " << cci\_avg(CCI\_buffer, 3, 3, SIZE) << std::endl; return 0; } ``` Upvotes: -1
2018/03/18
839
2,977
<issue_start>username_0: I have an situation where I have a render function that passes some data to a scoped slot. As part of this data I'd like to include some VNodes constructed by the render function that could optionally be used by the scoped slot. Is there anyway when writing the scoped slot in a template to output the raw VNodes that were received?<issue_comment>username_1: Vue 3 ===== You can use in the template to render the vnode: ```html ``` This only seems to work for a single vnode. If you want to render multiple vnodes (an array) then use `v-for` or render it as a functional component: ```html ``` or ensure the vnode is a single containing the child vnodes. You can also use a similar approach to the Vue 2 way below. Vue 2 ===== You can use a functional component to render the vnodes for that section of your template: ```html ``` ```js components: { VNodes: { functional: true, render: (h, ctx) => ctx.props.vnodes } } ``` Upvotes: 6 <issue_comment>username_2: In vue3 with typescript you'd do this: ### Define a wrapper functional component. This is necessary because vue doesn't allow you to mix and match function and template functions. ``` const VNodes = (props: any) => { return props.node; }; VNodes.props = { node: { required: true, }, }; export default VNodes; ``` ### Use the functional component in a template component ``` import { defineProps } from "vue"; import type { VNode } from "vue"; import VNodes from "./VNodes"; // <-- this is not a magic type, its the component from (1) const props = defineProps<{ comment: string; render: () => VNode }>(); {{ props.comment }} ``` ### Pass the `VNode` to the component ``` import type { Story } from "@storybook/vue3"; import { h } from "vue"; import type { VNode } from "vue"; import ExampleComponent from "./ExampleComponent.vue"; export default { title: "ExampleComponent", component: ExampleComponent, parameters: {}, }; interface StoryProps { render: () => VNode; comment: string; } const Template: Story = (props) => ({ components: { ExampleComponent }, setup() { return { props, }; }, template: ``, }); export const Default = Template.bind({}); Default.args = { comment: "hello", render: () => h("div", {}, ["world"]), }; export const ChildComponent = Template.bind({}); ChildComponent.args = { comment: "outer", render: () => h( ExampleComponent, { comment: "inner", render: () => h("div", {}, ["nested component"]), }, [] ), }; ``` Long story short: The above is a work around by rendering vnodes in a functional component (no template), and rendering the functional component in a template. So, no. You cannot render `VNodes` from templates. This is functionality that vue *doesn't have*, compared to other component systems. Upvotes: 0 <issue_comment>username_3: **Vue 3 example** ``` components: { vNodes: { props: ['vnodes'], render: (h) => h.vnodes, }, }, ``` Upvotes: 1
2018/03/18
344
1,068
<issue_start>username_0: To speed up some operations I transfered image to GPU memory. After some processing I have to crop some area: ``` image = cv2.UMat(image) ... crop = image[y1:y2,x1:x2] ``` The problem is that it is not possible to slice image inside GPU memory. Above code will raise error: "UMat object is not subscriptable". The solution I found is to transfer image back to numpy object, than slice it, and transfer back to GPU: ``` image = cv2.UMat(image) ... image = image.get() crop = image[y1:y2,x1:x2] crop = cv2.UMat(crop) ... ``` But above solution looks costly, as transferring data to/from GPU memory takes time. I have a feeling that there is a way to crop an image within GPU memory. Any hints?<issue_comment>username_1: After some study of UMat class source code and tests I found this solution: ``` crop = cv2.UMat(image, [y0, y1], [x0, x1]) ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: ``` def crop_umat(umat, height, width, left=0, top=0): return cv.UMat(umat, [top, height+top], [left, width+left]) ``` Upvotes: 0
2018/03/18
548
1,888
<issue_start>username_0: I am trying to delete rows from one table. So this what i have done so far. I imported a .CSV file which created a temp table. I would like to delete the rows in my original table with matching with temp table. I tried the following code : ``` Delete From Table1 Where postid and userid in (Select postid, userid from Table2) ``` but it does not work. The goal is to delete rows in Table 1 using Table 2.<issue_comment>username_1: A simple `INNER JOIN` should do the job: ``` DELETE T1 FROM Table1 T1 INNER JOIN Table2 T2 ON T1.postid = T2.postid AND T1.userid = T2.userid ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: This is just another funny way : ``` DELETE FROM Table1 WHERE STR(postid) + STR(userid) IN (SELECT STR(postid) + STR(userid) FROM Table2) ``` Upvotes: 1 <issue_comment>username_3: As far as I understand you want to Delete from Table1 where you want to create a composite condition based on postid and userid the from Table2 the problem is that you subquery in(Select postid,userid from Table2) is not returning the correct value as to match the in condition please modify the query to ``` DELETE T1 FROM Table1 T1 INNER JOIN Table2 T2 ON T1.postid = T2.postid AND T1.userid = T2.userid ``` as stated in the previous answer Upvotes: 0 <issue_comment>username_4: You can use a Merge statement. In this case you're only interested in deletes. A semicolon is required after the delete section, followed by a final semicolon to end the merge statement. For example: ``` MERGE table1 AS target USING table2 AS source ON target.postid = source.postid and target.userid = source.userid WHEN Matched THEN DELETE;; ``` An example sqlfiddle: <http://sqlfiddle.com/#!18/a932d/1/0> The Merge documentation: <https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql> Upvotes: 0
2018/03/18
4,263
15,709
<issue_start>username_0: Introduction ------------ I'm working on a project where a user is able to enter facts and rules in a special format but I'm having some trouble with checking if that format is correct and obtaining the information. When the program is launched the user can enter "commands" into a textarea and this text is send to a `parseCommand` method which determine what to do based on what the user has written. For example to add a fact or a rule you can use the prefix `+`. or use `-` to remove a fact or rule and so on. I've created the system which handles the prefix but i'm having trouble with the facts and rules format. Facts and rules --------------- **Facts:** These are defined by an alphanumeric name and contain a list of properties (each is withing `<>` signs) and a truth value. Properties are also defined by an alphanumeric name and contain 2 strings (called arguments), again each is withing `<>` signs. Properties can also be negative by placing an `!` before it in the list. For example the user could type the following to add these 3 facts to the program: ``` +father(,)>, true) +father(,)>, false) +father(!,)>, true) +familyTree(,)>, ,)> , true) +fathers(,)>, !,)> , true) ``` The class I use to store facts is like this: ``` public class Fact implements Serializable{ private boolean truth; private ArrayList properties; private String name; public Fact(boolean truth, ArrayList properties, String name){ this.truth = truth; this.properties = properties; this.name = name; } //getters and setters here... } ``` **Rules:** These are links between 2 properties and they are identified by the `=>` sign Again their name is alphanumeric. The properties are limited though as they can only have arguments made up of uppercase letters and the arguments of the second property have to be the same as those the first one. Rules also have 2 other arguments which are either set or not set by entering the name or not (each of these arguments correspond with a property for the rule which can be `Negative` or `Reversive`). for example: ``` +son(,)> => ,)>) +son(,)> => ,)>, Negative, Reversive) +son(,)> => ,)>, Reversive) +son(,)> => ,)>, Negative) ``` **Rule Properties** A normal rule tells us that if, in the example below, `X` is a parent of `Y` this implies that `Y` is a child of `X` : ``` son(,)> => ,)>) ``` While a `Negative` rule tells us that if, in the example below, `X` is a parent of `Y` this implies that `Y` is not a child of `X` : ``` son(,)> => ,)>, Negtive) ``` A `Reversive` rule however tells us that if, in the example below, `Y` is a child of `X` this implies that `X` is a parent of `Y` ``` son(,)> => ,)>, Reversive) ``` The last case is when the rule is both `Negative` and `Reversive`. This tells us that if, in the example below, `Y` is not a child of `X` this implies that `X` is a parent of `Y`. ``` son(,)> => ,)>, Negative, Reversive) ``` This is the class I use to store rules: ``` public class Rule implements Serializable{ private Property derivative; private Property impliant; private boolean negative; private boolean reversive; private String name; public Rule(Property derivative, Property impliant, boolean negative, boolean reversive) throws InvalidPropertyException{ if(!this.validRuleProperty(derivative) || !this.validRuleProperty(impliant)) throw new InvalidPropertyException("One or more properties are invalid"); this.derivative = derivative; this.impliant = impliant; this.negative = negative; this.reversive = reversive; } //getters and setters here } ``` Property class: ``` public class Property implements Serializable{ private String name; private String firstArgument; private String secondArgument; public Property(String name, String firstArgument, String secondArgument){ this.name = name; this.firstArgument = firstArgument; this.secondArgument = secondArgument; } ``` The above examples are all valid inputs. Just to clarify here are some invalid input examples: **Facts:** No true or false is provided for the argument: ``` +father(,)>) ``` No property given: ``` +father(false) ``` An invalid property is provided: ``` +father()>, true) +father(, true) +father(, true) +father(parent(,), true) ``` Note the missing bracket in the last one. **Rules:** One or more properties are invalid: ``` +son(,)> => child(,)) +son(parent(,) => child(,)) +son(,)> => ,)>) (Note the Z in the child property) +son(,)> => child(,)) (Invalid argument for first property) +son(=> child(,)) ``` The problem ----------- I'm able to get the input from the user and I'm also able to see which kind of action the user wants to preform based on the prefix. However I'm not able to figure out how to process strings like: ``` +familyTree(,)>, ,)> , true) ``` This is due to a number of reasons: 1. The number of properties for a fact entered by the user is variable so I cant just split the input string based on the `()` and `<>` signs. 2. For rules, sometimes, the last 2 properties are variable so it can happen that the 'Reversive' property is on the place in the string where you would normally find the `Negative` property. 3. If I want to get arguments from this part of the input string: `+familyTree(,)>,` to setup the property for this fact I can check for anything that is in between `<>` that might form a problem because there are 2 opening `<` before the first `>` What I've tried --------------- My first idea was to start at the beginning of the string (which I did for getting the action from the prefix) and then remove that piece of string from the main string. However I don't know how to adapt this system to the problems above(specially problem number 1 and 2). I've tried to use functions like: `String.split()` and `String.contains()`. How would I go about doing this? How can I get arount the fact that not all strings contain the same information? (In a sense that some facts have more properties or some rules have more attributes than others.) **EDIT:** I forgot to say that all the methods used to store the data are finished and work and they can be used by calling for example: `infoHandler.addRule()` or `infoHandler.removeFact()`. Inside these functions I could also validate input data if this is better. I could, for example, just obtain all data of the fact or rule from the string and validate things like are the arguments of the properties of rules only using uppercase letters and so on. **EDIT 2:** In the comments someone has suggested using a parser generator like ANTLR or JavaCC. I'e looked into that option in the last 3 days but I can't seem to find any good source on how to define a custom language in it. Most documentation assumes you're trying to compile an exciting language and recommend downloading the language file from somewhere instead of writing your own. I'm trying to understand the basics of ANTLR (which seems to be the one which is easiest to use.) However there is not a lot of recources online to help me. If this is a viable option, could anyone help me understand how to do something like this in ANTLR? Also once I've written a grammer file how am I sopposed to use it? I've read something about generating a parser from the language file but I cant seem to figure out how that is done... **EDIT 3:** I've begon to work on a grammer file for ANTLR which looks like this: ``` /** Grammer used by communicate parser */ grammar communicate; /* * Parser Rules */ argument : '<' + NAMESTRING + '>' ; ruleArgument : '<' + RULESTRING + '>' ; property : NAMESTRING + '(' + argument + ',' + argument + ')' ; propertyArgument : (NEGATIVITY | POSITIVITY) + property + '>' ; propertyList : (propertyArgument + ',')+ ; fact : NAMESTRING + '(' + propertyList + ':' + (TRUE | FALSE) + ')'; rule : NAMESTRING + '(' + ruleArgument + '=>' + ruleArgument + ':' + RULEOPTIONS + ')' ; /* * Lexer Rules */ fragment LOWERCASE : [a-z] ; fragment UPPERCASE : [A-Z] ; NAMESTRING : (LOWERCASE | UPPERCASE)+ ; RULESTRING : (UPPERCASE)+ ; TRUE : 'True'; FALSE : 'False'; POSITIVITY : '!<'; NEGATIVITY : '<' ; NEWLINE : ('\r'? '\n' | '\r')+ ; RULEOPTIONS : ('Negative' | 'Negative' + ',' + 'Reversive' | 'Reversive' ); WHITESPACE : ' ' -> skip ; ``` Am I on the right track here? If this is a good grammer file how can I test and use it later on?<issue_comment>username_1: I dont think a syntax analyzer is good for your problem. anyway you can handle it simpler by using regex and some string utilities. It's better to start from small problem and move to the bigger ones: first parsing the property itself seems easy so we write a method to do that: ``` private static Property toProp(String propStr) { String name = propStr.substring(1,propStr.indexOf("(")); String[] arguments = propStr.substring(propStr.indexOf('(')+1,propStr.indexOf(')')).split(","); return new Property(name, arguments[0].substring(1,arguments[0].length()-1), arguments[1].substring(1,arguments[1].length()-1)); } ``` To parse Fact string, using regex make things easier,regex for property is ***/<[\w\d]*([<>\w\d,]*)>/*** and by the help of toProp method we have written already we can create another method to parse Facts: ``` public static Fact handleFact(String factStr) { Pattern propertyPattern = Pattern.compile("<[\\w\\d]*\\([<>\\w\\d,]*\\)>"); int s = factStr.indexOf("(") + 1; int l = factStr.lastIndexOf(")"); String name = factStr.substring(0,s-1); String params = factStr.substring(s, l); Matcher matcher = propertyPattern.matcher(params); List props = new ArrayList<>(); while(matcher.find()){ String propStr = matcher.group(); props.add(toProp(propStr)); } String[] split = propertyPattern.split(params); boolean truth = Boolean.valueOf(split[split.length-1].replaceAll(",","").trim()); return new Fact(truth,props,name); } ``` Parsing rules is very similar to facts: ``` private static Rule handleRule(String ruleStr) { Pattern propertyPattern = Pattern.compile("<[\\w\\d]*\\([<>\\w\\d,]*\\)>"); String name = ruleStr.substring(0,ruleStr.indexOf('(')); String params = ruleStr.substring(ruleStr.indexOf('(') + 1, ruleStr.lastIndexOf(')')); Matcher matcher = propertyPattern.matcher(params); if(!matcher.find()) throw new IllegalArgumentException(); Property prop1 = toProp(matcher.group()); if(!matcher.find()) throw new IllegalArgumentException(); Property prop2 = toProp(matcher.group()); params = params.replaceAll("<[\\w\\d]*\\([<>\\w\\d,]*\\)>","").toLowerCase(); return new Rule(name,prop1,prop2,params.contains("negative"),params.contains("reversive")); } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I'm afraid I can't make out the exact grammar you are trying to parse from your description, but I understand you are trying to create entity objects from the parsed grammar. The following few demo files demonstrate how to do that using ANTLR-4 and Maven: *pom.xml:* ```xml 4.0.0 com.stackoverflow communicate 0.0.1-SNAPSHOT 3.6.1 1.8 4.5.3 2.5 4.12 src/test/resources com/stackoverflow/test/communicate/resources maven-compiler-plugin ${maven-compiler.version} ${java.version} ${java.version} org.antlr antlr4-maven-plugin ${antlr.version} ${basedir}/src/main/resources ${basedir}/src/main/java/com/stackoverflow/communicate/frontend antlr4 org.antlr antlr4-runtime ${antlr.version} commons-io commons-io ${commons-io.version} junit junit ${junit.version} test ``` *src/main/resources/communicate.g4* ``` grammar communicate; @header { package com.stackoverflow.communicate.frontend; } fact returns [com.stackoverflow.communicate.ir.Property value] : property { $value = $property.value; } ; property returns [com.stackoverflow.communicate.ir.Property value] : STRING '(<' argument { com.stackoverflow.communicate.ir.ArgumentTerm lhs = $argument.value; } '>,<' argument '>)' { $value = new com.stackoverflow.communicate.ir.Property($STRING.text, lhs, $argument.value); } ; argument returns [com.stackoverflow.communicate.ir.ArgumentTerm value] : STRING { $value = new com.stackoverflow.communicate.ir.ArgumentTerm($STRING.text); } ; STRING : [a-zA-Z]+ ; ``` *src/main/java/com/stackoverflow/communicate/ir/ArgumentTerm.java* ```java package com.stackoverflow.communicate.ir; public class ArgumentTerm { public String Value; public ArgumentTerm(String value) { Value=value; } } ``` *src/main/java/com/stackoverflow/communicate/ir/Property.java* ```java package com.stackoverflow.communicate.ir; public class Property { public String Name; public ArgumentTerm Lhs; public ArgumentTerm Rhs; public Property(String name, ArgumentTerm lhs, ArgumentTerm rhs) { Name=name; Lhs=lhs; Rhs=rhs; } } ``` *src/test/resources/frontend/father.txt* ``` parent(,) ``` *src/test/java/com/stackoverflow/test/communicate/frontend/FrontendTest.java* ```java package com.stackoverflow.test.communicate.frontend; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Test; import com.stackoverflow.communicate.frontend.communicateLexer; import com.stackoverflow.communicate.frontend.communicateParser; public class FrontendTest { private String testResource(String path) throws IOException { File file=null; try { file=File.createTempFile("test", ".txt"); try(InputStream is=new BufferedInputStream( FrontendTest.class.getResource(path).openStream()); OutputStream fos=new FileOutputStream(file); OutputStream os=new BufferedOutputStream(fos)) { IOUtils.copy(is, os); } CharStream fileStream=new ANTLRFileStream(file.getAbsolutePath()); communicateLexer lexer=new communicateLexer(fileStream); TokenStream tokenStream=new CommonTokenStream(lexer); communicateParser parser=new communicateParser(tokenStream); ParseTree tree=parser.fact(); return tree.toStringTree(parser); } finally { FileUtils.deleteQuietly(file); } } @Test public void testArgumentTerm() throws IOException { Assert.assertEquals( "(fact (property parent (< (argument John) >,< (argument Jane) >)))", testResource( "/com/stackoverflow/test/communicate/resources/frontend/father.txt")); } } ``` The attached POM file generates the parser classes (*communicateParser*) for the grammar *communicate.g4* if you call *mvn antlr4:antlr4*. *FrontendTest* is a JUnit unit test which parses the content of *father.txt*, which creates a *Property* entity with the name "parent" and containing two argument term objects *John* and *Jane*. A full Eclipse Java project with these files is uploaded here: <https://www.file-upload.net/download-13056434/communicate.zip.html> Upvotes: 2
2018/03/18
1,399
3,562
<issue_start>username_0: How can I replace a NA value by the average of the previous non-NA and next non-NA values? For example, I want to replace the first NA value by -0.873, and the 4th/5th by the average of -0.497+53.200. Thanks! ``` t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) ``` =================== ADD ON =================== Thank you all for answering the question! Sorry for the late response. This is only a part of a dataframe (10000 \* 91) and I only took out the first 10 rows from the first column in order to simplify the question. I think David and MKR have the result that I am expected to have.<issue_comment>username_1: This function imputes values for `NA` in a vector based on the average of the non-`NA` values in a rolling window from the first element to the next element. ``` t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) roll_impute <- function(x){ n <- length(x) res <- x for (i in seq_along(x)){ if (is.na(x[i])){ res[i] <- mean(rep_len(x, i+1), na.rm = TRUE ) } } if (is.na(x[n])) x[n] <- mean(x, na.rm = TRUE) res } roll_impute(t) # [1] -0.87300 -0.87300 -0.49700 -0.68500 17.27667 53.20000 17.27667 17.27667 19.48250 # [10] 26.10000 ``` `roll_impute()` includes code that corrects the rolling window in the case that the final element is `NA`, so that the vector isn't recycled. This isn't the case in your example, but is needed in order to generalize the function. Any improvements on this function would be welcome :) It does use a for loop, but doesn't grow any vectors. No simple way to avoid the for loop and rely on the structure of the objects jumps to my mind right now. Upvotes: 2 <issue_comment>username_2: One `dplyr` and `tidyr` based solution could be: ``` library(dplyr) library(tidyr) t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) data.frame(t) %>% mutate(last_nonNA = ifelse(!is.na(t), t, NA)) %>% mutate(next_nonNA = ifelse(!is.na(t), t, NA)) %>% fill(last_nonNA) %>% fill(next_nonNA, .direction = "up") %>% mutate(t = case_when( !is.na(t) ~ t, !is.na(last_nonNA) & !is.na(next_nonNA) ~ (last_nonNA + next_nonNA)/2, is.na(last_nonNA) ~ next_nonNA, is.na(next_nonNA) ~ last_nonNA ) ) %>% select(t) # t # 1 -0.8730 # 2 -0.8730 # 3 -0.4970 # 4 26.3515 # 5 26.3515 # 6 53.2000 # 7 39.6500 # 8 39.6500 # 9 39.6500 # 10 26.1000 ``` **Note:** It looks a bit complicated but it does the trick. One can achieve same thing via for loop. Upvotes: 1 <issue_comment>username_3: Here's a possible vectorized approach using base R (some steps could be probably improved but I have no time to look into it right now) ``` x <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) # Store a boolean vector of NA locaiotns for firther use na_vals <- is.na(x) # Find the NAs location compaed to the non-NAs start_ind <- findInterval(which(na_vals), which(!na_vals)) # Createa right limit end_ind <- start_ind + 1L # Replace zero locations with NAs start_ind[start_ind == 0L] <- NA_integer_ # Calculate the means and replace the NAs x[na_vals] <- rowMeans(cbind(x[!na_vals][start_ind], x[!na_vals][end_ind]), na.rm = TRUE) x # [1] -0.8730 -0.8730 -0.4970 26.3515 26.3515 53.2000 39.6500 39.6500 39.6500 26.1000 ``` This should work properly for NAs on both sides of the vector. Upvotes: 3 [selected_answer]
2018/03/18
1,138
4,520
<issue_start>username_0: When should I use Clojure's `core.async` library, what kind of applications need that kinda *async* thing? Clojure provides 4 basic mutable models like **refs**, **agents**, **atoms** and **thread locals/vars**. Can't these mutable references provide in any way what `core.async` provides with ease? Could you provide real world use cases for *async programming*? How can I gain an understanding of it so that when I see a problem, it clicks and I say *"This is the place I should apply core.async"*? Also we can use `core.async` in *ClojureScript* which is a single threaded environment, what are the advantages there (besides avoiding callback hell)?<issue_comment>username_1: You may wish to read this: * [Clojure core.async Channels](https://clojure.org/news/2013/06/28/clojure-clore-async-channels) Introductory blog by <NAME> * [Mastering Concurrent Processes with core.async](https://www.braveclojure.com/core-async/) Brave Clojure entry The best use case for core.async is ClojureScript, since it allows you to simulate multi-threaded programming and avoid *Callback Hell*. In JVM Clojure, core.async can also by handy where you want a (lightweight) producer-consumer architecure. Of course, you could always [use native Java queues](https://docs.oracle.com/javase/9/docs/api/java/util/Queue.html) for that, as well. Upvotes: 4 [selected_answer]<issue_comment>username_2: I find it useful for fine-grained, configurable control of side-effect parallelism on the JVM. e.g. If the following executes a read from Cassandra, returning an async/chan: ``` (arche.async/execute connection :key {:values {:id "1"}}) ``` Then the following performs a series of executes in parallel, where that parallelism is configurable, and the results are returned in-order. ``` (async/pipeline-async n-parallelism out #(arche/execute connection :key {:values %1 :channel %2}) (async/to-chan [{:id "1"} {:id "2"} {:id "3"} ... ])) ``` Probably quite particular to my niche, but you get the idea. * <https://github.com/troy-west/arche> Upvotes: 2 <issue_comment>username_3: Core.async provides building blocks for socket like programming which is useful for coordinating producer/consumer interaction in Clojure. Core.async's lightweight threads (go blocks) let you write imperative style code reading from channels instead of using callbacks in the browser. On the JVM, the lightweight threads let you utilize your full CPU threads. You can see an example of a full-stack CLJ/CLJS producer/consumer Core.async chat room here: <https://github.com/briangorman/hablamos> Another killer feature of core.async is the pipeline feature. Often in data processing you will have the initial processing stage take up most of the CPU time, while later stages e.g. reducing will take up significantly less. With the async pipeline feature, you can split up the processing over channels to add parallelization to your pipeline. Core.async channels work with transducers, so channels play nice with the rest of the language now. Upvotes: 2 <issue_comment>username_4: It's important to point out that there are 2 common meanings associated to the word 'async' in programming circles: 1. **asynchronous messaging:** Systems in which components send messages without expecting a response from their consumers, and often without even knowing who the consumers are (via queues) 2. **non-blocking (a.k.a event-driven) I/O:** Programs structured in such a way that they don't block expensive computational resources (threads, cores, ...) while awaiting a response. There are several approches, with varying levels of abstraction, for dealing with such systems: **callback-based APIs** (low-level, difficult to manage because based on side-effects), **Promise/Futures/Deferreds** (representations of values that we don't yet have, more manageable as they are value-based), **Green Threads** ('logical' threads which emulate ordinary control flow, but are inexpensive) `core.async` is very opinionated towards 1 (asynchronous messaging via queues), and provides a macro for implementing Green Threading (the `go` macro). From my experience, if non-blocking is all you need, I would personally recommend starting with [Manifold](https://github.com/ztellman/manifold), which makes fewer assumptions about your use case, then use [core.async](https://github.com/clojure/core.async) for the more advanced use cases where it falls short; note that both libraries interoperate well. Upvotes: 3
2018/03/18
1,114
3,594
<issue_start>username_0: I'm new to C++, and I've been searching all day to find a way to randomly select one of two distinct integers. Everything I've found so far works only for integers within a range (1-10, etc) rather than for (1 **or** 3). For ex. code I've been using elsewhere in the program (for a range of numbers) is ``` int c; int Min = 1; int Max = 3; c = rand() % (Max + 1 - Min) + Min; ``` which returns a random integer within the range, rather than one or the other integers given.<issue_comment>username_1: First of all you shouldn't use C random in C++. Use C++ random. The way to chose from a set of elements is to randomly generate an index. You can wrap the logic in a class: ``` #include #include #include #include class Random\_choice { std::random\_device rd\_{}; public: template auto get\_choice(std::initializer\_list elements) -> T { std::uniform\_int\_distribution dist{0, elements.size() - 1}; std::size\_t i = dist(rd\_); return \*(elements.begin() + i); } }; int main() { Random\_choice rc; std::cout << rc.get\_choice({3, 5}) << std::endl; } ``` Or without the abstraction: ``` #include #include #include int main() { std::vector choices = {3, 5}; std::random\_device rd; std::mt19937 e{rd()}; std::uniform\_int\_distribution dist{0, choices.size() - 1}; std::size\_t i = dist(e); std::cout << choices[i] << std::endl; } ``` Upvotes: 2 <issue_comment>username_2: If you have a range of numbers that you don't want numbersin, then you have *two* ranges that you *do* want numbers in. For example, if your range is 1 to 3 (inclusive) then the two ranges you do want numbers in are -∞ to 0, and 4 to ∞. Infinity is a little tricky on computers, but can easily be emulated for example by [`std::numeric_limits`](http://en.cppreference.com/w/cpp/types/numeric_limits) to get the min and max for the wanted type. So in your case you want a random number in the range `std::numeric_limits::min()` to `0`, and `4` to `std::numeric_limits::max()`. Two get two random numbers from a random choice of either range, first pick (randomly) one range, and get a number from that. Then again (randomly) pick a range and get the second number from that. Upvotes: 1 <issue_comment>username_3: Randomly choosing one of two integers, a or b: ``` c = (rand() % 2) ? a : b ``` Randomly choosing an integer from a list of integers: ``` std::vector numbers; c = numbers.at(rand() % numbers.size()); ``` Randomly choosing an integer from two intervals [a, b) and [c, d): ``` H = (b-a); L = (b-a) + (d-c); k = rand() % L; c = (k < H) ? (a + k) : (c + (k - H)); ``` In case you do C++11 then you may definitely have look into [pseudo-random numer generation](http://en.cppreference.com/w/cpp/numeric/random), like [discrete\_distribution](http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution) and [uniform\_int\_distribution](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution). *Update.* Removed the claim that we would choose uniformly from the given set. Since rand() chooses from [0, RAND\_MAX], this is only true if the divisor of the above modulo operations divides (RAND\_MAX+1). (Which is true for the first example in most implementations where RAND\_MAX is 32767 or another power-of-two minus 1.) However, the defect from being uniform is roughly of the order of divisor/RAND\_MAX. Nevertheless, C++11 [uniform\_int\_distribution](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) is recommended instead. Thanks, <NAME>. Upvotes: 2 [selected_answer]
2018/03/18
850
3,086
<issue_start>username_0: I have a JavaScript that updates a html every couple of seconds based on the return value from an ajax call. I'd like to add a nice effect on the so that whenever the html inside changes, the background of the changes to some other color for a second and then change back. It is similar to how Yahoo Finance page shows the current price of a stock. - eg <https://finance.yahoo.com/quote/BABA?p=BABA> How would I achieve something like this, preferably using CSS? So far, I've tried the following. ``` setInterval(function () { $("#bid").html(Math.random()).addClass('textColor').delay(1000).removeClass('textColor'); }, 1000); ``` And CSS ``` .textColor { background-color: coral; } ``` And HTML ``` ``` It looks like the effect is too fast, so the color change is not even visible. <https://jsfiddle.net/yn5gq1wd/1/> Update: ------- Here is the latest jsfiddle <https://jsfiddle.net/yn5gq1wd/19/><issue_comment>username_1: You can achieve this behavior in 3 steps: **1. create one css animation keyframe** ``` @keyframes color-key-frame { from {color: black;} to {color: red;} } ``` **2. create one css class that is playing the animation ones** ``` .color-animation { animation-name: color-key-frame ; animation-duration: 1s; } ``` **3. add the 'color-animation' class to the desired HTML node when your ajax call is finished** ``` //inside your ajax callBack var node = document.getElementById('idOfyourNode'); //remove prev adjusted class first if(node.classList.contains('color-animation')){ node.classList.remove('color-animation'); } //hack to skip one tick setTimout(setTimeout(function(){ node.classList.add('color-animation'); },0); ``` Upvotes: 0 <issue_comment>username_2: Use MutationObserver: ```js const element = document.getElementById('spy-on-me'); setInterval(function () { // This is just to show how it works element.innerHTML = element.innerHTML + element.innerHTML; }, 3000); const observer = new MutationObserver( function (mutations) { mutations.forEach(function (mutation) { if (mutation.type = 'childList') { element.style.backgroundColor = 'lightgreen'; setTimeout(function () { element.style.backgroundColor = 'white'; }, 200); } }); }); const config = { childList: true }; observer.observe(element, config); ``` ```html some text ``` Upvotes: 1 <issue_comment>username_3: Create a css class that has the background color you want to change it to. When the html in the paragraph changes, add the css class to the paragraph and then use the setTimeout() method to remove the class after a set time (in milliseconds). Here is an example of using setTimeout to add and remove the class on clicking the paragraph. You just need to replace the click event with some other event to fire the code. ``` $("#bid").click(function() { $("#bid").addClass('textColor'); setTimeout(function() { $("#bid").removeClass('textColor'); }, 1000); }) ``` Upvotes: 4 [selected_answer]
2018/03/18
1,375
3,956
<issue_start>username_0: Attempting to get the body fixed conditions of planets, RA, DEC, PM, using the NASA example at. <ftp://naif.jpl.nasa.gov/pub/naif/toolkit_docs/FORTRAN/spicelib/tipbod.html> TIPBOD is used to transform a position in J2000 inertial coordinates to a state in bodyfixed coordinates. TIPM = TIPBOD ('J2000', BODY, ET) Then convert position, the first three elements of STATE, to bodyfixed coordinates. What is STATE? BDPOS = MXVG( TIPM, POSTN) My code: ``` Targ = 399 (Earth) et = spice.str2et(indate) TIPM = spice.tipbod( "J2000", Targ, et ) BDPOS = spice.mxvg(TIPM, POSTN, BDPOS ) ``` but what is POSTN and what is BDPOS?<issue_comment>username_1: You can get a bit more detail about the inputs to the spiceypy functions by searching for the relevant function [here](http://spiceypy.readthedocs.io/en/master/documentation.html). In your particular case `TIPM` will be a 3x3 2D matrix that provides the transformation between an object in the inertial frame and a body fixed frame. The required inputs to the `mxvg` function are given [here](http://spiceypy.readthedocs.io/en/master/documentation.html?highlight=mxvg#spiceypy.spiceypy.mxvg). In your case `POSTN` should be a list (or numpy array) of 3 values giving the x, y, and z positions of the body you're interested in. `BODPOS` will be the output of `mxvg`, which will be the matrix `TIPM` multiplied by the vector `POSTN`, so will be a vector containing three values: the transformed x, y, and z positions of the body. I'm not entirely sure what you require, but an example might be: ``` from astropy.time import Time from spiceypy import spiceypy as spice # create a time t = Time('2010-03-19 11:09:00', format='iso') # put in spice format - this may require a leap seconds kernel to be # downloaded, e.g. download https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/naif0012.tls # and then load it with spice.furnsh('naif0012.tls') et = spice.str2et(t.iso) # get the transformation matrix - this may require a kernel to be # downloaded, e.g. download https://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/pck00010.tpc # and then load it with spice.furnsh('pck00010.tpc') target = 399 # Earth TIPM = spice.tipbod( "J2000", target, et ) # get the position that you want to convert from astropy.coordinates import Angle, ICRS ra = Angle('12:32:12.23', unit='hourangle') dec= Angle('-01:23:52.21', unit='deg') # make an ICRS object (you can also input a proper motion as a radial velocity or using 'pm_dec' and 'pm_ra_cosdec' keyword arguments) sc = ICRS(ra=ra, dec=dec) # get position in xyz xyz = sc.cartesian.xyz.value # perform conversion to body centred frame newpos = spice.mxvg(TIPM, xyz, 3, 3) # convert to latitude and longitude scnew = SkyCoord(x=newpos[0], y=newpos[1], z=newpos[2], representation_type='cartesian') # print out new RA and dec print(scnew.spherical.lon, scnew.spherical.lat) ``` There are probably ways of doing this entirely within astropy, either with a predefined frame or by definition your own, and using the `transform_to()` method of the [`ICRS`](http://docs.astropy.org/en/v2.0.x/api/astropy.coordinates.ICRS.html#astropy.coordinates.ICRS) object. For example, you could convert from ICRS to [GCRS](http://docs.astropy.org/en/stable/api/astropy.coordinates.GCRS.html#astropy.coordinates.GCRS). Upvotes: 3 [selected_answer]<issue_comment>username_2: Thanks Matt, looks like tipbod and reclat works. Tell me if I wrong, but the numbers look ok. ``` #Saturn Tilt Negative rotation Targ = 699 TIPM = spice.tipbod( "J2000", Targ, et ) #Rotation Radius, Long, lat = spice.reclat(TIPM[0]) fy = r2d * Long if fy < 0.0: fy = fy + 360.0 #if degrees/radians are negative, add 360 #print 'X Longitude = ' +str(fy) #Tilt Radius, Long, lat = spice.reclat(TIPM[1]) fy = r2d * Long if fy < 0.0: fy = fy + 360.0 #print 'Y Longitude = ' +str(fy) ``` Upvotes: 0
2018/03/18
402
1,563
<issue_start>username_0: We have images table with following columns:- 1) imageId, 2) productId, 3)isApproved [flag 1/0]. One product can have multiple images. We have stored procedure that has to return all approved images of a particular productId + count of all images (approved/non-approved) of that productId. ``` select * from images where isApproved=1 where productId = {user_entered_id}; select count(*) from images where productId = {user_entered_id}; ``` Is there any better way to get this 2 information from images table in just 1 query? It's a huge table and we want to minimize the SQL queries as much as possible. One workaround is- to modify query1 and return all images to application server and filter isApproved=1 images there BUT it returns back isApproved=0 images to the application server which is unnecessary and risky. Any better way?<issue_comment>username_1: There is a way of doing it. But the count will be repeated several times (depending on the number of instances with product id as "user-input"). ``` SELECT imageId, count from Images NATURAL JOIN (SELECT productId, count(*) as count from images where isApproved=1 GROUP BY productId HAVING productId = ) WHERE productId = ; ``` The GROUP BY clause can be skipped however. Hope this helps. Upvotes: 0 <issue_comment>username_2: You could aggregate the values: ``` select group_concat(case when isApproved = 1 then image_id end) as approved_image_ids, count(*) as num_images from images i where productId = {user_entered_id}; ``` Upvotes: 2 [selected_answer]
2018/03/18
1,025
4,074
<issue_start>username_0: I'm using the WooCommerce REST API to e.g. get all products with variations, but I encounter a fairly large problem regarding the number of fired requests. I need help optimizing the situation below. Situation: A webshop with 50 products and 5 variations for each product. 1. Get all master products (~1 request) 2. Get all variations for each product (50 requests) Total count of request = 51 How can I do this without firing of 51 requests? Is't possible to get all products with their variations eager loaded somehow?<issue_comment>username_1: Yes, you can do it by customizing the WooCommerce Product REST API Response. Here I have attached some code that will help you. ``` add_filter('woocommerce_rest_prepare_product_object', 'custom_change_product_response', 20, 3); add_filter('woocommerce_rest_prepare_product_variation_object', 'custom_change_product_response', 20, 3); function custom_change_product_response($response, $object, $request) { $variations = $response->data['variations']; $variations_res = array(); $variations_array = array(); if (!empty($variations) && is_array($variations)) { foreach ($variations as $variation) { $variation_id = $variation; $variation = new WC_Product_Variation($variation_id); $variations_res['id'] = $variation_id; $variations_res['on_sale'] = $variation->is_on_sale(); $variations_res['regular_price'] = (float)$variation->get_regular_price(); $variations_res['sale_price'] = (float)$variation->get_sale_price(); $variations_res['sku'] = $variation->get_sku(); $variations_res['quantity'] = $variation->get_stock_quantity(); if ($variations_res['quantity'] == null) { $variations_res['quantity'] = ''; } $variations_res['stock'] = $variation->get_stock_quantity(); $attributes = array(); // variation attributes foreach ( $variation->get_variation_attributes() as $attribute_name => $attribute ) { // taxonomy-based attributes are prefixed with `pa_`, otherwise simply `attribute_` $attributes[] = array( 'name' => wc_attribute_label( str_replace( 'attribute_', '', $attribute_name ), $variation ), 'slug' => str_replace( 'attribute_', '', wc_attribute_taxonomy_slug( $attribute_name ) ), 'option' => $attribute, ); } $variations_res['attributes'] = $attributes; $variations_array[] = $variations_res; } } $response->data['product_variations'] = $variations_array; return $response; } ``` I have done by this way. I have got all variations in the single parameter `product_variations`. Upvotes: 4 <issue_comment>username_2: You can get product variations all in 1 request making ``` GET /products//variations/ ``` then iterate over the results to find the matching one and retrieve the id Upvotes: -1 <issue_comment>username_3: Unfortunately this is not possible with their "new" API without having access to the server. So third party companies developing tools for their customers who run WooCommerce are screwed. The problem of having to make a request per variation is not the only issue. Counting products is also impossible. We now have to load the data of all products just to count them... If a customer has 10,000 products in their store and 3 variations for each we have to make 30K+ individual requests... (instead of a couple dozen, one per page). Personally since this is totally impractical, and is most likely to get us blacklisted by some firewall, I decided to use the old API: <https://woocommerce.github.io/woocommerce-rest-api-docs/v3.html#view-products-count> Instead of the "new" one: <https://woocommerce.github.io/woocommerce-rest-api-docs/> When will the old API be completely removed from WooCommerce? I have no idea but there is no other realistic option anyway. Upvotes: 2
2018/03/18
144
370
<issue_start>username_0: **intput**: iprange1, iprange2 iprange3 iprange4 **output**: iprange1 iprange2 iprange3 iprange4 I have no clue how to do that.<issue_comment>username_1: ``` sed 's/,[[:space:]]*/\n/g' file ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: replaces ", " with 2 empty rows. ``` awk '{sub(/, /,"\n\n")}1' file ``` Upvotes: 0
2018/03/18
823
3,591
<issue_start>username_0: For some reason when receiving data from fire base real time database, no matter which account I log into or whatever the database will always return "points" as 0, even when the value store in the database is not zero. The Uid is definitely correct as I checked that.I do not understand why and I have been trying to fix this problem for a while now.The code has worked in different activities and nothing has changed. [![This is the Data that is store in the fire base database](https://i.stack.imgur.com/fLfov.png)](https://i.stack.imgur.com/fLfov.png) ``` databaseUsers =FirebaseDatabase.getInstance().getReference("Users"); final FirebaseAuth firebaseAuth; firebaseAuth = FirebaseAuth.getInstance(); user = firebaseAuth.getCurrentUser(); databaseUsers.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { points = dataSnapshot.child(user.getUid()).child("points").getValue(int.class); } @Override public void onCancelled(DatabaseError databaseError) { } }); //Getting Total Points from Firebase Database databaseUsers.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { totalpoints = dataSnapshot.child(user.getUid()).child("totalpoints").getValue(int.class); } @Override public void onCancelled(DatabaseError databaseError) { } }); ```<issue_comment>username_1: To solve this, please use the following code: ``` String uid = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference uidRef = rootRef.child("Users").child(uid); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { long points = dataSnapshot.child("points").getValue(Long.class); Log.d("TAG", points + ""); } @Override public void onCancelled(DatabaseError databaseError) {} }; uidRef.addListenerForSingleValueEvent(valueEventListener); ``` Don't also forget to set your security rules like this: ``` { "rules": { ".read": "auth != null", ".write": "auth != null" } } ``` So only authenticated users can read or write data to your database. Upvotes: 2 [selected_answer]<issue_comment>username_2: The Solution that I found was to move the section of the code that displayed "points" in a text view to inside the "onDataChange" subroutine. ``` DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference uidRef = rootRef.child("Users").child(uid); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Integer value = dataSnapshot.child("points").getValue(Integer.class); if (value != null) { points = value; } else { points = 0; } value = dataSnapshot.child("totalpoints").getValue(Integer.class); if (value != null) { totalpoints = value; } else { totalpoints = 0; } txtpoints.setText("Points: "+ points); } @Override public void onCancelled(DatabaseError databaseError) { Log.d("my tag","data Snapshot Cancelled"); } }; uidRef.addListenerForSingleValueEvent(valueEventListener); ``` Upvotes: 0
2018/03/18
993
3,431
<issue_start>username_0: I have an Android App that converts text to voice. each word/string on the array is a button that when selected it converts to voice. I am looking to implement this in Flutter. ``` private TextToSpeech tts; ``` GridView grid; ``` String[] words = { "Flutter", "Dart", "React, "Java" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tts =new TextToSpeech(this, this); setContentView(R.layout.activity_main); grid = (GridView) findViewById(R.id.grid); ``` Can anyone provide a solution in Dart/Flutter? Thank you.<issue_comment>username_1: You may find the `tts` package for Flutter useful: <https://pub.dartlang.org/packages/tts> Here is the simple example ``` import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(new Scaffold( body: new Center( child: new RaisedButton( onPressed: speak, child: new Text('Say Hello'), ), ), )); } speak() async { Tts.speak('Hello World'); } ``` While you may find a more in-depth example here: <https://pub.dartlang.org/packages/tts#-example-tab-> As for wiring this all together: > > Can anyone provide a solution in Dart/Flutter? > > > Here is a simple example using a list to render buttons for each String in the list along with the `onPressed` actions to `speak` the words: ``` @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("The App"), ), body: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: _buildWords(), ), ), ); } List words = ['hello', 'world', 'flutter', 'is', 'awesome']; List \_buildWords() { return words.map((String word) { return new RaisedButton( child: new Text(word), onPressed: () => Tts.speak(word), ); }).toList(); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can not use tts package as it is INCOMPATIBLE with Dart 2.0: go for "flutter\_tts " as it's working with Dart 2.0 <https://pub.dartlang.org/packages/flutter_tts> ``` FlutterTts flutterTts = new FlutterTts(); Future _speak() async{ var result = await flutterTts.speak("Hello World"); if (result == 1) setState(() => ttsState = TtsState.playing); } Future _stop() async{ var result = await flutterTts.stop(); if (result == 1) setState(() => ttsState = TtsState.stopped); } List languages = await flutterTts.getLanguages; await flutterTts.setLanguage("en-US"); await flutterTts.setSpeechRate(1.0); await flutterTts.setVolume(1.0); await flutterTts.setPitch(1.0); await flutterTts.isLanguageAvailable("en-US"); ``` Upvotes: 2 <issue_comment>username_3: ''' import 'package:flutter\_tts/flutter\_tts.dart';''' ``` Future _speak(String text) async{ var result = await flutterTts.speak(text); if (result == 1) setState(() => ttsState = TtsState.playing); } ``` ''' you can adjust the time duration if your list is large''' The function I used: ``` Future.forEach (YOUR_LIST,(ITEM_IN_LIST) => new Future.delayed(new Duration(seconds: 2), () { /// YOUR FUNCTION for speak _speak("$ITEM_IN_LIST"); }).then(print)).then(print).catchError(print); ``` Upvotes: 0
2018/03/18
993
3,410
<issue_start>username_0: I'm having an issue with a selection box. When I select the option I can't get the value that I just selected. I read a lot of answers, but none of them seems to work for me. Here is my code. HTML: ``` Choose an option {{selectedType}} ``` Controller: ``` elements:[ { desc: "example1", article: "OF", type: "example1Type" }, { desc: "example2", article: "P-8955625", type: "example2Type" } ]; $scope.selectedType = ""; ``` The `{{selectedType}}` shows nothing. Thanks in advance<issue_comment>username_1: You may find the `tts` package for Flutter useful: <https://pub.dartlang.org/packages/tts> Here is the simple example ``` import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(new Scaffold( body: new Center( child: new RaisedButton( onPressed: speak, child: new Text('Say Hello'), ), ), )); } speak() async { Tts.speak('Hello World'); } ``` While you may find a more in-depth example here: <https://pub.dartlang.org/packages/tts#-example-tab-> As for wiring this all together: > > Can anyone provide a solution in Dart/Flutter? > > > Here is a simple example using a list to render buttons for each String in the list along with the `onPressed` actions to `speak` the words: ``` @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("The App"), ), body: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: _buildWords(), ), ), ); } List words = ['hello', 'world', 'flutter', 'is', 'awesome']; List \_buildWords() { return words.map((String word) { return new RaisedButton( child: new Text(word), onPressed: () => Tts.speak(word), ); }).toList(); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can not use tts package as it is INCOMPATIBLE with Dart 2.0: go for "flutter\_tts " as it's working with Dart 2.0 <https://pub.dartlang.org/packages/flutter_tts> ``` FlutterTts flutterTts = new FlutterTts(); Future _speak() async{ var result = await flutterTts.speak("Hello World"); if (result == 1) setState(() => ttsState = TtsState.playing); } Future _stop() async{ var result = await flutterTts.stop(); if (result == 1) setState(() => ttsState = TtsState.stopped); } List languages = await flutterTts.getLanguages; await flutterTts.setLanguage("en-US"); await flutterTts.setSpeechRate(1.0); await flutterTts.setVolume(1.0); await flutterTts.setPitch(1.0); await flutterTts.isLanguageAvailable("en-US"); ``` Upvotes: 2 <issue_comment>username_3: ''' import 'package:flutter\_tts/flutter\_tts.dart';''' ``` Future _speak(String text) async{ var result = await flutterTts.speak(text); if (result == 1) setState(() => ttsState = TtsState.playing); } ``` ''' you can adjust the time duration if your list is large''' The function I used: ``` Future.forEach (YOUR_LIST,(ITEM_IN_LIST) => new Future.delayed(new Duration(seconds: 2), () { /// YOUR FUNCTION for speak _speak("$ITEM_IN_LIST"); }).then(print)).then(print).catchError(print); ``` Upvotes: 0
2018/03/18
646
2,226
<issue_start>username_0: I try the instance query as below to convert a commas separated list into multiple records and I found the cte table 'tmp' can run on its own until all sub-strings were loaded in a new record. This example query is from this [thread](https://stackoverflow.com/questions/5493510/turning-a-comma-separated-string-into-individual-rows). I don't want to focus on this functionality but the use of the temporary table here. Can anyone please advise what term is used in T-SQL to describe this computing techniques for the cte table? The cte table is recalled by itself in the definition statements and without explicit looping statements the table actually run iteratively until the filter statement `where Data > ''` return NULL. ``` create table Testdata(SomeID int, OtherID int, Data varchar(max)) insert Testdata select 1, 9, '18,20,22,25,26' insert Testdata select 2, 8, '17,19' insert Testdata select 3, 7, '13,19,20' insert Testdata select 4, 6, '' ;with tmp(SomeID, OtherID, DataItem, Data) as ( select SomeID, OtherID, LEFT(Data, CHARINDEX(',',Data+',')-1), STUFF(Data, 1, CHARINDEX(',',Data+','), '') from Testdata union all select SomeID, OtherID, LEFT(Data, CHARINDEX(',',Data+',')-1), STUFF(Data, 1, CHARINDEX(',',Data+','), '') from tmp where Data > '' ) select SomeID, OtherID, DataItem from tmp order by SomeID ```<issue_comment>username_1: After a quick research, I found a term 'Recursive Common Table Expressions' which should fit this topic. Any other advice is more than welcome. Upvotes: 0 <issue_comment>username_2: You are correct, the term is Recursive Common Table Expression, AKA rCTE. See: <https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx> A couple things to note: First, for most things in T-SQL, rCTEs are slow and generate a lot of IO. For splitting (AKA tokenizing) a delimited string they are a poor choice. rCTEs are good for handling hierarchal data which is why, if you do a Google search for Recursive CTE, the most common example will be how to traverse a hierarchical employee table or the like. A great article about rCTEs and what they are good for can be found here: <http://www.sqlservercentral.com/articles/T-SQL/90955/> Upvotes: 1
2018/03/18
1,250
5,264
<issue_start>username_0: I have a data table in which rows are added based on data available on the internet. Each time I add a row, I also put a timestamp on the row. This has been working for a number of years, with hundreds of users with no errors occurring. I now wish to delete rows from the data table based on the age of the data. I have a timer that fires every user defined interval and then I search for all rows that are older and I delete them. The problem is, that I am receiving various errors that seem to change and even though I have try catch statements on all methods, the errors are not caught. The error is caught only on an error catch on the whole application in program.cs The errors are "Exit error: Object reference not set to an instance of an object. at System.Windows.Forms.DataGridViewCell.PaintWork, or Exit error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get\_Item(Int32 index) or Exit error: Object reference not set to an instance of an object. at System.Windows.Forms.DataGridViewTextBoxCell.PaintPrivate but there is no useful information in the rest of the errors. Here is the code: ``` public void ageTimer_Elapsed(object source, System.Timers.ElapsedEventArgs e) { try { spotAge = Convert.ToDouble(Properties.Settings.Default.SpotAge); //Select all rows in datatable where the age is older than spotAge and delete them. //date is stored in dt as 20:12:2017: 21:49:02 derived from DateTime.UtcNow.ToString("dd:MM:yyyy: HH:mm:ss") //spotTime is the time from the table DateTime spotTime; dt.AcceptChanges(); var rowCount = dt.Rows.Count; for (int i = rowCount -1; i >= 0; i--) { DataRow dr = dt.Rows[i]; spotTime = DateTime.ParseExact(Convert.ToString(dr["date"]), "dd:MM:yyyy: HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); if (spotTime.AddMinutes(spotAge) <= DateTime.UtcNow) { dr.Delete(); } } dt.AcceptChanges(); dataGridView1.Update(); dataGridView1.Refresh(); dataGridView1.FirstDisplayedScrollingRowIndex = 0; } catch (Exception x) { } } ``` Now the interesting thing is that on my system this will not crash at all ever. However, if I run visual studio in debug mode it will. It will also crash on a small number of users as well. But not everyone. I tried the same code except I always will delete only one row and it works perfectly fine. I tried deleting every row except for the first, the first two and it still crashes. Based on the comment below which pointed out that the timer was running on a separate thread, I added the following: ``` public void ageTimer_Elapsed(object source, System.Timers.ElapsedEventArgs e) { DeleteRows(""); } ``` and the above code now now has the following: ``` private void DeleteRows(string details) { if (InvokeRequired) { this.Invoke(new Action(DeleteRows), new object[] { details}); return; } ``` and the rest of the code is as above. This solves the issue completely. Many thanks!<issue_comment>username_1: The problem over here is, that you´r calling the delete row.delete statement inside your for loop. This is manipulating the length of your row collection thus you get the index out of bound exception. One quote from msdn: > > Delete should not be called in a foreach loop while iterating through a DataRowCollection object. Delete modifies the state of the collection. > > > Upvotes: 0 <issue_comment>username_2: Just read your question again. This was working for years. Now it's not working, cause you added timer, running in a new, separate thread. This might be a race condition. Obviously, dt is a shared resource which is not properly used in a multithreaded environment. Assuming `dt` is source of your data grid view, in one situation, user might be doing something with it (just scrolling would be enough to read from dt in order to paint newly visible rows - thus, I suppose you get the PaintWork error from there, as the state was changed in the mean time by a timer event handler). Imagine user deletes row from the grid, that reflects to the underlying source `dt`, but, your timer just happened to delete those rows just a moment ago and you get index out of range exception. Instead of working with `dt` in your timer event handler, can you try and make a copy of it `dt_copy` (just pay attention not to make a shallow copy). Make your changes, and once you're done, just bind that copy as a new source of datagridview and all should be good. Another approach, which also might perform faster would be to call stored procedure and do deletion by database directly and just refresh your `dt` once that call returns (just repopulate `dt`). In both cases, depending how fast deletion is, you should check if 'dt' is dirty (updated by a user in the mean time) and might want to merge those changes so they are not lost. Upvotes: 2 [selected_answer]
2018/03/18
468
1,228
<issue_start>username_0: Hi i was just wondering if someone can explain to me how the following php code evaluates to 5 ``` php $a = 12 ^ 9; echo $a; ? ``` so I know the output will be 5, but can someone explain to me how this works?<issue_comment>username_1: As far as I understand the process, php converts the numbers into binary and performs an XOR operation on them. ``` 12 -> 1100 9 -> 1001 1100 XOR 1001 = 0101 = 5. ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` 12 = 1100 09 = 1001 Xor = 0101 = 5 ``` Exclusive or means only 1 bit at the same position to be high. Upvotes: 1 <issue_comment>username_3: The `^` operator as you say is bitwise, so it converts the integer to a binary value. `12` is `00001100` in binary. `9` is `00001001` in binary. ``` A: 00001100 12 XOR(^) B: 00001001 9 --------- Output: 00000101 5 ``` It is simply `1` if **only** one of the inputs is `1`, here is the truth table for XOR: ``` +---+---+--------+ | A | B | Output | +---+---+--------+ | 0 | 0 | 0 | +---+---+--------+ | 0 | 1 | 1 | +---+---+--------+ | 1 | 0 | 1 | +---+---+--------+ | 1 | 1 | 0 | +---+---+--------+ ``` Upvotes: 2
2018/03/18
997
3,101
<issue_start>username_0: I have 10 objects here, but I have to intiliaze 20 more, is there a shorter way to do it? ``` Gallina[] gallina=new Gallina[10]; gato[0]=new Gato(true, "Siames", "Fluffy", 10); gato[1]=new Gato(false, "Persa", "Fluffy", 11); gato[2]=new Gato(true, "<NAME>", "Fluffy", 9); gato[3]=new Gato(false, "Ragdoll", "Fluffy", 4); gato[4]=new Gato(false, "Bengala", "Fluffy", 1); gato[5]=new Gato(true, "Sphynx", "Fluffy", 6); gato[6]=new Gato(true, "Abisinio", "Fluffy", 3); gato[7]=new Gato(false, "Azulruso", "Fluffy", 9); gato[8]=new Gato(true, "Siberiano", "Fluffy", 2); gato[9]=new Gato(true, "Siames", "Fluffy", 4); ```<issue_comment>username_1: You can avoid all the assignments, but I'm afraid it's not going to be much shorter: ``` Gato[] gato = new Gato[] { new Gato(true, "Siames", "Fluffy", 10), new Gato(false, "Persa", "Fluffy", 11), ... }; ``` This has two slight advantages over your technique: * You cannot skip and/or overwrite an item by mixing up your indexes, and * Java compiler will size your array according to the number of items that you put in it. Obviously, this assumes that the array gets fully populated during initialization. Upvotes: 3 <issue_comment>username_2: ``` class Gallina { private int gatoIndex = 0; private Gato[] gatos; public Gallina(int gatosLength) { gatos = new Gato[gatosLength]; } public void addGato(boolean state, String name, String type, int value) { if (gatoIndex > gatos.length) { // an exception probably or resize array } gatos[gatoIndex] = new Gato(state, name, type, value); gatoIndex += 1; } } class Test { public static void main(String[] args) { Gallina gallina = new Gallina(10); gallina.addGato(true, "ABC", "Fluffy", 10); } } ``` Using a `List` instead of `Gato[]` will help you get rid of `gatoIndex` and resizing the array yourself. Basically with the above, you won't need to write the same `new Gato()` boilerplate everytime. Upvotes: 1 [selected_answer]<issue_comment>username_3: Consider using static factory methods instead of constructors. It gives you some advantages: * Static factory methods have names * Static factory methods are not required to create a new object each time they're invoked * Static factory methods can return an object of any subtype of their return type Implementation ``` class Gato { private boolean field1; private String field2; private String field3; private int field4; private Gato (boolean field1, String field2, String field3, int field4) { this.field1 = field1; this.field2 = field2; this.field3 = field3; this.field4 = field4; } public static Gato newInstance (boolean field1, String field2, String field3, int field4) { return new Gato(field1, field2, field3, field4); } ``` So in your method you will use that implementation ``` gato[0] = Gato.newInstance(true, "Siames", "Fluffy", 10); ``` Upvotes: 0
2018/03/18
394
1,470
<issue_start>username_0: While in XML resources I can use a system reference style color like this (*just an example*): ``` android:textColor="?android:itemTextColor"> ``` I would like to know how to get that color in java programmatically, when I need to set that color like this (*unrelated another example*): ``` button.setBackgroundColor(myColor); ``` How can I set `myColor` to be `?android:itemTextColor` ?<issue_comment>username_1: Does something like this help? ``` TypedValue typedValue = new TypedValue(); getTheme().resolveAttribute(R.attr.textColorHint, typedValue, true); button.setBackgroundColor(typedValue.data); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: What you're seeing there is an attribute, it's a reference for a resource (not necessarily a color). An attributes is resolved by a `Theme`, this means that the same attributes can be resolved to different values according to the `Theme` by which are resolved. If you are in an `Acitivity` you can (and probably should) use the `Activity`'s theme ``` val typedValue = TypedValue() val found = theme.resolveAttribute(android.R.attr.textColorHint,typedValue, true) ``` After that you should check the type of the value you've resolved ``` when(typedValue.type){ TypedValue.TYPE_INT_COLOR_ARGB8 -> ... TypedValue.TYPE_INT_COLOR_ARGB4 -> ... ... } ``` And then you could (eventually) use the value of the color which is stored in `typedValue.data` Upvotes: 1
2018/03/18
928
3,171
<issue_start>username_0: I want to check if string one in array contain the letters from words in string 2. Here's my example array: `(["Floor", "far"]);` function should return false because "a" is not in string "Floor" But for array like this: `(["Newbie", "web"]);` It should return true because all of letters from "web" are in "Newbie". Here's my code so far... ``` function mutation(arr) { var newArr = []; for (i=0; i ``` I know that it won't work and I'm out of ideas how to make it. I try to make a set of all letters in two array and compare them. If there is at least one *false* the function should return false. Should I nest *indexOf()* method somewhere?<issue_comment>username_1: The cool way would be: ``` const mutation =([one, two]) => (set => [...two.toLowerCase()].every(char => set.has(char)))(new Set(one.toLowerCase())); ``` How it works: At first we destructure the passed array into the first and the second word: ``` [one, two] ``` Now that we got both, we build up a Set of characters from the first word: ``` (set => /*...*/)(new Set(one)) ``` All that in an IIFE cause we need the set here: ``` [...two].every(char => set.has(char)) ``` That spreads the second word in an array, so we got an array of chars and then checks if all characters are part of the set we built up from the other word. Upvotes: 1 <issue_comment>username_2: I think this should work for you. Break up the string of letters to check for into an array. Iterate over the array getting each letter and checking if the string passed in contains the letter, setting our result to false if it doesn't. ``` function mutation(arr) { var charArr = arr[1].toLowerCase().split(""); var result = true; charArr.forEach(element => { if (!arr[0].toLowerCase().includes(element)) { result = false; } }); return result; } console.log(mutation(["Newbie", "web"])); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: If you want to be sure that one word, which might have several repeating letters, is contained in another, use [`Array.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) to count the letters, and store create a [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) of letter -> counts. Do that for both words. Check if all [entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries) of 2nd word are contained in the 1st word map using [`Array.every()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every): ```js const countLetters = (w) => w.toLowerCase() .split('') .reduce((r, l) => r.set(l, (r.get(l) || 0) + 1), new Map()); const mutation = ([a, b]) => { const al = countLetters(a); const bl = countLetters(b); return [...bl].every(([k, v]) => v <= (al.get(k) || 0)); }; console.log(mutation(["Floor", "far"])); // false console.log(mutation(["Floor", "for"])); // true console.log(mutation(["Floor", "foroo"])); // false console.log(mutation(["Newbie", "web"])); // true ``` Upvotes: 1
2018/03/18
1,233
4,205
<issue_start>username_0: I have this function to add clients on a .txt but now i wanna delete one who you puts. I want to go through the array to find the client entered in the "removeClient" function [The full code is here: https://pastebin.com/xaJ61THK](https://pastebin.com/xaJ61THK) The function to add clientes is: ``` void aniadirCliente() { if(clientes[n].dni[0]=='\0'){ printf("\nIntroduce el nombre del archivo: \nNombre por defecto: clientes.txt\n\n"); gets(nom_archivo); fflush(stdin); //Cuando abrimos el fichero le tenemos que poner rw para que podamos escribir y leer. archivo=fopen(nom_archivo,"rw"); if ((archivo = fopen(nom_archivo, "rw")) == NULL) { fprintf(stderr, "\n\nEl archivo no existe."); system("cls"); //En windows limpia pantalla }else { int i; printf("\n\nArchivo cargado correctamente.|\n"); for(i=0; i ``` Function to delete clients. ¿How i can delete all of this client?:clientes[i].dni, clientes[i].nombre, clientes[i].apellido, clientes[i].direccion. ``` void eliminarCliente(){ if(clientes[n].dni[0]=='\0') { printf("\nIntroduce el nombre del archivo: \nNombre por defecto: clientes.txt\n\n"); fflush(stdin); gets(nom_archivo); //Cuando abrimos el fichero le tenemos que poner rw para que podamos escribir y leer. archivo=fopen(nom_archivo,"rw"); if ((archivo = fopen(nom_archivo, "rw")) == NULL) { fprintf(stderr, "\n\nEl archivo no existe."); }else{ int i, y; char delcliente; for(i=0; i ```<issue_comment>username_1: The cool way would be: ``` const mutation =([one, two]) => (set => [...two.toLowerCase()].every(char => set.has(char)))(new Set(one.toLowerCase())); ``` How it works: At first we destructure the passed array into the first and the second word: ``` [one, two] ``` Now that we got both, we build up a Set of characters from the first word: ``` (set => /*...*/)(new Set(one)) ``` All that in an IIFE cause we need the set here: ``` [...two].every(char => set.has(char)) ``` That spreads the second word in an array, so we got an array of chars and then checks if all characters are part of the set we built up from the other word. Upvotes: 1 <issue_comment>username_2: I think this should work for you. Break up the string of letters to check for into an array. Iterate over the array getting each letter and checking if the string passed in contains the letter, setting our result to false if it doesn't. ``` function mutation(arr) { var charArr = arr[1].toLowerCase().split(""); var result = true; charArr.forEach(element => { if (!arr[0].toLowerCase().includes(element)) { result = false; } }); return result; } console.log(mutation(["Newbie", "web"])); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: If you want to be sure that one word, which might have several repeating letters, is contained in another, use [`Array.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) to count the letters, and store create a [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) of letter -> counts. Do that for both words. Check if all [entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries) of 2nd word are contained in the 1st word map using [`Array.every()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every): ```js const countLetters = (w) => w.toLowerCase() .split('') .reduce((r, l) => r.set(l, (r.get(l) || 0) + 1), new Map()); const mutation = ([a, b]) => { const al = countLetters(a); const bl = countLetters(b); return [...bl].every(([k, v]) => v <= (al.get(k) || 0)); }; console.log(mutation(["Floor", "far"])); // false console.log(mutation(["Floor", "for"])); // true console.log(mutation(["Floor", "foroo"])); // false console.log(mutation(["Newbie", "web"])); // true ``` Upvotes: 1
2018/03/18
664
2,346
<issue_start>username_0: I am trying to use this package here without using any bundlers(webpack/browserify). I have already downloaded this package to my project by running `npm install --save mtgsdk`. To use this package in Javascript, I would call `const mtg = require('mtgsdk')`. If I don't want to install/configure webpack, how would I load this package into my project? Note that I am using `Gulp` and `NPM`. My project is an AngularJS project so I am not using `node`. Package I am trying to load: <https://github.com/MagicTheGathering/mtg-sdk-javascript><issue_comment>username_1: You don't need Webpack to use require. Once you've run `npm install`, the package has been downloaded to the `node_modules` folder of your project. You can require the package perfectly fine from any script within your project folder. Node itself will handle finding the package in `node_modules` when you call `require`. Upvotes: 0 <issue_comment>username_2: Quick answer ------------ You can't without using any bundlers like webpack or browserify. Try to use [requireJs](http://requirejs.org/) however It depends on the modules: > > RequireJS does not contain code that will magically make a npm-installed module work in the browser. It ultimately depends on how the modules are structured. > > > To know more about this please check the last section of this [answer](https://stackoverflow.com/a/35409155/6836839) by @Louis ### MTG API > > The Gathering SDK Javascript implementation: It is a wrapper around the MTG API of [magicthegathering.io](https://magicthegathering.io) > > > I don't really see the point of using a `npm` module if you aren't going to use node in your project. As mentioned before the module is just a wrapper for the [`api`](https://docs.magicthegathering.io/) so you can still do an http request usign the api endpoint: ``` https://api.magicthegathering.io// ``` ### Example: client.js > > This call will return a maximum of 100 cards > > > ``` // Get All Cards const api = 'https://api.magicthegathering.io/v1'; fetch(`${api}/cards`).then(res => res.json()) .then(json => console.log(json)); ``` ### Output ``` { cards: [...] } ``` To know more about the api please read the [api-docs](https://docs.magicthegathering.io/#documentationgetting_started) Upvotes: 3 [selected_answer]
2018/03/18
1,340
5,131
<issue_start>username_0: I went back to programming my old program <https://github.com/JonkiPro/REST-Web-Services>. I've updated Spring Boot from version 15.6 to version 2.0.0. I have encountered many problems with compilation, but I can not deal with one. Well, during compilation, he throws me in the console ``` 2018-03-18 21:54:53.339 ERROR 3220 --- [ost-startStop-1] com.zaxxer.hikari.HikariConfig : HikariPool-1 - jdbcUrl is required with driverClassName. 2018-03-18 21:54:55.392 INFO 3220 --- [ost-startStop-1] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'unit' 2018-03-18 21:54:56.698 INFO 3220 --- [ost-startStop-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'unit' 2018-03-18 21:54:56.778 ERROR 3220 --- [ost-startStop-1] com.zaxxer.hikari.HikariConfig : HikariPool-1 - jdbcUrl is required with driverClassName. 2018-03-18 21:54:56.782 ERROR 3220 --- [ost-startStop-1] o.s.b.web.embedded.tomcat.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService' defined in file [C:\Users\Jonatan\Documents\GitHub\REST-Web-Services\web\out\production\classes\com\web\web\security\service\impl\UserDetailsServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#65d6e77b' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#65d6e77b': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory': Post-processing of FactoryBean's singleton object failed; nested exception is java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName. 2018-03-18 21:54:56.821 WARN 3220 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat ``` I've never had such a mistake. I do not know what it means completely. My properties for the base look like this ``` spring: datasource: driver-class-name: org.postgresql.Driver url: jdbc:postgresql:database username: root password: <PASSWORD> schema: classpath:/db/init/schema.sql ``` I do not know how to deal with this error. I've been programming quite a long time, but for the first time I'm meeting the concept of `hikari`. I'm using a Tomcat(in Spring Boot) server and a PostgreSQL database.<issue_comment>username_1: I had the same issue in another context. From the [79. Data Access - Configure a Custom DataSource](https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-configure-a-datasource) > > if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no url property (but does have a jdbcUrl property) > > > Hikari is the default pool in spring boot 2. so you can replace the config `url: jdbc:postgresql:database` -> `jdbc-url: jdbc:postgresql:database` or you can keep the config but you need to define another Bean to handle the mapping (aliases) ``` @Bean @Primary @ConfigurationProperties("app.datasource") public DataSourceProperties dataSourceProperties() { return new DataSourceProperties(); } @Bean @ConfigurationProperties("app.datasource") public DataSource dataSource(DataSourceProperties properties) { return properties.initializeDataSourceBuilder(). .build(); } ``` Upvotes: 5 <issue_comment>username_2: Either remove `spring.datasource.driver-class-name` property or rename the `spring.datasource.url` property to `spring.datasource.jdbc-url`. This is reported in your error: > > java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName > > > First option looks cleaner and Spring Boot will figure out the default driver class name based on the `spring.datasource.url` property value (see `org.springframework.boot.jdbc.DatabaseDriver` class if you want to debug this). Upvotes: 5 <issue_comment>username_3: I've also faced the same issue while configuring two database and below solution resolved my issue. Solution: rename the `spring.datasource.url` property to `spring.datasource.jdbc-url` Upvotes: 1
2018/03/18
533
1,442
<issue_start>username_0: I have a Pandas Dataframe that looks as follows: ``` streak 0 1.0 1 2.0 2 0.0 3 1.0 4 2.0 5 0.0 6 0.0 ``` I want to delete every row after the first `0.0` in the `streak` column. The result should look like this: ``` streak 0 1.0 1 2.0 ```<issue_comment>username_1: Get index of first `0` by [`idxmax`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.idxmax.html) and slice by [`iloc`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html), only need default unique indices: ``` #df = df.reset_index(drop=True) df = df.iloc[:df['streak'].eq(0).idxmax()] print (df) streak 0 1.0 1 2.0 ``` **Detail**: ``` print (df['streak'].eq(0).idxmax()) 2 ``` EDIT: For more general solution is necessary use `numpy` - get position by [`numpy.argmax`](https://docs.scipy.org/doc/numpy-1.9.3/reference/generated/numpy.argmax.html): ``` print (df) streak a 1.0 b 2.0 c 0.0 d 1.0 e 2.0 f 0.0 g 0.0 df = df.iloc[:df['streak'].eq(0).values.argmax()] print (df) streak a 1.0 b 2.0 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This is a generalized solution via `numpy.where`. It will work for matching first instance of any specified value. ``` df = df.iloc[:np.where(df['streak']==0)[0][0]] # streak # 0 1.0 # 1 2.0 ``` Upvotes: 0
2018/03/18
3,131
8,062
<issue_start>username_0: How do I configure Spring Boot Gradle plugin 2 to disable the Boot distribution in Gradle Script Kotlin. The distribution i want is a assembly bundle zip with all dependencies (and the jar) in the lib folder. I have enabled the Jar task and disabled the bootJar task. Current source of my build file <https://github.com/Skatteetaten/mokey/blob/825a81f20c21a2220876a09ebf7f01fe7c61f2fd/build.gradle.kts> Note that the aurora skatteetaten gradle plugin adds the distribution mechanism. <https://github.com/Skatteetaten/aurora-gradle-plugin><issue_comment>username_1: In spring-boot 2, the gradle plugin reconfigures the build to include the boot tar and zip distributions in the uploadArchives task when you apply the application and maven plugins. From what I can tell from your question, you want a single zip-file with all the jar files in it, similar to what the application plugin creates, but want to exclude everything "extra" that the spring boot plugin adds? If that is the case it is a simple matter of telling gradle to do exactly that; ``` apply plugin: 'application' apply plugin: 'maven' jar.enabled = true [bootJar, distTar, bootDistTar, bootDistZip]*.enabled = false configurations.archives.artifacts.removeIf { !it.archiveTask.is(distZip) } ``` This is groovy, but hopefully you are able to apply this in a similar way in your kotlin file. Upvotes: 3 <issue_comment>username_2: When the application plugin is configured, Spring Boot creates an additional distribution that contains the application packages as a fat jar. The default distribution is left intact and you should be able to use it without disabling Boot's distribution. The default distribution relies on the standard `jar` task. This task is disabled by Spring Boot's plugin by default as the assumption is that you will want to use the fat jar produced by `bootJar` instead. When that's not the case, you can re-enable the jar like this: ``` jar { enabled = true } ``` With this change in place, you can run the `distZip` task: ``` $: ./gradlew clean distZip --console=plain :clean :bootBuildInfo :compileJava :processResources :classes :jar :startScripts :distZip BUILD SUCCESSFUL in 1s 7 actionable tasks: 7 executed ``` It will create a zip that packages the application and all of its dependencies as separate jars in the `lib` directory of the distribution. ``` $: unzip -l build/distributions/application-distribution-0.0.1-SNAPSHOT.zip Archive: build/distributions/application-distribution-0.0.1-SNAPSHOT.zip Length Date Time Name --------- ---------- ----- ---- 0 03-19-2018 07:31 application-distribution-0.0.1-SNAPSHOT/ 0 03-19-2018 07:31 application-distribution-0.0.1-SNAPSHOT/lib/ 1860 03-19-2018 07:31 application-distribution-0.0.1-SNAPSHOT/lib/application-distribution-0.0.1-SNAPSHOT.jar 588 03-01-2018 05:24 application-distribution-0.0.1-SNAPSHOT/lib/spring-boot-starter-web-2.0.0.RELEASE.jar 645 03-01-2018 05:24 application-distribution-0.0.1-SNAPSHOT/lib/spring-boot-starter-json-2.0.0.RELEASE.jar 592 03-01-2018 05:23 application-distribution-0.0.1-SNAPSHOT/lib/spring-boot-starter-2.0.0.RELEASE.jar 590 03-01-2018 05:24 application-distribution-0.0.1-SNAPSHOT/lib/spring-boot-starter-tomcat-2.0.0.RELEASE.jar 1117582 01-08-2018 11:43 application-distribution-0.0.1-SNAPSHOT/lib/hibernate-validator-6.0.7.Final.jar 782155 02-19-2018 10:08 application-distribution-0.0.1-SNAPSHOT/lib/spring-webmvc-5.0.4.RELEASE.jar 1244848 02-19-2018 10:08 application-distribution-0.0.1-SNAPSHOT/lib/spring-web-5.0.4.RELEASE.jar 1145432 03-01-2018 05:23 application-distribution-0.0.1-SNAPSHOT/lib/spring-boot-autoconfigure-2.0.0.RELEASE.jar 922427 03-01-2018 05:23 application-distribution-0.0.1-SNAPSHOT/lib/spring-boot-2.0.0.RELEASE.jar 613 03-01-2018 05:23 application-distribution-0.0.1-SNAPSHOT/lib/spring-boot-starter-logging-2.0.0.RELEASE.jar 26586 03-01-2018 05:23 application-distribution-0.0.1-SNAPSHOT/lib/javax.annotation-api-1.3.2.jar 1079064 02-19-2018 10:08 application-distribution-0.0.1-SNAPSHOT/lib/spring-context-5.0.4.RELEASE.jar 360034 02-19-2018 10:08 application-distribution-0.0.1-SNAPSHOT/lib/spring-aop-5.0.4.RELEASE.jar 654022 02-19-2018 10:08 application-distribution-0.0.1-SNAPSHOT/lib/spring-beans-5.0.4.RELEASE.jar 263410 02-19-2018 10:08 application-distribution-0.0.1-SNAPSHOT/lib/spring-expression-5.0.4.RELEASE.jar 1216414 02-19-2018 10:08 application-distribution-0.0.1-SNAPSHOT/lib/spring-core-5.0.4.RELEASE.jar 297518 10-24-2017 03:28 application-distribution-0.0.1-SNAPSHOT/lib/snakeyaml-1.19.jar 33391 01-30-2018 09:16 application-distribution-0.0.1-SNAPSHOT/lib/jackson-datatype-jdk8-2.9.4.jar 98261 01-30-2018 09:16 application-distribution-0.0.1-SNAPSHOT/lib/jackson-datatype-jsr310-2.9.4.jar 8643 01-30-2018 09:16 application-distribution-0.0.1-SNAPSHOT/lib/jackson-module-parameter-names-2.9.4.jar 1345154 01-30-2018 09:16 application-distribution-0.0.1-SNAPSHOT/lib/jackson-databind-2.9.4.jar 257309 02-14-2018 08:07 application-distribution-0.0.1-SNAPSHOT/lib/tomcat-embed-websocket-8.5.28.jar 3109223 02-14-2018 08:07 application-distribution-0.0.1-SNAPSHOT/lib/tomcat-embed-core-8.5.28.jar 240498 02-14-2018 08:07 application-distribution-0.0.1-SNAPSHOT/lib/tomcat-embed-el-8.5.28.jar 93107 01-08-2018 11:43 application-distribution-0.0.1-SNAPSHOT/lib/validation-api-2.0.1.Final.jar 66469 02-20-2018 12:53 application-distribution-0.0.1-SNAPSHOT/lib/jboss-logging-3.3.2.Final.jar 65100 09-19-2017 07:31 application-distribution-0.0.1-SNAPSHOT/lib/classmate-1.3.4.jar 290339 06-16-2017 04:40 application-distribution-0.0.1-SNAPSHOT/lib/logback-classic-1.2.3.jar 17519 11-28-2017 08:42 application-distribution-0.0.1-SNAPSHOT/lib/log4j-to-slf4j-2.10.0.jar 4596 03-27-2017 12:22 application-distribution-0.0.1-SNAPSHOT/lib/jul-to-slf4j-1.7.25.jar 15836 02-19-2018 10:08 application-distribution-0.0.1-SNAPSHOT/lib/spring-jcl-5.0.4.RELEASE.jar 66519 08-03-2017 05:28 application-distribution-0.0.1-SNAPSHOT/lib/jackson-annotations-2.9.0.jar 320923 01-30-2018 09:16 application-distribution-0.0.1-SNAPSHOT/lib/jackson-core-2.9.4.jar 471901 06-16-2017 04:40 application-distribution-0.0.1-SNAPSHOT/lib/logback-core-1.2.3.jar 41203 03-27-2017 12:22 application-distribution-0.0.1-SNAPSHOT/lib/slf4j-api-1.7.25.jar 255485 11-28-2017 08:42 application-distribution-0.0.1-SNAPSHOT/lib/log4j-api-2.10.0.jar 0 03-19-2018 07:31 application-distribution-0.0.1-SNAPSHOT/bin/ 7002 03-19-2018 07:31 application-distribution-0.0.1-SNAPSHOT/bin/application-distribution 4042 03-19-2018 07:31 application-distribution-0.0.1-SNAPSHOT/bin/application-distribution.bat --------- ------- 15926900 42 files ``` Upvotes: 3 <issue_comment>username_3: this work for me (disable spring-boot bootJar task, and enable jar) ``` apply plugin: 'java' bootJar { enabled = false } ``` Upvotes: 2 <issue_comment>username_4: This kotlin DSL version of @username_3 answer works for me (disable spring-boot bootJar task and enable jar task): ``` import org.springframework.boot.gradle.tasks.bundling.BootJar tasks.getByName("bootJar") { enabled = false } tasks.getByName("jar") { enabled = true } ``` Upvotes: 4 <issue_comment>username_5: spring boot 2.x My project is multi-module, each module can execute jar root build.gradle ``` subprojects{ apply plugin: 'idea' apply plugin: 'java' apply plugin: 'org.springframework.boot' } bootJar { enabled = true } jar {enabled = true} } ``` Sub-module build.gradle ``` bootJar { mainClassName = 'space.hi.HelloApplication' } ``` Then you can click the bootRun submodule in the 'Tasks/application or build' of the idea gradle plugin, or click bootJar to generate the jar. Upvotes: 0
2018/03/18
3,997
13,071
<issue_start>username_0: I'm back at you with another question from Ionic 3 & Angularfire2 ! I changed my pages to make them run on android with plugins and all the stuff needed to use native functiuns at their maximum. BUT ! When I try to, I face a strange issue... I have no problems when I am coding, I can use "GeoPoint" type with no problems, Visual Studio Code can bind type with the folder ( '@firebase/firestore-types') but when I run my app on android I get a big error telling me that the compiler can't bind my folder with the type... So... I can't do anything, tried to change type to something else, tried to call the type directly from "firebase.firestore.GeoPoint" but nothing seems to work, even tried to delete the project and remake it but... NOTHING :( Anyway, I hope that you guys can help me with this, this is the error I get : ``` Error: ./src/pages/add-event/add-event.ts Module not found: Error: Can't resolve '@firebase/firestore-types' in 'C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\src\pages\add-event' resolve '@firebase/firestore-types' in 'C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\src\pages\add-event' Parsed request is a module using description file: C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\package.json (relative path: ./src/pages/add-event) Field 'browser' doesn't contain a valid alias configuration after using description file: C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\package.json (relative path: ./src/pages/add-event) resolve as module looking for modules in C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules using description file: C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\package.json (relative path: ./node_modules) Field 'browser' doesn't contain a valid alias configuration after using description file: C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\package.json (relative path: ./node_modules) using description file: C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\package.json (relative path: .) no extension Field 'browser' doesn't contain a valid alias configuration C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types is not a file .ts Field 'browser' doesn't contain a valid alias configuration C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types.ts doesn't exist .js Field 'browser' doesn't contain a valid alias configuration C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types.js doesn't exist .json Field 'browser' doesn't contain a valid alias configuration C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types.json doesn't exist as directory existing directory using path: C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\index using description file: C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\package.json (relative path: ./index) no extension Field 'browser' doesn't contain a valid alias configuration C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\index doesn't exist .ts Field 'browser' doesn't contain a valid alias configuration C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\index.ts doesn't exist .js Field 'browser' doesn't contain a valid alias configuration C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\index.js doesn't exist .json Field 'browser' doesn't contain a valid alias configuration C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\index.json doesn't exist [C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types] [C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types.ts] [C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types.js] [C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types.json] [C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\index] [C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\index.ts] [C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\index.js] [C:\Users\Damien\Documents\Ecole\GREP\18032018\Vennel\node_modules\@firebase\firestore-types\index.json] @ ./src/pages/add-event/add-event.ts 17:0-53 @ ./src/pages/add-event/add-event.module.ts @ ./src lazy @ ./node_modules/ionic-angular/util/ng-module-loader.js @ ./node_modules/ionic-angular/util/module-loader.js @ ./node_modules/ionic-angular/components/popover/popover-component.js @ ./node_modules/ionic-angular/index.js ``` My app.modules.ts : ``` import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { AngularFireModule } from 'angularfire2'; import { AngularFirestoreModule } from 'angularfire2/firestore'; import { MyApp } from './app.component'; import { FIREBASE_CONFIG } from './firebase.credentials'; import { GOOGLE_MAPS_APIKEY } from './google.credentials'; import { AgmCoreModule } from '@agm/core'; import { EventService } from '../services/events/event.service'; import { HttpClientModule } from '@angular/common/http'; import { } from '@firebase/firestore-types'; import { ToastService } from '../services/toast/toast.service'; import { NativeGeocoder } from '@ionic-native/native-geocoder'; import { AuthService } from '../services/auth/auth.service'; import { UserService } from '../services/users/user.service'; import { AngularFireAuth } from 'angularfire2/auth'; import { Geolocation } from '@ionic-native/geolocation'; @NgModule({ declarations: [ MyApp ], imports: [ BrowserModule, HttpClientModule, IonicModule.forRoot(MyApp), AngularFireModule.initializeApp(FIREBASE_CONFIG), AgmCoreModule.forRoot({ apiKey:GOOGLE_MAPS_APIKEY }), AngularFirestoreModule ], bootstrap: [IonicApp], entryComponents: [ MyApp ], providers: [ StatusBar, SplashScreen, NativeGeocoder, {provide: ErrorHandler, useClass: IonicErrorHandler}, EventService, ToastService, AuthService, UserService, AngularFireAuth, Geolocation ] }) export class AppModule {} ``` The add-event page : ``` import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import {Event} from '../../models/event/event.interface'; import { EventService } from '../../services/events/event.service'; import { GOOGLE_MAPS_APIKEY } from '../../app/google.credentials'; import { HttpClient } from '@angular/common/http'; import { ToastService } from '../../services/toast/toast.service'; import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult } from '@ionic-native/native-geocoder'; import { GeoPoint } from '@firebase/firestore-types'; import * as firebase from 'firebase/app'; @IonicPage() @Component({ selector: 'page-add-event', templateUrl: 'add-event.html', }) export class AddEventPage { event : Event = { name : ['',''], address : undefined, city : '', place : '', date : undefined, tags : '', description : '', isPaying : false } constructor( public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient, private eventsServ:EventService, private toast : ToastService, private nativeGeocoder : NativeGeocoder, private testGeo : GeoPoint ){} getCoordinates(address:string){ this.nativeGeocoder.forwardGeocode(address) .then((coordinates: NativeGeocoderForwardResult) => console.log('The coordinates are latitude=' + coordinates.latitude + ' and longitude=' + coordinates.longitude)) .catch((error: any) => console.log(error)); } addEvent(event){ let geopoint : firebase.firestore.GeoPoint; let address : String = event.address; let url = "https://maps.googleapis.com/maps/api/geocode/json?address="+address+"&key="+GOOGLE_MAPS_APIKEY; let response = this.httpClient.get(url); response.subscribe(data =>{ //var latitude = data.results[0].geometry.location.lat; //var longitude = data.results[0].geometry.location.lng; //s var latitude = 46; var longitude = 6; //s geopoint = new firebase.firestore.GeoPoint(latitude, longitude); event.address = geopoint; this.eventsServ.addEvent(event).then(ref=>{ console.log(ref); this.toast.show('Événement ajouté avec succès !', 3000); this.navCtrl.setRoot('HomePage', {key:ref.id}); }); }); } ionViewDidLoad() { console.log('ionViewDidLoad AddEventPage'); } } ``` The package.json : ``` { "name": "Vennel", "version": "0.0.1", "author": "Ionic Framework", "homepage": "http://ionicframework.com/", "private": true, "scripts": { "clean": "ionic-app-scripts clean", "build": "ionic-app-scripts build", "lint": "ionic-app-scripts lint", "ionic:build": "ionic-app-scripts build", "ionic:serve": "ionic-app-scripts serve" }, "dependencies": { "@agm/core": "^1.0.0-beta.2", "@angular/common": "5.0.3", "@angular/compiler": "5.0.3", "@angular/compiler-cli": "5.0.3", "@angular/core": "5.0.3", "@angular/forms": "5.0.3", "@angular/http": "5.0.3", "@angular/platform-browser": "5.0.3", "@angular/platform-browser-dynamic": "5.0.3", "@firebase/firestore": "^0.3.5", "@firebase/firestore-types": "^0.2.2", "@ionic-native/core": "4.4.0", "@ionic-native/geolocation": "^4.5.3", "@ionic-native/native-geocoder": "^4.5.3", "@ionic-native/splash-screen": "4.4.0", "@ionic-native/status-bar": "4.4.0", "@ionic/storage": "2.1.3", "angularfire2": "^5.0.0-rc.6", "cordova-android": "7.0.0", "cordova-plugin-device": "^2.0.1", "cordova-plugin-geolocation": "^4.0.1", "cordova-plugin-ionic-keyboard": "^2.0.5", "cordova-plugin-ionic-webview": "^1.1.16", "cordova-plugin-splashscreen": "^5.0.2", "cordova-plugin-whitelist": "^1.3.3", "firebase": "^4.11.0", "ionic-angular": "3.9.2", "ionicons": "3.0.0", "jquery": "^3.3.1", "rxjs": "5.5.2", "sw-toolbox": "3.6.0", "zone.js": "0.8.18" }, "devDependencies": { "@ionic/app-scripts": "3.1.8", "typescript": "2.4.2" }, "description": "An Ionic project", "cordova": { "plugins": { "cordova-plugin-whitelist": {}, "cordova-plugin-device": {}, "cordova-plugin-splashscreen": {}, "cordova-plugin-ionic-webview": {}, "cordova-plugin-ionic-keyboard": {}, "cordova-plugin-geolocation": { "GEOLOCATION_USAGE_DESCRIPTION": "To locate you" } }, "platforms": [ "android" ] } } ``` I hope you guys can help me out with this, thank you in advance guys ! Damien<issue_comment>username_1: The `-types` packages are just types and will not work as runtime values. Use the `@firebase/app` module instead. This works for me: ``` import * as firebase from 'firebase/app'; deleteMemberId(chatGroupId: string, memberId: string, userIdToken: string): void { this.afs.doc(`messageGroups/${chatGroupId}`).update({ memberIds: firebase.firestore.FieldValue.arrayRemove(memberId) //here }); } ``` Ref: <https://github.com/angular/angularfire/issues/1518#issuecomment-375103751> Upvotes: 3 <issue_comment>username_2: For future searchers, I'll post what I did to squash my errors in VSCode Old: ``` import {QueryDocumentSnapshot, DocumentData} from "@firebase/firestore-types"; await query.get().then((value:any) => { value.forEach((doc:QueryDocumentSnapshot) => { doc.ref.delete(); }); }); ``` New: ``` import admin from "firebase-admin"; await query.get().then((value:any) => { value.forEach((admin.firestore.QueryDocumentSnapshot) => { doc.ref.delete(); }); }); ``` Upvotes: 0 <issue_comment>username_3: Use `import { GeoPoint} from "@firebase/firestore";` instead of `import { GeoPoint} from "@firebase/firestore-types";` Upvotes: 1
2018/03/18
825
3,492
<issue_start>username_0: What are the Android SDK platform packages for? Do I need to download corresponding platform for every API level I'm targeting?<issue_comment>username_1: When you set `android:minSdkVersion` it means that you want to use the benefits and development tools of that version (also the users below that `minSdkVersion` can not use your application). So you have to download the SDK which supports your tools and needs for that minimum version. also if you have set `android:targetSdkVersion` it means that you have tested your application against that version. So obviously you need to download the required tools for testing that version too. If you don't set `android:targetSdkVersion` it will be equal to `minSdkVersion` by default. **Footnote:** using the latest version of SDK (as compileSdkVersion) gives you the power of using latest tools and platforms benefits. The development software will warn you if you use a tool which is not supported by `targeted` or `minSdkVersion` of your users. Upvotes: -1 <issue_comment>username_2: `minSdkVersion` is the minimum API version your app is compatible with. You don't need to download anything according to this value. If you set a value of, say, 21 (Marshmallow) your app *won't run* on a device with android version 19 (KitKat). `targetSdkVersion` is used to detect the highest sdk version your app is compatible with, it indicates forward-compatibility. The difference here is that if you set a target version of, say, 21 your app *will run* on a device with android 23. It can just be used by a future version of Android to know if there might be some new feature that your app won't support. Google Play policy has been recently updated so that you will be forced to use a recent API version as your target, read [here](https://android-developers.googleblog.com/2017/12/improving-app-security-and-performance.html). `compileSdkVersion` is the version of the Android SDK you use when compiling your app. You have to download that version of the SDK in order to compile your app and use classes from that version of the SDK. For instance, you might want to use the class `Context`, and call the method `getColor(int)`, the version 23 of the SDK has it so you can use it in your code. If you're using version 21 though, the method is not there so you can't call it in your app. You see here that `minSdkVersion` is also useful because you might want to use this method, but it's been introduced only in version 23 and since you have a min SDK 21 you will get a warning at compile time. The build tools are used to compile your app and you should be updating them to latest version regardless of the aforementioned values. I think with recent versions of the Android gradle plugin you don't need to set this value anymore, it will be handled automagically. To sum up, you only need to download the SDK of the API version you're compiling against, that is, `compileSdkVersion`. About the meaning of "compile against", when you write an app you compile your code and pack it into an apk, the apk is then deployed to a device. In your code you use classes from the Android SDK (e.g. `Context`) but the code for those classes is not included in the apk, it is provided from the OS of the device on which your app will run. If you want to compile a class that is using those SDK classes, you have to "show" those SDK classes to the compiler so that it can then compile your own classes. Upvotes: 3 [selected_answer]
2018/03/18
1,586
6,684
<issue_start>username_0: I am trying to simulate videocard (producer thread) and a monitor(consumer thread), to figure out what is going on in educational purposes. So here is the technical task description: Producer thread produces frames pixel data at 1000 fps. Consumer thread runs at 60 fps and every frame it must have access to last produced frame for at least 1/60th of second. Each frame is represented by some `int*`, for simplicity. So my solution is that i have array of 2 pointers: one for producer, one for consumer. And plus some free, unused pointer, which is not owned by consumer or producer at any given moment of time. ``` #define Producer 0 #define Consumer 1 int* usedPointers[2]; std::atomic freePointer; ``` * producer always writes frame pixels to `usedPointers[Producer]`, then does `usedPointers[Producer] = freePointer.exchange(usedPointers[Producer], memorySemanticsProducer);` so that last completely produced frame is now pointed by `freePointer`, and its free to write new frame, not destroying last actual complete frame. * consumer does `usedPointers[Consumer] = freePointer.exchange(usedPointers[Consumer], memorySemanticsConsumer);` so that it would own last actual frame data, and then is free to access `usedPointers[Consumer]` as long, as it desires to. Correct me if i am wrong. I miss what is `memorySemanticsXXX`. [There are descriptions](http://www.cplusplus.com/reference/atomic/memory_order/) but i cannot figure out which exactly should i use in every thread and why. So i am asking for some hints on that.<issue_comment>username_1: `memorySemanticsXXX` you're mentioning are about the rest of your code surrounding the `exchange()` lines. The default behavior for `std::atomic::exchange()` is that `memory_order_seq_cst` is used (the second parameter for `exchange()` you're not using). This means three things at the same time: * Any code you wrote before your `exchange()` call is guaranteed to execute before that call (otherwise compiler optimizations can reorder your code) **and** the results of that execution will be visible in all other threads (CPU cache propagation) before the `exchange()` call is made. * The same as previous but for the code you wrote after your `exchange()` line. * All of the code before and after `exchange()` call is executed in the exact order you wrote it (including other atomic operations). So, the whole point is that you may choose not to have one, two or all three of these restrictions, which *can* bring you speed improvements. You shouldn't bother with this **unless you have a performance bottleneck**. If there's no bottleneck then just use `std::atomic` without the second parameter (it will take the default value). In case you don't use all three restrictions you have to be really careful writing your code otherwise it can unpredictably crash. Read more about it here: [Memory order](http://en.cppreference.com/w/cpp/atomic/memory_order) Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is a perfect answer that I would answer myself back then, if I could have time machine: The choice of memory order depends on your specific use case and requirements. You should use the weakest memory order, that still ensures correctness and consistency of your algorithm. Typical choices include: * You should use `std::memory_order_seq_cst` if you want to avoid any surprises or complications, but you may pay a performance penalty for it. * You should use `std::memory_order_relaxed` if you don’t care about ordering or synchronization at all, but you may introduce subtle bugs or race conditions if you do. * You should use `std::memory_order_acquire` and `std::memory_order_release` if you want to implement a producer-consumer pattern, where one thread writes data and releases it, and another thread reads data and acquires it. * You should use `std::memory_order_acq_rel` if you want to implement a read-modify-write operation, where one thread reads data, modifies it, and writes it back atomically. Based on your exact description, it seems, that you want to implement a producer-consumer pattern, where the producer thread writes frame pixels to a buffer and the consumer thread reads them. You also want to avoid performance penalty by using weaker memory orders than sequential consistency. In that case, you can use `std::memory_order_release` for `memorySemanticsProducer` and `std::memory_order_acquire` for `memorySemanticsConsumer`. This way, you ensure that the producer thread does not write to the buffer before releasing the pointer, and that the consumer thread does not read from the buffer after acquiring the pointer. This also prevents any reordering of memory accesses around the exchange operation that could cause inconsistency or data races. Here is a possible demo snippet of your code using these memory orders: ``` #define Producer 0 #define Consumer 1 int* usedPointers[2]; std::atomic freePointer; void threadProducer() { while(true) { // write frame pixels to usedPointers[Producer] // ... // release the pointer and exchange it with freePointer usedPointers[Producer] = freePointer.exchange(usedPointers[Producer], std::memory\_order\_release); } } void threadConsumer() { while(true) { // acquire the pointer and exchange it with freePointer usedPointers[Consumer] = freePointer.exchange(usedPointers[Consumer], std::memory\_order\_acquire); // read frame pixels from usedPointers[Consumer] // ... } } int main() { // initialize usedPointers and freePointer usedPointers[Procuder] = init\_buf(); usedPointers[Consumer] = init\_buf(); freePointer.Store(init\_buf()); // create producer and consumer threads std::thread t1(threadProducer); std::thread t2(threadConsumer); // join threads t1.join(); t2.join(); return 0; } ``` moreover, instead of using global array of pointers - it *may be* better (may be easier for compiler/caching mechanisms, may be not) to define producer and consumer local buffer variable right inside corresponding thread functions themselves, but that may make buffer init code abit less beautiful - more scattered accross functions. Thich may be unwanted, if you plan to place functions across different files: ``` void threadConsumer() { auto buffer = init_buf(); while(true) { // acquire the consumer buffer pointer and exchange it with freePointer buffer = freePointer.exchange(buffer, std::memory_order_acquire); ... ``` That will led you to better understanding, that triple buffer global state - consists of only one atomic pointer, which is shared buffer and a mechanism that is aware how to init it - two buffers may be fully thread-local Upvotes: 1
2018/03/18
761
3,113
<issue_start>username_0: In [this question](https://stackoverflow.com/questions/46841534/pair-a-bluetooth-device-in-android-studio), @nhoxbypass provides this method for the purpose of adding found Bluetooth devices to a list: ``` private BroadcastReceiver myReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Message msg = Message.obtain(); String action = intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action)){ //Found, add to a device list } } }; ``` However, I do not understand how a reference to the found device can be obtained, how can this be done? I do not have permission to comment on the original question, so I have chosen to extend it here.<issue_comment>username_1: From the [`ACTION_FOUND` documentation](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_FOUND): > > Always contains the extra fields `EXTRA_DEVICE` and `EXTRA_CLASS`. Can contain the extra fields `EXTRA_NAME` and/or `EXTRA_RSSI` if they are available. > > > [`EXTRA_DEVICE` can be used to obtain the `BluetoothDevice` that was found](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#EXTRA_DEVICE) via code like: ``` BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); ``` Upvotes: 2 <issue_comment>username_2: [The Bluetooth guide in the Android documentation](https://developer.android.com/guide/topics/connectivity/bluetooth.html) explains this: > > In order to receive information about each device discovered, your application must register a BroadcastReceiver for the ACTION\_FOUND intent. The system broadcasts this intent for each device. The intent contains the extra fields EXTRA\_DEVICE and EXTRA\_CLASS, which in turn contain a BluetoothDevice and a BluetoothClass, respectively. > > > This sample code is included as well: > > > ``` > @Override > protected void onCreate(Bundle savedInstanceState) { > ... > > // Register for broadcasts when a device is discovered. > IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); > registerReceiver(mReceiver, filter); > } > > // Create a BroadcastReceiver for ACTION_FOUND. > private final BroadcastReceiver mReceiver = new BroadcastReceiver() { > public void onReceive(Context context, Intent intent) { > String action = intent.getAction(); > if (BluetoothDevice.ACTION_FOUND.equals(action)) { > // Discovery has found a device. Get the BluetoothDevice > // object and its info from the Intent. > BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); > String deviceName = device.getName(); > String deviceHardwareAddress = device.getAddress(); // MAC address > } > } > }; > > ``` > > If you are working with Bluetooth on Android, I suggest to read that guide carefully. Then read it one more time ;-) Upvotes: 3 [selected_answer]
2018/03/18
1,125
2,410
<issue_start>username_0: ``` A B C 0 2002-01-13 15:00:00 120 1 2002-01-13 15:30:00 110 2 2002-01-13 16:00:00 130 3 2002-01-13 16:30:00 140 4 2002-01-14 15:00:00 180 5 2002-01-14 15:30:00 165 6 2002-01-14 16:00:00 150 7 2002-01-14 16:30:00 170 ``` I want to select one row per each *A group*, with next conditions: * Select the *"minimum C column value + 10"*. * If it doesn´t exist *"minimum C column value + 10"*, take the next *C column value*. Output should be: ``` A B C 0 2002-01-13 15:00:00 120 5 2002-01-14 15:30:00 165 ```<issue_comment>username_1: As @Anton vBR commented, first remove rows by condition per groups and then get rows by minimal `C` by [`idxmax`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.idxmax.html) and select by `loc`: ``` df = df[df.groupby('A')['C'].transform(lambda x: x >= x.min() + 10)] #filtering with transform `min` only #df = df[df.groupby('A')['C'].transform('min') + 10 <= df['C']] print (df) A B C 0 2002-01-13 15:00:00 120 2 2002-01-13 16:00:00 130 3 2002-01-13 16:30:00 140 4 2002-01-14 15:00:00 180 5 2002-01-14 15:30:00 165 7 2002-01-14 16:30:00 170 df = df.loc[df.groupby('A')['C'].idxmin()] ``` What is same as: ``` idx=df.sort_values(['A','C']).groupby('A')['C'].apply(lambda x: (x >= x.min() + 10).idxmax()) df = df.loc[idx] ``` Alternative solution with [`sort_values`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html) with [`drop_duplicates`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html): ``` df = df.sort_values(['A','C']) df = df[df.groupby('A')['C'].transform(lambda x: x >= x.min() + 10)].drop_duplicates(['A']) ``` --- ``` print (df) A B C 0 2002-01-13 15:00:00 120 5 2002-01-14 15:30:00 165 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This is one vectorised solution. Sometimes a helper column is more efficient than an in-line `lambda`-based solution. ``` df['Floor'] = df['C'] - (df.groupby('A')['C'].transform('min') + 10) res = df.loc[df[df['Floor'] >= 0].groupby('A')['Floor'].idxmin()] ``` Result: ``` A B C Floor 0 2002-01-13 15:00:00 120 0 5 2002-01-14 15:30:00 165 5 ``` Upvotes: 1
2018/03/18
327
1,377
<issue_start>username_0: I've set up a `DataGridViewColumnCollection` as follows: ``` private DataGridViewColumnCollection columns; private void RemoveStaffFromList(object sender, EventArgs e) { columns = dataGridViewStaff.Columns; MessageBox.Show(columns.Count.ToString()); dataGridViewStaff.DataSource = null; MessageBox.Show(columns.Count.ToString()); } ``` MessageBox 1 returns "4", MessageBox 2 returns "0", so `columns` obviously resets when I nullify the DataSource. But why? Shouldn't `columns` be treated as a variable separate from `dataGridViewStaff` and hence be unaffected by the DataSource change?<issue_comment>username_1: Because your `columns` variable simply points to the same memory location as `dataGridViewStaff.Columns` so when you set datasource to `null` the `columns` becomes empty hence the 0. Upvotes: 1 <issue_comment>username_2: Don't forget to assign false to [DataGridView.AutoGenerateColumns](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autogeneratecolumns(v=vs.110).aspx) > > Gets or sets a value indicating whether columns are created > automatically when the DataSource or DataMember properties are set. > > > Columns are automatically generated when this property is set to true and the DataSource or DataMember properties are set or changed. Upvotes: 0
2018/03/18
5,499
21,743
<issue_start>username_0: I know many such questions have already been asked tried a lot then after posting the question. I`ll start from beginning: Few days ago I tried to sing in with my facebook user I get message from facebook: „URL isn't included in the app's domains!“ I solved it by adding URL in <https://developers.facebook.com/apps/.../fb-login/settings/> Valid OAuth redirect URIs. **The problems that I have now is when user tries to login with facebook account see this error** `Catchable fatal error: Argument 4 passed to Facebook\FacebookResponse::__construct() must be of the type array, null given, called in /home/sportobatai/public_html/TOTASPORT/facebook-php-sdk/FacebookClient.php on line 225 and defined in /home/sportobatai/public_html/TOTASPORT/facebook-php-sdk/FacebookResponse.php on line 75` **1. The link "Login with facebook"** <https://www.facebook.com/v2.2/dialog/oauth?client_id=XXXXXXXXXXXXX&state=829ee1c76aa23a76223dd500d49289b6&response_type=code&sdk=php-sdk-5.0.0&redirect_uri=http%3A%2F%2Ftotasport.com%2F&scope=email> **2. The link when user sings with facebook account:** [http://totasport.com/?code=AQBVHr63oHzB2nYdDQMet0NrpW7QJ\_LEdzRfApdGnyywLgzwT-nv8a3pfFmKPSGHYkjzsjt9D0y74nr-GWyLMSbPPC\_E8PKYYXG7G1-U8cn-KDPd3dd3Rw-Ysot8s8tq7MlQ6OIVk-YFbN7hc5SM\_-K9EbBb0ofpl5ypfRbIUvI3c-XxVoMKxIWRYf1PR9l5CPWNLWjbmx2ceADdS5cxvrx2gEK-5CR1ZB77y-YRCEB4yNhzcsWJKPc5xWvh2e4ss8S\_8CHvfvMF7JPK7mB8YrFdB0LK69adOMYjUF76fGqpnj2EybizYvo4GpsjkqANrC4&state=829ee1c76aa23a76223dd500d49289b6#*=*](http://totasport.com/?code=AQBVHr63oHzB2nYdDQMet0NrpW7QJ_LEdzRfApdGnyywLgzwT-nv8a3pfFmKPSGHYkjzsjt9D0y74nr-GWyLMSbPPC_E8PKYYXG7G1-U8cn-KDPd3dd3Rw-Ysot8s8tq7MlQ6OIVk-YFbN7hc5SM_-K9EbBb0ofpl5ypfRbIUvI3c-XxVoMKxIWRYf1PR9l5CPWNLWjbmx2ceADdS5cxvrx2gEK-5CR1ZB77y-YRCEB4yNhzcsWJKPc5xWvh2e4ss8S_8CHvfvMF7JPK7mB8YrFdB0LK69adOMYjUF76fGqpnj2EybizYvo4GpsjkqANrC4&state=829ee1c76aa23a76223dd500d49289b6#_=_) The error appears. **3. The Code what I used to make a login with Facebook:** <https://www.codexworld.com/login-with-facebook-using-php/> **4. Screens from developers.facebook.com:** [> facebook app settings image](https://i.stack.imgur.com/vV3NQ.png) [> facebook login settings image](https://i.stack.imgur.com/cDVyX.png) **5. FacebookClient.php** ```html php /** * Copyright 2014 Facebook, Inc. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to * use, copy, modify, and distribute this software in source code or binary * form for use in connection with the web services and APIs provided by * Facebook. * * As with any software that integrates with the Facebook platform, your use * of this software is subject to the Facebook Developer Principles and * Policies [http://developers.facebook.com/policy/]. This copyright notice * shall be included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ namespace Facebook; use Facebook\HttpClients\FacebookHttpClientInterface; use Facebook\HttpClients\FacebookCurlHttpClient; use Facebook\HttpClients\FacebookStreamHttpClient; use Facebook\Exceptions\FacebookSDKException; /** * Class FacebookClient * * @package Facebook */ class FacebookClient { /** * @const string Production Graph API URL. */ const BASE_GRAPH_URL = 'https://graph.facebook.com'; /** * @const string Graph API URL for video uploads. */ const BASE_GRAPH_VIDEO_URL = 'https://graph-video.facebook.com'; /** * @const string Beta Graph API URL. */ const BASE_GRAPH_URL_BETA = 'https://graph.beta.facebook.com'; /** * @const string Beta Graph API URL for video uploads. */ const BASE_GRAPH_VIDEO_URL_BETA = 'https://graph-video.beta.facebook.com'; /** * @const int The timeout in seconds for a normal request. */ const DEFAULT_REQUEST_TIMEOUT = 60; /** * @const int The timeout in seconds for a request that contains file uploads. */ const DEFAULT_FILE_UPLOAD_REQUEST_TIMEOUT = 3600; /** * @const int The timeout in seconds for a request that contains video uploads. */ const DEFAULT_VIDEO_UPLOAD_REQUEST_TIMEOUT = 7200; /** * @var bool Toggle to use Graph beta url. */ protected $enableBetaMode = false; /** * @var FacebookHttpClientInterface HTTP client handler. */ protected $httpClientHandler; /** * @var int The number of calls that have been made to Graph. */ public static $requestCount = 0; /** * Instantiates a new FacebookClient object. * * @param FacebookHttpClientInterface|null $httpClientHandler * @param boolean $enableBeta */ public function __construct(FacebookHttpClientInterface $httpClientHandler = null, $enableBeta = false) { $this-httpClientHandler = $httpClientHandler ?: $this->detectHttpClientHandler(); $this->enableBetaMode = $enableBeta; } /** * Sets the HTTP client handler. * * @param FacebookHttpClientInterface $httpClientHandler */ public function setHttpClientHandler(FacebookHttpClientInterface $httpClientHandler) { $this->httpClientHandler = $httpClientHandler; } /** * Returns the HTTP client handler. * * @return FacebookHttpClientInterface */ public function getHttpClientHandler() { return $this->httpClientHandler; } /** * Detects which HTTP client handler to use. * * @return FacebookHttpClientInterface */ public function detectHttpClientHandler() { return function_exists('curl_init') ? new FacebookCurlHttpClient() : new FacebookStreamHttpClient(); } /** * Toggle beta mode. * * @param boolean $betaMode */ public function enableBetaMode($betaMode = true) { $this->enableBetaMode = $betaMode; } /** * Returns the base Graph URL. * * @param boolean $postToVideoUrl Post to the video API if videos are being uploaded. * * @return string */ public function getBaseGraphUrl($postToVideoUrl = false) { if ($postToVideoUrl) { return $this->enableBetaMode ? static::BASE_GRAPH_VIDEO_URL_BETA : static::BASE_GRAPH_VIDEO_URL; } return $this->enableBetaMode ? static::BASE_GRAPH_URL_BETA : static::BASE_GRAPH_URL; } /** * Prepares the request for sending to the client handler. * * @param FacebookRequest $request * * @return array */ public function prepareRequestMessage(FacebookRequest $request) { $postToVideoUrl = $request->containsVideoUploads(); $url = $this->getBaseGraphUrl($postToVideoUrl) . $request->getUrl(); // If we're sending files they should be sent as multipart/form-data if ($request->containsFileUploads()) { $requestBody = $request->getMultipartBody(); $request->setHeaders([ 'Content-Type' => 'multipart/form-data; boundary=' . $requestBody->getBoundary(), ]); } else { $requestBody = $request->getUrlEncodedBody(); $request->setHeaders([ 'Content-Type' => 'application/x-www-form-urlencoded', ]); } return [ $url, $request->getMethod(), $request->getHeaders(), $requestBody->getBody(), ]; } /** * Makes the request to Graph and returns the result. * * @param FacebookRequest $request * * @return FacebookResponse * * @throws FacebookSDKException */ public function sendRequest(FacebookRequest $request) { if (get_class($request) === 'FacebookRequest') { $request->validateAccessToken(); } list($url, $method, $headers, $body) = $this->prepareRequestMessage($request); // Since file uploads can take a while, we need to give more time for uploads $timeOut = static::DEFAULT_REQUEST_TIMEOUT; if ($request->containsFileUploads()) { $timeOut = static::DEFAULT_FILE_UPLOAD_REQUEST_TIMEOUT; } elseif ($request->containsVideoUploads()) { $timeOut = static::DEFAULT_VIDEO_UPLOAD_REQUEST_TIMEOUT; } // Should throw `FacebookSDKException` exception on HTTP client error. // Don't catch to allow it to bubble up. $rawResponse = $this->httpClientHandler->send($url, $method, $body, $headers, $timeOut); static::$requestCount++; $returnResponse = new FacebookResponse( $request, $rawResponse->getBody(), $rawResponse->getHttpResponseCode(), $rawResponse->getHeaders() ); if ($returnResponse->isError()) { throw $returnResponse->getThrownException(); } return $returnResponse; } /** * Makes a batched request to Graph and returns the result. * * @param FacebookBatchRequest $request * * @return FacebookBatchResponse * * @throws FacebookSDKException */ public function sendBatchRequest(FacebookBatchRequest $request) { $request->prepareRequestsForBatch(); $facebookResponse = $this->sendRequest($request); return new FacebookBatchResponse($request, $facebookResponse); } } ``` **6. FacebookResponse.php** ```html php /** * Copyright 2014 Facebook, Inc. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to * use, copy, modify, and distribute this software in source code or binary * form for use in connection with the web services and APIs provided by * Facebook. * * As with any software that integrates with the Facebook platform, your use * of this software is subject to the Facebook Developer Principles and * Policies [http://developers.facebook.com/policy/]. This copyright notice * shall be included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ namespace Facebook; use Facebook\GraphNodes\GraphNodeFactory; use Facebook\Exceptions\FacebookResponseException; use Facebook\Exceptions\FacebookSDKException; /** * Class FacebookResponse * * @package Facebook */ class FacebookResponse { /** * @var int The HTTP status code response from Graph. */ protected $httpStatusCode; /** * @var array The headers returned from Graph. */ protected $headers; /** * @var string The raw body of the response from Graph. */ protected $body; /** * @var array The decoded body of the Graph response. */ protected $decodedBody = []; /** * @var FacebookRequest The original request that returned this response. */ protected $request; /** * @var FacebookSDKException The exception thrown by this request. */ protected $thrownException; /** * Creates a new Response entity. * * @param FacebookRequest $request * @param string|null $body * @param int|null $httpStatusCode * @param array|null $headers */ public function __construct(FacebookRequest $request, $body = null, $httpStatusCode = null, array $headers = []) { $this-request = $request; $this->body = $body; $this->httpStatusCode = $httpStatusCode; $this->headers = $headers; $this->decodeBody(); } /** * Return the original request that returned this response. * * @return FacebookRequest */ public function getRequest() { return $this->request; } /** * Return the FacebookApp entity used for this response. * * @return FacebookApp */ public function getApp() { return $this->request->getApp(); } /** * Return the access token that was used for this response. * * @return string|null */ public function getAccessToken() { return $this->request->getAccessToken(); } /** * Return the HTTP status code for this response. * * @return int */ public function getHttpStatusCode() { return $this->httpStatusCode; } /** * Return the HTTP headers for this response. * * @return array */ public function getHeaders() { return $this->headers; } /** * Return the raw body response. * * @return string */ public function getBody() { return $this->body; } /** * Return the decoded body response. * * @return array */ public function getDecodedBody() { return $this->decodedBody; } /** * Get the app secret proof that was used for this response. * * @return string|null */ public function getAppSecretProof() { return $this->request->getAppSecretProof(); } /** * Get the ETag associated with the response. * * @return string|null */ public function getETag() { return isset($this->headers['ETag']) ? $this->headers['ETag'] : null; } /** * Get the version of Graph that returned this response. * * @return string|null */ public function getGraphVersion() { return isset($this->headers['Facebook-API-Version']) ? $this->headers['Facebook-API-Version'] : null; } /** * Returns true if Graph returned an error message. * * @return boolean */ public function isError() { return isset($this->decodedBody['error']); } /** * Throws the exception. * * @throws FacebookSDKException */ public function throwException() { throw $this->thrownException; } /** * Instantiates an exception to be thrown later. */ public function makeException() { $this->thrownException = FacebookResponseException::create($this); } /** * Returns the exception that was thrown for this request. * * @return FacebookSDKException|null */ public function getThrownException() { return $this->thrownException; } /** * Convert the raw response into an array if possible. * * Graph will return 2 types of responses: * - JSON(P) * Most responses from Grpah are JSON(P) * - application/x-www-form-urlencoded key/value pairs * Happens on the `/oauth/access_token` endpoint when exchanging * a short-lived access token for a long-lived access token * - And sometimes nothing :/ but that'd be a bug. */ public function decodeBody() { $this->decodedBody = json_decode($this->body, true); if ($this->decodedBody === null) { $this->decodedBody = []; parse_str($this->body, $this->decodedBody); } elseif (is_bool($this->decodedBody)) { // Backwards compatibility for Graph < 2.1. // Mimics 2.1 responses. // @TODO Remove this after Graph 2.0 is no longer supported $this->decodedBody = ['success' => $this->decodedBody]; } elseif (is_numeric($this->decodedBody)) { $this->decodedBody = ['id' => $this->decodedBody]; } if (!is_array($this->decodedBody)) { $this->decodedBody = []; } if ($this->isError()) { $this->makeException(); } } /** * Instantiate a new GraphObject from response. * * @param string|null $subclassName The GraphNode sub class to cast to. * * @return \Facebook\GraphNodes\GraphObject * * @throws FacebookSDKException * * @deprecated 5.0.0 getGraphObject() has been renamed to getGraphNode() * @todo v6: Remove this method */ public function getGraphObject($subclassName = null) { return $this->getGraphNode($subclassName); } /** * Instantiate a new GraphNode from response. * * @param string|null $subclassName The GraphNode sub class to cast to. * * @return \Facebook\GraphNodes\GraphNode * * @throws FacebookSDKException */ public function getGraphNode($subclassName = null) { $factory = new GraphNodeFactory($this); return $factory->makeGraphNode($subclassName); } /** * Convenience method for creating a GraphAlbum collection. * * @return \Facebook\GraphNodes\GraphAlbum * * @throws FacebookSDKException */ public function getGraphAlbum() { $factory = new GraphNodeFactory($this); return $factory->makeGraphAlbum(); } /** * Convenience method for creating a GraphPage collection. * * @return \Facebook\GraphNodes\GraphPage * * @throws FacebookSDKException */ public function getGraphPage() { $factory = new GraphNodeFactory($this); return $factory->makeGraphPage(); } /** * Convenience method for creating a GraphSessionInfo collection. * * @return \Facebook\GraphNodes\GraphSessionInfo * * @throws FacebookSDKException */ public function getGraphSessionInfo() { $factory = new GraphNodeFactory($this); return $factory->makeGraphSessionInfo(); } /** * Convenience method for creating a GraphUser collection. * * @return \Facebook\GraphNodes\GraphUser * * @throws FacebookSDKException */ public function getGraphUser() { $factory = new GraphNodeFactory($this); return $factory->makeGraphUser(); } /** * Convenience method for creating a GraphEvent collection. * * @return \Facebook\GraphNodes\GraphEvent * * @throws FacebookSDKException */ public function getGraphEvent() { $factory = new GraphNodeFactory($this); return $factory->makeGraphEvent(); } /** * Convenience method for creating a GraphGroup collection. * * @return \Facebook\GraphNodes\GraphGroup * * @throws FacebookSDKException */ public function getGraphGroup() { $factory = new GraphNodeFactory($this); return $factory->makeGraphGroup(); } /** * Instantiate a new GraphList from response. * * @param string|null $subclassName The GraphNode sub class to cast list items to. * @param boolean $auto_prefix Toggle to auto-prefix the subclass name. * * @return \Facebook\GraphNodes\GraphList * * @throws FacebookSDKException * * @deprecated 5.0.0 getGraphList() has been renamed to getGraphEdge() * @todo v6: Remove this method */ public function getGraphList($subclassName = null, $auto_prefix = true) { return $this->getGraphEdge($subclassName, $auto_prefix); } /** * Instantiate a new GraphEdge from response. * * @param string|null $subclassName The GraphNode sub class to cast list items to. * @param boolean $auto_prefix Toggle to auto-prefix the subclass name. * * @return \Facebook\GraphNodes\GraphEdge * * @throws FacebookSDKException */ public function getGraphEdge($subclassName = null, $auto_prefix = true) { $factory = new GraphNodeFactory($this); return $factory->makeGraphEdge($subclassName, $auto_prefix); } } ``` Please give me some tips how to solve that problem.<issue_comment>username_1: if you using sdk facebook php, please make into method "getAccessToken()" the "redirect uri" valid, example: ``` php ... $helper-getAccessToken('https://your-site.com/re-OAuth.php'); ... ?> ``` where re-OAuth.php is is a return script.- (for example) This will solve the problem .. greetings.- Sorry for my bad english Upvotes: 1 <issue_comment>username_2: Thank you all who replied, your replies helped me to find a path to solve it. I have updated all facebook/php-graph-sdk files to 5.x version from <https://github.com/facebook/php-graph-sdk> and that solved this error. So, case is closed. Upvotes: 0
2018/03/18
2,607
5,119
<issue_start>username_0: I installed `fiona` as follows: ``` conda install -c conda-forge fiona ``` It installed without any errors. When I try to import `fiona`, I get the following error: Traceback (most recent call last): ``` File "", line 1, in File "/home/name/anaconda3/lib/python3.6/site-packages/fiona/\_\_init\_\_.py", line 69, in from fiona.collection import Collection, BytesCollection, vsi\_path File "/home/name/anaconda3/lib/python3.6/site-packages/fiona/collection.py", line 9, in from fiona.ogrext import Iterator, ItemsIterator, KeysIterator ImportError: /home/name/anaconda3/lib/python3.6/site-packages/fiona/../../.././libkea.so.1.4.7: undefined symbol: \_ZN2H56H5FileC1ERKSsjRKNS\_17FileCreatPropListERKNS\_15FileAccPropListE ``` Incase it helps with diagnosis, here is the output of `conda list`: ``` _ipyw_jlab_nb_ext_conf 0.1.0 py36he11e457_0 alabaster 0.7.10 py36h306e16b_0 anaconda custom py36hbbc8b67_0 anaconda-client 1.6.9 py36_0 anaconda-navigator 1.7.0 py36_0 anaconda-project 0.8.2 py36h44fb852_0 asn1crypto 0.24.0 py36_0 astroid 1.6.1 py36_0 astropy 2.0.3 py36h14c3975_0 attrs 17.4.0 py36_0 automat 0.6.0 py36_0 conda-forge Automat 0.6.0 babel 2.5.3 py36\_0 backports 1.0 py36hfa02d7e\_1 backports.shutil\_get\_terminal\_size 1.0.0 py36hfea85ff\_2 beautifulsoup4 4.6.0 py36h49b8c8c\_1 bitarray 0.8.1 py36h14c3975\_1 bkcharts 0.2 py36h735825a\_0 blaze 0.11.3 py36h4e06776\_0 bleach 2.1.2 py36\_0 bokeh 0.12.13 py36h2f9c1c0\_0 boost 1.66.0 py36\_1 conda-forge boost-cpp 1.66.0 1 conda-forge boto 2.48.0 py36h6e4cd66\_1 bottleneck 1.2.1 py36haac1ea0\_0 bzip2 1.0.6 h9a117a8\_4 ca-certificates 2018.1.18 0 conda-forge cairo 1.14.12 h77bcde2\_0 certifi 2018.1.18 py36\_0 conda-forge cffi 1.11.4 py36h9745a5d\_0 chardet 3.0.4 py36h0f667ec\_1 click 6.7 py36h5253387\_0 click-plugins 1.0.3 py36\_0 conda-forge cligj 0.4.0 py36\_0 conda-forge cloudpickle 0.5.2 py36\_1 clyent 1.2.2 py36h7e57e65\_1 colorama 0.3.9 py36h489cec4\_0 conda 4.3.34 py36\_0 conda-forge conda-build 3.4.1 py36\_0 conda-env 2.6.0 0 conda-forge conda-verify 2.0.0 py36h98955d8\_0 constantly 15.1.0 py\_0 conda-forge contextlib2 0.5.5 py36h6c84a62\_0 cryptography 2.1.4 py36hd09be54\_0 cssselect 1.0.3 py\_0 conda-forge curl 7.58.0 h84994c4\_0 cycler 0.10.0 py36h93f1223\_0 cython 0.27.3 py36h1860423\_0 cytoolz 0.9.0 py36h14c3975\_0 dask 0.16.1 py36\_0 dask-core 0.16.1 py36\_0 datashape 0.5.4 py36h3ad6b5c\_0 dbus 1.12.2 hc3f9b76\_1 decorator 4.2.1 py36\_0 distributed 1.20.2 py36\_0 docutils 0.14 py36hb0f60f5\_0 entrypoints 0.2.3 py36h1aec115\_2 et\_xmlfile 1.0.1 py36hd6bccc3\_0 expat 2.2.5 he0dffb1\_0 fastcache 1.0.2 py36h14c3975\_2 filelock 2.0.13 py36h646ffb5\_0 fiona 1.7.11 py36\_3 conda-forge flask 0.12.2 py36hb24657c\_0 flask-cors 3.0.3 py36h2d857d3\_0 fontconfig 2.12.4 h88586e7\_1 freetype 2.8 hab7d2ae\_1 freexl 1.0.5 0 conda-forge gdal 2.2.2 py36hc209d97\_1 geos 3.6.2 1 conda-forge get\_terminal\_size 1.0.0 haa9412d\_0 gevent 1.2.2 py36h2fe25dc\_0 giflib 5.1.4 0 conda-forge glib 2.53.6 h5d9569c\_2 glob2 0.6 py36he249c77\_0 gmp 6.1.2 h6c8ec71\_1 gmpy2 2.0.8 py36hc8893dd\_2 graphite2 1.3.10 hf63cedd\_1 greenlet 0.4.12 py36h2d503a6\_0 gst-plugins-base 1.12.4 h33fb286\_0 gstreamer 1.12.4 hb53b477\_0 h5py 2.7.1 py36h3585f63\_0 harfbuzz 1.7.4 hc5b324e\_0 hdf4 4.2.13 0 conda-forge hdf5 1.10.1 h9caa474\_1 heapdict 1.0.0 py36\_2 html5lib 1.0.1 py36h2f9c1c0\_0 hyperlink 17.3.1 py\_0 conda-forge icu 58.2 h9c2bf20\_1 idna 2.6 py36h82fb2a8\_1 imageio 2.2.0 py36he555465\_0 imagesize 0.7.1 py36h52d8127\_0 incremental 17.5.0 py\_0 conda-forge intel-openmp 2018.0.0 hc7b2577\_8 ipykernel 4.8.0 py36\_0 ipython 6.2.1 py36h88c514a\_1 ipython\_genutils 0.2.0 py36hb52b0d5\_0 ipywidgets 7.1.1 py36\_0 isort 4.2.15 py36had401c0\_0 itsdangerous 0.24 py36h93cc618\_1 jbig 2.1 hdba287a\_0 jdcal 1.3 py36h4c697fb\_0 jedi 0.11.1 py36\_0 jinja2 2.10 py36ha16c418\_0 jpeg 9b h024ee3a\_2 json-c 0.12.1 0 conda-forge jsonschema 2.6.0 py36h006f8b5\_0 jupyter 1.0.0 py36\_4 jupyter\_client 5.2.2 py36\_0 jupyter\_console 5.2.0 py36he59e554\_1 jupyter\_core 4.4.0 py36h7c827e3\_0 jupyterlab 0.31.5 py36\_0 jupyterlab\_launcher 0.10.2 py36\_0 kealib 1.4.7 4 conda-forge krb5 1.14.2 0 conda-forge lazy-object-proxy 1.3.1 py36h10fcdad\_0 libcurl 7.58.0 h1ad7b7a\_0 ``` (...) Any ideas what may be the problem?<issue_comment>username_1: I guess this problem comes from conflicts with stuff already installed in the Anaconda distribution. My inelegant workaround is: ``` conda install -c conda-forge geopandas conda remove geopandas fiona pip install geopandas fiona ``` Upvotes: 2 <issue_comment>username_2: Because I did not want to uninstall geopandas, I solved the issue by upgrading fiona via pip ``` pip install --upgrade fiona ``` Upvotes: 1
2018/03/18
466
1,540
<issue_start>username_0: Upon compilation, I got this error: ERROR in node\_modules/angular-in-memory-web-api/http-backend.service.d.ts(2,75): error TS2307: Cannot find module '@angular/http'. node\_modules/angular-in-memory-web-api/http-in-memory-web-api.module.d.ts(2,28): error TS2307: Cannot find module '@angular/http'. In package.json: "angular-in-memory-web-api": "^0.5.0" I've deleted node\_modules -> cleaned npm cache but still the same error<issue_comment>username_1: So I've tried to import the latest in-memory web API module but it didn't see http/module, so right from here <https://github.com/angular/in-memory-web-api/blob/master/http-client-backend.service.d.ts> just copied the latest code, committed 9 days ago and it worked Upvotes: 0 <issue_comment>username_2: I also got the same error. Perhaps because I used `-g` while installing. ``` npm install -g angular-in-memory-web-api --save ``` Instead of the instructed ``` npm install angular-in-memory-web-api --save ``` Re-installing without > > `-g` > > > solved the issue for me. Upvotes: 2 <issue_comment>username_3: Happened to me because when I installed the package I was in the parent directory. Make sure you are in the app directory before installing the package Upvotes: 0 <issue_comment>username_4: I had to add dependency to package.json and run npm install -i and that worked for me. Upvotes: 0 <issue_comment>username_5: just `npm install @angular/http` . Even though its derpecated. It fixes the problem for the time being Upvotes: 4
2018/03/18
526
1,724
<issue_start>username_0: In C++, I've constructed a basic class such as this: ``` class MyList { protected: list> nodes; int size; ... } ``` However later on in MyList when I try to insert a value into my nodes list, such as: ``` MyOtherClass\* temp = new MyOtherClass(size); nodes.push\_back(temp); ``` I receive a compilation error saying ``` cannot convert argument 1 from 'MyOtherClass \*' to 'MyOtherClass &&' ``` I've racked my brain and have tried everything I could think of to fix it. Thoughts?<issue_comment>username_1: That's because the type was not compatible. You list is of type `list>` and `temp` is of type `MyOtherClass\*`. Try this: ``` MyOtherClass temp(size); nodes.push\_back(temp); ``` or this: ``` class MyList { protected: list \*> nodes; int size; ... } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: > > However later on in MyList when I try to insert a value into my nodes list, such as: > > > > ``` > MyOtherClass\* temp = new MyOtherClass(size); > nodes.push\_back(temp); > > ``` > > I receive a compilation error > > > That's because you are not inserting a `MyOtherClass` value. You are inserting a pointer to an unnecessarily dynamically-allocated `MyOtherClass` value. Don't do that. Just create the new object in the normal fashion: ``` MyOtherClass temp(size); nodes.push\_back(temp); ``` Or even: ``` nodes.emplace_back(size); ``` Usually (and unless you are writing some library code or an allocator) when you have written `new`, you have made a mistake, or momentarily forgot what language you were writing in. :) And yes I know there are a million "tutorials" on the web telling you to `new` things. They are wrong. Upvotes: 0
2018/03/18
584
2,019
<issue_start>username_0: In my Django/Python application I am passing multiple iterable objects from views.py to index.html. I am essentially trying to make a standard for loop in which you can get an item by its index. Once I am iterating through the first object, how can I get the respective index of another iterable in that same loop? Conditions: All of the arrays will always be equal in length, but their length will change on a daily basis. **views.py** ``` name = ['John', 'Kim', 'Tim', 'Jill'] age = ['20', '30', '52', '27'] state = ['IN', 'IL', 'CA', 'TX'] city = ['Muncie', 'Champaign', 'Fresno', 'Dallas'] def index(request): args = {'names': name, 'ages': age, 'states': state, 'cities': city} return render(request, 'index.html', args) ``` **index.html** ``` {% extends 'base.html' %} {% load staticfiles %} {% block Data %} {% for name in names %} {{ name }} {{ age.forloop.counter0 }} {{ state.forloop.counter0 }} {{ city.forloop.counter0 }} {% endfor %} {% endblock %} ``` As you can see, I thought I would use 'forloop.counter0' as my index. But it doesn't work that way apparently. Any suggestions on how to achieve this goal? Thanks in advance!<issue_comment>username_1: You can `zip` the lists in the view and unpack them in the template: ``` def index(request): data = zip(name, age, state, city) args = {'data': data} return render(request, 'index.html', args) ``` And then in the template: ``` {% for name, age, state, city in data %} {{ name }} {{ age }} {{ state }} {{ city }} {% endfor %} ``` You could also use objects, or named tuples, with the appropriate attributes. Upvotes: 1 <issue_comment>username_2: I think what you are looking for is the "for loop counter". You can use {{ forloop.counter }} index start at 1 or {{ forloop.counter0 }} index start at 0. ``` {% for item in list %} {% if forloop.counter == 1 %} Do something {% endif %} {% endfor %} ``` Upvotes: 0
2018/03/18
333
1,195
<issue_start>username_0: I just installed Xamarin (Visual Studio). But I have a problem: When I start a new Android project (Blank app) and I open the `Main.axml` there is this message: > > This project contains resources that were not compiled successfully, rendering might be affected > > > Maybe it's easy to solve, but I can't find out what the solution is. Is there anyone who can help me?<issue_comment>username_1: You can `zip` the lists in the view and unpack them in the template: ``` def index(request): data = zip(name, age, state, city) args = {'data': data} return render(request, 'index.html', args) ``` And then in the template: ``` {% for name, age, state, city in data %} {{ name }} {{ age }} {{ state }} {{ city }} {% endfor %} ``` You could also use objects, or named tuples, with the appropriate attributes. Upvotes: 1 <issue_comment>username_2: I think what you are looking for is the "for loop counter". You can use {{ forloop.counter }} index start at 1 or {{ forloop.counter0 }} index start at 0. ``` {% for item in list %} {% if forloop.counter == 1 %} Do something {% endif %} {% endfor %} ``` Upvotes: 0
2018/03/18
332
787
<issue_start>username_0: If I have `x = [1,2,3,4,5]` `y = [6,7,8,9,10]` how can I get a two dimensional array in the form of `combined = [[1,6],[2,7],[3,8],[4,9],[5,10]]`<issue_comment>username_1: A few options. Numpy should be your go-to tool for performant array operations. Sticking with your original input values: `np.array([x,y]).T.tolist()` With vanilla python, a list comprehension will do: `[[j,k] for j,k in zip(x,y)]` Or if you don't mind tuples in place of inner lists, you can use the more terse: `list(zip(x,y))` Upvotes: 0 <issue_comment>username_2: Try numpy if you want: ``` import numpy as np x = [1,2,3,4,5] y = [6,7,8,9,10] print(np.reshape(np.dstack((x,y)),[-1,2])) ``` output: ``` [[ 1 6] [ 2 7] [ 3 8] [ 4 9] [ 5 10]] ``` Upvotes: -1
2018/03/18
655
2,129
<issue_start>username_0: I am currently having problems with a plugin. I want to give a player effects for 5 seconds and after the 5 seconds, it should be day. My problem is, that the day command is executing instantly, so it is day, before the effects are over. Can you help me, that the command for setting the time to 1000 waits 5 seconds before executing? Help would be appreciated, Till ``` p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 100, 100, true)); p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 100, 100, true)); p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 100, -100, true)); p.sendMessage("§aGute Nacht!"); //german, dont worry :D //here should be the delay of 5 seconds Bukkit.getWorld("world").setTime(1000); ```<issue_comment>username_1: You should look into `scheduleSyncDelayedTask` I haven't tested this, but you should be aiming for something like this. ``` myPlugin.getServer().getScheduler().scheduleSyncDelayedTask(myPlugin, new Runnable() { public void run() { Bukkit.getWorld("world").setTime(1000); } }, 100); ``` [scheduleSyncDelayedTask](https://jd.bukkit.org/org/bukkit/scheduler/BukkitScheduler.html#scheduleSyncDelayedTask(org.bukkit.plugin.Plugin,%20java.lang.Runnable,%20long)) > > Schedules a once off task to occur as soon as possible. This task will > be executed by the main server thread. > > > Parameters: > > > plugin - Plugin that owns the task > > > task - Task to be > executed > > > Returns: Task id number (-1 if scheduling failed) > > > Upvotes: 2 <issue_comment>username_2: I would also recommend using the [BukkitRunnable](https://hub.spigotmc.org/javadocs/spigot/org/bukkit/scheduler/BukkitRunnable.html). This class is provided as an easy way to handle scheduling tasks. ``` new BukkitRunnable( public void run() { Bukkit.getWorld("world").setTime(1000); } ).runTaskLater​(yourPluginInstance, delayInTicks); ``` Remember that 20 sever ticks is equal to 1 server second. So `delayInTicks = 5s * 20 = 100` Upvotes: 2
2018/03/18
495
1,706
<issue_start>username_0: Is is it possible to select Data like this in SQL Server? ``` select * from table(object_id) ``` I would like so pass the object\_id as parameter to the select because I need to select from a global temptable which looks different and has a different name every time. The object\_id I get like this: ``` select object_id('tempdb..##temptableXXX') ``` Thanks for your help!<issue_comment>username_1: You could do that with a little bit of T-SQL: ``` declare @tablename nvarchar(max) select @tablename = name from sys.tables where object_id = select object_id('tempdb..##temptableXXX') declare @sql nvarchar(max) = 'select * from ' + @tablename exec (@sql) ``` Upvotes: 3 <issue_comment>username_2: You can do the following, even though the answer looks a lot like what has already been provided. However this allows you to add more than just tables in the i.e. table valued functions views etc. It also takes into account that the object is not in calling user's default schema and uses two-part name in the from clause i.e. `[Schema].[Table]` Also it protects you against SQL-Injection attacks, using `QUOTENAME()` function. ``` /* input param*/ Declare @object_id INT = 117575457; Declare @SchemaName SYSNAME , @TableName SYSNAME , @Sql NVARCHAR(MAX); SELECT @TableName = [name] , @SchemaName = SCHEMA_NAME([SCHEMA_ID]) from sys.objects WHERE [type_desc] = 'USER_TABLE' --<- Can use IN Clause to add functions veiws etc AND [object_id] = @object_id; --<-- User Input variable SET @sql = N' SELECT * FROM ' + QUOTENAME(@SchemaName) + N'.' + QUOTENAME(@TableName); Exec sp_executesql @sql; ``` Upvotes: 2
2018/03/18
1,170
4,620
<issue_start>username_0: I came across the code which returned a list of "parse results" where always single result had only the exception value or successfuly parsed `T` object. ``` class SingleResult { Optional parseResult; Optional parseException; } ``` I refactored that "two purpose" class into separate classes representing successful or unsuccessfull import result, which follows also the processor refactor from returning `SingleResult` to publish to two `Consumer`s: ``` SingleResult process(Input ); ``` to: ``` void process(Input , Consumer> , Consumer ) ``` **Now I am wondering if there are some clean code rules/criteria when we should favor such `Consumer` over just returning the result?** Should we apply this approach even for single strict type returned alwyas when possible? Are there any additional drawbacks to the fact that we are "exporting" partial result during the processing still in progress? (which in many cases can be benefit for stream/event like processing and easily debuggable stack trace)<issue_comment>username_1: If you have a single immediate result, you should just return it, like Java developers did the last two decades. Deviating from the established pattern should have a reason. Reasons for using a `Consumer` are either, not having exactly one result value or not having an immediate result value. E.g. with [`Optional.ifPresent(Consumer)`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-) or [`Spliterator.tryAdvance(Consumer)`](https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html#tryAdvance-java.util.function.Consumer-) you are dealing with the possibility of not having a result value and with [`Iterable.forEach(Consumer)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-) or [`Stream.forEach(Consumer)`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer-) you might process more than one value. And with [`CompletableFuture.thenAccept(Consumer)`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#thenAccept-java.util.function.Consumer-) and its *async* variants, you have the possibility that the value still is not available when the method returns, so the consumer might get invoked at a later time. In your case, it may be reasonable to offer such a method as the result may not be present, but it might be better to offer a method like ``` void process(Input i, BiConsumer super SuccessResult<T, ? super Exception> c) ``` Compare with [`CompletableFuture.whenComplete(BiConsumer super T,? super Throwable action)`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#whenComplete-java.util.function.BiConsumer-) But there is no reason to lock your class on either pattern. Note that, e.g. both, `Optional` and `CompletableFuture`, offer methods to query the result value ([`get()`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#get--) resp, [`join()`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#join--)), together with methods to pre-check whether these methods may succeed ([`isPresent()`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#isPresent--) resp. [`isDone()`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#isDone--)/ [`isCompletedExceptionally()`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#isCompletedExceptionally--)) in addition to the consumer variants (and other chaining methods). So using a consumer is another opportunity, not meant to supersede existing patterns. Upvotes: 1 <issue_comment>username_2: The first approach is better in most cases because of KISS and YAGNI. The second approach can be useful if you are dealing with a stateful resource (e.g. InputStream) and want to enforce resource-safety. With the first approach an owner of the `Input` publishes `SingleResult` outside the `process` method and has no control over it. So in case of streaming parsing of a huge input it's very easy to run into memory problems. With the second approach parsed data never escapes the `process` method and an owner of the resource has full control over the data. So it open and close the input and apply consumers safely. Just continue with the simplest solution unless you want to leverage advantages of pure functional programming. But beware that it is often very awkward in Java. Upvotes: 0
2018/03/18
545
1,945
<issue_start>username_0: I'm trying to run a panel regression in Stata with both individual and time fixed effects. I have a lot of individuals and time periods in my sample so I don't want to print the results of all of them. But the documentation I've read online only shows how to run panel regression with one fixed effect without showing the fixed effect estimates: ``` xtset id time xtreg y x, fe //this makes id-specific fixed effects ``` or ``` areg y x, absorb(id) ``` The above two codes give the same results. Does anyone know how to run panel regressions with both id and time fixed effects but not show the estimates of either?<issue_comment>username_1: There are at least a few user-written commands that handle high-dimensional FEs in Stata. Here are two that I use a fair bit: ``` capture ssc install regxfe capture ssc install reghdfe webuse nlswork regxfe ln_wage age tenure hours union, fe(ind_code occ_code idcode year) reghdfe ln_wage age tenure hours union, absorb(ind_code occ_code idcode year) ``` You might also find this [Statalist thread](https://www.statalist.org/forums/forum/general-stata-discussion/general/1356812-fe-with-demeaned-variables-coefficients-do-not-match) interesting. Another option would be to use `margins` to show just the relevant output that you want to focus on after suppressing the regression output: ``` quietly xtreg ln_wage age tenure hours union i.(ind_code occ_code year), fe margins, dydx(age tenure hours union) ``` This is less tractable when the number of FEs get large, and can obscure other problems with the model. Upvotes: 3 [selected_answer]<issue_comment>username_2: I found another solution: ``` quietly xi: xtreg y x i.time, fe estimates store model1, title(Model 1) estimates table model1, keep(x) b se ``` This way the both time and individual fixed effects are included but only the estimates for the variable of interest (x) is printed. Upvotes: 0
2018/03/18
720
2,455
<issue_start>username_0: I'm trying to get the interior colours of a range of cells in Excel using win32com/python. Looping through each cell is not an option as that takes 3 to 5 seconds to complete while the colours change every second. Using [Range.Value(11)](https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xlrangevaluedatatype-enumeration-excel) seems like it can help, but win32com doesn't like it when any parameters are passed to Range.Value. ``` import win32com.client as win32 excel = win32.Dispatch('excel.application') fileName = r"myFile.xlsm" myBook = excel.Workbooks(fileName) mySheet = myBook.Sheets('Sheet1') myRange = mySheet.Range('I3:AL32') myState = myRange.Value # is acceptable but useless myState = myRange.Value(11) # TypeError: 'tuple' object is not callable ``` Executing myRange("I3:AL32").Value(11) in VBA within Excel works just fine, but I cannot create a custom UDF and use Application.Run from within win32com either because there is already VBA code running inside the base Excel file (which is what's changing the cell colours in the first place). Is there another way to pass that parameter into Range.Value?<issue_comment>username_1: There are at least a few user-written commands that handle high-dimensional FEs in Stata. Here are two that I use a fair bit: ``` capture ssc install regxfe capture ssc install reghdfe webuse nlswork regxfe ln_wage age tenure hours union, fe(ind_code occ_code idcode year) reghdfe ln_wage age tenure hours union, absorb(ind_code occ_code idcode year) ``` You might also find this [Statalist thread](https://www.statalist.org/forums/forum/general-stata-discussion/general/1356812-fe-with-demeaned-variables-coefficients-do-not-match) interesting. Another option would be to use `margins` to show just the relevant output that you want to focus on after suppressing the regression output: ``` quietly xtreg ln_wage age tenure hours union i.(ind_code occ_code year), fe margins, dydx(age tenure hours union) ``` This is less tractable when the number of FEs get large, and can obscure other problems with the model. Upvotes: 3 [selected_answer]<issue_comment>username_2: I found another solution: ``` quietly xi: xtreg y x i.time, fe estimates store model1, title(Model 1) estimates table model1, keep(x) b se ``` This way the both time and individual fixed effects are included but only the estimates for the variable of interest (x) is printed. Upvotes: 0
2018/03/18
356
1,135
<issue_start>username_0: I want to display some informations from the following API: <https://api.coinmarketcap.com/v1/ticker/?limit=1> But if I want to display the 24h\_volume, my browser gaves me an syntax error back: "Uncaught SyntaxError: Invalid or unexpected token" ``` var bitcoinvolume24 = "$" + r[0].24h_volume_usd + ""; ``` I know the Problem is the starting with the number 24 -> r[0].24h... , but how can I solve this. I am not able to change the API. Tried some things from here, but they don't work: ``` r[0].[24h_volume_usd] r[0].["24h_volume_usd"] ``` Thanks for your help :)<issue_comment>username_1: `r[0]["24h_volume_usd"]` you can access any object property like that Upvotes: 2 <issue_comment>username_2: You need to access properties of object using either array style braces or with dot like this ``` r[0]['24h_volume_usd'] ``` But you can't use dot here, because your key starts with number which can't be used as variable Below link can help you find more about this. <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors> Upvotes: 3 [selected_answer]
2018/03/18
245
918
<issue_start>username_0: I come the to problem with creating database table over JPA. I have some atributes for creating database table together with two fields for Date. I need to make sure, that input for DateEnd must be bigger than input for DateStart ``` @Column(name="START") private LocalDate dateStart @Column(name="END") private LocalDate dateEnd ``` Thanks for any advice<issue_comment>username_1: `r[0]["24h_volume_usd"]` you can access any object property like that Upvotes: 2 <issue_comment>username_2: You need to access properties of object using either array style braces or with dot like this ``` r[0]['24h_volume_usd'] ``` But you can't use dot here, because your key starts with number which can't be used as variable Below link can help you find more about this. <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors> Upvotes: 3 [selected_answer]
2018/03/18
345
1,148
<issue_start>username_0: I'm trying to import to a Google Sheet the number of reviews and average rating of a certain venue on Google Maps. Taking as an example this page: ``` https://www.google.com/maps?cid=8807257593070771217 ``` From Chrome's inspector, the XPath for the average should be: `//*[@id='pane']/div/div[1]/div/div/div[1]/div[3]/div[2]/div/div[1]/span[1]/span/span` However it always returns empty. Any idea why? PS - This URL redirects to another, but that shouldn't be the problem as the same thing happens with Facebook and it returns the correct values. Thanks in advance for any help<issue_comment>username_1: `r[0]["24h_volume_usd"]` you can access any object property like that Upvotes: 2 <issue_comment>username_2: You need to access properties of object using either array style braces or with dot like this ``` r[0]['24h_volume_usd'] ``` But you can't use dot here, because your key starts with number which can't be used as variable Below link can help you find more about this. <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors> Upvotes: 3 [selected_answer]
2018/03/18
413
1,222
<issue_start>username_0: Is there a way to do an assignment to a formal parameter? Something like: ``` sub myfunc($n) { $n = $n + 5; return $n; } ``` Or, would I have to create a new variable and assign the value of $n to it?<issue_comment>username_1: You can use the `is copy` trait on parameters: ``` sub myfunc($n is copy) { $n = $n + 5; return $n; } ``` See <https://docs.raku.org/type/Signature#index-entry-trait_is_copy> for more information. Upvotes: 4 [selected_answer]<issue_comment>username_2: As [mentioned by username_1](https://stackoverflow.com/a/49353402/215487) you probably want to use `is copy`. However, if you really intend to mutate a variable used as an argument to that function, you can use the `is rw` trait: ``` my $num = 3; mutating-func($num); say $num; # prints 8 sub mutating-func($n is rw) { $n = $n + 5; return $n; } ``` But this opens you up to errors if you pass it an immutable object (like a number instead of a variable): ``` # dies with "Parameter '$n' expected a writable container, but got Int value" say mutating-func(5); # Error since you can't change a value sub mutating-func($n is rw) { $n = $n + 5; return $n; } ``` Upvotes: 2
2018/03/18
568
1,812
<issue_start>username_0: I am trying to create an average solver which can take a tuple and average the numbers. I want to use the except hook to give an error message and then continue from the beginning of the while loop. 'continue' does not work. ``` import sys z = 1 x = [] y = 1 i = 1 print('Welcome to the Average Solver.') while z==1 : def my_except_hook(exctype, value, traceback): print('Please only use integers.') continue sys.excepthook = my_except_hook print("Enter your set with commas between numbers.") x=input() i=len(x) print('The number of numbers is:',i) y=float(float(sum(x))/i) print('Your average is', float(y)) print(' ') print("Would you like to quit? Press 0 to quit, press 1 to continue.") z=input() print('Thank you for your time.') ```<issue_comment>username_1: You can use the `is copy` trait on parameters: ``` sub myfunc($n is copy) { $n = $n + 5; return $n; } ``` See <https://docs.raku.org/type/Signature#index-entry-trait_is_copy> for more information. Upvotes: 4 [selected_answer]<issue_comment>username_2: As [mentioned by username_1](https://stackoverflow.com/a/49353402/215487) you probably want to use `is copy`. However, if you really intend to mutate a variable used as an argument to that function, you can use the `is rw` trait: ``` my $num = 3; mutating-func($num); say $num; # prints 8 sub mutating-func($n is rw) { $n = $n + 5; return $n; } ``` But this opens you up to errors if you pass it an immutable object (like a number instead of a variable): ``` # dies with "Parameter '$n' expected a writable container, but got Int value" say mutating-func(5); # Error since you can't change a value sub mutating-func($n is rw) { $n = $n + 5; return $n; } ``` Upvotes: 2
2018/03/18
490
1,812
<issue_start>username_0: I want to do local senstivity analysis in Dymola to evaluate different parameters affecting the energy consumption in a building (for multi-familyhouse). Can anyone give me some suggestions, how to do it in Dymola (Modelica) software?<issue_comment>username_1: Did you take a look at the "Design" library that comes with Dymola? It contains functions to sweep and perturb parameters. You can load it in File -> Libraries -> Design. Some examples on how to apply the library can be found in the first chapers of the Dymola Manual 2. From the question I guess the Calibration package should be most useful for you. Upvotes: 1 <issue_comment>username_2: One approach could be to do the modelling in Dymola (or OpenModelica, Simulation X, whatever), and then do the parameter sweep, pre- and post-processing, plotting, optimization and so on from Python. Dymola has a Python interface, so you can start simulation, read results, change parameters and so on from Python. Everything that can be done from the GUI is in theory also possible from the Python interface. A Matlab interface and a Javascript interface are also available. Upvotes: 1 <issue_comment>username_3: You could export you model as FMU and then follow one of many the different paths for sensitivity analysis with FMUs: * PyFMI + SAlib [Sensitivity Analysis using PyFMI - FMU in for-loop](https://stackoverflow.com/questions/47357897/sensitivity-analysis-using-pyfmi-fmu-in-for-loop) * FMI Toolbox for Excel by Modelon <http://www.modelon.com/products/modelon-deployment-suite/fmi-add-in-for-excel/> * openTURNS + FMI <https://www.researchgate.net/publication/321624302_A_Probabilistic_take_on_system_modeling_with_Modelica_and_Python>, <https://github.com/openturns/otfmi>, <http://www.openturns.org/> ... Upvotes: 3
2018/03/18
2,545
8,834
<issue_start>username_0: [![enter image description here](https://i.stack.imgur.com/qjNrO.jpg)](https://i.stack.imgur.com/qjNrO.jpg) [![enter image description here](https://i.stack.imgur.com/Ee5AU.jpg)](https://i.stack.imgur.com/Ee5AU.jpg) [![enter image description here](https://i.stack.imgur.com/JwMi4.jpg)](https://i.stack.imgur.com/JwMi4.jpg) I am working to have my buttons height and position adapt to screen size changes like the pictures shown above. The buttons themselves will remain clear and only serve as a simple way to handle taps that trigger the segues to different screens. My goal is to make it so that as the image stretches across different screen sizes, I would like the buttons to keep equal height and width and position with the windows. I know that if the windows had properties I could simply make the buttons have an equal size and width to them and be done, but as I mentioned the image is static and it has to stay that way for the time being. I've tried creating constraints for the buttons and that has only proven to be a headache and I don't know if stack views will help me here either, I know this is fairly complex, but I'm ok with that I just need some direction. UPDATE: In an effort to follow the instructions LGP listed properly I started from step 1. As I mentioned in the comments, I believe it's simply the ratio and the constraints conflicts since when I remove one or two it works fine, but then how do I set the constraints so it fills the entire screen and maintains the ratio of the picture? Also shown are the constraint conflicts for the image view an it isn't showing the aspect ratio of the parent container view either [![enter image description here](https://i.stack.imgur.com/YGWAO.png)](https://i.stack.imgur.com/YGWAO.png) [![enter image description here](https://i.stack.imgur.com/fnjnB.png)](https://i.stack.imgur.com/fnjnB.png) [![enter image description here](https://i.stack.imgur.com/PM0HI.png)](https://i.stack.imgur.com/PM0HI.png) [![enter image description here](https://i.stack.imgur.com/cQcdu.png)](https://i.stack.imgur.com/cQcdu.png) [![enter image description here](https://i.stack.imgur.com/FNKdt.png)](https://i.stack.imgur.com/FNKdt.png) [![enter image description here](https://i.stack.imgur.com/Y1OeD.png)](https://i.stack.imgur.com/Y1OeD.png) [![enter image description here](https://i.stack.imgur.com/eEpVC.png)](https://i.stack.imgur.com/eEpVC.png) [![enter image description here](https://i.stack.imgur.com/eT8vp.png)](https://i.stack.imgur.com/eT8vp.png) [![enter image description here](https://i.stack.imgur.com/oC4ay.png)](https://i.stack.imgur.com/oC4ay.png) [![enter image description here](https://i.stack.imgur.com/w1eG8.jpg)](https://i.stack.imgur.com/w1eG8.jpg) [![enter image description here](https://i.stack.imgur.com/uGV3u.jpg)](https://i.stack.imgur.com/uGV3u.jpg) [![enter image description here](https://i.stack.imgur.com/vZagY.jpg)](https://i.stack.imgur.com/vZagY.jpg) [![enter image description here](https://i.stack.imgur.com/xldhr.jpg)](https://i.stack.imgur.com/xldhr.jpg)<issue_comment>username_1: Use **percentage based positions and size**. Identify the positions of windows in percentage basis, and create the origin in x and y dimension by multiplying the percentage to the width and height of the screen. I am assuming that you are using **ScaleToFill** as content mode of the ImageView. Similarly for calculating size, identify the width and height of the ImageView on percentage basis, and multiply the values in percent with the total width and height of the screen. For example, to calculate the position of Window one- **Suppose, window1.x** in percentage basis is 25% & total image view width is 400 (for example), than window1.x pixel position will be- ``` window1X = (25 * 400) / 100 = 100 ``` **Suppose, window1.y** in percentage basis is 25% & total image view height is 300 (for example), than window1.y pixel position will be- ``` window1Y = (25 * 300) / 100 = 75 ``` **Suppose, width** is 7% of image views width, than width in pixel will be - ``` window1Width = (7 * 400) /100 = 28 ``` **Suppose, height** is 12% of image views height, than height in pixel will be - ``` window1Height = (12 * 300) /100 = 36 window1.frame = CGRectMake (window1X, window1Y, window1Width, window1Height) ``` Same approach for other windows, to calculate their positions(size will be same as window 1) This approach will work across all screen resolutions, since it uses **percentage based calculations** & **ScaleToFill** as content mode for image view. Upvotes: 0 <issue_comment>username_2: If you want to do it in interface builder it is not too hard. You should use *spacer views* and *proportional sizes* to position the buttons. That way, whatever size your background will have, all the elements will follow. **1. Create a container that has the same proportions as you image.** Add a regular `UIView` and set an `Aspect Ratio` constraint with a multiplier of `852:568`. This is the dimension of your background photo, 852 x 568 pixels, but the actual values don't matter, as long as the aspect ratio is the same. (Don't forget to also tie up the container view to however you want it in your view controller. See the UPDATE below on how to do this.) **2. Place the background image in the container.** Add an image view as a child to the container. Set the constraints to touch all four edges of the container. Set the `Image` property to you image, and set `Content Mode` to `Aspect Fit`. **3. Add the first spacer view.** Add a regular `UIView` to the container view (see leftmost, white view below) and set the constraints as follows: * `height = 1` (not important, I used 10 in the image) * `Top space to Superview = 90` (not important) * `Leading space to Superview = 0` * `Width equal to Superview` with multiplier **dw:cw** <- *This makes it proportional!* **dw** is the distance from the left edge to the first window/button, and **cw** is the width of the container. If your container is 375 wide, and your distance to the first button is 105, the multiplier will be 105:375. **4. Add the second space view.** This is the vertical spacer, going from top to first button. Set it up similar as the first spacer, except make the *height* proportional to the containers height, and the width fixed. **5. Add the first button.** Constrain its left and top edges to the spacers, then make its width and height proportional to the container. **6. Add the remaining spacers and buttons.** They are all the same. Just remember where to make them proportional. All buttons are constraint to the single vertical spacer. Finally, you should make the spacer views hidden. You can easily try it within your Storyboard by selecting different devices. [![enter image description here](https://i.stack.imgur.com/GihIc.jpg)](https://i.stack.imgur.com/GihIc.jpg) I chose to add everything on iPhone 8, but it is not really important. Here is what it looks like when I change to `iPad Pro 12.9"` and `iPhone SE`. Note how the buttons are positioned correctly. The spacer move around a little because they have partly fixed distances, but it works fine anyway. [![enter image description here](https://i.stack.imgur.com/6LQXa.jpg)](https://i.stack.imgur.com/6LQXa.jpg) [![enter image description here](https://i.stack.imgur.com/lrinY.png)](https://i.stack.imgur.com/lrinY.png) --- UPDATE: Here is how to constrain the container view in the view controller's view to make the container fill the whole view and still keep its aspect ratio. First, set the **image view's** (the one you added in step 2 above) `Content Compression Resistance Priority` to `200` for both `Horizontal` and `Vertical`. This will allow the image to compress rather then expand *if* it has a choice. Second, Add the following constraints to you container: * `Align Center X to Superview` * `Align Center Y to Superview` * `Equal Width to Superview >= 0` * `Equal Height to Superview >= 0` * `852:568 Ratio to View` <- *This you should already have!* Now the container will always center on screen, it will always fill *at least* the entire screen, but will also allow it to fill beyond in both X and Y. [![enter image description here](https://i.stack.imgur.com/rtgl4.png)](https://i.stack.imgur.com/rtgl4.png) --- UPDATE 2: If you want to ignore the photo's aspect ratio, and always fill the screen with the photo, you just add constraints for the container view to each side to its superview. Your container view's constraints should look like this. [![enter image description here](https://i.stack.imgur.com/xiqM8.png)](https://i.stack.imgur.com/xiqM8.png) In step 2 you will need to set the image's `Content Mode` to `Scale to fill`. The rest should be the same. Upvotes: 2 [selected_answer]
2018/03/18
268
1,016
<issue_start>username_0: I stumbled upon a roadblock with the development of a Swift playground I'm developing. I want to add an image to my ARSCNScene (ARKit + SceneKit). Not as a background, but as an actual node with positions and all. Does anyone know whether this is possible? I couldn't find anything online. Thanks!<issue_comment>username_1: You can easily add UIImage as diffuse material to your SCNPlane. Example: ``` let image = UIImage(named: "yourImageName") let node = SCNNode(geometry: SCNPlane(width: 1, height: 1)) node.geometry?.firstMaterial?.diffuse.contents = image ``` Further, you can modify your node as you like. I hope it helped! Upvotes: 5 [selected_answer]<issue_comment>username_2: I think I found a solution too for this problem since im having the same issue Write: ``` node.geometry?.firstmaterial?.diffuse.contents = #imageLiteral(resourceName: “yourimagename”) ``` Note that you have to add the image inside the assets first (as an image set of course) Upvotes: 1
2018/03/18
592
2,126
<issue_start>username_0: I've just installed AWS Command Line Interface on Windows 10 (64-bit). I ran 'aws configure' providing the two keys, a region value of us-east-1, and took the default json format. Then when I run 'aws s3 ls' I get the following error: Invalid endpoint: <https://s3..amazonaws.com> It's either not taking my region, or putting two dots where there should be one in the link. My /.aws/config file only has these lines in it: [default] region = us-east-1 Any ideas why I get 2 dots in place of my region in the s3 link, causing the invalid endpoint error? Thanks for any assistance.<issue_comment>username_1: I think that's not because of the region because you have already set default to **us-east-1** as shown by your **/.aws/config** file but your output type is not set and double check your **access key id** and **secret access key** it should be like: [![enter image description here](https://i.stack.imgur.com/UmDTk.png)](https://i.stack.imgur.com/UmDTk.png) [![enter image description here](https://i.stack.imgur.com/LKO9W.png)](https://i.stack.imgur.com/LKO9W.png) also check whether you are able to call other AWS API services such as try to create a dynamodb table using AWS CLI and check whether your IAM user have access permissions to s3 or not. Upvotes: 2 <issue_comment>username_2: You could also fix this by setting environment variables in your current session for `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION`. (in this case your error is actually caused by the CLI not finding a value for the region) Upvotes: 3 <issue_comment>username_3: This can happen if you set AWS\_DEFAULT\_REGION in your any of `.bash_profile` or `.bashrc` 1. Remove AWS\_DEFAULT\_REGION in any of those files. 2. ~/.aws/config should be like this [default] output = json region = eu-west-1 3. Restart your terminal. Upvotes: 0 <issue_comment>username_4: You can also just specify the region on the command line itself like below if you didn't want to rely on the default settings in the `~/.aws/config` file... ``` aws --region us-east-1 s3 cp s3:// ``` Upvotes: 0
2018/03/18
1,109
4,246
<issue_start>username_0: Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing? Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection. ``` jQuery(document).ready(function(){ $('.button').click(function(){ $('.input').val(); if ($('select').val() == "left"){ $('div.left').html($('.input').val()); } else { $('div.right').html($('.input').val()); } }); }); ``` Sorry if this is very basic - I am completely new to JS and jQuery. --- I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class): ``` ``` Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked. So far, I have only ever dealt with divs that had IDs, so I used document.getElementById("divId").innerHTML = ($('.input').val()); But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option. Thanks in advance!<issue_comment>username_1: Just use normal selectors, like css and jQuery does. <https://api.jquery.com/category/selectors/> in your case: ``` $('div.left').html($('.input').val()); ``` Upvotes: 2 <issue_comment>username_2: There are **plenty** of other ways to target HTML elements, but the one you're looking for in this case is **[`getElementsByTagName()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName)**. Note that this returns a **[NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)** collection of elements, so you'll additionally need to specify the index that you wish to target (starting at `0`). For example, if you want to target the second element, you can use `document.getElementsByTagName("div")[1]`. This can be seen in the following example: ```js let input = document.getElementsByTagName("input")[0]; let button = document.getElementsByTagName("button")[0]; let div2 = document.getElementsByTagName("div")[1]; button.addEventListener("click", function(){ div2.innerHTML = input.value; }); ``` ```html Output Output: ``` Upvotes: 1 <issue_comment>username_3: Since you have unique class names for each element, `document.getElementsByClassName` can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target. ```html Save function save() { var input = document.getElementsByClassName('input')[0].value; document.getElementsByClassName('left')[0].innerHTML = input; } ``` Upvotes: 1 <issue_comment>username_4: This is one of the many ways to do what you want:- Write the following in console: ``` document.getElementsByTagName("div"); ``` now you can see the total number of div elements used in your current document/page. You can select one of your choice to work on by using "index number"(as in array index) for that particular div. Lets say your div having class name = "right" is the 3rd one among the other div elements in your document. This will be used to access that div element. ``` document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write"; ``` Upvotes: 1 <issue_comment>username_5: As you see there are many ways to do this. You can get elements by [tag name](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName), [class](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName), [id](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)... But the most powerful way is to get it with [querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) ```js function save() { var input = document.querySelector('input').value; document.querySelector('div.left').innerHTML = input; } ``` ```html Save ``` Upvotes: 2
2018/03/18
920
3,522
<issue_start>username_0: I am working on a site, currently in development, and I see that only on Chrome for Mac text with an Absolute position is breaking to two lines. This doesn't happen on Chrome for PC, or Safari. The development link is <http://boldoriginal.com/sites/lana/> and here is a screenshot for reference: [![enter image description here](https://i.stack.imgur.com/pfxte.png)](https://i.stack.imgur.com/pfxte.png) If I remove the Absolute property from the text, it straightens out. I'm not entirely familiar with Mac's idiocracies so I feel like this is a common problem, but I can't find anything about it.<issue_comment>username_1: Just use normal selectors, like css and jQuery does. <https://api.jquery.com/category/selectors/> in your case: ``` $('div.left').html($('.input').val()); ``` Upvotes: 2 <issue_comment>username_2: There are **plenty** of other ways to target HTML elements, but the one you're looking for in this case is **[`getElementsByTagName()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName)**. Note that this returns a **[NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)** collection of elements, so you'll additionally need to specify the index that you wish to target (starting at `0`). For example, if you want to target the second element, you can use `document.getElementsByTagName("div")[1]`. This can be seen in the following example: ```js let input = document.getElementsByTagName("input")[0]; let button = document.getElementsByTagName("button")[0]; let div2 = document.getElementsByTagName("div")[1]; button.addEventListener("click", function(){ div2.innerHTML = input.value; }); ``` ```html Output Output: ``` Upvotes: 1 <issue_comment>username_3: Since you have unique class names for each element, `document.getElementsByClassName` can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target. ```html Save function save() { var input = document.getElementsByClassName('input')[0].value; document.getElementsByClassName('left')[0].innerHTML = input; } ``` Upvotes: 1 <issue_comment>username_4: This is one of the many ways to do what you want:- Write the following in console: ``` document.getElementsByTagName("div"); ``` now you can see the total number of div elements used in your current document/page. You can select one of your choice to work on by using "index number"(as in array index) for that particular div. Lets say your div having class name = "right" is the 3rd one among the other div elements in your document. This will be used to access that div element. ``` document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write"; ``` Upvotes: 1 <issue_comment>username_5: As you see there are many ways to do this. You can get elements by [tag name](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName), [class](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName), [id](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)... But the most powerful way is to get it with [querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) ```js function save() { var input = document.querySelector('input').value; document.querySelector('div.left').innerHTML = input; } ``` ```html Save ``` Upvotes: 2
2018/03/18
1,831
6,962
<issue_start>username_0: I have bootstrap 4 navbar component highly customed ,when I click navbar-toggle button at small screen it's not working however , in console it shows markup changes as if it's working , I tried to increase z-index , check display , check visibility but no thing works . here is a link to the page : <https://aboshalby2017.000webhostapp.com/> here is the html code : ``` <NAME>. mahmoud m. ---------- web designer * home * works * about * services * contact all copyright reserved © 2018 <NAME> * [![](images/upwork-green.png)](https://www.upwork.com/o/profiles/users/_~01f0908562a25e2c90/) * * * ``` here is scss code : ``` @import "bootstrap/functions"; @import "bootstrap/variables"; @import "bootstrap/breakpoints"; /**************************************************** navebar section ****************************************************/ .navbar { background: $mainColor1; width: 20%; top: 0; left: 0; bottom: 0; box-shadow: 5px -.0009px 20px #000; font-family: "opan-sans", sans-serif; position: fixed; z-index: 9000; @include media-breakpoint-down(lg) { width: 100%; bottom: auto; right: 0; min-height: 40px !important; height: 80px !important; overflow: hidden; } .navbar-brand { color: #333; padding: 40px 30px; font-family: 'Pacifico', cursive; span { margin-bottom: 20px; color: $mainColor4; } @include media-breakpoint-down(lg) { width: 30% !important; padding: 10px; display: inline-block; span { margin: 0; } } @include media-breakpoint-down(sm) { width: 50% !important; } } .navbar-toggler { border-color: #fff; margin: 14px 22px; i { color: #fff; width: 44px; height: 44px; font-size: 190%; line-height: 30px; padding: 5px; } } .navbar-collapse { flex-basis: auto; @include media-breakpoint-down(lg) { display: inline-block; float: right; width: 70% !important; height: 100%; } @include media-breakpoint-down(sm) { width: 100% !important; float: none; height: auto !important; } ul { @include media-breakpoint-down( lg) { display: inline-flex; margin: 0; justify-content: flex-end; } li { background: linear-gradient(#323b3f, #2e3639); color: lighten( $mainColor4, 20%); padding: 10px 25px; cursor: pointer; @include transition (.1s); &:hover { background: $mainColor2; color: #fff; padding-right: 30px } @include media-breakpoint-down( lg) { height: 100%; padding: 25px 20px; text-align: center !important; width: auto !important; display: inline-block; } @include media-breakpoint-down(sm){ height: auto; width: 100% !important; display: block; } } .active { background: $mainColor2; color: #fff; padding-right: 30px } } } footer { font-size: 15px; color: $mainColor4; margin-top: 100px; @include media-breakpoint-down(lg) { display: none; } .copyright { span { color: $mainColor2; } } } } ``` thanks anyway ;<issue_comment>username_1: Just use normal selectors, like css and jQuery does. <https://api.jquery.com/category/selectors/> in your case: ``` $('div.left').html($('.input').val()); ``` Upvotes: 2 <issue_comment>username_2: There are **plenty** of other ways to target HTML elements, but the one you're looking for in this case is **[`getElementsByTagName()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName)**. Note that this returns a **[NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)** collection of elements, so you'll additionally need to specify the index that you wish to target (starting at `0`). For example, if you want to target the second element, you can use `document.getElementsByTagName("div")[1]`. This can be seen in the following example: ```js let input = document.getElementsByTagName("input")[0]; let button = document.getElementsByTagName("button")[0]; let div2 = document.getElementsByTagName("div")[1]; button.addEventListener("click", function(){ div2.innerHTML = input.value; }); ``` ```html Output Output: ``` Upvotes: 1 <issue_comment>username_3: Since you have unique class names for each element, `document.getElementsByClassName` can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target. ```html Save function save() { var input = document.getElementsByClassName('input')[0].value; document.getElementsByClassName('left')[0].innerHTML = input; } ``` Upvotes: 1 <issue_comment>username_4: This is one of the many ways to do what you want:- Write the following in console: ``` document.getElementsByTagName("div"); ``` now you can see the total number of div elements used in your current document/page. You can select one of your choice to work on by using "index number"(as in array index) for that particular div. Lets say your div having class name = "right" is the 3rd one among the other div elements in your document. This will be used to access that div element. ``` document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write"; ``` Upvotes: 1 <issue_comment>username_5: As you see there are many ways to do this. You can get elements by [tag name](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName), [class](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName), [id](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)... But the most powerful way is to get it with [querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) ```js function save() { var input = document.querySelector('input').value; document.querySelector('div.left').innerHTML = input; } ``` ```html Save ``` Upvotes: 2
2018/03/18
1,132
3,942
<issue_start>username_0: So, here I have some variables initialized like this. ``` var center = Vector2.Zero; // For sample purpose, the real one gain the value dynamically. var size = 1F; var sizeHalf = size / 2; // The `size` variable will be like readonly after initialization in my project. var angle = 30F; var anCos = Mathf.Cos(angle); var anSin = Mathf.Sin(angle); ``` > > For the detail, `Vector2` is a `struct` and **NOT** a `class`. > > > > And I have four `Vector2` variables that I initialized like this. ``` var b = new Vector2 (center.x , center.y - sizeHalf); var t = new Vector2 (center.x , center.y + sizeHalf); var l = new Vector2 (center.x - sizeHalf , center.y); var r = new Vector2 (center.x + sizeHalf , center.y); // Re-assign to get the adjusted values b = new Vector2 (b.x , (b.x * anCos) + (b.y * anSin)); t = new Vector2 (t.x , (t.x * anCos) + (t.y * anSin)); l = new Vector2 ((l.x * anCos) - (l.y * anSin) , l.y); r = new Vector2 ((r.x * anCos) - (r.y * anSin) , r.y); ``` So, back to my question, * Is doing a variable initialization more than once re-assignment like that good approach and okay? * If it's not, should I just do something like this? ``` // Temporary variable to store most used calculated variable var pB = center.y - sizeHalf; var pT = center.y + sizeHalf; var pL = center.x - sizeHalf; var pR = center.x + sizeHalf; var b = new Vector2 (center.x, (center.x * anCos) + (pB * anSin)); var t = new Vector2 (center.x, (center.x * anCos) + (pT * anSin)); var l = new Vector2 ((pL * anCos) - (center.y * anSin), center.y); var r = new Vector2 ((pR * anCos) - (center.y * anSin), center.y); ``` * Or is there any good approach than I mentioned above? Thanks. EDIT : Here, in my code I use `var` instead of their real `TypeName`, that's because I wrote this code inside a function and just used in that scope, even more smaller scope (in that function, I have some `if`s and it's only used inside that `if`) and for the simplicity and faster variable writing, it's a simple function so I think using `var` is plenty.<issue_comment>username_1: It is absolutely OK. First option is better in terms of amount of variables in stack. Upvotes: -1 <issue_comment>username_2: > > Is doing a variable initialization more than once ... > > > First off, let's use words correctly. It is incoherent to ask what happens when you *initialize* something *twice* because by definition, the *initial value* is assigned *the initial time the variable is assigned*. That is, the *first* time. By the time the second assignment rolls around, the variable is already *initialized*; the second assignment doesn't initialize it again; **it already has its initial value**. But you meant to say "assigned", I understand. > > Is doing a variable assignment more than once like that good approach and okay in terms of memory and performance? > > > Seems fine to me. Are you experiencing memory or performance problems? If you are, this is not one of the places I would look at first. **I would use a profiler to examine my memory and performance characteristics**. Since performance is almost certainly irrelevant, the question you should have asked is: > > Is the second technique, using single assignment form, better in some other way? > > > Yes. **You should use single assignment form**, where every variable is assigned *once* if reasonably possible. The reason has nothing to do with memory or performance. The reason is because it is much easier to read, understand, debug and maintain code where the variables don't change often. A variable that changes only once, when it is initialized, is ideal. You never need to wonder what value it used to have, you never need to wonder how many times it has been mutated, and you can give your variables descriptive names the meanings of which do not change as control progresses through your method. Upvotes: 5 [selected_answer]
2018/03/18
3,604
12,284
<issue_start>username_0: I have created the app using Flutter create testapp. Now, I want to change the app name from "testapp" to "My Trips Tracker". How can I do that? I have tried changing from the `AndroidManifest.xml`, and it got changed, but is there a way that Flutter provides to do that?<issue_comment>username_1: UPDATE: From the comments this answer seems to be out of date The Flutter documentation points out where you can change the display name of your application for both Android and iOS. This may be what you are looking for: * [Preparing an Android App for Release](https://flutter.io/android-release/) * [Preparing an iOS App for Release](https://flutter.io/ios-release/) **For Android** It seems you have already found this in the `AndroidManifest.xml` as the `application` entry. > > Review the default **App Manifest** file **AndroidManifest.xml** located in > **/android/app/src/main/** and verify the values are correct, > especially: > > > **application**: Edit the **android:label** in the **application** tag to reflect the final name of the > app. > > > **For iOS** See the `Review Xcode project settings` section: > > Navigate to your target’s settings in Xcode: > > > In Xcode, open **Runner.xcworkspace** in your app’s **ios** folder. > > > > > To view your app’s settings, select the **Runner** project in the Xcode project > navigator. Then, in the main view sidebar, select the **Runner** target. > > > > > Select the **General** tab. Next, you’ll verify the most important > settings: > > > **Display Name**: the name of the app to be displayed on the home screen > and elsewhere. > > > Upvotes: 9 [selected_answer]<issue_comment>username_2: You can change it in iOS without opening Xcode by editing the project/ios/Runner/info.plist `CFBundleDisplayName` to the String that you want as your name. FWIW - I was getting frustrated with making changes in Xcode and Flutter, so I started committing all changes before opening Xcode, so I could see where the changes show up in the Flutter project. Upvotes: 5 <issue_comment>username_3: One problem is that in iOS Settings (iOS 12.x) if you change the Display Name, it leaves the app name and icon in iOS Settings as the old version. Upvotes: 3 <issue_comment>username_4: * Review the default app manifest file, `AndroidManifest.xml`, located in `/android/app/src/main` * Edit the `android:label` to your desired display name Upvotes: 4 <issue_comment>username_5: Android ------- Open `AndroidManifest.xml` (located at `android/app/src/main`) ``` // Your app name here ``` --- iOS --- Open `info.plist` (located at `ios/Runner`) ``` CFBundleDisplayName App Name // Your app name here ``` #### and/or [![enter image description here](https://i.stack.imgur.com/DiCzl.png)](https://i.stack.imgur.com/DiCzl.png) --- *Don't forget to stop and run the app again.* Upvotes: 9 <issue_comment>username_6: For Android, *change* the app name from the **Android** folder. In the *AndroidManifest.xml* file, in folder `android/app/src/main`, let the `android` label refer to the name you prefer, for example, ``` ``` Upvotes: 3 <issue_comment>username_7: There is a plugin called *[flutter\_launcher\_name](https://pub.dev/packages/flutter_launcher_name)*. Write file *pubspec.yaml*: ``` dev_dependencies: flutter_launcher_name: "^0.0.1" flutter_launcher_name: name: "yourNewAppLauncherName" ``` And run: ```none flutter pub get flutter pub run flutter_launcher_name:main ``` You can get the same result as editing `AndroidManifest.xml` and `Info.plist`. Upvotes: 6 <issue_comment>username_8: As of 2019-12-21, you need to change the name [NameOfYourApp] in file *pubspec.yaml*. Then go to menu *Edit* → *Find* → *Replace in Path*, and replace all occurrences of your previous name. Also, just for good measure, change the folder names in your *android* directory, e.g. android/app/src/main/java/com/example/*yourappname*. Then in the console, in your app's root directory, run ``` flutter clean ``` Upvotes: 2 <issue_comment>username_9: The way of changing the name for iOS and Android is clearly mentioned in the documentation as follows: * *[Build and release an Android app](https://flutter.dev/docs/deployment/android)* * *[Build and release an iOS app](https://flutter.dev/docs/deployment/ios)* But, the case of iOS after you change the *Display Name* from [Xcode](https://en.wikipedia.org/wiki/Xcode), you are not able to run the application in the Flutter way, like `flutter run`. Because the Flutter run expects the app name as *Runner*. Even if you change the name in Xcode, it doesn't work. **So, I fixed this as follows:** Move to the location on your Flutter project, *ios/Runner.xcodeproj/project.pbxproj*, and find and replace all instances of your new name with *Runner*. Then everything should work in the `flutter run` way. **But don't forget to change the name display name on your next release time. Otherwise, the [App Store](https://en.wikipedia.org/wiki/App_Store_%28iOS%29) rejects your name.** Upvotes: -1 <issue_comment>username_10: You can change it in iOS without opening Xcode by editing file \*project/ios/Runner/info.plist. Set `CFBundleDisplayName` to the string that you want as your name. For Android, *change* the app name from the Android folder, in the *AndroidManifest.xml* file, *android/app/src/main*. Let the android label refer to the name you prefer, for example, ``` ``` Upvotes: 3 <issue_comment>username_11: There are several possibilities: -------------------------------- ### 1- The use of a package: I suggest you to use [flutter\_launcher\_name](https://pub.dev/packages/flutter_launcher_name) because of the command-line tool which simplifies the task of updating your Flutter app's launcher name. **Usage:** Add your Flutter Launcher name configuration to your *pubspec.yaml* file: ``` dev_dependencies: flutter_launcher_name: "^0.0.1" flutter_launcher_name: name: "yourNewAppLauncherName" ``` After setting up the configuration, all that is left to do is run the package. ```none flutter pub get flutter pub run flutter_launcher_name:main ``` If you use this package, you don't need modify file *AndroidManifest.xml* or *Info.plist*. ### 2- Edit `AndroidManifest.xml` for Android and `info.plist` for iOS For **Android**, edit **only** `android:label` value in the **application** tag in file *AndroidManifest.xml* located in the folder: `android/app/src/main` **Code:** ``` ``` **Screenshot:** [![Enter image description here](https://i.stack.imgur.com/FD9bD.png)](https://i.stack.imgur.com/FD9bD.png) For **iOS**, edit **only** the value inside the **String** tag in file *Info.plist* located in the folder `ios/Runner` . **Code:** ``` CFBundleName Your Application Name //here ``` **Screenshot:** [![Enter image description here](https://i.stack.imgur.com/e6hpu.png)](https://i.stack.imgur.com/e6hpu.png) Do a `flutter clean` and restart your application if you have a problem. Upvotes: 4 <issue_comment>username_12: **First** Rename your AndroidManifest.xml file ``` android:label="Your App Name" ``` **Second** Rename Your Application Name in Pubspec.yaml file `name: Your Application Name` **Third** Change Your Application logo ``` flutter_icons: android: "launcher_icon" ios: true image_path: "assets/path/your Application logo.formate" ``` **Fourth** Run ``` flutter pub pub run flutter_launcher_icons:main ``` Upvotes: 1 <issue_comment>username_13: A few of the answers here suggest using the package `flutter_launcher_name`, but this package is no longer being maintained and will result in dependency issues within new Flutter 2.0 projects. The plugin `flutter_app_name` (<https://pub.dev/packages/flutter_app_name>) is a nearly identical package that has sound null safety and will work with Flutter 2.0. 1. Set your dev dependencies and your app's name ``` dev_dependencies: flutter_app_name: ^0.1.1 flutter_app_name: name: "My Cool App" ``` 2. Run `flutter_app_name` in your project's directory ``` flutter pub get flutter pub run flutter_app_name ``` Your launcher will now have the name of "My Cool App". Upvotes: 3 <issue_comment>username_14: You can change the Application name, by updating the name for both Android and iOS for **Android** just open **AndroidManifest.xml** file by, go to inside android>app>src>main>AndroidManifest.xml like this:- [![enter image description here](https://i.stack.imgur.com/TAwXW.jpg)](https://i.stack.imgur.com/TAwXW.jpg) so my application name is a "demo" so, I will update the label value. same as for **iOS** just open **Info.plist** file by, go to inside ios>Runner>Info.plist like this:- [![enter image description here](https://i.stack.imgur.com/45gB5.jpg)](https://i.stack.imgur.com/45gB5.jpg) And change this string value. Upvotes: 3 <issue_comment>username_15: I saw indeed the manual solution (to go to IOS and Android). But I found out a plugin which enables changing name from one single location: <https://pub.dev/packages/flutter_launcher_name> Just do the following: Add to `pubspec.yaml` ``` dev_dependencies: flutter_launcher_name: "^0.0.1" flutter_launcher_name: name: "yourNewAppLauncherName" ``` Run in Terminal: ``` flutter pub get flutter pub run flutter_launcher_name:main ``` Done. Upvotes: 2 <issue_comment>username_16: You can easily do this with [rename](https://pub.dev/packages/rename) package, It helps you to change your Flutter project's **AppName** and **BundleId** for any platform you want and it is currently supporting all the 6 platforms (Android, IOS, Linux, macOS, Windows, and Web). * To install the package run the following command: ``` flutter pub global activate rename ``` * To rename the App, use the following command: ``` flutter pub global run rename --appname "Your App Name" ``` **That's It!** --- You can check the [documentation](https://pub.dev/packages/rename) of the package for full details because it has some nice features to choose the target platform and more. Upvotes: 3 <issue_comment>username_17: in case you are releasing for multi-localizations (languages). **for Android:** in your app folder at **[appname]\android\app\src\main\res** add locale folders for example: **values-ar** **valuse-en** then inside each folder add a new **strings.xml** that contains the app name in that language. for *ar* ``` xml version="1.0" encoding="UTF-8"? ادارة الديون ``` for *en* ``` xml version="1.0" encoding="UTF-8"? debt management ``` The last thing you can do is go to your **AndroidManifest.xml** file and set the **android:label** to the new files you have created. ``` android:label="@string/app_name" ``` Upvotes: 2 <issue_comment>username_18: If you like to automate stuff from command line like me, you can use this ``` appName="TestApp" declare -a androidAppTypes=( "main" "debug" "profile" ) # Change app name for Android for appType in ${androidAppTypes[@]} do xmlstarlet ed -L -u '/manifest/application/@android:label' -v "$appName" android/app/src/$appType/AndroidManifest.xml done # Change app name for Android plutil -replace CFBundleDisplayName -string "$appName" ios/Runner/Info.plist ``` Upvotes: 0 <issue_comment>username_19: Android ------- **android/app/src/main/AndroidManifest.xml** iOS and macOS ------------- **ios/runner/Info.plist** ``` CFBundleDisplayName Display Name // <---- HERE ``` Windows ------- **windows/runner/Runner.rc** ``` BEGIN VALUE "CompanyName", "com.company" "\0" VALUE "FileDescription", "Display Name" "\0" // <---- HERE VALUE "FileVersion", VERSION_AS_STRING "\0" VALUE "InternalName", "Display Name" "\0" // <---- HERE VALUE "LegalCopyright", "Copyright (C) 2023 com.company. All rights reserved." "\0" VALUE "OriginalFilename", "appname.exe" "\0" VALUE "ProductName", "Display Name" "\0" // <---- HERE VALUE "ProductVersion", VERSION_AS_STRING "\0" END ``` --- **windows/CMakeLists.txt** (and not windows/runner/CMakeLists.txt) ``` set(BINARY_NAME "appname") // <---- HERE TO CHANGE OUTPUT FILE appname.exe ``` --- **windows/runner/main.cpp** ``` if (!window.Create(L"Display Name", origin, size)) { return EXIT_FAILURE; } ``` Upvotes: 2
2018/03/18
913
3,072
<issue_start>username_0: I am learning about inheritance in Python and I was experimenting with superclasses and the `super()` function. Here is my code: ``` class Person: def __init__(self, name, age, weight): self.name = name self.age = age self.weight = weight def describe(self): return f"{self.name}, {self.age}, {self.weight}" class Engineer(Person): def __init__(self, name, age, weight): super().__init__("Bla bla", 10, 100) self.name = name self.age = age self.weight = weight self.occupation = "Engineer" def describe(self): return super().describe() my_engineer = Engineer("Larry", 17, 120) print(my_engineer.describe()) ``` I have a Java background, and apparently `super()` works differently in Python than it does in Java. In Java, the output of code equivalent to this would be `Bla bla, 17, 120`, but this code is outputting `Larry, 17, 120`. Why is this code printing out `Larry, 17, 120` rather than what I expected it to? To my understanding, I am instantiating the class `Engineer` and passing in `"Larry"`, `17`, and `120` to `__init__`, but then I pass in `"Bla bla"`, `10`, and `100` to the superclass's `__init__`, so the superclass should be initialized with those values. Then when I call `my_engineer.describe()`, it should call `describe()` in the superclass and use the superclass's passed in values. But apparently, this is not what is happening. Can anyone explain what is going on?<issue_comment>username_1: `super` is working correctly; however, after the `super` call, you override every attribute with the values passed to the child constructor. Instead, simply call `super` and do not initialize the child class with the same attributes: ``` class Engineer(Person): def __init__(self, *args): super().__init__("Bla bla", 10, 100) def describe(self): return super().describe() my_engineer = Engineer("Larry", 17, 120) print(my_engineer.describe()) ``` Output: ``` Bla bla, 10, 100 ``` Upvotes: 2 <issue_comment>username_2: You're seeing the attributes being overridden. What's happening in these lines of code: ``` super().__init__("Bla bla", 10, 100) self.name = name self.age = age self.weight = weight self.occupation = "Engineer" ``` * `super().__init__("Bla bla", 10, 100)` calls `Person`'s `__init__` with these values i.e. `self = Person("Bla bla", 10, 100)`. If you stopped here, you'd have instantiated a subclass of `Person` and not really changed anything. (Same attributes, same method.) * When you then specify the next four attributes, you override what what you did in the previous line. These are set directly as the attributes of the class instance. Essentially, that looks to Python something like: ``` my_engineer = Person("Bla bla", 10, 100) my_engineer.name = "Larry" my_engineer.age = 17 my_engineer.weight = 120 my_engineer.occupation = "Engineer" ``` As mentioned by @username_1, it seems like you want to just get rid of those four lines altogether. Upvotes: 3 [selected_answer]
2018/03/18
3,667
13,528
<issue_start>username_0: <https://i.stack.imgur.com/pteDe.png> A: When the man page for open says: The flags specified are formed by or'ing the following values: ``` O_RDONLY open for reading only O_WRONLY open for writing only ... ``` it means we should use a logical or between the flags like this: O\_RDONLY || O\_WRONLY to specify the combination of permissions we want. B: To indicate different options we use bit flags (rather than characters or integers) in order to save space. C: Performing operations on bit flags is fast. D: Bit flags used in system calls are defined in library files. E: The command chmod uses bit flag constants defined in octal because there are eight possible permission states. I know bit flags are not defined in library files if it is a good system library. They are usually constants or #defines in the header, not the compiled object, if that is what "library files" refers to. However, I don't understand how they save space, aren't bit flags just integers after all?<issue_comment>username_1: **A Brief Overview of What Bitflags are** Bit flags are constants that define a set of some kind, usually options of various kinds. Bit flags are typically defined as hexadecimal constants and the intent is to use the bitwise operators with these constants in order to create some subset out of the total set of constants by using the bitwise operators. The bitwise operators are the operators such as `|` (bitwise Or), `&` (bitwise And), `^` (bitwise Exclusive Or), and `~` (bitwise Not) which perform bit by bit the Boolean logic operation designated by the operator on the two values to generate a new value. The bitwise operators are different from the logical operators such as `||` (logical Or), `&&` (logical And) which are used with expressions that evaluate to a boolean value of true (non-zero) or false (zero). An example of a typical definition using C Preprocessor `define` directives to create bitwise flags would be: ``` #define ITM_FLAG_EXAMPLE1 0x00000001L // an example bitwise flag #define ITM_FLAG_EXAMPLE2 0x00000002L // another example flag #define ITM_FLAG_JUMP01 0x00040000L // another example #define ITM_FLAG_JUMP02 0x00080000L // another example ``` In addition modern C compilers will allow the use of `enum` types as well. ``` typedef enum { ITEM_FLAG_1 = 1, ITEM_FLAG_2 = 2, ITEM_FLAG_3 = 4 } ItemType; ItemType AnItem = ITEM_FLAG_1; // defining a variable of the type ItemType AnItem2 = ITEM_FLAG_1 | ITEM_FLAG_2; // defining a second variable ``` or ``` enum { ITEM_FLAG_1 = 1, ITEM_FLAG_2 = 2, ITEM_FLAG_3 = 4 } ItemType; enum ItemType AnItem = ITEM_FLAG_1; // defining a variable of the type enum ItemType AnItem2 = ITEM_FLAG_1 | ITEM_FLAG_2; // defining a second variable ``` And for a few examples of how these can be used: ``` unsigned long ulExample = ITM_FLAG_EXAMPLE2; // ulExample contains 0x00000002L unsigned long ulExamplex = ITM_FLAG_EXAMPLE1 | ITM_FLAG_EXAMPLE2; // ulExamplex contains 0x00000003L unsigned long ulExampley = ulExamplex & ITM_FLAG_EXAMPLE2; // ulExampley contains 0x00000002L ``` See this blog posting, [Intro to Truth Tables & Boolean Algebra](https://medium.com/i-math/intro-to-truth-tables-boolean-algebra-73b331dd9b94), which describes the various Boolean Algebra operations and this [Wikipedia topic on Truth Tables](https://en.wikipedia.org/wiki/Truth_table). **Some Considerations Using Bitflags** There can be a few gotchas when using bitflags and a few things to look out for. * use of a bitflag defined constant that is zero, no bits set, can cause problems * bitwise operations mixed with logical operations can be an area for defects In general using a bitflag whose definition is a value of zero rather non-zero can lead to errors. Most programmers expect that a bitflag will have a non-zero value that represents membership in a set of some kind. A bitflag whose definition is zero is a kind of breach of expectations and when used in bitwise operations can lead to unexpected consequences and behavior. When combining bitwise operations on bitflag variables along with logical operators, parenthesis to enforce specific operator precedence is generally more understandable as it does not require the reader to know the [C operator precedence table](https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B). **On to the Posted Questions** When a library is provided there is typically one or more include files that accompany the library file in order to provide a number of needed items. * function prototypes for the functions provided by the library * variable type declarations and definitions for the types used by the library * special constants for operands and flags that govern the behavior of the library functions Bit flags are a time honored way to provide options for a function interface. Bit flags have a couple of nice properties that make them appealing for a C programmer. * compact representation that is easy to transfer over an interface * a natural fit for Boolean Algebra operations and set manipulation * a natural fit with the C bitwise operators to perform those operations Bit flags save space because the name of the flag may be long and descriptive but compile down to a single unsigned value such as unsigned short or unsigned long or unsigned char. Another nice property of using bit flags is that when using bitwise operators on constants in an expression, most modern compilers will evaluate the bitwise operation as a part of compiling the expression. So a modern compiler will take multiple bitwise operators in an expression such as `O_RDONLY | O_WRONLY` and do the bitwise Or when compiling the source and replace the expression with the value of the evaluated expression. In most computer architectures the bitwise operators are performed using registers into which the data is loaded and then the bitwise operation is performed. For a 32 bit architecture, using a 32 bit variable to contain a set of bits fits naturally into CPU registers just as in a 64 bit architecture, using either a 32 or 64 bit variable to contain a set of bits fits naturally into registers. This natural fit allows multiple bitwise operations on the same variables without having to do a fetch from the CPU cache or main memory. The bitwise operators of C almost always have a CPU machine instruction analogue so that the C bitwise operators have an almost exactly similar CPU operation so the resulting machine code generated by the compiler is quite efficient. The compact representation of bit flags can be easily seen by using an `unsigned long` to pass 32 different flags or an `unsigned long long` to pass 64 different flags to a function. An array of `unsigned char` can be used to pass many more flags by using an array offset and bit flag method along with a set of C Processor macros or a set of functions to manipulate the array. **Some Examples of What is Possible** The bitwise operators are very similar to the logical operators used with sets and representing sets with bit flags works out well. If you have a set that contains operands, some of which should not be used with some of the other flags then using the bitwise operators and masking of bits makes it easy to see if both of the conflicting flags are specified. ``` #define FLAG_1 0x00000001L // a required flag if FLAG_2 is specified #define FLAG_2 0x00001000L // must not be specified with FLAG_3 #define FLAG_3 0x00002000L // must not be specified with FLAG_2 int func (unsigned long ulFlags) { // check if both FLAG_2 and FLAG_3 are specified. if so error // we do a bitwise And to isolate specific bits and then compare that // result with the bitwise Or of the bits for equality. this approach // makes sure that a check for both bits is turned on. if (ulFlags & (FLAG_2 | FLAG_3) == (FLAG_2 | FLAG_3)) return -1; // check to see if either FLAG_1 or FLAG_3 is set we can just do a // bitwise And against the two flags and if either one or both are set // then the result is non-zero. if (ulFlags & (FLAG_1 | FLAG_3)) { // do stuff if either or both FLAG_1 and/or FLAG_3 are set } // check that required option FLAG_1 is specified if FLAG_2 is specified. // we are using zero is boolean false and non-zero is boolean true in // the following. the ! is the logical Not operator so if FLAG_1 is // not set in ulFlags then the expression (ulFlags & FLAG_1) evaluates // to zero, False, and the Not operator inverts the False to True or // if FLAG_1 is set then (ulFlags & FLAG_1) evaluates to non-zero, True, // and the Not operator inverts the True to False. Both sides of the // logical And, &&, must evaluate True in order to trigger the return. if ((ulFlags & FLAG_2) && ! (ulFlags & FLAG_1)) return -2; // other stuff } ``` For example see [Using select() for non-blocking sockets](https://stackoverflow.com/questions/6715736/using-select-for-non-blocking-sockets) for a brief overview of the standard `socket()` interface of using bit flags and the `select()` function for examples of using a set manipulation abstraction that is similar to what can be done with bit flags. The `socket` functions allow for the setting of various characteristics such as non-blocking through the use of bit flags with the `fcntl()` function and the `select()` function has an associated set of function/macros (`FD_SET()`, `FD_ZERO()`, etc.) that provides an abstraction for indicating which socket handles are to be monitored in the `select()`. I do not mean to imply that `select()` socket sets are bit maps, though in the original UNIX, I believe they were. However the abstract design of `select()` and its associated utilities provides a kind of sets that could be implemented with bit flags. The evaluation of a variable containing bitwise flags can also be quicker and easier and more efficient and more readable. For instance in a function being called with some of the defined flags: ``` #define ITEM_FLG_01 0x0001 #define ITEM_FLG_02 0x0002 #define ITEM_FLG_03 0x0101 #define ITEM_FLG_04 0x0108 #define ITEM_FLG_05 0x0200 #define ITEM_FLG_SPL1 (ITEM_FLG_01 | ITEM_FLG_02) ``` there may be a `switch()` statement such as: ``` switch (bitwiseflags & ITEM_FLG_SPL1) { case ITEM_FLG_01 | ITEM_FLG_02: // do things if both ITEM_FLG_01 and ITEM_FLG_02 are both set break; case ITEM_FLG_01: // do things if ITEM_FLG_01 is set break; case ITEM_FLG_02: // do things if ITEM_FLG_02 is set break; default: // none of the flags we are looking for are set so error return -1; } ``` And you can do some short and simple expressions such as the following using the same defines as above. ``` // test if bitwiseflags has bit ITEM_FLG_5 set and if so then call function // doFunc(). (bitwiseflags & ITEM_FLG_5) == ITEM_FLG_5 && doFunc(); ``` **Addendum: A Technique for Really Large Sets of Bitflags** See this answer, [Creating bitflag variables with large amounts of flags or how to create large bit-width numbers](https://stackoverflow.com/a/49406316/1466970) for an approach for large sets, larger than can fit in a 32 bit or 64 bit variable, of bitflags. Upvotes: -1 <issue_comment>username_2: First of all, `|` and `||` are different operators. `|` is the bit-wise OR operator which does an OR on every bit and you get the result of that. `||` is the logical OR operator which returns true if the left side is true or the right side is true, false otherwise. In case of bit flag, you should use `|`, like `O_RDONLY | O_WRONLY` > > B: To indicate different options we use bit flags (rather than characters or integers) in order to save space. > > > I think that this phrasing is a bit missleading, to be honest. The nice thing about bit flags, is that you can pack in a single `int`, mostly 32 bit long, up to 32 different values that have a ON/OFF semantic. So the function that takes these kind of options, only has to use a single `int` to get multiple options from the caller because the single bits represent such a on/off property. If the bit is 1, then the propery is ON, otherwise OFF. In constract, when you don't use bit flags, the function would have to take a separate variable for every options and if you have many options, you would need a lot of variables in the function declaration. So you can "save space" if you use bit flags instead. Consider this: ``` // lot's of other has_property_x cases int somefunc(int has_property_a, int has_property_b, int has_property_c, ...) { if(has_property_a) do_something_based_on_a(); if(has_property_b) do_something_based_on_b(); .... } void foo(void) { somefunc(1, 1, 0, 1, 1); } ``` This is not very efficient, it's hard to read, it's a pain in the butt to code, overall not a good design. However if you use bit flags, you can save a lot of variables in the functions: ``` // lot's of other HAS_PROPERTY_X cases #define HAS_PROPERTY_A 1 #define HAS_PROPERTY_B 2 #define HAS_PROPERTY_C 4 ... int somefunc(int flags) { if(flags & HAS_PROPERTY_A) do_something_based_on_a(); if(flags & HAS_PROPERTY_B) do_something_based_on_b(); ... } void foo(void) { somefunc(HAS_PROPERTY_A | HAS_PROPERTY_B | HAS_PROPERTY_E); } ``` is much more compact and readable. Upvotes: 3 [selected_answer]
2018/03/18
829
3,054
<issue_start>username_0: I’m experimenting with XGBoost and am blocked by an error I can’t figure out. I have sklearn installed in the active environment and can verify it by training a sklearn RandomForestClassifier *in the same notebook*. When I try to train a XGBoost model I get the error `XGBoostError: sklearn needs to be installed in order to use this module` This works: ``` clf = RandomForestClassifier(n_estimators=200, random_state=0, n_jobs=-1) ``` This throws the exception: ``` clf = xgb.XGBClassifier(max_depth=3, n_estimators=300, learning_rate=0.05).fit(train_X, train_y) ``` UPDATE: Created a PyCharm module with *exactly* the same code and imports and it executed without an exception. So this appears to be a Jupyter Notebook issue. PyCharm is pointed to the same Anaconda environment as the notebook. UPDATE 2: Created a *new* notebook and copied the code from the one that was throwing the exception. The code runs OK in the new notebook. Sigh. Case closed.<issue_comment>username_1: Ran into the same issue, I had installed `sklearn` **after** installing `xgboost` **while** my jupyter notebook was running. By restarting my Jupyter notebook server, `xgboost` was able to find the `sklearn` installation. Tested this in another fresh environment where I've installed `sklearn` **before** installing `xgboost` **then** starting my jupyter notebook without the issue. Upvotes: 3 <issue_comment>username_2: I got the same error with a more complicated project, after releasing a new version suddenly it failed. luckily in my case, I had docker images for each version, and was able to use `pip freeze` to see what changed. In both version I used `xgboost==0.81` In the version that worked I had `scikit-learn==0.21.3` and in the new version it was `scikit-learn==0.22` surprisingly enough, that's now what caused the issue. I've tried to uninstall and reinstall `xgboost` and reverted `scikit-learn` to the version is was originally on, and still no luck (even after making sure to install one after the other in the right order). what did cause the issue was an update of `numpy` from `1.17.4` to `1.18.0`. reverting it solved it for me (not sure why) this was python 3.6 on ubuntu Upvotes: 0 <issue_comment>username_3: I had the same issue. All the already given answers did not work. I tried downgrading numpy versions as well, as it was said to work at some other forum I eventually reinstalled Anaconda and then installed pip installed xgboost again. This worked. Upvotes: 0 <issue_comment>username_4: If you have the correct version of xgboost and sklearn. Then after installing on Jupyter notebook. you will see it is not working just restart your jupyter notebook. I solved using this way from this source: <https://www.titanwolf.org/Network/q/9e5adeeb-f57f-4283-8989-d213d7c61864/y> says: Ran into the same issue, I had installed sklearn after installing xgboost while my jupyter notebook was running. By restarting my Jupyter notebook server, xgboost was able to find the sklearn installation. Upvotes: 0
2018/03/18
1,928
6,560
<issue_start>username_0: I work with Nibs. I have two screens that will use the "same" `UIView` component with the same behavior. It's not the same component because in each screen i placed a `UIView` and made the same configuration, as show on the image. [![The two Screens](https://i.stack.imgur.com/LhN5O.png)](https://i.stack.imgur.com/LhN5O.png) To solve this and prevent replicate the same code in other classes i wrote one class, that is a `UIView` subclass, with all the functions that i need. After that i made my custom class as superclass of these `UIView` components to inherit the `IBOutlets` and all the functions. [![Added as SuperClass of UIView Components](https://i.stack.imgur.com/RXnF9.png)](https://i.stack.imgur.com/RXnF9.png) [![Custom superclass add success](https://i.stack.imgur.com/Vsrod.png)](https://i.stack.imgur.com/Vsrod.png) My custom class is not defined in a `Nib`, is only a `.swift` class. I made all the necessary connections but at run time the `IBOutlets` is `Nil`. [![IBOutlets Connected](https://i.stack.imgur.com/nfjGN.png)](https://i.stack.imgur.com/nfjGN.png) [![Connections on View](https://i.stack.imgur.com/Sd22t.png)](https://i.stack.imgur.com/Sd22t.png) [![Connections on UITableViewCell](https://i.stack.imgur.com/20s5a.png)](https://i.stack.imgur.com/20s5a.png) The code of my custom class: ``` class FeelingGuideView: UIView { @IBOutlet weak var firstScreen: UILabel! @IBOutlet weak var secondScreen: UILabel! @IBOutlet weak var thirdScreen: UILabel! @IBOutlet weak var fourthScreen: UILabel! private var labelsToManage: [UILabel] = [] private var willShow: Int! private var didShow: Int! override init(frame: CGRect) { super.init(frame: frame) self.initLabelManagement() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initLabelManagement() } private func initLabelManagement() { self.initLabelVector() self.willShow = 0 self.didShow = 0 self.setupLabelToShow(label: labelsToManage[0]) self.setupLabels() } private func initLabelVector() { self.labelsToManage.append(self.firstScreen) self.labelsToManage.append(self.secondScreen) self.labelsToManage.append(self.thirdScreen) self.labelsToManage.append(self.fourthScreen) } private func setupLabels() { for label in labelsToManage { label.layer.borderWidth = 2.0 label.layer.borderColor = UIColor(hex: "1A8BFB").cgColor } } func willShowFeelCell(at index: Int) { self.willShow = index if willShow > didShow { self.setupLabelToShow(label: labelsToManage[willShow]) } else if willShow < didShow { for i in didShow ... willShow + 1 { let label = labelsToManage[i] self.setupLabelToHide(label: label) } } } private func setupLabelToShow(label: UILabel) { label.textColor = UIColor.white label.backgroundColor = UIColor(hex: "1A8BFB") } private func setupLabelToHide(label: UILabel) { label.textColor = UIColor(hex: "1A8BFB") label.backgroundColor = UIColor.white } } ``` I found this question similar to mine: [Custom UIView from nib inside another UIViewController's nib - IBOutlets are nil](https://stackoverflow.com/questions/20014437/custom-uiview-from-nib-inside-another-uiviewcontrollers-nib-iboutlets-are-nil) But my `UIView` is not in a nib. **EDIT:** I overrided the `awakeFromNib` but it neither enter the method. **More explanation:** My custom class is only superClass of this component: [![Custom UIView](https://i.stack.imgur.com/f5ztI.png)](https://i.stack.imgur.com/f5ztI.png) Which i replicate on two screens. One screen is a `UITableViewCell` and the another a `UIViewController`. It's all about to manage the behavior of the labels depending on the screen that is showing at the moment on the `UICollectionView` When the `initLabelVector()` function is called at the `required init?(coder aDecoder:)` it arrises a unwrap error: [![Error](https://i.stack.imgur.com/zTdYV.png)](https://i.stack.imgur.com/zTdYV.png) The error when try to open the `View`: [![enter image description here](https://i.stack.imgur.com/J2nE7.png)](https://i.stack.imgur.com/J2nE7.png) Cannot show the error with the `UITableViewCell` because it is called at the beginning of the app and don't appear nothing. To show the error with the screen i needed to remove the call of the `UITableViewCell`. The `UITableViewCell` is registered first with the `tableView.register(nib:)` and after using the `tableView.dequeueReusebleCell`. The `UIViewController` is called from a menu class that way: ``` startNavigation = UINavigationController(rootViewController: FellingScreenViewController()) appDelegate.centerContainer?.setCenterView(startNavigation, withCloseAnimation: true, completion: nil) ```<issue_comment>username_1: When the `init()` from my custom class is called the `IBOutlets` are not hooked up yet. So, I created a reference on the parent view and called the `iniLabelManagement()` from the `viewDidLoad()` method and everything worked. Thank you username_2, for the help and patience! Upvotes: 1 <issue_comment>username_2: The problem is this code: ``` required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initLabelManagement() } ``` The trouble is that `init(coder:)` is *too soon* to speak of the view's outlets, which is what `initLabelManagement` does; the outlets are not hooked up yet. Put this instead: ``` required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() self.initLabelManagement() } ``` --- ### How I arrived at this answer: As a test, I tried this: ``` class MyView : UIView { @IBOutlet var mySubview : UIView! required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) print(#function, self.mySubview) } override func awakeFromNib() { super.awakeFromNib() print(#function, self.mySubview) } } ``` Here's the output: ``` init(coder:) nil awakeFromNib() ``` What this proves: * `init(coder:)` is *too soon*; the outlet is not hooked up yet * `awakeFromNib` is *not* too soon; the outlet *is* hooked up * `awakeFromNib` *is called*, despite your claim to the contrary Upvotes: 3 [selected_answer]
2018/03/18
980
3,259
<issue_start>username_0: I have an array of objects ``` myArray= [{"FName":"", "LastName":"", "data" :[{ active:true, times: 50 },{ active: false, times:450 } ]}] myArray.map(x => x.data = x.data.sort((y,z) => y.times > z.times)) ``` But how do I sort so that Initially I ihave the data whose active field is TRUE, and then sort by Times ? Thank you.<issue_comment>username_1: use a custom sorter ``` var sorter = function(a, b) { if (a.active || b.active) { return 1 } return 0 } var array = [{active: false, name: 'one'}, {active: true, name: 'two'}, {active: true, name: 'three'}, {active: false, name: 'four'}] array.sort(sorter).map((obj) => {console.log(obj)}) ``` Works :D Upvotes: -1 <issue_comment>username_2: You can first sort the data array on times. Then add one more sort function on data to sort by active flag; ```js myArray= [ { "FName": "", "LastName": "", "data": [ { "active": true, "times": 50 }, { "active": false, "times": 450 }, { "active": true, "times": 20 }, { "active": true, "times": 350 }, { "active": true, "times": 200 }, { "active": false, "times": 100 } ] } ] myArray.map(x => { x.data = x.data.sort((y,z) => y.times > z.times).sort((y,z) => y.active < z.active); }); console.log(myArray) ``` Upvotes: -1 <issue_comment>username_3: The [`Array.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) compareFunction(a, b) function should return a number: * Negative number - **a** should come before **b**. * 0 - **a** and **b** have the same priority. * Positive number - **b** should come before **a**. In your case the logic is find the order by `active`, and if both have the same `active` value, check the `times`. We can use simple subtraction, since booleans are treated as numbers (0 | 1): ``` z.active - y.active || z.times - y.times ``` **Notes:** 1. Since you are using [`Array.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), return clones of the objects, and arrays to prevent changes to the originals. If you want to change the original, use [`Array.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) instead. I clone the objects and arrays using the [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). 2. In sort, if two items have the same value (comparator result 0), the order is not guaranteed, and depends on the browser's implementation. **Example:** ```js const myArray = [{"FName":"","LastName":"","data":[{"active":true,"times":50},{"active":false,"times":450},{"active":false,"times":50},{"active":true,"times":450}]}] const result = myArray.map(x => ({ ...x, data: [...x.data].sort((y,z) => z.active - y.active || z.times - y.times) })) console.log(result) ``` Upvotes: 1
2018/03/18
2,322
7,365
<issue_start>username_0: I am trying to overcome an issue when trying to display new maps. The goal of this code is to have the dropdown menu selection overwrite the existing map in the Content pane as well as overwrite the information in the Legend on the tab container. When running the code, I am running into the following error: ``` Error: Tried to register widget with id==legend1 but that id is already registered ``` I understand that the destroy function I created should delete the code I created previously, but I am unsure as to the origin of the issue. I was wondering what could be the cause of this issue and how I could get around it? Any help would be appreciated. ``` Lab 6 Web API Map selection var map, scalebar, legendDijit, overviewMapDijit; require([ "dojo/parser", "dijit/form/Select", "dijit/layout/BorderContainer", "dijit/layout/TabContainer", "dijit/layout/ContentPane", "dojo/on", "dojo/dom", "dijit/registry", "dojo/dom-construct", "esri/map", "esri/urlUtils", "esri/arcgis/utils", "esri/dijit/Legend", "esri/dijit/Scalebar", "esri/dijit/OverviewMap", "dojo/domReady!" ], function ( parser, select, BorderContainer, TabContainer, ContentPane, on, dom, registry, domConstruct, Map, urlUtils, arcgisUtils, Legend, Scalebar, OverviewMap ) { parser.parse(); //Initial map creation for Chicago youth arcgisUtils.createMap("c63cdcbbba034b62a2f3becac021b0a8", "MapArea").then(function (response) { dom.byId("title").innerHTML = response.itemInfo.item.title; var map = response.map; var scalebar = new Scalebar({ map: map, scalebarUnit: "english" }); var legendLayers = arcgisUtils.getLegendLayers(response); var legendDijit = new Legend({ map: map, layerInfos: legendLayers }, "legend1"); legendDijit.startup(); var overviewMapDijit = new OverviewMap({ map: map, visible: true }); overviewMapDijit.startup(); }); var dropdown = registry.byId("mapoption").attr('value'); var switch1 = registry.byId("mapoption"); //function which swtiches between the maps and creates new map aspects //for each new map. switch1.on('change', function(event){ var dropdown = registry.byId('mapoption').attr('value'); dom.byId('title').innerHTML = dropdown; switch (dropdown){ case "Chicago": destroyerFunc(); arcgisUtils.createMap("c63cdcbbba034b62a2f3becac021b0a8", "MapArea").then(function (response) { dom.byId("title").innerHTML = response.itemInfo.item.title; var map = response.map; var scalebar = new Scalebar({ map: map, scalebarUnit: "english" }); var legendLayers = arcgisUtils.getLegendLayers(response); var legendDijit = new Legend({ map: map, layerInfos: legendLayers }, "legend1"); legendDijit.startup(); var overviewMapDijit = new OverviewMap({ map: map, visible: true }); overviewMapDijit.startup(); }); break; case "MedianInc": destroyerFunc(); arcgisUtils.createMap("1e79439598494713b553f990a4040886", "MapArea").then(function (response) { dom.byId("title").innerHTML = response.itemInfo.item.title; var map = response.map; var scalebar = new Scalebar({ map: map, scalebarUnit: "english" }); var legendLayers = arcgisUtils.getLegendLayers(response); var legendDijit = new Legend({ map: map, layerInfos: legendLayers }, "legend1"); legendDijit.startup(); var overviewMapDijit = new OverviewMap({ map: map, visible: true }); overviewMapDijit.startup(); }); break; case "Topographic": destroyerFunc(); map = new Map("MapArea", { basemap: "topo", center: [-90.34, 47.21], zoom: 5 }); var scalebar = new Scalebar({ map: map, scalebarUnit: "english" }); var overviewMapDijit = new OverviewMap({ map: map, visible: true }); overviewMapDijit.startup(); break; } }); //function which destroys the elements in the old map while making new ones function destroyerFunc(){ var oldLegend = dom.byId("legend1"); oldLegend.remove(); var legendTab = dom.byId("TabData"); var newLegend = document.createElement("div"); newLegend.setAttribute("id", "legend1"); legendTab.appendChild(newLegend); if (map != undefined) { map.destroy(); scalebar.destroy(); legendDijit.destroy(); overviewMapDijit.destroy(); }}; }); html, body { height: 100%; width: 100%; margin: 0; padding: 0; } #header { background-color: #E8E8E8; height: 65px; margin: auto; } #mainWindow { width: 100%; height: 100%; } #title { padding-top: 2px; padding-left: 10px; font-size: 18pt; font-weight: 700; } #map { margin: 5px; padding: 0; } Chicago Youth Population USA Median Household Income Topo Map ```<issue_comment>username_1: use a custom sorter ``` var sorter = function(a, b) { if (a.active || b.active) { return 1 } return 0 } var array = [{active: false, name: 'one'}, {active: true, name: 'two'}, {active: true, name: 'three'}, {active: false, name: 'four'}] array.sort(sorter).map((obj) => {console.log(obj)}) ``` Works :D Upvotes: -1 <issue_comment>username_2: You can first sort the data array on times. Then add one more sort function on data to sort by active flag; ```js myArray= [ { "FName": "", "LastName": "", "data": [ { "active": true, "times": 50 }, { "active": false, "times": 450 }, { "active": true, "times": 20 }, { "active": true, "times": 350 }, { "active": true, "times": 200 }, { "active": false, "times": 100 } ] } ] myArray.map(x => { x.data = x.data.sort((y,z) => y.times > z.times).sort((y,z) => y.active < z.active); }); console.log(myArray) ``` Upvotes: -1 <issue_comment>username_3: The [`Array.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) compareFunction(a, b) function should return a number: * Negative number - **a** should come before **b**. * 0 - **a** and **b** have the same priority. * Positive number - **b** should come before **a**. In your case the logic is find the order by `active`, and if both have the same `active` value, check the `times`. We can use simple subtraction, since booleans are treated as numbers (0 | 1): ``` z.active - y.active || z.times - y.times ``` **Notes:** 1. Since you are using [`Array.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), return clones of the objects, and arrays to prevent changes to the originals. If you want to change the original, use [`Array.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) instead. I clone the objects and arrays using the [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). 2. In sort, if two items have the same value (comparator result 0), the order is not guaranteed, and depends on the browser's implementation. **Example:** ```js const myArray = [{"FName":"","LastName":"","data":[{"active":true,"times":50},{"active":false,"times":450},{"active":false,"times":50},{"active":true,"times":450}]}] const result = myArray.map(x => ({ ...x, data: [...x.data].sort((y,z) => z.active - y.active || z.times - y.times) })) console.log(result) ``` Upvotes: 1
2018/03/18
1,023
3,351
<issue_start>username_0: I'm new to R and I would like to know how to take a certain number of samples from a csv file made entirely of numbers in Excel. I managed to import the data to R and use each number as a row and then take random rows as samples but it seems impractical. The whole file is displayed as a column and I took some samples with the next code: ``` Heights[sample(nrow(Heights), 5), ] [1] 1.84 1.65 1.73 1.70 1.72 ``` Also please let me know if there is a way to repeat this step at least 100 times and save each sample in another chart maybe, to work with it later.<issue_comment>username_1: use a custom sorter ``` var sorter = function(a, b) { if (a.active || b.active) { return 1 } return 0 } var array = [{active: false, name: 'one'}, {active: true, name: 'two'}, {active: true, name: 'three'}, {active: false, name: 'four'}] array.sort(sorter).map((obj) => {console.log(obj)}) ``` Works :D Upvotes: -1 <issue_comment>username_2: You can first sort the data array on times. Then add one more sort function on data to sort by active flag; ```js myArray= [ { "FName": "", "LastName": "", "data": [ { "active": true, "times": 50 }, { "active": false, "times": 450 }, { "active": true, "times": 20 }, { "active": true, "times": 350 }, { "active": true, "times": 200 }, { "active": false, "times": 100 } ] } ] myArray.map(x => { x.data = x.data.sort((y,z) => y.times > z.times).sort((y,z) => y.active < z.active); }); console.log(myArray) ``` Upvotes: -1 <issue_comment>username_3: The [`Array.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) compareFunction(a, b) function should return a number: * Negative number - **a** should come before **b**. * 0 - **a** and **b** have the same priority. * Positive number - **b** should come before **a**. In your case the logic is find the order by `active`, and if both have the same `active` value, check the `times`. We can use simple subtraction, since booleans are treated as numbers (0 | 1): ``` z.active - y.active || z.times - y.times ``` **Notes:** 1. Since you are using [`Array.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), return clones of the objects, and arrays to prevent changes to the originals. If you want to change the original, use [`Array.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) instead. I clone the objects and arrays using the [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). 2. In sort, if two items have the same value (comparator result 0), the order is not guaranteed, and depends on the browser's implementation. **Example:** ```js const myArray = [{"FName":"","LastName":"","data":[{"active":true,"times":50},{"active":false,"times":450},{"active":false,"times":50},{"active":true,"times":450}]}] const result = myArray.map(x => ({ ...x, data: [...x.data].sort((y,z) => z.active - y.active || z.times - y.times) })) console.log(result) ``` Upvotes: 1
2018/03/18
685
2,665
<issue_start>username_0: Consider the following React code: ``` class Todos extends React.Component { constructor(props) { super(props); this.state = { item: 'Test', }; } render() { return } } class TodoItem extends React.PureComponent { render() { return {this.props.item} } } function TodoItem(props) { return {props.item} } ``` Above there is a stateful parent component `Todos` and 2 versions of the same child component `TodoItem`. One of the versions is a pure component and the other is a stateless functional component. I understand the performance benefits from using a PureComponent, but I am wondering if React 16 applies the same shallow comparison and performance benefits to a stateless functional component? If not then why? It seems that by using either I am telling React my component has no state and therefore will only update if the parent component's state changes.<issue_comment>username_1: > > I understand the performance benefits from using a PureComponent, but I am wondering if React 16 applies the same shallow comparison and performance benefits to a stateless functional component? > > > No, not yet. There were indications from the React team this will change in the future, but as of today, stateless functional components still behave like React.Component in regards to rerendering. If you need to optimize for performance, stick with `React.PureComponent` or `React.Component` implementing `shouldComponentUpdate`. Keep in mind that if you're using redux and react-redux, `connect()` will try to handle the shallow compares for you as well on both functional and class-based components ([read up on in in the docs](https://github.com/reactjs/redux/blob/master/docs/faq/ImmutableData.md#how-does-react-redux-use-shallow-equality-checking)). You might also want to check out [recompose and its `onlyUpdateForKeys`](https://github.com/acdlite/recompose/blob/master/docs/API.md#onlyupdateforkeys) helper, for example. Upvotes: 3 <issue_comment>username_2: It really depends on how you call your pure component in JSX. When using mounting (as in your snippet) it don't get you a lot of optimization. @username_1inik and folks in comments to question describe why. But [here](https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f) guy states that calling pure components as functions can result in 45% speed up. `Todos` component will look like this: ``` class Todos extends React.Component { constructor(props) { super(props); this.state = { item: 'Test', }; } render() { return TodoItem({ item: this.state.item }); } } ``` Upvotes: 2
2018/03/18
698
2,476
<issue_start>username_0: I am a python noob trying to parse through an XML API response using Elementtree. The response contains custom data from a form and I am having trouble trying to access some of the nested elements. Below is my code: ``` response = requests.get("https://crm.zoho.com/crm/private/xml/Deals/getCVRecords?newFormat=1&authtoken=authtoken&scope=crmapi&cvName=Open Deals") tree = ElementTree.fromstring(response.content) print (response.text) ``` Through this call I am able to get this response: ``` xml version="1.0" encoding="UTF-8" ? 123456789 0000000000 helpme ``` I am trying to access the DEALID# (123456789) as well as HELPME inside [CDATA[helpme]] elements. Any help is greatly appreciated. Thanks!<issue_comment>username_1: > > I understand the performance benefits from using a PureComponent, but I am wondering if React 16 applies the same shallow comparison and performance benefits to a stateless functional component? > > > No, not yet. There were indications from the React team this will change in the future, but as of today, stateless functional components still behave like React.Component in regards to rerendering. If you need to optimize for performance, stick with `React.PureComponent` or `React.Component` implementing `shouldComponentUpdate`. Keep in mind that if you're using redux and react-redux, `connect()` will try to handle the shallow compares for you as well on both functional and class-based components ([read up on in in the docs](https://github.com/reactjs/redux/blob/master/docs/faq/ImmutableData.md#how-does-react-redux-use-shallow-equality-checking)). You might also want to check out [recompose and its `onlyUpdateForKeys`](https://github.com/acdlite/recompose/blob/master/docs/API.md#onlyupdateforkeys) helper, for example. Upvotes: 3 <issue_comment>username_2: It really depends on how you call your pure component in JSX. When using mounting (as in your snippet) it don't get you a lot of optimization. @username_1inik and folks in comments to question describe why. But [here](https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f) guy states that calling pure components as functions can result in 45% speed up. `Todos` component will look like this: ``` class Todos extends React.Component { constructor(props) { super(props); this.state = { item: 'Test', }; } render() { return TodoItem({ item: this.state.item }); } } ``` Upvotes: 2
2018/03/18
877
3,045
<issue_start>username_0: Currently building Petrol-powered RC car controlled by a raspberry pi and 16ch adafruit servo controller Pi hat. Pretty novice query from a beginner but how can simple Python commands be carried out by a single key press. E.g. Holding the "w" key on a keyboard to run "pwm.setPWM(0, 0, servoMax)". (In order for the servo to push the throttle to move the vehicle forward). What follows is the code currently used: ``` #!/usr/bin/python from Adafruit_PWM_Servo_Driver import PWM import time pwm = PWM(0x40) servoMin = 150 servoMax = 600 def setServoPulse(channel, pulse): pulseLength = 1000000 pulseLength /= 60 print "%d us per period" % pulseLength pulseLength /= 4096 print "%d us per bit" % pulseLength pulse *= 1000 pulse /= pulseLength pwm.setPWM(channel, 0, pulse) pwm.setPWMFreq(60) While (True): pwm.setPWM(0, 0, servoMin) #throttle servo set to off position -should be default pwm.setPWM(0, 0, servoMAX) #throttle servo set on -to be run by "W" key pwm.setPWM(1, 0, servoMin) #steering servo left -by holding "A" key pwm.setPWM(1, 0, servoMax) #steering servo right -by holding "D" key ``` I would assume the answer involves If and ElseIf commands, but I really would just like to run a program then input() keyboard presses to run the code.<issue_comment>username_1: > > I understand the performance benefits from using a PureComponent, but I am wondering if React 16 applies the same shallow comparison and performance benefits to a stateless functional component? > > > No, not yet. There were indications from the React team this will change in the future, but as of today, stateless functional components still behave like React.Component in regards to rerendering. If you need to optimize for performance, stick with `React.PureComponent` or `React.Component` implementing `shouldComponentUpdate`. Keep in mind that if you're using redux and react-redux, `connect()` will try to handle the shallow compares for you as well on both functional and class-based components ([read up on in in the docs](https://github.com/reactjs/redux/blob/master/docs/faq/ImmutableData.md#how-does-react-redux-use-shallow-equality-checking)). You might also want to check out [recompose and its `onlyUpdateForKeys`](https://github.com/acdlite/recompose/blob/master/docs/API.md#onlyupdateforkeys) helper, for example. Upvotes: 3 <issue_comment>username_2: It really depends on how you call your pure component in JSX. When using mounting (as in your snippet) it don't get you a lot of optimization. @username_1inik and folks in comments to question describe why. But [here](https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f) guy states that calling pure components as functions can result in 45% speed up. `Todos` component will look like this: ``` class Todos extends React.Component { constructor(props) { super(props); this.state = { item: 'Test', }; } render() { return TodoItem({ item: this.state.item }); } } ``` Upvotes: 2
2018/03/18
708
2,612
<issue_start>username_0: I am new to Java. In my course, we must input an existing file using the Scanner object. ``` import java.io.*; import java.util.Scanner; public class InputFile { public static void main(String[] args) { Scanner inFile; public class InputFile { public static void main(String[] args) { Scanner inFile = new Scanner(new File("artwork_info.txt")); int quantity = new Integer(inFile.nextLine()); } } ``` That gives "me unreported exception FileNotFoundException". ``` try { inFile = new Scanner(new File("info.txt")); } catch (FileNotFoundException e) { System.out.println("Try Again"); } int quantity = new Integer(inFile.nextLine()); ``` Then I get an error that inFile might not be initialized. I walked through the steps from [This question](https://stackoverflow.com/questions/11553042/the-system-cannot-find-the-file-specified-in-java#_=_) and the file names are right and still the same problems. Any ideas?<issue_comment>username_1: First way: add `throws`: ``` public static void main(String[] args) throws FileNotFoundException { ``` Second way: put `int quantity = ...` line (and subsequent statements) inside the `try` block: ``` try { inFile = new Scanner(new File("info.txt")); int quantity = new Integer(inFile.nextLine()); // ... } catch (FileNotFoundException e) { // ... } ``` The first way is preferable to the second way, if you're not actually going to do anything "interesting" with the exception, because it doesn't indent the code using the `inFile` unnecessarily. A third way: ``` Scanner inFile; try { inFile = new Scanner(new File("info.txt")); } catch (FileNotFoundException e) { System.out.println("Try Again"); return; } int quantity = new Integer(inFile.nextLine()); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You are directly accessing the file, that means your Java file must working on the same location where **artwork\_info.txt** is places, if you put this file on a nested directory then you will get **FileNotFoundException**. so if your **txt** file is inside a folder you have to provide the folder name >> You have used as ``` Scanner inFile = new Scanner(new File("artwork_info.txt")); ``` Replace it as ``` Scanner inFile = new Scanner(new File("YourFolderPath\artwork_info.txt")); ``` In your case you get **FileNotFoundException** that mean your program not able to detect the file you have provide, that mean its clear there is something problem in **FileName** or **ExtentionName** or **NestedDirectory**. Try to fix this you may get rid of it, Gud Luck!! Upvotes: 0
2018/03/18
636
2,199
<issue_start>username_0: Below is a representation of some malformed HTML that I get ``` ![](xyz)![](xyz)ABC EFG. HIJ. KLM NOP ``` How do I retrieve every thing within the first 'p' tag i.e. the entire ``` ![](xyz)![](xyz)ABC EFG. ``` I have tried ``` output = tree.xpath("//article/p") ``` When I try to loop through the child nodes (len(output[0])), it gives me a count of 0 meaning it has no child nodes. When I do ``` print output[0].text ``` I get None. If I do ``` lxml.etree.tostring(output[0]) ``` I get ``` ```<issue_comment>username_1: First way: add `throws`: ``` public static void main(String[] args) throws FileNotFoundException { ``` Second way: put `int quantity = ...` line (and subsequent statements) inside the `try` block: ``` try { inFile = new Scanner(new File("info.txt")); int quantity = new Integer(inFile.nextLine()); // ... } catch (FileNotFoundException e) { // ... } ``` The first way is preferable to the second way, if you're not actually going to do anything "interesting" with the exception, because it doesn't indent the code using the `inFile` unnecessarily. A third way: ``` Scanner inFile; try { inFile = new Scanner(new File("info.txt")); } catch (FileNotFoundException e) { System.out.println("Try Again"); return; } int quantity = new Integer(inFile.nextLine()); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You are directly accessing the file, that means your Java file must working on the same location where **artwork\_info.txt** is places, if you put this file on a nested directory then you will get **FileNotFoundException**. so if your **txt** file is inside a folder you have to provide the folder name >> You have used as ``` Scanner inFile = new Scanner(new File("artwork_info.txt")); ``` Replace it as ``` Scanner inFile = new Scanner(new File("YourFolderPath\artwork_info.txt")); ``` In your case you get **FileNotFoundException** that mean your program not able to detect the file you have provide, that mean its clear there is something problem in **FileName** or **ExtentionName** or **NestedDirectory**. Try to fix this you may get rid of it, Gud Luck!! Upvotes: 0
2018/03/18
702
2,817
<issue_start>username_0: I have an MS Access database with a form based on a query with simplified data taken from a couple of tables. The primary Key (ItemNumber) in both the relevant tables is present in the query that the form is based on. I want to be able to use a button to move a record from the table Products to SuspendedProducts - so three part process: 1. Select the record in Products with the same ItemNumber as the one currently selected in the form 2. Copy this record to SuspendedProducts 3. Delete it from Products Just to get it to copy the record over I've tried a few things, none of which seem to work. In VBA I've written ``` "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber =" Me.ItemNumber ``` but it's not copying anything into SuspendedProducts. Slight changes have had it do nothing, or had it complain about syntax errors.<issue_comment>username_1: LeeMac commented that `Me.ItemNumber` may be `String` data type, and proposed this solution, which worked: ``` CurrentDb.Execute "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber ='" & Me.ItemNumber & "'" ``` June7 Suggested that better design may be to add a field in the `Products` table designating whether an item is suspended or not, to avoid having to move records. Upvotes: 0 <issue_comment>username_2: *Since this has been resolved in the comments, I'll post my suggestion as an answer so that this question may be marked as resolved.* --- There were essentially three issues with your current code: * Either `CurrentDb.Execute` or `DoCmd.RunSQL` methods are required to execute the SQL expression you have constructed - the SQL expression is otherwise just a string. * You were missing the concatenation operator (`&`) when constructing your SQL string: Your code: ``` "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber =" Me.ItemNumber ``` Should have read: ``` "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber =" & Me.ItemNumber ``` * Since the inclusion of the concatenation operator did not prove successful, I suggested that your `ItemNumber` field may be of string datatype, and the criteria value would therefore need to be quoted within the SQL expression: ``` "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber ='" & Me.ItemNumber & "'" ``` This could also be written: ``` "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber =""" & Me.ItemNumber & """" ``` Since `""` results in a literal `"` in VBA; however, this is slightly less readable. --- Taking the above into consideration, the final code could be: ``` CurrentDb.Execute _ "INSERT INTO SuspendedProducts " & _ "SELECT * FROM Products WHERE ItemNumber ='" & Me.ItemNumber & "'" ``` Upvotes: 3 [selected_answer]
2018/03/18
727
2,915
<issue_start>username_0: I'm having some issues with a section of code I'm writing and was hoping someone may be able to help me see where I've gone wrong and explain why so I can better understand it. I'm being told that my doubly linked list is no longer linked in both directions but I'm failing to see where I've gone wrong. I'll include the problematic section of code below: ``` public void deleteWithValue(int searchValue) { // Delete the first node in the list with the given value. if (head.data == searchValue) { head = head.next; return; } DoublyLinkedListNode current = head; DoublyLinkedListNode prev = current; while (current.next != null) { prev = current; current = current.next; if (current.data == searchValue) { prev = current.next; current = current.next; current.prev = prev; break; } } } ``` Many thanks, Jess<issue_comment>username_1: LeeMac commented that `Me.ItemNumber` may be `String` data type, and proposed this solution, which worked: ``` CurrentDb.Execute "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber ='" & Me.ItemNumber & "'" ``` June7 Suggested that better design may be to add a field in the `Products` table designating whether an item is suspended or not, to avoid having to move records. Upvotes: 0 <issue_comment>username_2: *Since this has been resolved in the comments, I'll post my suggestion as an answer so that this question may be marked as resolved.* --- There were essentially three issues with your current code: * Either `CurrentDb.Execute` or `DoCmd.RunSQL` methods are required to execute the SQL expression you have constructed - the SQL expression is otherwise just a string. * You were missing the concatenation operator (`&`) when constructing your SQL string: Your code: ``` "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber =" Me.ItemNumber ``` Should have read: ``` "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber =" & Me.ItemNumber ``` * Since the inclusion of the concatenation operator did not prove successful, I suggested that your `ItemNumber` field may be of string datatype, and the criteria value would therefore need to be quoted within the SQL expression: ``` "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber ='" & Me.ItemNumber & "'" ``` This could also be written: ``` "INSERT INTO SuspendedProducts SELECT * FROM Products WHERE ItemNumber =""" & Me.ItemNumber & """" ``` Since `""` results in a literal `"` in VBA; however, this is slightly less readable. --- Taking the above into consideration, the final code could be: ``` CurrentDb.Execute _ "INSERT INTO SuspendedProducts " & _ "SELECT * FROM Products WHERE ItemNumber ='" & Me.ItemNumber & "'" ``` Upvotes: 3 [selected_answer]
2018/03/18
775
2,300
<issue_start>username_0: I tried to make Android Project I have ``` OS Windwows 10, Intellige IDEA 2017.2 JDK jdk1.8.0_161 Android API 27 Platform Gradle 4.6 Android SDK 25.5.2 ``` Installed packages [![enter image description here](https://i.stack.imgur.com/J5M9t.jpg)](https://i.stack.imgur.com/J5M9t.jpg) [![enter image description here](https://i.stack.imgur.com/sfgiK.jpg)](https://i.stack.imgur.com/sfgiK.jpg) [![enter image description here](https://i.stack.imgur.com/F0lKK.jpg)](https://i.stack.imgur.com/F0lKK.jpg) create Emulator [![enter image description here](https://i.stack.imgur.com/yJk1K.jpg)](https://i.stack.imgur.com/yJk1K.jpg) settings SDK [![enter image description here](https://i.stack.imgur.com/wr58G.jpg)](https://i.stack.imgur.com/wr58G.jpg) tried make project [![enter image description here](https://i.stack.imgur.com/MzZmG.jpg)](https://i.stack.imgur.com/MzZmG.jpg) returned error ``` Error:(26, 13) Failed to resolve: com.android.support:appcompat-v7:27.+ [Install Repository and sync project](install.m2.repo) [Show in File](openFile:C:/Server/Repositories/projects/MyApplication/app/build.gradle) ``` How solve this problem?<issue_comment>username_1: Just follow this link: <https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0> > > **Important**: The support libraries are now available through Google's > Maven repository. You do not need to download the support repository > from the SDK Manager. For more information, see [Support Library Setup](https://developer.android.com/topic/libraries/support-library/setup.html). > > > Another option (check CommonsWare comment): [Failed to resolve: com.android.support:appcompat-v7:27.+](https://stackoverflow.com/questions/49353457/failed-to-resolve-com-android-supportappcompat-v727#comment85707433_49353457) Upvotes: 0 <issue_comment>username_2: You need to add the google maven to your root build.gradle like this: ``` allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } } ``` For Gradle build tools plugin version 3.0.0, you can use google() repository (more at Migrate to Android Plugin for Gradle 3.0.0): ``` allprojects { repositories { jcenter() google() } } ``` Upvotes: 2 [selected_answer]
2018/03/18
2,416
7,336
<issue_start>username_0: I have attempted several methods of getting my slider menu to work using jQuery and at best could only get it to function once, and then I would have to refresh the page in order for it to work again. Now I've managed to outdo myself and it has ceased to work at all. I am sharing my code in the hopes that someone might notice a glaring error - the script is a simple add/removeClass function. I originally had the document ready function in my external JS file but moved it to the head, as seen here, because I clearly have no clue what I am doing. A common error message I'm getting is that $ is not defined, however, I placed a console.log in the original external menu.js file, which suggests to me that my jQuery library would be called without issue - but like I said, I have no idea what I am doing. ``` $( document ).ready(function() { console.log( "document loaded" ); }); $( window ).on( "load", function() { console.log( "window loaded" ); }); xxxxxxxxxxxxxxxxxxxxxxxxxx [![](img/header-banner.gif)](https://www.w3schools.com/css/css_link.asp) * [news](https://www.w3schools.com/css/css_link.asp) * [text](https://www.w3schools.com/css/css_link.asp) * [exhibition](https://www.w3schools.com/css/css_link.asp) * [about](https://www.w3schools.com/css/css_link.asp) ` ``` main.css ``` @import url('https://fonts.googleapis.com/css?family=Muli'); html, body {font-size: 12px; margin: 0; padding: 0 } header {width: 970px; height: 90px; } .toggle_menu { position: fixed; padding: 15px 20px 15px 15px; margin-top: 0px; margin-left: 40px; color: black; cursor: pointer; background-color: #648B79; z-index: 1000000; font-size: 2em; opacity: 1; } .sidebar_menu { position: fixed; width: 200px; margin-left: -100%; overflow: hidden; height: 100vh; background-color: rgba(17, 17, 17, 0.9); opacity: 0.9; transition: all 0.3s ease-in-out; text-align: left; } .fa-times { right: 10px; top: 10px; opacity: 0.4; cursor: pointer; position: absolute; color: white; transition: all 0.3s ease-in-out; } .fa-times:hover {opacity: 1; } .navigation { font-family: 'Muli'; font-size: 1.5em; list-style-type: none; display: block; margin-top: 20px; margin-left: 10px; margin-right: auto; transition: all 0.3s ease-in-out; } .navigation_item { margin: 10px; transition: all 0.3s ease-in-out; } .show_menu { margin-left: 0px; } .opacity_zero { opacity: 0; transition: all 0.3s ease-in-out; } #main { background-color: aqua; font-family: 'Muli', 'sans-serif'; font-size: 1em; width: 900px; height: 900px; position: relative; top: 0px; left: 201px; } #slide-show {font-family: 'Muli', sans-serif; padding: 15px; } #footer{font-family: 'Muli'; background-color: aqua; border: 10px; position: fixed; bottom: 100%; bottom: 0; width: 100%; } a:link {color: #555; text-decoration:none} a:visited {color: #555; text-decoration:none} a:hover {color:aqua; text-decoration:none; transition: 0.05s;} /* media queries */ ``` Javascipt ``` $(".toggle_menu").click(function(){ $(".sidebar_menu").addClass("show_menu"); $(".toggle_menu").addClass("opacity_zero"); }); $(".fa-times").click (function(){ $(".sidebar_menu").removeClass("show_menu"); $(".toggle_menu").removeClass("opacity_zero"); }); ```<issue_comment>username_1: Most likely it's **FontAwsome** causing the problem here. The latest version of this library replaces the **i** tags with **svg**, which doesn't inherit the **toggle\_menu** class. Try wrapping up the FontAwsome icon with **button** element. The code should look like this: ``` ``` Upvotes: 1 <issue_comment>username_2: 1- wrap your action codes inside DOM ready to make a listener on them. 2- bring your action classes out of because the fontawsome library replaces the html tags with relevant svg so it no more works. (thanks to [@username_1](https://stackoverflow.com/questions/49353480/trying-to-incorporate-simple-slider-menu-using-add-and-removeclass-function-with/#49353859)) 3- If you get errors about $ sign perhaps you have inserted your codes before jquery library or your tests are offline and you have no access to CDN files. Try replacing jquery with an offline version and check again. ```js $(document).ready(function(){ $(".toggle_menu").click(function(){ $(".sidebar_menu").addClass("show_menu"); $(".toggle_menu").addClass("opacity_zero"); }); $(".fa-times").click (function(){ $(".sidebar_menu").removeClass("show_menu"); $(".toggle_menu").removeClass("opacity_zero"); }); }) ``` ```css @import url('https://fonts.googleapis.com/css?family=Muli'); html, body {font-size: 12px; margin: 0; padding: 0 } header {width: 970px; height: 90px; } .toggle_menu { position: fixed; padding: 15px 20px 15px 15px; margin-top: 0px; margin-left: 40px; color: black; cursor: pointer; background-color: #648B79; z-index: 1000000; font-size: 2em; opacity: 1; } .sidebar_menu { position: fixed; width: 200px; margin-left: -100%; overflow: hidden; height: 100vh; background-color: rgba(17, 17, 17, 0.9); opacity: 0.9; transition: all 0.3s ease-in-out; text-align: left; } .fa-times { right: 10px; top: 10px; opacity: 0.4; cursor: pointer; position: absolute; color: white; transition: all 0.3s ease-in-out; } .fa-times:hover {opacity: 1; } .navigation { font-family: 'Muli'; font-size: 1.5em; list-style-type: none; display: block; margin-top: 20px; margin-left: 10px; margin-right: auto; transition: all 0.3s ease-in-out; } .navigation_item { margin: 10px; transition: all 0.3s ease-in-out; } .show_menu { margin-left: 0px; } .opacity_zero { opacity: 0; transition: all 0.3s ease-in-out; } #main { background-color: aqua; font-family: 'Muli', 'sans-serif'; font-size: 1em; width: 900px; height: 900px; position: relative; top: 0px; left: 201px; } #slide-show {font-family: 'Muli', sans-serif; padding: 15px; } #footer{font-family: 'Muli'; background-color: aqua; border: 10px; position: fixed; bottom: 100%; bottom: 0; width: 100%; } a:link {color: #555; text-decoration:none} a:visited {color: #555; text-decoration:none} a:hover {color:aqua; text-decoration:none; transition: 0.05s;} ``` ```html * [news](https://www.w3schools.com/css/css_link.asp) * [text](https://www.w3schools.com/css/css_link.asp) * [exhibition](https://www.w3schools.com/css/css_link.asp) * [about](https://www.w3schools.com/css/css_link.asp) ` ``` Upvotes: 0
2018/03/18
730
2,727
<issue_start>username_0: I have a map of maps ``` siteId -> (AppName -> App) ``` I want to iterate all of the Apps in the inner map and create a new map of ``` (appId -> App) ``` I do it without stream ``` Map result = new HashMap<>(); siteIdToAppNameToAppMap.forEach((siteId, map) -> map.forEach((appName, app) -> result.put(app.token, app) ) ); ``` How do I do it with stream?<issue_comment>username_1: What about something like this? ``` siteIdToAppNameToAppMap.values() .stream() .flatMap(m -> m.values().stream()) .collect( Collectors.toMap(App::getToken, Function.identity()) ); ``` We will need to use [Stream#flatMap](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#flatMap-java.util.function.Function-) to extract `App` from nested map. So `stream().values()` will give us `Stream>` now we need to transform it into `Stream` using flatMap: ``` Stream> -> flatMap -> Stream ``` and after is we can finally collect to a new `Map` Upvotes: 3 [selected_answer]<issue_comment>username_2: A slightly different variant to @username_1's answer. ``` Map resultSet = siteIdToAppNameToAppMap.values() .stream() .map(Map::values) .flatMap(Collection::stream) .collect(Collectors.toMap(App::getToken, Function.identity(), (left, right) -> { throw new RuntimeException("duplicate key"); }, HashMap::new)); ``` This solution creates a stream from the `siteIdToAppNameToAppMap` map values, which we then perform a `map` operation to the map values yielding a `Stream>` and then `flatMap` will collapse all the nested `Stream>` to a `Stream` and then finally the `toMap` collector will return a `Collector` that accumulates the elements into a Map whose keys are the return value of `App::getToken` and values are the return value of `Function.identity()`. The function `(left, right) -> { throw new RuntimeException("duplicate key");}` above is the merge function, used to resolve collisions between values associated with the same key. in this particular case, you don't need it but it's only there so we can use this overload of the `toMap` collector which then allows us to specify that we specifically want a `HashMap` instance. All, the other `toMap` overloads don't guarantee on the type, mutability, serializability, or thread-safety of the Map returned. *Note* - if you're not expecting duplicate keys then throwing an exception, as shown above, is the way to go as it indicates there's a problem as opposed to doing something else. However, if in the case of a duplicate key you want to return a value then you can simply change the merge function to `(left, right) -> left` or `(left, right) -> right` depending on what you want. Upvotes: 2
2018/03/18
918
3,148
<issue_start>username_0: I have a `product` model with a `has_and_belongs_to_many` association with `tags`. I am trying to create a custom query to exclude certain products with a particular tag. With the code below I get the error `PG::UndefinedColumn: ERROR: column products.product_id does not exist...` If I remove `.where.not(products_tags: 'Mouldings')` from the `@stones` query, products will list based on the `@products` model. **product.rb** ``` class Product < ApplicationRecord include PgSearch pg_search_scope :search_for, against: %i(name body), associated_against: { variations: :name, categories: :name, tags: :name }, using: { tsearch: { any_word: true } } has_and_belongs_to_many :categories has_and_belongs_to_many :tags ... end ``` **tag.rb** ``` class Tag < ApplicationRecord has_and_belongs_to_many :products end ``` **products\_controller.rb** ``` ... def index if params[:query] @products = Product.search_for(params[:query]) @stones = @products.where.not(products_tags: 'Mouldings') else ... end end ... ```<issue_comment>username_1: Try [include or joins](http://tomdallimore.com/blog/includes-vs-joins-in-rails-when-and-where/). For example, if include the tag table, and then query: ``` @products = Product.search_for(params[:query]).includes(:tag) @stones = @products.where('tag.name != ?', 'Mouldings') ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I could not find a solution to my problem (which is similar). Here is what I did: My Models ``` class Allergy < ApplicationRecord has_and_belongs_to_many :items end class Item < ApplicationRecord has_and_belongs_to_many :allergies end ``` Given a list of allergies, I want to find the items that do not have those allergies. Example: ``` allergies = ['dairy', 'eggs'] ``` So I did was create two scopes, it makes the code more understandable (and useful): ``` class Item < ApplicationRecord has_and_belongs_to_many :allergies scope :with_allergy, ->(n) { includes(:allergies).where(allergies: {name: n}) } scope :free_of, ->(a) { self.all.where.not(id: self.with_allergy(a)) } end # I can pass one allergy Item.free_of('dairy') # I can pass multiple allergies Item.free_of(['dairy', 'eggs']) ``` You can change 'name' to any attribute you want (including id). I had to create the two scopes because the following: ``` Item.includes(:allergies).where.not(allergies: {name: n}) ``` **Did not return items that are not associated with any allergies**. Instead, it returns records that have at least one association. **Possible solution for Rails 6.1>** Rails 6.1 added a `.missing` method that **returns all records that do not have any association**. ``` Item.missing(:allergies) # returns items that do not have any associated allergies. ``` The latter can be combined with where clauses. Source: <https://boringrails.com/tips/activerecord-where-missing-associations> Upvotes: 0
2018/03/18
713
2,394
<issue_start>username_0: I'm trying to make a cone-shaped button in React-Native. Something like this: [Sorry I can't display images yet, but one of these sections.](https://i.stack.imgur.com/beEi5.gif) I've played around with TouchableOpacity and custom styled views inside, but it seems like the only way of doing so is with transparent borders that still register when pressed. Is it possible to make a button in React-Native with the shape I'm looking for and also with the collision box to match?<issue_comment>username_1: Try [include or joins](http://tomdallimore.com/blog/includes-vs-joins-in-rails-when-and-where/). For example, if include the tag table, and then query: ``` @products = Product.search_for(params[:query]).includes(:tag) @stones = @products.where('tag.name != ?', 'Mouldings') ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I could not find a solution to my problem (which is similar). Here is what I did: My Models ``` class Allergy < ApplicationRecord has_and_belongs_to_many :items end class Item < ApplicationRecord has_and_belongs_to_many :allergies end ``` Given a list of allergies, I want to find the items that do not have those allergies. Example: ``` allergies = ['dairy', 'eggs'] ``` So I did was create two scopes, it makes the code more understandable (and useful): ``` class Item < ApplicationRecord has_and_belongs_to_many :allergies scope :with_allergy, ->(n) { includes(:allergies).where(allergies: {name: n}) } scope :free_of, ->(a) { self.all.where.not(id: self.with_allergy(a)) } end # I can pass one allergy Item.free_of('dairy') # I can pass multiple allergies Item.free_of(['dairy', 'eggs']) ``` You can change 'name' to any attribute you want (including id). I had to create the two scopes because the following: ``` Item.includes(:allergies).where.not(allergies: {name: n}) ``` **Did not return items that are not associated with any allergies**. Instead, it returns records that have at least one association. **Possible solution for Rails 6.1>** Rails 6.1 added a `.missing` method that **returns all records that do not have any association**. ``` Item.missing(:allergies) # returns items that do not have any associated allergies. ``` The latter can be combined with where clauses. Source: <https://boringrails.com/tips/activerecord-where-missing-associations> Upvotes: 0
2018/03/18
661
2,509
<issue_start>username_0: I can't get class\_exists to see my class file. More annoyingly, if I actually include the class file directly, it moans that I can't include it as the class already exists! Talk about a slap in the face. There's obviously a lot of parts to this so I'll just try to include the relevant bits : The class I'm checking for is **Posts.php** in a function inside Router.php Dir structure : ``` app | --->Project | |--->Controllers | | | --->Posts.php | |--->Core | | | --->Router.php ``` The class name (controller) is being pulled from a part of the query string and it is tested and working. ie - mysite.com/posts/view will result in the class name being passed as "Posts" just as it should be for psr4. The part of the router dispatch function where the trouble lies. ``` if (class_exists($controller)) { $controller_object = new $controller(); } else { echo "Controller class $controller missing"; } ``` I've tried including the class directly, like I said, I get get a warning about including the same class twice. I've also tried using the class constant : ``` if (class_exists($controller::class)) { ``` But got : ``` Fatal error: Dynamic class names are not allowed in compile-time ``` And also tried using the full namespaced url to it : ``` if (class_exists('Project\\Controllers\\' . $controller)) ``` But again, class not found. Here is Posts.php ``` namespace Project\Controllers; class Posts { public function index() { echo 'It Works'; } } ``` Am I missing something obvious here?<issue_comment>username_1: Cracked it! Needed to concatenate the namespace url with the class and set it as a variable before I could create the new $controller object with it. So it was passing the class\_exists check when feeding it with the namespaced url, but failing on the new object as it was out of scope. ``` $controller = 'Project\\Controllers\\' . $controller; if (class_exists($controller)) { $controller_object = new $controller(); ....... ``` Upvotes: 3 <issue_comment>username_2: I think I found where you missed something . You got this piece of code correctly and your code gets inside this if condition however when you are instantiating the object you forgot to use the full namespaced path . So PHP looks for a class called "Posts" that doesn't exist in the same namespace with the script . ``` if (class_exists('Project\\Controllers\\' . $controller)) ``` Upvotes: 1