date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/18
1,360
4,707
<issue_start>username_0: I have a block of data for scatter plots - about 500 rows, single column of X values and 10 columns of Y values. I have a second block of data for scatter plots with 200 rows, single column of X values and as high as 20 columns of Y values. It's easy to plot separate scatter plots for each block of data. Is there a simpler way to combine both scatter plots into one than manually selecting X and Y data 20 times over. Both groups of scatter plots have similar X and Y ranges so that's not going to be an issue. Example images of each scatter group is in the links below. Appreciate the tips. [Example Scatter Group 1:](https://i.stack.imgur.com/tP2LE.png) [Example Scatter Group 2:](https://i.stack.imgur.com/0QYMY.png) EDIT: PowerQuery Approach @QHarr Thank you for suggesting the approach. Unfortunately, when I try and **Merge** the tables on the first column, it doesn't work as expected. Maybe I've not uderstood the steps properly but I think it's because my x-axis value (the common column 1) are not exactly the same on both tables. I.e the Simulation data has somewhat ordered coordinate values like 0.001, 0.002, 0.003... and so on whereas the experimental data is more random 0.00121, 0.00189, 0.0022 and so on. This might be why I see the "The selection has matched 1 out of the first 460 rows" on the **Merge** window. [Merge Window Screenshot](https://i.stack.imgur.com/H6azO.png)<issue_comment>username_1: So the best I have come up with, without code, is to: 1. Create two tables from the distinct ranges and add them via powerquery (via data from table) as connection only. With a cell selected in the table to add via powerquery > Powerquery tab (Excel 2016)/Data tab (2016) > From table 2. Then create a new query > merge query and merge the two tables you just created. Join on column 1 from each (the x axis) and use 3. Make sure when creating the merge query to i) connection only load ii) add to data model iii)delete the additional column 1 and rename any columns if wanted 4. Create a pivot insert > pivottable > external connection > choose connection > merge query 5. Arrange data in subsequent pivot as required 6. Create pivotchart > line chart > choose a chart style with markers > format each data series with Line = No line. 7. Format chart in any other desired way, e.g. hide buttons on chart Bit annoying to set-up but then will update when you add new data and refresh the query and pivottable. You can do this by pressing the Data > Refresh All icon. Step 1 [![Step 1](https://i.stack.imgur.com/v3E62.png)](https://i.stack.imgur.com/v3E62.png) [![Step 1 contd](https://i.stack.imgur.com/urvtz.png)](https://i.stack.imgur.com/urvtz.png) Step 2: [![step2 contd](https://i.stack.imgur.com/czBly.png)](https://i.stack.imgur.com/czBly.png) Step 3 [![Remove column ](https://i.stack.imgur.com/HHwU5.png)](https://i.stack.imgur.com/HHwU5.png) Step 4 [![Step 4](https://i.stack.imgur.com/DVBVH.png)](https://i.stack.imgur.com/DVBVH.png) Step 6 [![Step 6](https://i.stack.imgur.com/QVzQU.png)](https://i.stack.imgur.com/QVzQU.png) Output (Step 7): [![Result](https://i.stack.imgur.com/GQTOc.png)](https://i.stack.imgur.com/GQTOc.png) Upvotes: 1 <issue_comment>username_2: In excel, this is the simplest way I have found to combine two already created scatter plots into a single plot: 1. Select one plot 2. Press Control-C, or Right click on the plot and select Copy 3. Select the second plot 4. Press Control-V, or Right click on the plot and select Paste Excel will copy all Data Series from the first plot into the second. The only problem is that it will copy all formatting from the first to the second plot as well, such as axis titles and ranges. The copied data series will keep the same colors, markers, etc., but the ones in the destination plot will have formatting applied from the copied plot. See the figures below: [![figures demonstrating series data merging](https://i.stack.imgur.com/e8pHj.png)](https://i.stack.imgur.com/e8pHj.png) Chart 3 is the result of copying Chart 2 and pasting into Chart 1. Note the axis range and series colors/formats were kept from Chart 2. The series data is now part of Chart 3, but none of the formatting from Chart 1 was kept. I haven't yet found a way to preserve data series formatting when doing this. Would appreciate any comments to help with that. EDIT: After selecting the destination Chart, you can select Paste Special from the ribbon, and it will give you options of All, Formats, Formulas. So you can choose either to copy the format over, or copy the data series over, but thus far I see no option to merge the data and preserve formatting of both sets. Upvotes: 0
2018/03/18
578
2,054
<issue_start>username_0: I'm attempting to create a function that returns if the ending of a string is the same as a given variable without using .endsWith(). I'm not sure why this isn't working. Chaining .join("") and comparing the two values as strings works, but not as arrays. ``` const confirmEnding = (str, target) => { // split string into array, splice end of array based on target length console.log(str.split("").splice(str.length - target.length, target.length)); // split target into array console.log(target.split("")); // compare two arrays return str.split("").splice(str.length - target.length, target.length) === target.split(""); console.log(confirmEnding("Congratulation", "on")); ``` OUTPUT ``` [ 'o', 'n' ] [ 'o', 'n' ] false ``` Clearly, the arrays are exactly the same. Why does the boolean return false?<issue_comment>username_1: You can change your logic to make it simple. Just get the `lastIndexOf` the `target` string from the `str` so that you can take substring of the last word and compare it with the `target`: ```js const confirmEnding = (str, target) => { var indexOfTarget = str.lastIndexOf(target); var lastStr = str.substr(indexOfTarget, str.length - 1); if(lastStr === target){ return true; } return false; }; //match console.log(confirmEnding("Congratulation", "on")); //match console.log(confirmEnding("Congratulation", "tion")); //no match console.log(confirmEnding("Congratulation", "ons")); ``` Upvotes: -1 <issue_comment>username_2: You can not compare two arrays with the same content, but with different object references. You need to compare the item by using a counter for the characters who are equal end iterate from the end of the string. ```js const confirmEnding = (str, target) => { var i = 0; while (i < target.length && str[str.length - 1 - i] === target[target.length - 1 - i]) { i++; } return i === target.length; } console.log(confirmEnding("Congratulation", "on")); console.log(confirmEnding("Congratulation", "off")); ``` Upvotes: 0
2018/03/18
789
2,873
<issue_start>username_0: Using Selenium 3.8.1 with Python 2.7 with Firefox Portable 54, 64 bit, I get the following error message when running this script: ``` from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary_argument = FirefoxBinary(r'C:\Users\[removed]\FirefoxPortable.exe') driver = webdriver.Firefox(firefox_binary=binary_argument) driver.get("http://icanhazip.com") ``` . ``` Traceback (most recent call last): File "F:/cp/python-selenium3/ToyScripts/launch_portable_browser.py", line 5, in driver = webdriver.Firefox(firefox\_binary=binary\_argument) File "C:\ProgramData\Anaconda2\envs\automation2\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 162, in \_\_init\_\_ keep\_alive=True) File "C:\ProgramData\Anaconda2\envs\automation2\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 154, in \_\_init\_\_ self.start\_session(desired\_capabilities, browser\_profile) File "C:\ProgramData\Anaconda2\envs\automation2\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 243, in start\_session response = self.execute(Command.NEW\_SESSION, parameters) File "C:\ProgramData\Anaconda2\envs\automation2\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute self.error\_handler.check\_response(response) File "C:\ProgramData\Anaconda2\envs\automation2\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check\_response raise exception\_class(message, screen, stacktrace) selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities ``` I do see the splash screen for a moment before it disappears. Also worth noting is that the browser works fine when used manually. I suspect that the portable browser needs some settings switched to allow Selenium to take over, but that is the extent of what i know/suspect. Thank you for any help with this.<issue_comment>username_1: Solved by modifying DesiredCapabilities: ``` from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.common.desired_capabilities import DesiredCapabilities binary_argument = FirefoxBinary(r'C:\Users\[removed]\FirefoxPortable.exe') capabilities_argument = DesiredCapabilities().FIREFOX capabilities_argument["marionette"] = False driver = webdriver.Firefox(firefox_binary=binary_argument, capabilities=capabilities_argument) driver.get("http://icanhazip.com") ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: I was able to resolve this issue by installing the latest geckodriver from <https://www.seleniumhq.org/download/> and latest firefox from <https://www.mozilla.org/en-US/firefox/>. Please consider your windows when downloading geckodriver (32 bit or 64 bit). I hope this helps. Upvotes: 2
2018/03/18
3,226
8,400
<issue_start>username_0: I need to have a circular progress bar which I can use to show a user what percent they got in a test. Ideally, there would be some fixed HTML and then change the value in the JavaScript or jQuery. They could look like any of the circles below. [![like thisre](https://i.stack.imgur.com/4NA2D.jpg)](https://i.stack.imgur.com/4NA2D.jpg) --- Thank you in advance.<issue_comment>username_1: Progress bar Circle using HTML5 and CSS3 ```css @import url(https://fonts.googleapis.com/css?family=Lato:700); *, *:before, *:after { -webkit-box-sizing: border-box; box-sizing: border-box; } html, body { background: #ecf0f1; color: #444; font-family: 'Lato', Tahoma, Geneva, sans-serif; font-size: 16px; padding: 10px; } .set-size { font-size: 10em; } .charts-container:after { clear: both; content: ""; display: table; } .pie-wrapper { height: 1em; width: 1em; float: left; margin: 15px; position: relative; } .pie-wrapper:nth-child(3n+1) { clear: both; } .pie-wrapper .pie { height: 100%; width: 100%; clip: rect(0, 1em, 1em, 0.5em); left: 0; position: absolute; top: 0; } .pie-wrapper .pie .half-circle { height: 100%; width: 100%; border: 0.1em solid #3498db; border-radius: 50%; clip: rect(0, 0.5em, 1em, 0); left: 0; position: absolute; top: 0; } .pie-wrapper .label { background: #34495e; border-radius: 50%; bottom: 0.4em; color: #ecf0f1; cursor: default; display: block; font-size: 0.25em; left: 0.4em; line-height: 2.6em; position: absolute; right: 0.4em; text-align: center; top: 0.4em; } .pie-wrapper .label .smaller { color: #bdc3c7; font-size: .45em; padding-bottom: 20px; vertical-align: super; } .pie-wrapper .shadow { height: 100%; width: 100%; border: 0.1em solid #bdc3c7; border-radius: 50%; } .pie-wrapper.style-2 .label { background: none; color: #7f8c8d; } .pie-wrapper.style-2 .label .smaller { color: #bdc3c7; } .pie-wrapper.progress-30 .pie .right-side { display: none; } .pie-wrapper.progress-30 .pie .half-circle { border-color: #3498db; } .pie-wrapper.progress-30 .pie .left-side { -webkit-transform: rotate(108deg); transform: rotate(108deg); } .pie-wrapper.progress-60 .pie { clip: rect(auto, auto, auto, auto); } .pie-wrapper.progress-60 .pie .right-side { -webkit-transform: rotate(180deg); transform: rotate(180deg); } .pie-wrapper.progress-60 .pie .half-circle { border-color: #9b59b6; } .pie-wrapper.progress-60 .pie .left-side { -webkit-transform: rotate(216deg); transform: rotate(216deg); } .pie-wrapper.progress-90 .pie { clip: rect(auto, auto, auto, auto); } .pie-wrapper.progress-90 .pie .right-side { -webkit-transform: rotate(180deg); transform: rotate(180deg); } .pie-wrapper.progress-90 .pie .half-circle { border-color: #e67e22; } .pie-wrapper.progress-90 .pie .left-side { -webkit-transform: rotate(324deg); transform: rotate(324deg); } .pie-wrapper.progress-45 .pie .right-side { display: none; } .pie-wrapper.progress-45 .pie .half-circle { border-color: #1abc9c; } .pie-wrapper.progress-45 .pie .left-side { -webkit-transform: rotate(162deg); transform: rotate(162deg); } .pie-wrapper.progress-75 .pie { clip: rect(auto, auto, auto, auto); } .pie-wrapper.progress-75 .pie .right-side { -webkit-transform: rotate(180deg); transform: rotate(180deg); } .pie-wrapper.progress-75 .pie .half-circle { border-color: #8e44ad; } .pie-wrapper.progress-75 .pie .left-side { -webkit-transform: rotate(270deg); transform: rotate(270deg); } .pie-wrapper.progress-95 .pie { clip: rect(auto, auto, auto, auto); } .pie-wrapper.progress-95 .pie .right-side { -webkit-transform: rotate(180deg); transform: rotate(180deg); } .pie-wrapper.progress-95 .pie .half-circle { border-color: #e74c3c; } .pie-wrapper.progress-95 .pie .left-side { -webkit-transform: rotate(342deg); transform: rotate(342deg); } .pie-wrapper--solid { border-radius: 50%; overflow: hidden; } .pie-wrapper--solid:before { border-radius: 0 100% 100% 0%; content: ''; display: block; height: 100%; margin-left: 50%; -webkit-transform-origin: left; transform-origin: left; } .pie-wrapper--solid .label { background: transparent; } .pie-wrapper--solid.progress-65 { background: -webkit-gradient(linear, left top, right top, color-stop(50%, #e67e22), color-stop(50%, #34495e)); background: linear-gradient(to right, #e67e22 50%, #34495e 50%); } .pie-wrapper--solid.progress-65:before { background: #e67e22; -webkit-transform: rotate(126deg); transform: rotate(126deg); } .pie-wrapper--solid.progress-25 { background: -webkit-gradient(linear, left top, right top, color-stop(50%, #9b59b6), color-stop(50%, #34495e)); background: linear-gradient(to right, #9b59b6 50%, #34495e 50%); } .pie-wrapper--solid.progress-25:before { background: #34495e; -webkit-transform: rotate(-270deg); transform: rotate(-270deg); } .pie-wrapper--solid.progress-88 { background: -webkit-gradient(linear, left top, right top, color-stop(50%, #3498db), color-stop(50%, #34495e)); background: linear-gradient(to right, #3498db 50%, #34495e 50%); } .pie-wrapper--solid.progress-88:before { background: #3498db; -webkit-transform: rotate(43.2deg); transform: rotate(43.2deg); } ``` ```html 30% 60% 90% 45% 75% ``` Upvotes: 3 <issue_comment>username_2: Using canvas. Change the percent for changing the angle. ```js var canvas = document.getElementById("cvs"); canvas.width = innerWidth; canvas.height = innerHeight; var ctx = canvas.getContext("2d"); var percent = 90; ctx.beginPath(); ctx.arc(innerWidth/2, innerHeight/2, 100, 0, Math.PI * 2); ctx.strokeStyle = "#111"; ctx.lineWidth = 20; ctx.stroke(); ctx.closePath(); var angle = percent/100 * 360; ctx.beginPath(); ctx.arc(innerWidth/2, innerHeight/2, 100, -90 * Math.PI/180, (angle - 90) * Math.PI/180); ctx.strokeStyle = "#fff"; ctx.lineWidth = 20; ctx.stroke(); ctx.closePath(); ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.font = "40px arial bold"; ctx.fillStyle = "#fff" ctx.fillText(percent + "%", innerWidth/2, innerHeight/2); ``` ```css body { overflow: hidden; background: #000; } ``` ```html ``` Upvotes: 1 <issue_comment>username_3: You might be looking for this one ```js var svg ; function drawProgress(end){ d3.select("svg").remove() if(svg){ svg.selectAll("*").remove(); } var wrapper = document.getElementById('radialprogress'); var start = 0; var colours = { fill: '#FF0000', track: '#555555', text: '#00C0FF', stroke: '#FFFFFF', } var radius = 80; var border = 12; var strokeSpacing = 4; var endAngle = Math.PI * 2; var formatText = d3.format('.0%'); var boxSize = radius * 2; var count = end; var progress = start; var step = end < start ? -0.01 : 0.01; //Define the circle var circle = d3.svg.arc() .startAngle(0) .innerRadius(radius) .outerRadius(radius - border); //setup SVG wrapper svg = d3.select(wrapper) .append('svg') .attr('width', boxSize) .attr('height', boxSize); // ADD Group container var g = svg.append('g') .attr('transform', 'translate(' + boxSize / 2 + ',' + boxSize / 2 + ')'); //Setup track var track = g.append('g').attr('class', 'radial-progress'); track.append('path') .attr('fill', colours.track) .attr('stroke', colours.stroke) .attr('stroke-width', strokeSpacing + 'px') .attr('d', circle.endAngle(endAngle)); //Add colour fill var value = track.append('path') .attr('fill', colours.fill) .attr('stroke', colours.stroke) .attr('stroke-width', strokeSpacing + 'px'); //Add text value var numberText = track.append('text') .attr('fill', colours.text) .attr('text-anchor', 'middle') .attr('dy', '.5rem'); //update position of endAngle value.attr('d', circle.endAngle(endAngle * end)); //update text value numberText.text(formatText(end)); } $('#submitClick').click(function(){ var val = parseInt($('#percent').val()); drawProgress(val/100) }) drawProgress(10/100) ``` ```html Type a percent! Render ``` Upvotes: 4 [selected_answer]
2018/03/18
725
2,371
<issue_start>username_0: I was expecting vowel free string from the code below but it doesn't give me what I'm expecting. Help please. ``` def disemvowel(word): words = list(word) for i in words: if i.upper() == "A" or i.upper() == "E" or i.upper() == "I" or i.upper() == "O" or i.upper() == "U": words.remove(i) return print(''.join(words)) disemvowel("uURII") ``` I was expecting the output to be 'R' but I'm getting 'URI'.<issue_comment>username_1: This should help. ``` def disemvowel(word): words = list(word) v = ["a", "e", "i", "o", "u"] #list of vowel return "".join([i for i in words if i.lower() not in v]) #check if alphabet not in vowel list print disemvowel("uURII") ``` **Output:** ``` R ``` Upvotes: -1 <issue_comment>username_2: Don't call `remove` on a list while iterating over it. Think about what happens when you do it. * First, `words = 'uURII'`, and `i` is pointing at its first character. * You call `words.remove(i)`. Now `words = 'URII'`, and `i` is pointing at its first character. * Next time through the loop, `words = 'URII'`, and `i` is pointing to its second character. Oops, you've missed the `U`! There are a few ways to fix this—you can iterate over a copy of the list, or you can index it from the end instead of the start, or you can use indices in a `while` loop and make sure not to increment until you've found something you don't want to delete, etc. But the simplest way is to just build up a new list: ``` def disemvowel(word): words = list(word) new_letters = [] for i in words: if i.upper() == "A" or i.upper() == "E" or i.upper() == "I" or i.upper() == "O" or i.upper() == "U": pass else: new_letters.append(i) print(''.join(new_letters)) ``` This means you no longer need `list(word)` in the first place; you can just iterate over the original string. And you can simplify this in a few other ways—use a set membership check instead of five separate `==` checks, turn the comparison around, and roll the loop up into a list comprehension (or a generator expression): ``` def disemvowel(word): vowels = set('AEIOU') new_letters = [letter for letter in word if letter.upper() not in vowels] print(''.join(new_letters)) ``` … but the basic idea is the same. Upvotes: 4 [selected_answer]
2018/03/18
693
2,256
<issue_start>username_0: I have a named array of cells called `Cars` which runs from say `A1:B10` Inside this I have a named cell called `Toyota` say at `A4` position. So i do: ``` Private cars As Variant cars = Range("Cars").Value Dim toyota As String toyota = cars.Range("Toyota").Value ??? ``` I am a beginner in vba so excuse my novicity.<issue_comment>username_1: This should help. ``` def disemvowel(word): words = list(word) v = ["a", "e", "i", "o", "u"] #list of vowel return "".join([i for i in words if i.lower() not in v]) #check if alphabet not in vowel list print disemvowel("uURII") ``` **Output:** ``` R ``` Upvotes: -1 <issue_comment>username_2: Don't call `remove` on a list while iterating over it. Think about what happens when you do it. * First, `words = 'uURII'`, and `i` is pointing at its first character. * You call `words.remove(i)`. Now `words = 'URII'`, and `i` is pointing at its first character. * Next time through the loop, `words = 'URII'`, and `i` is pointing to its second character. Oops, you've missed the `U`! There are a few ways to fix this—you can iterate over a copy of the list, or you can index it from the end instead of the start, or you can use indices in a `while` loop and make sure not to increment until you've found something you don't want to delete, etc. But the simplest way is to just build up a new list: ``` def disemvowel(word): words = list(word) new_letters = [] for i in words: if i.upper() == "A" or i.upper() == "E" or i.upper() == "I" or i.upper() == "O" or i.upper() == "U": pass else: new_letters.append(i) print(''.join(new_letters)) ``` This means you no longer need `list(word)` in the first place; you can just iterate over the original string. And you can simplify this in a few other ways—use a set membership check instead of five separate `==` checks, turn the comparison around, and roll the loop up into a list comprehension (or a generator expression): ``` def disemvowel(word): vowels = set('AEIOU') new_letters = [letter for letter in word if letter.upper() not in vowels] print(''.join(new_letters)) ``` … but the basic idea is the same. Upvotes: 4 [selected_answer]
2018/03/18
487
1,716
<issue_start>username_0: when I try to pass a image template to style in react element, the image doesn't show up in the background. ``` ``` when I try to inspect the element. it shows ``` ``` the style is not set. what am i doing wrong here?<issue_comment>username_1: Probably, your expression `'/images/covers/${this.state.artists.cover}.jpg'` is not parsed by engine because you used simple string without escaping and string literal can't transform the expression `${this.state.artists.cover}` into the value. So, you need to do something like this: ``` ``` Hope it will helps. Upvotes: 1 <issue_comment>username_2: If you are using webpack you should set a loader such [url-loader](https://github.com/webpack-contrib/url-loader) to use jpg files in JSX. Then you should import the jpg photo before using it like this: ``` ``` Or like this: ``` ``` Upvotes: 0 <issue_comment>username_3: Try this: ``` style={{"background: url(" + ( this.state.artists.cover ) + ")" }} ``` Upvotes: 1 <issue_comment>username_4: As mentioned in Kotsur's answer, your expression contains some characters like `'` so it is not parsed. But you should encode `this.state.artists.cover` rather than encoding quotes outside. Try something like: ``` ``` Upvotes: 0 <issue_comment>username_5: Okay, I don't see your css, and I think I see the problem. The fact is the tag is inline element - it can't have image on backround while it is empty. You should add some block styles to it (or place some content into it) ``` span { display: block; // or inline-block width: 100px; height: 100px; } ``` and then don't play hard with ticks - in this case you can use only a single ones ``` ``` Upvotes: 1
2018/03/18
641
2,286
<issue_start>username_0: How do I add a new empty Parent instance to the list of parents in the code sample below? I keep getting ``` UnimplementedFeatureError: Copying of type struct Test.Child memory[] memory to storage not yet supported. ``` Minimal example: ``` contract Test { struct Child { } struct Parent { Child[] children; } Parent[] parents; function test() { parents.push(Parent(new Child[](0))); } } ```<issue_comment>username_1: You can't really do what you're trying to do with dynamic arrays. You'll need to change your approach slightly to get it to work. ``` contract Test { struct Child { } struct Parent { mapping(uint => Child) children; uint childrenSize; } Parent[] parents; function testWithEmptyChildren() public { parents.push(Parent({childrenSize: 0})); } function testWithChild(uint index) public { Parent storage p = parents[index]; p.children[p.childrenSize] = Child(); p.childrenSize++; } } ``` Use `Parent.childrenSize` if you need to iterate through `Parent.children` somewhere else in your contract. Alternatively, you can increase the size of the `parents` array and use Solidity's default zero values. ``` contract Test { struct Child { } struct Parent { Child[] children; } Parent[] parents; function test() public { parents.length++; Parent storage p = parents[parents.length - 1]; Child memory c; p.children.push(c); } } ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: It doesn’t work (as of Solidity 0.4.24, at least) if the child array type is another struct, but it works if the child array type is a primitive type like `uint256`. So if you have e.g. ``` struct Child { uint256 x; bytes32 y; } ``` then you could define: ``` struct Parent { uint256[] childXs; bytes32[] childYs; } ``` and then you could write: ``` parents.push(Parent({ childXs: new uint256[](0), childYs: new bytes32[](0) })); ``` (Same workaround is applicable when you want to pass an array of structs as an argument to a public function.) It’s not ideal, but it works. P.S. Actually (if you are using the primitive array children) you could just write: ``` Parent memory p; parents.push(p); ``` Upvotes: 2
2018/03/18
454
1,500
<issue_start>username_0: I am trying Instagram api to fetch followers list. I have generated client id, secret and access token. ``` https://api.instagram.com/v1/users/self/?access_token=72951<PASSWORD>.9<PASSWORD>.6<PASSWORD> ``` This API works properly. It shows follows count as 2. But when I run below API with same access token, It does not return any data of the username, etc: ``` https://api.instagram.com/v1/users/self/follows?access_token=7295104237.9<PASSWORD>.68<PASSWORD>931642a18e3758b3cd<PASSWORD> ``` Please could anyone help me with this. I've been searching for this since hours now.<issue_comment>username_1: You may not have access to theses actions. Go to the <https://www.instagram.com/developer/> Click the settings icon. Find your api account and click Manage, after that click Permission. You'll see there about your api information. Approved - featured - which you can use N/A - featured - which you cannot use Upvotes: 2 <issue_comment>username_2: Finally found an answer to this! My app is in sandbox mode. Until one of your followers/someone you follow doesn't become your sandbox users, their data will not be listed by the followers/followed-by API, or any other API for that matter. This is because this info is considered as public\_content and will only completely accessible after app is live and completely given permission for by Instagram. So.. Just add one of your followers/someone you follow to your sandbox users! And your sorted!! Upvotes: 0
2018/03/18
2,910
8,962
<issue_start>username_0: I need to send stock market data and the formatting sucks right now. Need to send something liike this ``` | Symbol | Price | Change | |--------|-------|--------| | ABC | 20.85 | 1.626 | | DEF | 78.95 | 0.099 | | GHI | 23.45 | 0.192 | | JKL | 98.85 | 0.292 | ``` This is what I have tried. ``` | Symbol | Price | Change | |--------|-------|--------| | ABC | 20.85 | 1.626 | | DEF | 78.95 | 0.099 | | GHI | 23.45 | 0.192 | | JKL | 98.85 | 0.292 | ```<issue_comment>username_1: You can use **HTML** or **Markdown** markup to send something like in HTML. Just like [this example](https://tg.sean.taipei/payload.php?sendMessage-9d9fa8fc). Upvotes: 3 <issue_comment>username_2: Set the Telegram API **parse\_mode** parameter to **HTML** and wrap the message in , but remember that telegram API does not support nested tags. ``` ``` | Tables | Are | Cool | |----------|:-------------:|------:| | col 1 is | left-aligned | $1600 | | col 2 is | centered | $12 | | col 3 is | right-aligned | $1 | ``` ``` **Result in Telegram messanger:** [![ScreenShot from telegram bot](https://i.stack.imgur.com/AxoSp.png)](https://i.stack.imgur.com/AxoSp.png) **Updated. How convert the tables in the picture** There will be a problem on the small screens of smartphones. So this method is not good. The only option is to convert the tables in the picture and so send : 1. Or you can convert HTML to image using a headerless browser on your server. 2. Or you can convert HTML to image using here external [API services](https://stackoverflow.com/questions/10721884/render-html-to-an-image) 3. Or you can convert HTML to image using more difficult way by [php GD](https://stackoverflow.com/questions/53520857/how-can-we-convert-html-tables-in-to-png-using-gd-library-in-php) Upvotes: 5 [selected_answer]<issue_comment>username_3: I found this library - [TableJs](https://www.npmjs.com/package/table) - that solves this problem. Works great on desktop clients however android clients didn't seem to render it properly. Upvotes: 2 <issue_comment>username_4: Try this ``` ```| Symbol | Price | Change | |--------|-------|--------| | ABC | 20.85 | 1.626 | | DEF | 78.95 | 0.099 | | GHI | 23.45 | 0.192 | | JKL | 98.85 | 0.292 |``` ``` Upvotes: 4 <issue_comment>username_5: Formatting the text as "Monospace" works too Upvotes: 1 <issue_comment>username_6: Import "prettytable" library in python to format your table: ```py import prettytable as pt from telegram import ParseMode from telegram.ext import CallbackContext, Updater def send_table(update: Updater, context: CallbackContext): table = pt.PrettyTable(['Symbol', 'Price', 'Change']) table.align['Symbol'] = 'l' table.align['Price'] = 'r' table.align['Change'] = 'r' data = [ ('ABC', 20.85, 1.626), ('DEF', 78.95, 0.099), ('GHI', 23.45, 0.192), ('JKL', 98.85, 0.292), ] for symbol, price, change in data: table.add_row([symbol, f'{price:.2f}', f'{change:.3f}']) update.message.reply_text(f' ``` {table} ``` ', parse_mode=ParseMode.HTML) # or use markdown update.message.reply_text(f'```{table}```', parse_mode=ParseMode.MARKDOWN_V2) ``` You will receive message like: ``` +--------+-------+--------+ | Symbol | Price | Change | +--------+-------+--------+ | ABC | 20.85 | 1.626 | | DEF | 78.95 | 0.099 | | GHI | 23.45 | 0.192 | | JKL | 98.85 | 0.292 | +--------+-------+--------+ ``` Upvotes: 4 <issue_comment>username_7: I wrote a code to build a Telegram html table from an array of strings. Just build an array with the lines with columns data separated by ";" and this code will output the Telegram ready table. Enjoy, figure out the parameters :) > > **You must use "parse\_mode" = "html" when sending the message to Telegram Api.** > > > ```cs public string BuildTelegramTable( List table\_lines, string tableColumnSeparator = "|", char inputArraySeparator = ';', int maxColumnWidth = 0, bool fixedColumnWidth = false, bool autoColumnWidth = false, int minimumColumnWidth = 4, int columnPadRight = 0, int columnPadLeft = 0, bool beginEndBorders = true) { var prereadyTable = new List() { " ``` " }; var columnsWidth = new List(); var firstLine = table\_lines[0]; var lineVector = firstLine.Split(inputArraySeparator); if (fixedColumnWidth && maxColumnWidth == 0) throw new ArgumentException("For fixedColumnWidth usage must set maxColumnWidth > 0"); else if (fixedColumnWidth && maxColumnWidth > 0) { for(var x=0;x columnFullLength = line.Split(inputArraySeparator)[x].Length > columnFullLength ? line.Split(inputArraySeparator)[x].Length : columnFullLength); columnFullLength = columnFullLength < minimumColumnWidth ? minimumColumnWidth : columnFullLength; var columnWidth = columnFullLength + columnPadRight + columnPadLeft; if (maxColumnWidth > 0 && columnWidth > maxColumnWidth) columnWidth = maxColumnWidth; columnsWidth.Add(columnWidth); } } foreach(var line in table\_lines) { lineVector = line.Split(inputArraySeparator); var fullLine = new string[lineVector.Length+(beginEndBorders ? 2 : 0)]; if (beginEndBorders) fullLine[0] = ""; for(var x=0;x dataLength ? dataLength : columnSizeWithoutTrimSize; var columnData = clearedData.Substring(0,dataCharsToRead); columnData = columnData.PadRight(columnData.Length + columnPadRight); columnData = columnData.PadLeft(columnData.Length + columnPadLeft); var column = columnData.PadRight(columnWidth); fullLine[x+(beginEndBorders ? 1 : 0)] = column; } if (beginEndBorders) fullLine[fullLine.Length - 1] = ""; prereadyTable.Add(string.Join(tableColumnSeparator,fullLine)); } prereadyTable.Add(" ``` "); return string.Join("\r\n",prereadyTable); } ``` Upvotes: 0 <issue_comment>username_8: Here is my solution using puppeteer to screenshot on the table element First of all you need to generate the table HTML code here is the code to generate that code ``` async function generateHtml(rows) { return ` thead, tfoot { background-color: #3f87a6; color: #fff; } tbody { background-color: #e4f0f5; } caption { padding: 10px; caption-side: bottom; } table { border-collapse: collapse; border: 2px solid rgb(200, 200, 200); letter-spacing: 1px; font-family: sans-serif; font-size: .8rem; } td, th { border: 1px solid rgb(190, 190, 190); padding: 5px 10px; } td { text-align: center; } Pornhub Pages Summary| ID | Progress | Stucked | Finished | Busy | | --- | --- | --- | --- | --- | ${rows} ` } ``` And here is the code for generate the `rows` argument of the above function ``` async function getTheImgOfTheSummaryOfThePages() { const rows = [] for (const [index, val] of statuesOfThePages.entries()) { const row = `| ${index} | ${val.progress} | ${val.stucked} | ${val.finished} | ${val.pageBusy} | ` rows.push(row) } const path = './summaryOfThePagesOfPornhub.png' const html = await generateHtml(rows.join('\n')) await util.takescrrenshotOnTheHtml(html, browser, path, 'table') return path } ``` And here is the code for screenshot on the table element ``` async function takescrrenshotOnTheHtml(html, browser, pathToSave, onElement) { const page = await newPage(browser); await page.setContent(html) const element = await page.$(onElement) await element.screenshot({path: pathToSave}) await page.close() } ``` Here is the result [![enter image description here](https://i.stack.imgur.com/fV5DM.png)](https://i.stack.imgur.com/fV5DM.png) Well you just need to change the table headers and the rows of the table Upvotes: 2 <issue_comment>username_9: ``` import warnings from PIL import Image, ImageDraw, ImageFont def table_to_image(my_table): warnings.filterwarnings('ignore', category=DeprecationWarning) font = ImageFont.truetype("courbd.ttf", 15) text_width, text_height = font.getsize_multiline(my_table.get_string()) im = Image.new("RGB", (text_width + 15, text_height + 15), "white") draw = ImageDraw.Draw(im) draw.text((7, 7), my_table.get_string(), font=font, fill="black") im.show() im.save(my_table_image.png, 'PNG') ``` Upvotes: 0 <issue_comment>username_10: The easiest and most professional method is to use `Telegram Web App Bot`, which was added in the recent update. ---------------------------------------------------------------------------------------------------------------- **step 1**: create html file and write your table. **step2**: add this script to your html file. **step 3**: redirect user to page with this method of api ``` { "text": "Test web_app", "web_app": { "url": "https://yourDomain/yourFile.html" } } ``` > > note: **page will show in bot page not browser** > > > for more info read official document: <https://core.telegram.org/bots/webapps#initializing-web-apps> Upvotes: 2
2018/03/18
433
1,246
<issue_start>username_0: I have a ul/li menu that I'm trying to add `:hover` and `:focus` attributes to: ``` * [Item 1](/page1) * [Item 2](/page2) * [Item 3](/page3) * [Item 4](/page4) ``` So using the following CSS I'm able to grab the first 2 items, but nothing of the latter 2. Adding additional selectors for the and `-` tags doesn't seem to work. ``` ul li:hover, ul li:focus{ color: #0077ff; } ```<issue_comment>username_1: If you grab & `-` that's good. The problem is your and tags are inside a tag. In these cases, the styling always comes before its content. So you'll have to make somthing like this : ``` ul li:hover a, ul li:focus a{ color: #0077ff; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: To add to the previous answer: ```css ul li:hover a, ul li:focus a{ color: #0077ff; } ``` ```html * [Item 1](/page1) * [Item 2](/page2) * [Item 3](/page3) * [Item 4](/page4) ``` This code will have the following effect. ``` ul li:hover, ul li:focus{ color: #0077ff; } ``` The tags will take up the space inside the `-` tags. Therefore when you put your mouse on the `-`. Therefore your mouse won't actually be on an `-` tag but on an tag and thus the css rules won't work. Upvotes: 0
2018/03/18
469
1,672
<issue_start>username_0: `.env` file is parsed when running a Symfony 4 command (if dotenv is available). This is working fine when developping, but also, I want to test my code (so another environment), hence I need to load another `.env` file. I love what Docker did to run a container: ``` docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash ``` So I am looking to achieve same thing with Symfony: ``` php bin/console --env-file ./.env.test ``` right now, I am doing this: ``` export $(grep -v '^#' .env.test | xargs) && php bin/console ```<issue_comment>username_1: I opted for editing the `bin/console` file directly to facilitate the different `.env` file, which isn't an issue since it's a file the developer has control over. I updated the relevant section to; ``` if (!isset($_SERVER['APP_ENV'])) { if (!class_exists(Dotenv::class)) { throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.'); } } $input = new ArgvInput(); $env = $input->getParameterOption(['--env', '-e'], $_SERVER['APP_ENV'] ?? 'dev', true); switch ($env) { case 'test': (new Dotenv())->load(__DIR__.'/../.env.test'); break; case 'dev': default: (new Dotenv())->load(__DIR__.'/../.env'); break; } ``` Upvotes: 2 <issue_comment>username_2: Make sure that your app/bootstrap.php and bin/console binary is well updated. In my case I just updated bin/console by adding : ``` require dirname(__DIR__).'/app/bootstrap.php'; ``` Upvotes: 0
2018/03/18
1,054
3,565
<issue_start>username_0: I am currently writing a program that is composed of a string vector full of words that have a certain letter all in the same position. For example my vector might look like this: ``` vector v = { "CRYPT", "CYSTS", "WRYLY", "TRYST" }; ``` The idea is a letter is guessed i.e "Y" in this case and the program chooses the first string in the vector, goes through the string vector and keeps in the words that have the Y in the same position as the first word in the vector. In this case, the program would choose "CRYPT". Now, I need the program to go through the string vector and remove any words that have duplicates of that letter in some additional position as compared to the first word "CRYPT" while keeping in words that have the "Y" in the same exact position with no other "Y"s in other places than the first words place. So I need the output of the vector to look something like this after removing any additional duplicates and keeping the other words that have the letter in the same position. ``` vector v = { "CRYPT", "TRYST" }; ``` I was thinking about looping through the vector and looping through each string to go through each char and check however I cannot remove the element from the vector while looping through it or it will cause issues. Maybe using remove\_if for vectors but unsure of how to write the predicate. Any help is appreciated! Thanks!<issue_comment>username_1: Let's start with your vector, following by guessed character and your "main" string ``` vector v = { "CRYPT", "CYSTS", "WRYLY", "TRYST" }; string mainStr = v[0]; char guessed = 'Y'; ``` As you said, we need to iterate over all strings and remove them, if they don't follow our rules. So just do it, but we will not iterate with "for\_each", we'll use simple loop ``` for (size_t i = 1; i < v.size(); ++i) { for (size_t j = 0; j < v[i].size(); ++j) { if (v[i][j] == guessed && (j >= mainStr.size() || mainStr[j] != guessed) || j < mainStr.size() && mainStr[j] == guessed && v[i][j] != guessed) { v.erase(find(v.begin(), v.end(), v[i])); --i; break; } } } ``` In the inner loop, as you can see, when we removing such a string that we don't want to see in the collection, we just step back with our "iterator", so we don't break any vector conditions and we can continue iterate over strings. In the end you can simply see, that we've done right ``` for (auto& str : v) { cout << str << '\n'; } ``` Upvotes: 0 <issue_comment>username_2: One approach is to define a functor that evaluates whether a given string matches the criteria for getting copied to a result vector. The functor is then used with `copy_if`. Something like: ``` #include #include #include struct do\_copy { do\_copy(char m) : match(m) {} char match; size\_t pos; bool found {false}; bool operator()(const std::string& s) { if (found) { return s.size() > pos && s[pos] == match && std::count(s.begin(), s.end(), match) == 1; } for (int p = 0; p < s.size(); ++p) { if (s[p] == match) { pos = p; found = true; return true; } } return false; } }; int main() { std::vector v = { "CRYPT", "CYSTS", "WRYLY", "TRYST" }; std::vector r; char guess = 'Y'; std::copy\_if(v.begin(), v.end(), std::back\_inserter(r), do\_copy(guess)); // Print the result std::cout << r.size() << " elements found:" << std::endl; for (auto& s : r) { std::cout << s << std::endl; } return 0; } ``` Output: ``` 2 elements found: CRYPT TRYST ``` Upvotes: 1
2018/03/18
1,141
4,281
<issue_start>username_0: I'm using EF Core 2.1 preview which was supposed to reduce N+1 queries problem. I'm trying to make query, that selects Forum Threads with authors of posts: ``` dbContext.ForumThreads .Include(t => t.Posts) .Take(n) .Select(t => new { t.Id, t.Title, PostAuhtors = t.Posts.Select(p => p.Author).Take(5) }).ToArray(); ``` This produces n+1 queries: For each ForumThread it selects post authors The schema is simple: ``` public class ForumThread { public Guid Id {get;set;} public string Title {get;set;} public ICollection Posts {get;set;} } public class ForumPost { public Guid Id {get;set;} public string Author {get;set;} public string Content {get;set;} } ```<issue_comment>username_1: I think you can achieve that with less queries (only 2), making some of that behavior in memory. Does this code do what you want? ``` class Program { static void Main(string[] args) { using (var db = new SampleContext()) { Console.ReadLine(); var result = db.Threads .Include(t => t.Posts) .Take(10) .Select(t => new { t.Id, t.Title, t.Posts // Do this in memory //PostAuhtors = t.Posts.Select(p => p.Author).Take(5) }).ToArray(); Console.WriteLine($"» {result.Count()} Threads."); foreach (var thread in result) { // HERE !! var PostAuhtors = thread.Posts.Select(p => p.Author).Take(5); Console.WriteLine($"» {thread.Title}: {string.Join("; ", PostAuhtors)} authors"); } Console.ReadLine(); } } } public class SampleContext : DbContext { public static readonly LoggerFactory MyLoggerFactory = new LoggerFactory(new[] { new ConsoleLoggerProvider((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Debug, true) }); public DbSet Threads { get; set; } public DbSet Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder .EnableSensitiveDataLogging() .UseLoggerFactory(MyLoggerFactory) .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFStart;Trusted\_Connection=True;"); } } public class ForumThread { public Guid Id { get; set; } public string Title { get; set; } public ICollection Posts { get; set; } } public class ForumPost { public Guid Id { get; set; } public string Author { get; set; } public string Content { get; set; } } ``` This is the output: [![enter image description here](https://i.stack.imgur.com/U5DhH.png)](https://i.stack.imgur.com/U5DhH.png) Upvotes: 1 <issue_comment>username_2: *There are pros and cons of your approach.Let me explain,* **Your approach** ----------------- Cons => queries n+1 times. Pros => You requested just 5 Authors of your Posts. (n times). ``` SELECT TOP(@__p_0) [t].[Id], [t].[Title] FROM [ForumThreads] AS [t] => 1 time SELECT TOP(5) [p].[Author] FROM [ForumPosts] AS [p] => n time (n => number of ForumThread) ``` **Other approach you can choose according to the size of your data in DB.** --------------------------------------------------------------------------- ``` var source = dbContext.ForumThreads.Include(t => t.Posts).Take(5).ToList(); var result = source.Select(t => new { t.Id, t.Title, PostAuhtors = t.Posts.Select(p => p.Author).Take(5).ToList() }).ToArray(); ``` Pros => queries 1 time. Cons => You get all Authors of your Posts from DB, then filter them. (This can be cost too much according to the size of your data). ``` SELECT [t.Posts].[Id], [t.Posts].[Author], [t.Posts].[Content], [t.Posts].[ForumThreadId] FROM [ForumPosts] AS [t.Posts] INNER JOIN (SELECT TOP(@__p_0) [t0].[Id] FROM [ForumThreads] AS [t0] ORDER BY [t0].[Id] ) AS [t1] ON [t.Posts].[ForumThreadId] = [t1].[Id] ORDER BY [t1].[Id] ``` Upvotes: 0
2018/03/18
794
3,098
<issue_start>username_0: I have a class called accountinfo and I want to display the username after the user logs in. ``` public class accountinfo extends AppCompatActivity { TextView name; TextView nameTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_accountinfo); nameTV=(TextView)findViewById(R.id.name); name=(TextView) findViewById(R.id.email); nameTV.setText("Welcome " + name); } } ``` This returns "Welcome null" Email is the username stored on database<issue_comment>username_1: Use `name.getText().toString()`. At `onClick(View v)`, not `onCreate()`, after calling `loginbutton.setonclicklistener(this)` in `oncreate()` because the user cannot enter text before `onCreate()` ends. And to allow user to enter his/her info, it is better to use **EditText** instead of **TextView**. E.g. ``` public class accountinfo extends AppCompatActivity implements Button.onClickListener { EditText name; TextView nameTV; Button loginButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_accountinfo); nameTV=(TextView)findViewById(R.id.name); name=(EditText) findViewById(R.id.email); loginButton=(Button)findViewById(R.id.loginButton); loginButton.setOnClickListener(this); } @override public void onClick(View v) { if(!TextUtils.isEmpty(name.getText().toString())){ nameTV.setText("Welcome " + name.getText().toString()); } } } ``` And `activity_accountinfo.xml`: ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 1 <issue_comment>username_2: If login successfull, you can save data via sharedpreferences. Save "name" to your shared preferences and then retrieve it. Sure. it's easy. Just take a look Put this at login activity ``` userName = edtName.getText().toString(); SharedPreferences prefs = this.getSharedPreferences( "com.example.app", Context.MODE_PRIVATE); prefs.edit().putString("name",userName).apply(); ``` And then you need to retrive data from sharedpreferences like this: ``` SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String name = pres.getString("name", ""); ``` So you can send any data with easily. Upvotes: 3 [selected_answer]<issue_comment>username_3: use put extra in loginclass: ``` LoginButton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { //your text do u want pass String s=edit.getText().toString(); Intent ii=new Intent(LoginActivity.this, newclass.class); ii.putExtra("name", s); startActivity(ii); } ``` in second class: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intent); Textv = (TextView)findViewById(R.id.tv2); Intent iin= getIntent(); Bundle b = iin.getExtras(); if(b!=null) { String j =(String) b.get("name"); } } ``` Upvotes: 1
2018/03/18
1,161
3,180
<issue_start>username_0: I am trying to retrieve json data into a php array and giving me the error on foreach() loop Json Data is as given bellow: ``` {"_id":{"$oid":"59043fcee557e6ad53662ed5"},"url":"http://farm3.staticflickr.com/2893/34203321321_f9a2ff200b_b.jpg","asc":0,"id":1} {"_id":{"$oid":"59043fcee557e6ad53662ed6"},"url":"http://farm3.staticflickr.com/2840/34175955132_ab92628fb3_b.jpg","asc":1,"id":1} ``` And the code I used for: ``` $file="jsonfile.json"; $jsondata=file_get_contents($file); $data=json_decode($jsondata,true); print_r ($data); foreach($data as $row){ $insql ="INSERT INTO mysqltable(Nurl,Nid,sort) VALUES('".$row["url"]."','".$row["id"]."','".$row["asc"]."')"; echo "$insql"; mysql_query($dbconnect,$insql); print_r ($data); } ``` Above returning me the bellow error: Any help will be highly appreciated. ``` Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\a\json\index2.php on line 15 ```<issue_comment>username_1: As per comment above - it is not valid json, more a collection of strings that individually can be parsed correctly. The embedding of variables directly in the sql makes this potentially vulnerable to sql injection if there is any form of user interaction but could also be troublesome if the data itself contains single quotes etc. That said you can process the file like this perhaps - though I'd suggest using a `prepared statement` with either `mysqli` or `PDO`. The `mysql` api has been deprecated for quite a while now so you really ought to change to either mysqli or PDO! ``` $file = __DIR__ . "/jsonfile.json"; $lines= file( $file );/* read file into an array - use a foreach to process each item separately */ foreach( $lines as $line ){ $json=json_decode( $line ); $sql ="insert into `mysqltable` ( `nurl`, `nid`, `sort` ) values('{$json->url}','{$json->id}','{$json->asc}')"; printf('%s ',$sql); mysql_query($dbconnect,$insql); } ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: You have to enclose the data with `[]` to make an array. And separate the 2 json with a `,`. Like: On your *jsonfile.json* ``` [ {"_id":{"$oid":"59043fcee557e6ad53662ed5"},"url":"http://farm3.staticflickr.com/2893/34203321321_f9a2ff200b_b.jpg","asc":0,"id":1}, {"_id":{"$oid":"59043fcee557e6ad53662ed6"},"url":"http://farm3.staticflickr.com/2840/34175955132_ab92628fb3_b.jpg","asc":1,"id":1} ] ``` On your *php file* ``` $jsondata=file_get_contents($file); $data=json_decode($jsondata,true); echo " ``` "; print_r( $data ); echo " ``` "; ``` This will result to: ``` Array ( [0] => Array ( [_id] => Array ( [$oid] => 59043fcee557e6ad53662ed5 ) [url] => http://farm3.staticflickr.com/2893/34203321321_f9a2ff200b_b.jpg [asc] => 0 [id] => 1 ) [1] => Array ( [_id] => Array ( [$oid] => 59043fcee557e6ad53662ed6 ) [url] => http://farm3.staticflickr.com/2840/34175955132_ab92628fb3_b.jpg [asc] => 1 [id] => 1 ) ) ``` Upvotes: 1
2018/03/18
664
2,261
<issue_start>username_0: Table `employeeAccount`: ``` CREATE TABLE employeeAccount ( employAccID NUMBER(2), emplyUsername VARCHAR(20), emplyFirstName VARCHAR(20), emplyLastName VARCHAR(20), ) INSERT INTO employeeAccount(employAccID ,emplyUsername ) VALUES (1,'TestAccount1') INSERT INTO employeeAccount(employAccID ,emplyUsername ) VALUES (2,'TestAccount2') ``` Table `JobRole`: ``` CREATE TABLE Jobrole ( jobNo NUMBER(2), jobName VARCHAR(20), ) INSERT INTO Jobrole(jobNo ,jobName) VALUES (001,'Admin') INSERT INTO Jobrole(jobNo ,jobName) VALUES (002,'CEO') ``` And here is my `employeeJob` code: ``` CREATE TABLE employeeJob ( empid NUMBER(2), empjob NUMBER(2), CONSTRAINT pk_employeeJob PRIMARY KEY(empid,empjob), CONSTRAINT fk_empassignjob1 FOREIGN KEY(empid) REFERENCES employeeAccount(employAccID), CONSTRAINT fk_empassignjob2 FOREIGN KEY(empjob) REFERENCES Jobrole(jobNo) ) ``` Below is the insertion query: ``` INSERT INTO employeeJob(empid,empjob) VALUES (1,'001') ``` Any idea how do I make it automatic take all the data like `emplyFirstName`, `emplyLastName` from `employeeAccount` table & insert to `employeeJob`. How should I do that to make it auto insert other data that existing from `employeeAccount` duplicate to `employeeJob` table?<issue_comment>username_1: Yes you can, ``` INSERT INTO table2 SELECT * FROM table1 WHERE condition; ``` You can populate `table2` automatically from `table1`. If you want all the records, ignore the `WHERE` condition. However, if you want to automatically populate only certain records from `table1` to `table2` write the `condition` in `WHERE` statement. Upvotes: 1 <issue_comment>username_2: You can create a trigger on the `employeejob` table on insert like ``` Create trigger trgGetOtherDetails On employeejob AFTER INSERT -- the AFTER key word is Necessary AS BEGIN Declare @emplyFirstname varchar(30), @emplyLastname varchar(30), @empId varchar(5) select @empId = empId from inserted Select @emplyFirstname = emplyFirstname, @emplyLastname = emplyLastname from employeeAccount where employAccID = @empId Update employeejob Set emplyFirstname = @emplyFirstname, emplyLastname = @emplyLastname Where empId = @empId END ``` Upvotes: 0
2018/03/18
2,983
8,794
<issue_start>username_0: I received a question in a code interview that I unfortunately was not able to solve in an efficiant manner. I solved it as O(n^2) and I believe it can be solved in O(n log n). Here's my attempt to it, is it the right way to solve it or can it be improved? Question ======== You have arrays `A`, `B` and `C` that all contains `n` integer values. How many combination of values can we find between A, B and C if the value in B have to be higher than A, and C have to be higher than B. E.g. ``` A = [29, 49, 65] B = [31, 55, 78] C = [45, 98, 100] # Combinations 29, 31, 45 29, 31, 98 29, 31, 100 29, 55, 98 29, 55, 100 49, 55, 98 49, 55, 100 65, 78, 98 65, 78, 100 ``` Solution ======== I solved it by sorting the lists and then doing a Binary Search for the index closest, and higher than the previous value. ```py def getClosest(arr, left, right, val, closest=None): mid = right-int(abs(left-right)/2) if left >= right: if arr[mid] == val: return val return closest if arr[mid] == val: return mid elif val > arr[mid]: return getClosest(arr, mid+1, right, val, closest) elif val < arr[mid]: if closest is None or mid < closest: closest = mid return getClosest(arr, left, mid-1, val, closest) return closest def getLocationGTE(arr, limit): index = getClosest(arr, 0, len(arr)-1, limit) if index is None: return [] else: return arr[index:] def countStops(A, B, C): A.sort() B.sort() C.sort() total = 0 for i in range(len(A)): a = A[i] b_locations = getLocationGTE(B, a+1) for b in b_locations: c_locations = getLocationGTE(C, b+1) total += len(c_locations) return total ```<issue_comment>username_1: Yes you are right, it can be solved in O(nlogn). 1. sort all the arrays 2. for each index b in B, count how many elements in C are greater than B[b] ```java int[] count = new int[n]; int c = 0; for (int b = 0; b < n; b++) { while (c < n && C[c] <= B[b]) c++; count[b] = n - c; } ``` 3. build the cumulative sum of the counts in reverse ```java int[] cumSum = new int[n]; cumSum[n - 1] = count[n - 1]; for (int i = n - 2; i >= 0; i--) cumSum[i] = cumSum[i + 1] + count[i]; ``` 4. for each element in A find the first index in B and add the corresponding cumulative sum to the total count ```java int total = 0, b = 0; for (int a = 0; a < n; a++) { while (b < n && B[b] <= A[a]) b++; if (b == n) break; total += cumSum[b]; } ``` Step 1. takes O(nlogn) and step 2. to 4. are O(n), which gives O(nlogn) overall. Here is the complete implementation in javascript: ```js function countCombos(A, B, C) { A.sort(function (a, b) {return a - b}) B.sort(function (a, b) {return a - b}) C.sort(function (a, b) {return a - b}) let count = [], c = 0, n = A.length for (let b = 0; b < n; b++) { while (c < n && C[c] <= B[b]) c++ count[b] = n - c } for (let i = n - 2; i >= 0; i--) // building cumSum directly in count count[i] = count[i] + count[i + 1] let total = 0, b = 0 for (let a = 0; a < n; a++) { while (b < n && B[b] <= A[a]) b++ if (b == n) break total += count[b] } return total } console.log(countCombos([29, 49, 65], [31, 55, 78], [45, 98, 100])) ``` Btw. you are missing 4 combos in your list: [29, 78, 98], [29, 78, 100], [49, 78, 98] and [49, 78, 100], therefore 13 is the correct answer. Upvotes: 0 <issue_comment>username_2: Your intuition is right, we can beat `O(n^2)`, because the sorting and binary search solution generates extra work (elements of arrays `B` and `C` are read multiple times) which we would like to avoid. ### Solution A - `O(n.log2(n))` An `O(nlogn)` solution can be constructed using a binary search tree as an auxiliary data structure. We would need to decorate each node with a color, identifying the array from which the node's value was extracted. Let's use for instance the following color conventions: * `Amber` for array `A` * `Blue` for array `B` * `Cyan` for array `C` Then, we perform with an in-order depth-first search of the tree, counting the number of `Cyan` nodes, `Cyan -> ... -> Blue` and `Cyan -> ... -> Blue -> ... -> Amber` transitions. ``` BST tree = new BST(AscendingOrder); for (a: A) { tree.add(new Node(Amber, a)); } for (b: B) { tree.add(new Node(Blue, b)); } for (c: C) { tree.add(new Node(Cyan, c)); } int cyans, cyanThenBlues, solutions = 0; DFS(tree.root(), cyans, cyanThenBlues, solutions) ``` with ``` DFS(Node node, int& cyans, int& cyanThenBlues, int& solutions) { if (node == null) { return; } DFS(node.left(), cyans, cyanThenBlues, solutions); cyans += node.color() == Cyan ? 1 : 0; cyanThenBlues += node.color() == Blue ? cyans : 0; solutions += node.color() == Amber ? cyanThenBlues : 0; DFS(node.right(), cyans, cyanThenBlues, solutions); } ``` If the values of `A`, `B` and `C` are arbitrarily ordered, the construction of the BST costs `O(n.log2(n))`, and the DFS `O(n)`. However, depending on how close to be sorted the input arrays `A`, `B` and `C` are, the tree may become unbalanced enough for the `O(n.log2(n))` to become too optimistic. * Average time complexity: `O(n.log2(n))` * Worst case complexity: `O(n^2)` * Space complexity: `O(n)` ### Solution B - `O(n.log2(n))` It is essentially the same approach as before, the difference is that we first sort the arrays `A`, `B` and `C`, create an auxiliary array of length `3.n` which elements are decorated with colors similarly to the previous solution, populating this arrays with the values of `A`, `B` and `C`, then traverse the array and transitively count the number of transitions of colors we are interested in. ``` sort(A); sort(B); sort(C); // Constructing guards, loose syntax int[] A' = A + { Integer.MIN_VALUE }; int[] B' = B + { Integer.MIN_VALUE }; int[] C' = C + { Integer.MIN_VALUE }; int[] D = new int[3 * n]; int i, j, k = 0; for (int t = 0; t < 3 * n; ++t) { if (A'[i] >= B'[j] && A'[i] >= C'[k]) { D[t] = new Node(A'[i++], Amber); } else if (B'[j] >= A'[i] && B'[j] >= C'[k]) { D[t] = new Node(B'[j++], Blue); } else if (C'[k] >= A'[i] && C'[k] >= B'[j]) { D[t] = new Node(C'[k++], Cyan); } } int cyans, cyanThenBlues, solutions = 0; for (int t = 0; t < 3 * n; ++t) { cyans += D[t].color() == Cyan ? 1 : 0; blues += D[t].color() == cyanThenBlues ? cyans : 0; solutions += D[t].color() == Amber ? cyanThenBlues : 0; } ``` Assuming we are using a quick sort: * Average time complexity: `O(n.log2(n))` * Worst case complexity: `O(n^2)` * Space complexity: `O(n)` Note that the memory footprint of the second solution will be smaller than the first one (cost of the BST). **Follow-up comments** * Assuming the arrays are sorted, `Theta(n)` is the best possible time complexity achievable (because each element needs to be read at least once). The overall time complexity in these solutions is dominated by the sort or the construction of the BST. * In both cases, the key was to exhibit an ordering relationship spanning all three arrays. * Could we think of another [sorting algorithm](http://bigocheatsheet.com/) for the array of integers? Upvotes: 0 <issue_comment>username_3: The answers given so far look a bit complicated to me, so let me add another approach. The main idea is to calculate the number of combinations using a given B element. It's the number of smaller A elements multiplied by the number of larger C elements. Let's assume all three arrays are sorted in ascending order. Your example arrays are already sorted, but the fact isn't mentioned explicitly in the text, so maybe we need an initial sort, accounting for O(nlogn). We need a loop over all B elements, and inside the loop we need to maintain two indexes into the A and C array, the A index `ia` identifying the last A element lower than the B element, and the C index `ic` identifying the first C element larger than the B element. This loop is O(n), as the A and C indexes can't be incremented more than n times. A Java class implementing the algorithm: ``` public class Combinations { // array access guarded against index-out-of-range. private static int arrayAccess(int[] array, int index) { if (index < 0) return Integer.MIN_VALUE; else if (index >= array.length) return Integer.MAX_VALUE; else return array[index]; } public static int combinations(int[] a, int[] b, int[] c) { int ia = -1; int ic = 0; int nCombinations = 0; for (int ib=0; ib ``` Upvotes: 3 [selected_answer]
2018/03/18
911
3,250
<issue_start>username_0: In my website I use oauth for login via google, twitter and facebook. Since 24 hours I noticed that the facebook login does not work anymore. I get the following error message when I try to log in: "Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings." I am not using https but http. Can anybody please shed some light on this new situation? Thanks.<issue_comment>username_1: Just ran into this as well. Looks like Facebook started enforcing strict mode for redirect URIs this month. Resolution is to enter in your auth callback URL in the "Valid OAuth redirect URIs" field. Look at Step 3 at this site: <https://auth0.com/docs/connections/social/facebook> Upvotes: 2 <issue_comment>username_2: Double check your "Valid OAuth redirect URIs". All of URLs must be set where exact as you use it (with GET params)! For example, if you redirect URL is <http://somesite.com/auth?type=facebook> you cannot set just <http://somesite.com/auth> from now. TIP: You can find this URL as a param in page address where you see an error message. Upvotes: 1 <issue_comment>username_3: Make sure have entered the key hashes Steps : <https://developers.facebook.com/apps> 1.Basic 2.Add Platform(android,ios) 3.fill the details and make sure you entered correct Key Hashes. Give it a try !! Upvotes: 0 <issue_comment>username_4: In march 2018, facebook change Oauth url, <https://developers.facebook.com/blog/post/2017/12/18/strict-uri-matching/>. I use Hwioauth bundle, just solved the problem. Make sure you add all Valid OAuth redirect URIs. In my app has <http://localhost:8000/> <http://localhost:8000/connect/check-facebook> <http://localhost:8000/connect/facebook> Upvotes: 1 <issue_comment>username_5: 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: 0 <issue_comment>username_6: As username_2 said in one of the answers above I solved this problem by adding as Valid OAuth Redirect URI <http://mydomain......com/login-base-url.php?hauth_done=Facebook> . Upvotes: 0 <issue_comment>username_7: @username_2 is right. In addition, if you have dynamic query parameters in your redirect uri, those should go in the **state** parameter of the authorization request. For details on this check my [answer](https://stackoverflow.com/questions/48684164/facebook-login-with-strict-mode-for-redirect-uris/49410014#49410014) on a similar question. Upvotes: 0 <issue_comment>username_8: I got the same problem with the same symptoms where the callback URL on logon pop-up with some weird app\_id. Finally, after a lot of search (rare case), I found that which caused by the conflict between Manychat Script and FB login button. (the weird app\_id on pop-up comes from Many Chat). It's just a tips for your search, I'm not sure our problem caused from the same issue. Hope that help. Bryan Upvotes: 1
2018/03/18
727
1,650
<issue_start>username_0: **input**: ``` random abcD .and$ 5487>1.2.3.4:random fghij & 9101112 ``` **output**: ``` 1.2.3.4 ``` **What I have done so far**: ``` sed -e 's/'>'\(.*\)':'/\1/' ``` **I have also tried**: ``` sed -e 's/>\(.*\):/\1/' ``` *note*: I can do it with awk: ``` awk 'BEGIN { FS = ">" } ; { print $2 }' | awk 'BEGIN { FS = ":" } ; { print $1 }' ``` but it's a little bit heavy, isnt it?<issue_comment>username_1: ***Solution 1st:*** This simple `sed` may help you on same. ``` sed 's/.*>//;s/:.*//' Input_file ``` ***Solution 2nd:*** Adding `awk` solution too now. ``` awk '{gsub(/.*>|:.*/,"")} 1' Input_file ``` ***Solution 3rd:*** Using another `awk` with field separator logic. ``` awk -F'[>:]' '{print $2}' Input_file ``` ***Solution 4th:*** Using another `sed` with back references logic. ``` sed 's/\(.*>\)\([^:]*\)\(.*\)/\2/' Input_file ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: if there are other chars ":" and ">" in the line, and you are sure that the substring to match contain only "." and digitis [ 0 to 9 ], it will be better to use : ``` sed "s/.*>\([0-9|.][0-9|.]*\):.*/\1/g" ``` or better : ``` sed "s/.*>\([0-9|.]\+\):.*/\1/g" ``` or ( to match the first one occurence ) : ``` sed "s/.*>\([0-9|.]\+\):.*/\1/" ``` you can also use: ``` grep -o ">[0-9|.]*:" | grep -o "[0-9|.]*" ``` test : ``` echo "random > abcD .and$ 5487>1.2.3.4:random : fghij > & 9101112" | sed "s/.*>\([0-9|.][0-9|.]*\):.*/\1/g" 1.2.3.4 echo "random > abcD .and$ 5487>1.2.3.4:random : fghij > & 9101112" | sed "s/.*>\([0-9|.]\+\):.*/\1/" 1.2.3.4 ``` Upvotes: 0
2018/03/18
504
1,541
<issue_start>username_0: So I am going to be working with Php and summing values up so I need the last div to be generated after all the other divs are. Is there a way to align the last div (Div #4) with the top right of the beige box? My issue is I have to place it right below or above Div #1 in order for it to float right properly, but I want to place it after Div #3 and still have it float right but float at the top of the beige box. Essentially what I am trying to do is get the green box to be in the top right of the beige box, but with having the html code for it after Div #3. ```html Div 1 Div 2 Div 3 Div 4 ``` [![enter image description here](https://i.stack.imgur.com/iz8eD.png)](https://i.stack.imgur.com/iz8eD.png)<issue_comment>username_1: This is a weird stuff to wanna make this this way. Here is what you can do : ``` Div 1 Div 2 Div 3 Div 4 ``` Take off your `float: right`. It'll stuck the left floating blocks on the right. Then you set the left blocks to 70% width, your right block to 20%, so 70 - 20 = 10% staying. Add a `margin-left: 10%;` and the job is done. Upvotes: 0 <issue_comment>username_2: ``` Div 1 Div 4 Div 2 Div 3 ``` Upvotes: -1 <issue_comment>username_3: Try to remove `float:right` from last `div` and use `margin-left` which will be `100%-width` ```html Div 1 Div 2 Div 3 Div 4 ``` Or if you are allowed to change some markup, try to wrap `left` and `right` boxes in different div ```html Div 1 Div 2 Div 3 Div 4 ``` Upvotes: 0
2018/03/18
1,344
4,956
<issue_start>username_0: I'm baffled to find out neither of `typing.Awaitable` nor `collections.abc.Awaitable` cover a generator-based coroutine which is one of *awaitable*s defined in * <https://www.python.org/dev/peps/pep-0492/#await-expression> As of Python 3.6, several `asyncio` APIs such as `sleep()` and `open_connection()` actually return generator-based coroutines. I usually have no problems with applying `await` keywords to the return values of them, but I'm going to handle a mixture of normal values and *awaitable*s and I'd need to figure out which ones require `await` to yield an actual value. So here's my question, what satisfies `isinstance(c, ???) == True` for an arbitrary generator-based coroutine `c`? I'm not insisting on using `isinstance` for this purpose, maybe `getattr()` can be a solution... Background ---------- I'm working on a tiny mock utility for unit testing of async function based on <https://blog.miguelgrinberg.com/post/unit-testing-asyncio-code> which internally has a `asyncio.Queue()` of mocked return values, and I want to enhance my utility so that the queue can have *awaitable* elements, each of which triggering `await` operation. My code will look like ``` async def case01(loop): f = AsyncMock() f.side_effect = loop, [] await f() # blocks forever on an empty queue async def case02(loop): f = AsyncMock() f.side_effect = loop, ['foo'] await f() # => 'foo' await f() # blocks forever async def case03(loop): f = AsyncMock() f.side_effect = loop, [asyncio.sleep(1.0, 'bar', loop=loop)] await f() # yields 'bar' after 1.0 sec of delay ``` For usability reason, I don't want to manually wrap the return values with `create_task()`. I'm not sure my queue will ever legitimely contain normal, non-coroutine generators; still, the ideal solution should be able to distinguish normal generators from generator-based coroutines and skip applying `await` operation to the former.<issue_comment>username_1: I'm not sure what you're trying to test here, but [the `inspect` module](https://docs.python.org/3/library/inspect.html#types-and-members) has functions for checking most things like this: ``` >>> async def f(c): ... await c >>> co = f() >>> inspect.iscoroutinefunction(f) True >>> inspect.iscoroutine(co) True >>> inspect.isawaitable(co) True ``` The difference between the last two is that `isawaitable` is true for anything you can `await`, not just coroutines. If you really want to test with `isinstance`: `isinstance(f)` is just `types.FunctionType`, which isn't very useful. To check whether it's a function that returns a `coroutine`, you need to also check its flags: `f.__code__.co_flags & inspect.CO_COROUTINE` (or you could hardcode 0x80 if you don't want to use `inspect` for some reason). `isinstance(co)` is `types.CoroutineType`, which you *could* test for, but it's still probably not a great idea. Upvotes: 3 <issue_comment>username_2: The documented way to detect objects that can be passed to `await` is with [`inspect.isawaitable`](https://docs.python.org/3/library/inspect.html#inspect.isawaitable). According to [PEP 492](https://www.python.org/dev/peps/pep-0492/#await-expression), `await` requires an awaitable object, which can be: * A *native coroutine* - a Python function defined with `async def`; * A generator-based coroutine - a Python generator decorated with `@types.coroutine`; * Instance of a Python class that defines `__await__`; * Instance of an extension type that implements `tp_as_async.am_await`. `isinstance(o, collections.abc.Awaitable)` covers all except the 2nd one. This could be reported as a bug in `Awaitable` if it wasn't [explicitly documented](https://docs.python.org/3/library/collections.abc.html#collections.abc.Awaitable), pointing to `inspect.isawaitable` to check for *all* awaitable objects. Note that you cannot distinguish generator-based coroutine objects from regular generator-iterators by checking the type. The two have the exact same type because the `coroutine` decorator doesn't wrap the given generator, it just sets a flag on its code object. The only way to check if the object is a generator-iterator produced by a generator-based coroutine is to check its code flags, which how `inspect.isawaitable` is [implemented](https://github.com/python/cpython/blob/master/Lib/inspect.py#L221). A related question is why `Awaitable` only checks for the existence of `__await__` and not for other mechanisms that `await` itself uses. This is unfortunate for code that tries to use `Awaitable` to check the actual awaitability of an object, but it is not without precedent. A similar discrepancy exists between iterability and the the `Iterable` ABC: ``` class Foo: def __getitem__(self, item): raise IndexError >>> iter(Foo()) >>> list(Foo()) [] ``` Despite instances of `Foo` being iterable, `isinstance(Foo(), collections.abc.Iterable)` returns false. Upvotes: 3 [selected_answer]
2018/03/18
878
3,297
<issue_start>username_0: I am using charles proxy to collect http logs in my automation test framework, I want to launch the charles from terminal after initializing the automation framework. Is there any way to launch charles proxy and stop without manually launching the same. I am using mac.<issue_comment>username_1: I'm not sure what you're trying to test here, but [the `inspect` module](https://docs.python.org/3/library/inspect.html#types-and-members) has functions for checking most things like this: ``` >>> async def f(c): ... await c >>> co = f() >>> inspect.iscoroutinefunction(f) True >>> inspect.iscoroutine(co) True >>> inspect.isawaitable(co) True ``` The difference between the last two is that `isawaitable` is true for anything you can `await`, not just coroutines. If you really want to test with `isinstance`: `isinstance(f)` is just `types.FunctionType`, which isn't very useful. To check whether it's a function that returns a `coroutine`, you need to also check its flags: `f.__code__.co_flags & inspect.CO_COROUTINE` (or you could hardcode 0x80 if you don't want to use `inspect` for some reason). `isinstance(co)` is `types.CoroutineType`, which you *could* test for, but it's still probably not a great idea. Upvotes: 3 <issue_comment>username_2: The documented way to detect objects that can be passed to `await` is with [`inspect.isawaitable`](https://docs.python.org/3/library/inspect.html#inspect.isawaitable). According to [PEP 492](https://www.python.org/dev/peps/pep-0492/#await-expression), `await` requires an awaitable object, which can be: * A *native coroutine* - a Python function defined with `async def`; * A generator-based coroutine - a Python generator decorated with `@types.coroutine`; * Instance of a Python class that defines `__await__`; * Instance of an extension type that implements `tp_as_async.am_await`. `isinstance(o, collections.abc.Awaitable)` covers all except the 2nd one. This could be reported as a bug in `Awaitable` if it wasn't [explicitly documented](https://docs.python.org/3/library/collections.abc.html#collections.abc.Awaitable), pointing to `inspect.isawaitable` to check for *all* awaitable objects. Note that you cannot distinguish generator-based coroutine objects from regular generator-iterators by checking the type. The two have the exact same type because the `coroutine` decorator doesn't wrap the given generator, it just sets a flag on its code object. The only way to check if the object is a generator-iterator produced by a generator-based coroutine is to check its code flags, which how `inspect.isawaitable` is [implemented](https://github.com/python/cpython/blob/master/Lib/inspect.py#L221). A related question is why `Awaitable` only checks for the existence of `__await__` and not for other mechanisms that `await` itself uses. This is unfortunate for code that tries to use `Awaitable` to check the actual awaitability of an object, but it is not without precedent. A similar discrepancy exists between iterability and the the `Iterable` ABC: ``` class Foo: def __getitem__(self, item): raise IndexError >>> iter(Foo()) >>> list(Foo()) [] ``` Despite instances of `Foo` being iterable, `isinstance(Foo(), collections.abc.Iterable)` returns false. Upvotes: 3 [selected_answer]
2018/03/18
1,142
3,815
<issue_start>username_0: I am writing a code that would display images one by one after the user sends input signal like enter.Following is my code ``` import numpy as np import matplotlib.pyplot as plt from logistic_regression_class.utils_naseer import getData import time X,Y=getData(balances=False) // after getting X data and Y labels # X and Y are retrieved using famous kaggle facial expression dataset label_map=['Anger','Disgust','Fear','Happy','Sad','Surprise','Neutral'] plt.ion() for i in range(len(Y)): x=X[i] plt.figure() plt.imshow(x.reshape(48,48),cmap='gray') plt.title(label_map[Y[i]]) plt.show() _ = input("Press [enter] to continue.") plt.close() ``` **Output:** I am only getting blank images with no data and each time I presses enter I get a new blank image.But When I removed plt.close() then all the plots showed up in separate window but that will be too many windows popping up. I also used suggestion from stackoverflow [this](https://stackoverflow.com/questions/11129731/can-i-generate-and-show-a-different-image-during-each-loop-with-matplotlib) link. What is the correct way to show images in a loop one after another using a use command input? **Screen Shots:** **a) With plt.close()** [![enter image description here](https://i.stack.imgur.com/PnO30.png)](https://i.stack.imgur.com/PnO30.png) **b) Without plt.close()** [![enter image description here](https://i.stack.imgur.com/TRZ8L.png)](https://i.stack.imgur.com/TRZ8L.png)<issue_comment>username_1: I had a very similar problem, and placing plt.ion() within the for loop worked for me. Like so: ``` for i in range(len(Y)): x=X[i] plt.ion() plt.figure() plt.imshow(x.reshape(48,48),cmap='gray') plt.title(label_map[Y[i]]) plt.show() _ = input("Press [enter] to continue.") plt.close() ``` Upvotes: 1 <issue_comment>username_2: I was trying to implement something similar for an image labeling program (i.e. present an image, take some user input and put the image in the correct folder). I had some issues and the only way I could get it to work was by creating a thread (I know it's messy but it works!) that allows user input while the image is open and then closes it once there has been input. I passed the `plt` object into the thread so I could close it from there. My solution looked something like this ... maybe you could use a similar approach! ``` import os import matplotlib.pyplot as plt import matplotlib.image as mpimg import threading from shutil import copyfile import msvcrt #define folders CAR_DATA = 'car_data' PASSENGER = 'passenger' NO_PASSENGER = 'no_passenger' UNSURE = 'unsure' extensionsToCheck = ['jpg', '.png'] listing = os.listdir(CAR_DATA) def userInput(plt, file_name): print('1:No Passenger - 2:Passenger - Any Other:Unsure - e:exit') user_input = msvcrt.getch() user_input = bytes.decode(user_input) if(user_input=='1'): print("No Passenger") copyfile(CAR_DATA+'/'+file_name, NO_PASSENGER+'/'+file_name) elif(user_input=='2'): print("Passenger") copyfile(CAR_DATA+'/'+file_name, PASSENGER+'/'+file_name) elif(user_input=="e"): print("exit") os._exit(0) else: print("unsure") copyfile(CAR_DATA+'/'+file_name, UNSURE+'/'+file_name) plt.close() def main(): for file in listing: if any(ext in file for ext in extensionsToCheck): plt.figure(file) img=mpimg.imread(CAR_DATA + '/' + file) imgplot = plt.imshow(img) plt.title(file) mng = plt.get_current_fig_manager() mng.full_screen_toggle() threading.Thread(target=userInput, args=(plt,file)).start() plt.show() if __name__ == '__main__':main() ``` Upvotes: -1
2018/03/18
549
1,935
<issue_start>username_0: I want to store my images using ck editor. But it returns 419 http status even if I set csrf token to request header. ``` let token = document.head.querySelector('[name=csrf-token]').content, document.querySelector('#article_editor').on('fileUploadRequest', function (evt) { var xhr = evt.data.fileLoader.xhr; xhr.setRequestHeader('Cache-Control', 'no-cache'); xhr.setRequestHeader('X-File-Name', this.fileName); xhr.setRequestHeader('X-File-Size', this.total); xhr.setRequestHeader('X-CSRF-Token', token); xhr.send(this.file); // Prevented the default behavior. evt.stop() }); ``` How can I fix this ? I already set csrf meta in between head tags. Despite this, I keep getting errors.. ``` ... ... ```<issue_comment>username_1: I had a similar issue. I did add the upload URL to **VerifyCsrfToken.php** (app/Http/Middleware). In this file, I added **'upload-image/'**. This could solve your problem. However, posting data without CSRF could create risk. Upvotes: 3 <issue_comment>username_2: Just add in your blade: ``` ``` Then in your simpleUpload config (if you use it): ``` simpleUpload: { uploadUrl: '/* your path */', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'), } } ``` Upvotes: 0 <issue_comment>username_3: Add this to your blade file: ``` ``` In Js File add like this ``` simpleUpload: { uploadUrl: 'your_url?_token='+document.querySelector('meta[name="csrf-token"]').getAttribute('content') } ``` For more details check this link: <https://ckeditor.com/docs/ckeditor5/latest/features/image-upload/simple-upload-adapter.html> Upvotes: 1 <issue_comment>username_4: you should make like that: ``` filebrowserUploadUrl: "{{route('ckeditor.upload', ['_token' => csrf_token() ])}}", filebrowserUploadMethod: 'form' ``` Upvotes: 1
2018/03/18
514
1,761
<issue_start>username_0: How can I use CONVERT from mysql within Doctrine. ``` $now = new \DateTime('now', new DateTimeZone('Europe/Berlin')); $selectedDate = new \DateTime($flightDate); $selectedDate = $selectedDate->format('Y-m-d H:i:s'); $query= $this->createQueryBuilder('o') ->where('CONVERT(:selectedDate, DATE) + o.time >= :currentTime') ->setParameter('selectedDate', $selectedDate) ->setParameter('currentTime', $now->format('Y-m-d H:i:s')) ->setMaxResults(20) ->getQuery(); ``` For which I get an error > > Error: Expected known function, got 'CONVERT' > > ><issue_comment>username_1: I had a similar issue. I did add the upload URL to **VerifyCsrfToken.php** (app/Http/Middleware). In this file, I added **'upload-image/'**. This could solve your problem. However, posting data without CSRF could create risk. Upvotes: 3 <issue_comment>username_2: Just add in your blade: ``` ``` Then in your simpleUpload config (if you use it): ``` simpleUpload: { uploadUrl: '/* your path */', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'), } } ``` Upvotes: 0 <issue_comment>username_3: Add this to your blade file: ``` ``` In Js File add like this ``` simpleUpload: { uploadUrl: 'your_url?_token='+document.querySelector('meta[name="csrf-token"]').getAttribute('content') } ``` For more details check this link: <https://ckeditor.com/docs/ckeditor5/latest/features/image-upload/simple-upload-adapter.html> Upvotes: 1 <issue_comment>username_4: you should make like that: ``` filebrowserUploadUrl: "{{route('ckeditor.upload', ['_token' => csrf_token() ])}}", filebrowserUploadMethod: 'form' ``` Upvotes: 1
2018/03/18
623
1,991
<issue_start>username_0: mongodb service cannot start with `systemctl start mongodb.service`, it would ask for a password. After then when I try `mongo` command, it throws : `MongoDB shell version v3.6.2 connecting to: mongodb://127.0.0.1:27017 2018-03-18T16:05:39.307+0700 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused 2018-03-18T16:05:39.307+0700 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed : connect@src/mongo/shell/mongo.js:251:13 @(connect):1:6 exception: connect failed` I've been through all google page 1 solution but did nothing, also I try another query, but still again dont work for me, uninstall & install again also didnt work. My current OS distribution is Linux Manjaro. Any help is appreciated.<issue_comment>username_1: I had a similar issue. I did add the upload URL to **VerifyCsrfToken.php** (app/Http/Middleware). In this file, I added **'upload-image/'**. This could solve your problem. However, posting data without CSRF could create risk. Upvotes: 3 <issue_comment>username_2: Just add in your blade: ``` ``` Then in your simpleUpload config (if you use it): ``` simpleUpload: { uploadUrl: '/* your path */', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'), } } ``` Upvotes: 0 <issue_comment>username_3: Add this to your blade file: ``` ``` In Js File add like this ``` simpleUpload: { uploadUrl: 'your_url?_token='+document.querySelector('meta[name="csrf-token"]').getAttribute('content') } ``` For more details check this link: <https://ckeditor.com/docs/ckeditor5/latest/features/image-upload/simple-upload-adapter.html> Upvotes: 1 <issue_comment>username_4: you should make like that: ``` filebrowserUploadUrl: "{{route('ckeditor.upload', ['_token' => csrf_token() ])}}", filebrowserUploadMethod: 'form' ``` Upvotes: 1
2018/03/18
586
2,099
<issue_start>username_0: I am following a tutorial in React. I have created my very first component and expecting to see component in my application homepage, but I don't. I am not getting any error either. In my homePage.Js **(This is a component that I am trying to render)**, I have : ``` var React = require('react'); var Home = React.createClass({ render: function(){ return( Administration ============== React, React Router. ); } }); module.exports = Home; ``` In my Main.js file I have (This main.js serves as the base file for referencing my components): ``` $ = jQuery = require('jquery'); var React = require('react'); var Home = require('./components/homePage'); React.render(, document.getElementById('app')); ``` and in my index.html file I have : ``` Administrator ``` When I run the app, I see an empty page, and when I check the page source code I can see below HTML in the BODY tag: ``` ```<issue_comment>username_1: I had a similar issue. I did add the upload URL to **VerifyCsrfToken.php** (app/Http/Middleware). In this file, I added **'upload-image/'**. This could solve your problem. However, posting data without CSRF could create risk. Upvotes: 3 <issue_comment>username_2: Just add in your blade: ``` ``` Then in your simpleUpload config (if you use it): ``` simpleUpload: { uploadUrl: '/* your path */', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'), } } ``` Upvotes: 0 <issue_comment>username_3: Add this to your blade file: ``` ``` In Js File add like this ``` simpleUpload: { uploadUrl: 'your_url?_token='+document.querySelector('meta[name="csrf-token"]').getAttribute('content') } ``` For more details check this link: <https://ckeditor.com/docs/ckeditor5/latest/features/image-upload/simple-upload-adapter.html> Upvotes: 1 <issue_comment>username_4: you should make like that: ``` filebrowserUploadUrl: "{{route('ckeditor.upload', ['_token' => csrf_token() ])}}", filebrowserUploadMethod: 'form' ``` Upvotes: 1
2018/03/18
397
1,522
<issue_start>username_0: [![C# code](https://i.stack.imgur.com/i8Xzm.png)](https://i.stack.imgur.com/i8Xzm.png) I am a new c# learner, that' why I have some of the dumbest question! But I want to know if we have already used "using System" statement in our app then why do we need to use statements like "using System.Data" or any other shown in the image. Haven't we already imported the main namespace, then why is there even need of adding using statements for sub-namespaces?<issue_comment>username_1: Because `using` is not recursive down the namespace tree. When you import `System` you import only the definitions strictly inside `System` not the ones inside `System.Collections`. That's why you need to specify them. Upvotes: 0 <issue_comment>username_2: Because the Language Spec says so: C# language specification section 9.4.2 Using namespace directives: > > A using-namespace-directive imports the types contained in the given namespace, **but specifically does not import nested namespaces**. > > > A reason for this might be that if every nested namespace is imported, then there would be too many name conflicts. This reduces the benefits of using `using` directives. Here are some name conflicts that I could think of if `using` directives imported nested namespaces: * `System.Drawing.Path` and `System.IO.Path` * `System.Windows.Forms.Button` and `System.Web.UI.WebControls.Button` * `System.Timers.Timer`, `System.Threading.Timer` and `System.Windows.Forms.Timer` Upvotes: 4 [selected_answer]
2018/03/18
244
813
<issue_start>username_0: i cannot print my desire path in the form action i set a condition that id the **$edit** array is set then page goes to **add\_new\_proposal** function which i define in my controller and if the **$edit** variable is not set then it goes to **edit\_new\_proposal** function **here is the code of action of form** ``` ```<issue_comment>username_1: Change: ``` echo 'base_url();proposal/add_new_proposal'; ``` to: ``` echo base_url().'proposal/add_new_proposal'; ``` And ``` echo 'base_url();proposal/edit_new_proposal'; ``` to: ``` echo base_url().'proposal/edit_new_proposal'; ``` Upvotes: 1 <issue_comment>username_2: According to your code base\_url() is a function and you are adding it as a string in the echo statement. Change it as shown below: ``` ``` Upvotes: -1
2018/03/18
302
1,117
<issue_start>username_0: I had a few Javascript projects and I need to copy or move to another machine. And I would like to ignore files which are already in `.gitignore`. Now, when I copy the folder I got git ignored folders and files. But, I want to ignore those when I copy (`Command` + `C`). How can I configure it?<issue_comment>username_1: You can use git clone: ``` $ git clone machine1:/path/to/project machine2:/target/path ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: To remove ignored files from a repository, you can use `git clean`. ``` git clean -nx ``` * `-n` means dry-run; it will cause it to list the files it would delete without actually deleting them. * `-x` means remove ignored files. If you also need to remove directories, specify `-d`. After making sure that what above command prints is what you want to remove, replace `-n` with `-f` to run it for real. ``` git clean -fx ``` **Keep in mind that this will delete files**, and there is no way of getting them back unless you have a backup. More info at [man git-clean](https://gitirc.eu/git-clean.html). Upvotes: 1
2018/03/18
1,371
4,318
<issue_start>username_0: I want to do a simple timer who can run from 25 to 0 and reset whenever we want to. For this I've made a clickable div, and I want one click to start the timer and another one to reset it to 25 and stop the timer, is this possible ? A toggable start/reset timer? This is what I came up with so far : HTML ``` ``` CSS ``` #result { background: pink; height: 200px; width: 200px; border-radius: 50%; margin-left: 400px; margin-top: 200px; } #result:hover { border: black solid; } #output{ margin-left: 70px; position: fixed; font-size: 60px; } ``` And the most important the JS : ``` var duree=25; var toggle = true; function playReset () { if(toggle == true) { var time = setInterval(function(){ duree--; document.getElementById('output').innerHTML = duree; }, 1000); toggle = false } else if (toggle == false) { clearInterval(time); duree = 25; toggle = true; } } document.getElementById('output').innerHTML = duree; ``` Thank's if someone can give me a hand, I have SO MUCH trouble understanding setInterval/timeout, clearInterval/timeout ...<issue_comment>username_1: I simplified that code a little, where you can use the actual `time` variable to check whether it is running or not. Stack snippet ```js var duree = 2; var time; function playReset() { if (time) { clearInterval(time); time = null; duree = 25; document.getElementById('output').innerHTML = duree; } else { time = setInterval(function() { duree--; document.getElementById('output').innerHTML = duree; if (duree == 0) { clearInterval(time); } }, 1000); } } document.getElementById('output').innerHTML = duree; ``` ```css #result { background: pink; height: 200px; width: 200px; border-radius: 50%; margin-left: 40px; margin-top: 20px; border: transparent solid; } #result:hover { border: black solid; } #output { margin-left: 70px; position: fixed; font-size: 60px; } ``` ```html ``` --- When you later on have increased your skills, you likely want these stuff and their variable hidden from the global environment. With closure one can do something like this, where only the function name is public. Stack snippet ```js (function (output,duree,time) { //declared as static variables this.init_time = duree; this.playReset = function() { if (time) { clearInterval(time); time = null; output.innerHTML = duree = init_time; // set init value } else { time = setInterval(function() { output.innerHTML = --duree; if (duree == 0) { clearInterval(time); } }, 1000); } } window.playReset = this.playReset; //make it public output.innerHTML = duree; // set init value })(document.getElementById('output'),25); // pass in the output element and default time ``` ```css #result { background: pink; height: 200px; width: 200px; border-radius: 50%; margin-left: 40px; margin-top: 20px; border: transparent solid; } #result:hover { border: black solid; } #output { margin-left: 70px; position: fixed; font-size: 60px; } ``` ```html ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Here is same solution, but with the event listener and I check the count to know if a reset is to be done. You can try this here: <https://jsfiddle.net/0bej5tyn/> html ``` 25 ``` css ``` #timer{ width:150px; height:100px; line-height:100px; border-radius:100px; border:5px solid #444; background:#555; font-size:50px; text-align:center; color:#fff; font-family:arial; } #timer:hover{ border:5px solid #333; } ``` js ``` var timerButton = document.getElementById("timer"); var countStart = timerButton.innerHTML var count = countStart; var timer; timerButton.addEventListener('click',function(){ if (count == countStart){ timer = setInterval(function(){ count--; timerButton.innerHTML = count; if (count == 0){ clearInterval(timer); } },1000); } else{ /* Reset here */ clearInterval(timer); count = countStart; timerButton.innerHTML = count; } }); ``` Upvotes: 0
2018/03/18
535
1,740
<issue_start>username_0: The following example seems to compile with Clang but not with gcc. Which one is right? ``` #include template struct MyType { constexpr MyType () = default; //constexpr MyType () {} constexpr bool is\_int () const { return std::is\_same\_v; } }; constexpr auto foo () { MyType retval; //MyType retval {}; return retval; } int main () { static\_assert (foo ().is\_int ()); } ``` Also, note that un-commenting any of the two commented lines (and removing the respective line above it) makes the program compile with gcc, too. If gcc is right here, why doesn't it compile?<issue_comment>username_1: The [complaint](https://godbolt.org/g/pfdAeP) is that you're using an uninitialized variable in a constexpr function. However - that's not the case, i.e. `retval` is default-initialized. So GCC is wrong, unless the standard has very weird language (which I doubt, but don't know for sure). @StoryTeller suggests this is related to [this bug report](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83921). Upvotes: 3 [selected_answer]<issue_comment>username_2: This was [core issue 253 "Why must empty or fully-initialized `const` objects be initialized?"](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#253). It was resolved by [P0490R0: "Core language changes addressing National Body comments for CD C++17"](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0490r0.html) (scroll down to the "RU 1" heading at the end) just in time for C++17. The change was further applied as a "defect report" against C++14. You'll see implementation variance between "new" compilers that have implemented this C++17 fix (in both 17 and 14 modes) and "old" compilers that have not. Upvotes: 0
2018/03/18
3,198
8,258
<issue_start>username_0: I have been going through [Introduction to Algorithms](https://mitpress.mit.edu/books/introduction-algorithms), and have been trying to implement the `MERGE-SORT` algorithm in C programming language to gain a better understanding of it. The book presents two pseudo-codes: [![<code>MERGE</code>](https://i.stack.imgur.com/FWV9V.png)](https://i.stack.imgur.com/FWV9V.png) and [![enter image description here](https://i.stack.imgur.com/NTuji.png)](https://i.stack.imgur.com/NTuji.png) While I do understand the above procedures, I must be missing something during the implementation. I must be missing something from the pseudo-code but cannot figure it out yet. Any suggestions as to why this is happening would be appreciated. **EDIT: Updated Code and Output** ``` /* C program for Merge Sort */ #include #include void MERGE(int [], int , int , int ); void printArray(int [], int ); void MERGE\_SORT(int [], int , int ); int main(void) { int A[] = { 12, 11, 13, 5, 6, 7, 2, 9 }; int arr\_size = sizeof(A) / sizeof(A[0]); printf("Given array is \n"); printArray(A, arr\_size); MERGE\_SORT(A, 0, arr\_size); //Fixed: Index to start from zero printf("\nSorted array is \n"); printArray(A, arr\_size); return 0; } void MERGE(int A[], int p, int q, int r) { int i = 0; int j = 0; int n1 = q - p + 1; //Computing length of sub-array 1 int n2 = r - q; //Computing length of sub-array 2 int \*L = malloc((n1 + 2) \* sizeof(\*L + 1)); //Creating Left array int \*R = malloc((n2 + 2) \* sizeof(\*R + 1)); //Creating Right array for (int i = 0; i <= n1; i++) { //Fixed: <=, i start from 0 L[i] = A[p + i - 1]; } for (int j = 0; j <= n2; j++) { //Fixed: <=, i start from 0 R[j] = A[q + j]; } L[n1 + 1] = 99; //Placing Sentinel at the end of array R[n2 + 1] = 99; i = 1; j = 1; /\*Prior to the first iteration k = p, so the subarray is empty. Both L[i] and R[j] are the smallest elements of their arrays and have not been copied back to A\*/ for (int k = p; k <= r; k++) { //Fixed: <= if (L[i] <= R[j]) { A[k] = L[i]; i++; } else { //Fixed: Assignment and not condition check for A[k] A[k] = R[j]; j++; } } free(L); free(R); } void MERGE\_SORT(int A[], int p, int r) { //During first iteration p = 1 & r = 8 if (p < r) { int q = (p + r) / 2; MERGE\_SORT(A, p, q); MERGE\_SORT(A, q + 1, r); MERGE(A, p, q, r); } } /\* Function to print an array \*/ void printArray(int Arr[], int size) { int i; for (i = 0; i < size; i++) printf("%d ", Arr[i]); printf("\n"); } ``` [![enter image description here](https://i.stack.imgur.com/1qyFy.png)](https://i.stack.imgur.com/1qyFy.png)<issue_comment>username_1: Looked in the pseudo code and found out that some things have been mistakenly written wrong. 1. You need to be careful with the array index to start from 0 or 1 2. Merge last part in for loop is actually an assignment instead for conditional check. **Edit: Have updated the code to fix for the error `Stack around the variable A was corrupted`** Please find the corrected code here(Lookout for //Fixed for fixes) ``` /* C program for Merge Sort */ #include #include void MERGE(A, p, q, r); void printArray(Arr, size); void MERGE\_SORT(A, p, r); int main(void) { int A[] = { 12, 11, 13, 5, 6, 7, 2, 9 }; int arr\_size = sizeof(A) / sizeof(A[0]); printf("Given array is \n"); printArray(A, arr\_size); MERGE\_SORT(A, 0, arr\_size - 1); //Fixed: Index to start from zero, arr\_size - 1 printf("\nSorted array is \n"); printArray(A, arr\_size); return 0; } void MERGE(int A[], int p, int q, int r) { int i = 0; int j = 0; int n1 = q - p + 1; //Computing length of sub-array 1 int n2 = r - q; //Computing length of sub-array 2 int \*L = malloc((n1+1) \* sizeof(\*L+1)); //Creating Left array int \*R = malloc((n2+1) \* sizeof(\*R+1)); //Creating Right array for (int i = 0; i < n1; i++) { //Fixed: i start from 0 L[i] = A[p + i]; } // int arr\_size = sizeof(A) / sizeof(A[0]); for (int j = 0; j < n2; j++) { //Fixed: j start from 0 R[j] = A[q + j + 1]; } L[n1] = 99; //Placing Sentinel at the end of array R[n2] = 99; i = 0; //Fixed: i and j to start from 0 j = 0; /\*Prior to the first iteration k = p, so the subarray is empty. Both L[i] and R[j] are the smallest elements of their arrays and have not been copied back to A\*/ for (int k = p; k <= r; k++) { //Fixed: <= if (L[i] <= R[j]) { A[k] = L[i]; i++; } else { //Fixed: Assignment and not condition check for A[k] A[k] = R[j]; j++; } } free(L); free(R); } void MERGE\_SORT(int A[], int p, int r) { //During first iteration p = 1 & r = 8 if (p < r) { int q = (p + r) / 2; MERGE\_SORT(A, p, q); MERGE\_SORT(A, q + 1, r); MERGE(A, p, q, r); } } /\* Function to print an array \*/ void printArray(int Arr[], int size) { int i; for (i = 0; i < size; i++) printf("%d ", Arr[i]); printf("\n", size); } ``` Hope it helps. Revert for any doubts. Upvotes: 3 [selected_answer]<issue_comment>username_2: here are some changes i have done to your code ` ``` #include #include void MERGE(int \*A,int p,int q,int r); void printArray(int \*Arr,int size); void MERGE\_SORT(int \*A,int p,int r); int main(void){ int A[] = { 12, 11, 13, 5, 6, 7, 2, 9 }; int arr\_size = sizeof(A) / sizeof(A[0]); printf("Given array is \n"); printArray(A, arr\_size); MERGE\_SORT(A, 0, arr\_size -1); // pass the indices of the array printf("\nSorted array is \n"); printArray(A, arr\_size); return 0; } void MERGE(int A[], int p, int q, int r){ int i = 0; int j = 0; int k; //declair it here int n1 = q - p + 1; //Computing length of sub-array 1 int n2 = r - q; //Computing length of sub-array 2 int \*L = malloc((n1) \* sizeof(\*L+1)); //Creating Left array int \*R = malloc((n2) \* sizeof(\*R+1)); //Creating Right array for (int i = 0; i < n1; i++) { //start coping from zero L[i] = A[p + i]; } for (int j = 0; j < n2; j++) { R[j] = A[q +1 + j]; } // L[n1] = 99; we won't be needing these as to mark the end we already know the size of arrays // R[n2] = 99; // i = 1; // j = 1; /\*Prior to the first iteration k = p, so the subarray is empty. Both L[i] and R[j] are the smallest elements of their arrays and have not been copied back to A\*/ for (k = p; k < r+1 && i < n1 && j ``` first of all you were not passing the right parameters to the function. then the concept of using infinity to indicate is not good as one can want to sort bigger number than that in that case you would have to increase infinity an alternative approach is given above. Mean while i also solved the problem with your code here it was again with the array index were not rightly used check it out now its working:` ``` #include #include void MERGE(A, p, q, r); void printArray(Arr, size); void MERGE\_SORT(A, p, r); int main(void) { int A[] = { 12, 11, 13, 5, 6, 7, 2, 9 }; int arr\_size = sizeof(A) / sizeof(A[0]); printf("Given array is \n"); printArray(A, arr\_size); MERGE\_SORT(A, 1, arr\_size); printf("\nSorted array is \n"); printArray(A, arr\_size); return 0; } void MERGE(int A[], int p, int q, int r) { int i = 0; int j = 0; int n1 = q - p + 1; //Computing length of sub-array 1 int n2 = r - q; //Computing length of sub-array 2 int \*L = malloc((n1+1) \* sizeof(\*L+1)); //Creating Left array int \*R = malloc((n2+1) \* sizeof(\*R+1)); //Creating Right array for (int i = 1; i < n1; i++) { L[i] = A[p + i - 1]; } for (int j = 1; j < n2; j++) { R[j] = A[q + j]; } L[n1] = 99; //Placing Sentinel at the end of array R[n2] = 99; i = 1; j = 1; /\*Prior to the first iteration k = p, so the subarray is empty. Both L[i] and R[j] are the smallest elements of their arrays and have not been copied back to A\*/ for (int k = p; k < r; k++) { if (L[i] <= R[j]) { A[k] = L[i]; i++; } else if (A[k] == L[i]) j++; } free(L); free(R); } void MERGE\_SORT(int A[], int p, int r) { //During first iteration p = 1 & r = 8 if (p < r) { int q = (p + r) / 2; MERGE\_SORT(A, p, q); MERGE\_SORT(A, q + 1, r); MERGE(A, p, q, r); } } /\* Function to print an array \*/ void printArray(int Arr[], int size) { int i; for (i = 0; i < size; i++) printf("%d ", Arr[i]); printf("\n"); } ``` Upvotes: 1
2018/03/18
650
2,464
<issue_start>username_0: I joined two tables and get different columns from both tables to load them into dataTable. I want to order the columns by using dataTable but how can I understand which columns belogns to which tables? I mean, when I click order button on a **last\_name column** from datatable, how can I write `order by table1_.last_name desc` because there are columns from table2 though. So my code looks like this; ``` public Page findByCriteria(String columnName, final String filters, String sort, Pageable pageable) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(UserDTO.class); Root iRoot = cq.from(UserDTO.class); Join bJoin= iRoot.join("user"); cq.multiselect(bJoin.get("id"), bJoin.get("login"), bJoin.get("firstName"), bJoin.get("lastName"), bJoin.get("dayOfBirth"), iRoot.get("district")); ........ if (!columnName.equals("district")) { ..... } ....... if (sort.split(":")[0].equals("district") || columnName.equals("district")) { ....... } ......... } ``` As you see, I've used `!columnName.equals("district")` to distinguish tables from each other but this is not a generic way. I cannot use this method for another tables because they may use different columns so I'll have to change the columnName to differentitate tables again and again. What I'm asking is that, is there a method like `contains` for **iRoot** and **bJoin** to check if **table contains** that **columnName** ?<issue_comment>username_1: In Criteria API you should think in terms of entities and their properties, not in terms of tables and columns. So, assuming you want to order on (for instance) `UserDTO.lastName`, this will be probably something along the lines: ``` cq.orderBy(iRoot.get("lastName")); ``` > > What I'm asking is that, is there a method like contains for iRoot and bJoin to check if table contains that columnName ? > > > `Root` has a method `getModel` which returns an `EntityType` which provides metadata on the entity. You can check for attributes etc. there. Not exactly column names, but close. Upvotes: 1 <issue_comment>username_2: I solved my problem by using **try catch**: ``` try { bJoin.get(sort.split(":")[0]).as(String.class); //Use bJoin table to order }catch(Exception e) { //Use iRoot table to order } ``` By implementing **try catch**, I aimed to make a generic way to distinguish tables from each other. Upvotes: 1 [selected_answer]
2018/03/18
334
1,262
<issue_start>username_0: Is it at all possible to post HTML to an HTML file using jquery's post method. for example: ``` $.post("database.html", "Content") ``` once a button is clicked I want to post to the database file and have this current file load in content from the database file using. ``` $.load("database.html") ``` Does anyone know how I could implement this method properly?<issue_comment>username_1: If I rewrite your question a bit: you want to pass data between two html pages. If you only use static html you cannot do that with javascript only. You have to send the data to a server and then use this data in your second html file. But I think you quite misunderstood what http can or cannot do, I would recommend reading [mozilla explanation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) Upvotes: 1 <issue_comment>username_2: **It is possible to pass HTML content in POST** from one HTML page to another. But in order to use or process received the data at the second HTML page, **you'll need a programming language**. Read the [accepted answer](https://stackoverflow.com/a/1409029/2408342) to question [*How to read the post request parameters using javascript*](https://stackoverflow.com/q/1409013/2408342). Upvotes: 0
2018/03/18
357
1,449
<issue_start>username_0: Debug tab: ``` { "response": "We're sorry, but something went wrong. Please try again.", "expectUserResponse": false, "conversationToken": "", "audioResponse": "" } ``` I create the sample project in Dialogflow and it works, but in the simulator Actions on Google it doesn't!<issue_comment>username_1: Please go to the Actions console and enter the 'Backend services' - it's in the left menu below the 'Simulator'. There should be one card for Cloud Functions. Does this say, that there's an error? If so, you can find out more in the logs of Firebase Functions, which is linked in this card. Upvotes: 0 <issue_comment>username_2: Please read the "Preview the app" section of this page: <https://developers.google.com/actions/dialogflow/first-app?hl=en> To preview your app: Turn on the following permissions on the Activity controls page for your Google account: * Web & App Activity * Device Information * Voice & Audio Activity You need to do this to use the Actions Simulator, which lets you test your actions on the web without a hardware device. Activity control page: <https://myactivity.google.com/activitycontrols> Upvotes: 3 <issue_comment>username_3: Check the settings and permissions, if you are a developer, owner etc. of the application. I got this fixed by changing the settings...need to dig a little more to understand the exact reason. Will do an update if I understand more Upvotes: -1
2018/03/18
468
1,806
<issue_start>username_0: I have a little task that I am struggling with. So basically we have to read columns from a TSV file and export all possible subsets of the columns to a CSV. Before exporting we have to sanitize the code (remove special chars except .,spaces). I came across this subset code but I am not sure how to utilize it with my requirement: ``` import pandas as pd from itertools import chain, combinations def all_subsets(ss): return chain(*map(lambda x: combinations(ss,x), range(0, len(ss) + 1))) subsets = all_subsets([1, 2, 3, 4]) for subset in subsets: print(subset) ``` [Pictorial Explanation](https://i.stack.imgur.com/MGjxk.png)<issue_comment>username_1: Please go to the Actions console and enter the 'Backend services' - it's in the left menu below the 'Simulator'. There should be one card for Cloud Functions. Does this say, that there's an error? If so, you can find out more in the logs of Firebase Functions, which is linked in this card. Upvotes: 0 <issue_comment>username_2: Please read the "Preview the app" section of this page: <https://developers.google.com/actions/dialogflow/first-app?hl=en> To preview your app: Turn on the following permissions on the Activity controls page for your Google account: * Web & App Activity * Device Information * Voice & Audio Activity You need to do this to use the Actions Simulator, which lets you test your actions on the web without a hardware device. Activity control page: <https://myactivity.google.com/activitycontrols> Upvotes: 3 <issue_comment>username_3: Check the settings and permissions, if you are a developer, owner etc. of the application. I got this fixed by changing the settings...need to dig a little more to understand the exact reason. Will do an update if I understand more Upvotes: -1
2018/03/18
759
1,804
<issue_start>username_0: I'm constructing a `data.table` from two (or more) input vectors with different lengths: ``` x <- c(1,2,3,4) y <- c(8,9) dt <- data.table(x = x, y = y) ``` And need the shorter vector(s) to be filled with `NA` rather than recycling their values, resulting in a `data.table` like this: ``` x y 1: 1 8 2: 2 9 3: 3 NA 4: 4 NA ``` Is there a way to achieve this without explicitly filling the shorter vector(s) with `NA` before passing them to the `data.table()` constructor? Thanks!<issue_comment>username_1: An option is `cbind.fill` from `rowr` ``` library(rowr) setNames(cbind.fill(x, y, fill = NA), c("x", "y")) ``` --- Or place the `vector`s in a `list` and then pad `NA` at the end based on the maximum length of the `list` elements ``` library(data.table) lst <- list(x = x, y = y) as.data.table(lapply(lst, `length<-`, max(lengths(lst)))) # x y #1: 1 8 #2: 2 9 #3: 3 NA #4: 4 NA ``` Upvotes: 2 <issue_comment>username_2: One can use *out of range* indices: ``` library("data.table") x <- c(1,2,3,4) y <- c(8,9) n <- max(length(x), length(y)) dt <- data.table(x = x[1:n], y = y[1:n]) # > dt # x y # 1: 1 8 # 2: 2 9 # 3: 3 NA # 4: 4 NA ``` Or you can extend `y` by doing (as @Roland recommended in the comment): ``` length(y) <- length(x) <- max(length(x), length(y)) dt <- data.table(x, y) ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: The "out of range indices" answer provided by [username_2](https://stackoverflow.com/users/5414452/username_2) can be extended cleanly to in-place assignment using `.N`: ``` x <- c(1,2,3,4) y <- c(8,9) n <- max(length(x), length(y)) dt <- data.table(x = x[1:n], y = y[1:n]) z <- c(6,7) dt[, z := z[1:.N]] # x y z # 1: 1 8 6 # 2: 2 9 7 # 3: 3 NA NA # 4: 4 NA NA ``` Upvotes: 2
2018/03/18
819
2,755
<issue_start>username_0: I have the first pandas.DataFrame ``` first_key second_key 0 0 1 1 0 1 2 0 2 3 0 3 4 0 3 ``` and also the second pandas.DataFrame ``` key status 0 1 'good' 1 2 'bad' 2 3 'good' ``` And I want to get the following pandas.DataFrame ``` first_key second_key status 0 0 1 'good' 1 0 1 'good' 2 0 2 'bad' 3 0 3 'good' 4 0 3 'good' ``` How to do this?<issue_comment>username_1: Use [`map`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html) by Series created from second `DataFrame`: ``` df['status'] = df['second_key'].map(df1.set_index('key')['status']) print (df) first_key second_key status 0 0 1 'good' 1 0 1 'good' 2 0 2 'bad' 3 0 3 'good' 4 0 3 'good' ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: you can also use `merge()` method: ``` In [75]: d1.merge(d2.rename(columns={'key':'second_key'})) Out[75]: first_key second_key status 0 0 1 'good' 1 0 1 'good' 2 0 2 'bad' 3 0 3 'good' 4 0 3 'good' ``` `.map()` method shown in @username_1's answer is more preferrable (and more efficient) if you want to add a single column. Use `.merge()` method if you need to add multiple columns. Upvotes: 2 <issue_comment>username_3: ### `pd.DataFrame.join` ``` df1.join(df2.set_index('key'), on='second_key') first_key second_key status 0 0 1 'good' 1 0 1 'good' 2 0 2 'bad' 3 0 3 'good' 4 0 3 'good' ``` Upvotes: 2 <issue_comment>username_4: Here is another example using the [`merge`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html) function (rather than the `merge` method). ``` In [16]: merged = pd.merge(df1, df2, how="inner", left_on="second_key", right_on="key") In [17]: merged.drop("key", axis=1, inplace=True) In [18]: merged Out[18]: first_key second_key status 0 0 1 good 1 0 1 good 2 0 2 bad 3 0 3 good 4 0 3 good In [19]: ``` IMHO, using the function makes the transformation slightly more explicit. But this is obviously a matter or taste... Upvotes: 0
2018/03/18
639
2,508
<issue_start>username_0: I'm working on Android project that related to GPS I still new to android so I don't know a lot about it. My project is an app where it calculates the distance between user location and a specified other location so if the distance is less than (X) say 1KM the app will send a notification to the user.[[I know how to calculate the distance between two locations]]. My problem is: how can I do this even if the user didn't open the app (I mean if there's anyway that I can make the app calculates the distance in the background while the app is closed).so I want the GPS feature works in the background. Thanks in Advance.<issue_comment>username_1: User `services`. They are simple to use and all you need. Here is [the documentation](http://developer.android.com/guide/components/services.html). A **service** is another component of an android application (like activity). You need to define the service in manifest. After that you could start the device using `startService` (intent). If you need to take some info (communicate with one activity) you can use `bindService` instead of `startService`. (Also need to implement `onBind`). Another solution is to sendData using a broadcast receiver. Or you can simple set a notification in service and use it. Upvotes: -1 <issue_comment>username_2: You can use a service for background process. For your question for getting location, you should try these links: [Best way to get user GPS location in background in Android](https://stackoverflow.com/questions/28535703/best-way-to-get-user-gps-location-in-background-in-android) [Get GPS location via a service in Android](https://stackoverflow.com/questions/8828639/get-gps-location-via-a-service-in-android) Upvotes: 1 [selected_answer]<issue_comment>username_3: To get the app to run in the background, you'll need to learn about a service. Service is a service that causes applications to run in the background such as gps, notification and more .. link: <https://developer.android.com/reference/android/app/Service.html> Upvotes: -1 <issue_comment>username_4: My solution for this problem was simply :- you can use **Services** for working in the background (when the Activity isn't showing) check this : -[Get GPS location via a service in Android](https://stackoverflow.com/questions/8828639/get-gps-location-via-a-service-in-android) \*\*if you want this service to run for ever, even if the app is closed/killed you can use broadcast receivers \*\* Upvotes: 0
2018/03/18
666
2,408
<issue_start>username_0: I use the dynamic route in the detail component: ``` dataCenterDetail: '/data-center/detail/:id' ``` in the component there is a props with `id`: ``` export default{ props: { id:{ type: Number, required: true } }, ``` when I push to the detail route: in the browser: `http://localhost:8080/data-center/detail/1` I will get the error: ``` [Vue warn]: Missing required prop: "id" found in ---> at src/views/数据中心/wx-number-detail.vue at src/views/index.vue at src/app.vue ```<issue_comment>username_1: User `services`. They are simple to use and all you need. Here is [the documentation](http://developer.android.com/guide/components/services.html). A **service** is another component of an android application (like activity). You need to define the service in manifest. After that you could start the device using `startService` (intent). If you need to take some info (communicate with one activity) you can use `bindService` instead of `startService`. (Also need to implement `onBind`). Another solution is to sendData using a broadcast receiver. Or you can simple set a notification in service and use it. Upvotes: -1 <issue_comment>username_2: You can use a service for background process. For your question for getting location, you should try these links: [Best way to get user GPS location in background in Android](https://stackoverflow.com/questions/28535703/best-way-to-get-user-gps-location-in-background-in-android) [Get GPS location via a service in Android](https://stackoverflow.com/questions/8828639/get-gps-location-via-a-service-in-android) Upvotes: 1 [selected_answer]<issue_comment>username_3: To get the app to run in the background, you'll need to learn about a service. Service is a service that causes applications to run in the background such as gps, notification and more .. link: <https://developer.android.com/reference/android/app/Service.html> Upvotes: -1 <issue_comment>username_4: My solution for this problem was simply :- you can use **Services** for working in the background (when the Activity isn't showing) check this : -[Get GPS location via a service in Android](https://stackoverflow.com/questions/8828639/get-gps-location-via-a-service-in-android) \*\*if you want this service to run for ever, even if the app is closed/killed you can use broadcast receivers \*\* Upvotes: 0
2018/03/18
623
2,326
<issue_start>username_0: I want to change a icon for an element on success (Ajax), here is how my icons looks: ``` $.ajax({ url: '@Url.Action("getClass", "app")', type: "GET", data: { id: ClassID }, success: function (data) { // How to get element above i change it's class } ); ``` Acctually I'm wondering what is proper way of getting this element which contains `class = "fa fa-check"`.. I tried few things but It does not work :( Thanks guys! Cheers!<issue_comment>username_1: User `services`. They are simple to use and all you need. Here is [the documentation](http://developer.android.com/guide/components/services.html). A **service** is another component of an android application (like activity). You need to define the service in manifest. After that you could start the device using `startService` (intent). If you need to take some info (communicate with one activity) you can use `bindService` instead of `startService`. (Also need to implement `onBind`). Another solution is to sendData using a broadcast receiver. Or you can simple set a notification in service and use it. Upvotes: -1 <issue_comment>username_2: You can use a service for background process. For your question for getting location, you should try these links: [Best way to get user GPS location in background in Android](https://stackoverflow.com/questions/28535703/best-way-to-get-user-gps-location-in-background-in-android) [Get GPS location via a service in Android](https://stackoverflow.com/questions/8828639/get-gps-location-via-a-service-in-android) Upvotes: 1 [selected_answer]<issue_comment>username_3: To get the app to run in the background, you'll need to learn about a service. Service is a service that causes applications to run in the background such as gps, notification and more .. link: <https://developer.android.com/reference/android/app/Service.html> Upvotes: -1 <issue_comment>username_4: My solution for this problem was simply :- you can use **Services** for working in the background (when the Activity isn't showing) check this : -[Get GPS location via a service in Android](https://stackoverflow.com/questions/8828639/get-gps-location-via-a-service-in-android) \*\*if you want this service to run for ever, even if the app is closed/killed you can use broadcast receivers \*\* Upvotes: 0
2018/03/18
617
2,478
<issue_start>username_0: I am building a Spring-boot application where I am using Spring data jpa feature. Please find below my dao layer code ``` package com.adv.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CustomerDao extends JpaRepository { } ``` I am using a DaoProvider class as follows: ``` package com.adv.dao; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class DaoProvider implements Serializable { private static final long serialVersionUID = 1L; @Autowired private CustomerDao customerDao; public CustomerDao getCustomerDao() { return customerDao; } } ``` My spring boot main class is defined as follows: ``` @SpringBootApplication @ComponentScan(basePackages="com.adv") public class AdvMain extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(AdvMain.class); } public static void main(String[] args) { SpringApplication.run(AdvMain.class, args); } } ``` Now during runtime I am getting following exception: ``` Field customerDao in com.adv.dao.DaoProvider required a bean of type 'com.adv.dao.CustomerDao' that could not be found. ``` I guess that `@Repository` annotation on interface `CustomerDao` is not working. But I am unable to figure out the issue.Can anyone figure out the problem?<issue_comment>username_1: Try to add `@EnableJpaRepositories("com.adv.dao")` on `AdvMain` as suggested by @hang321 on [Can't Autowire @Repository annotated interface in Spring Boot Ask](https://stackoverflow.com/questions/29221645/cant-autowire-repository-annotated-interface-in-spring-boot) Upvotes: 4 [selected_answer]<issue_comment>username_2: Just remove the `@ComponentScan` annotation altogether.The `@SpringBootApplication` annotation already includes the component scan as specified [here](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html). Upvotes: 0 <issue_comment>username_3: Remove the annotation @Repository from the dao interface. That annotation must be put only on implented classes. Be careful also to implement both the empty constructor than the all args constructor of the Customer class. Upvotes: 1
2018/03/18
410
1,422
<issue_start>username_0: Assume I have such Dockerfile: ``` FROM ubuntu:16.04 EXPOSE 5000 CMD ["some", "app"] ``` And such docker-compose.yml: ``` version: '2.3' services: app: build: context: . exposes: - 6000 ``` After I do docker-compose up -d docker ps outputs: ``` CONTAINER ID NAMES STATUS CREATED PORTS 3315ec1be1b3 app Up 41 hours 41 hours ago 5000/tcp, 6000/tcp ``` Is it possible to unexpose port 5000 and leave only 6000?<issue_comment>username_1: Try to add `@EnableJpaRepositories("com.adv.dao")` on `AdvMain` as suggested by @hang321 on [Can't Autowire @Repository annotated interface in Spring Boot Ask](https://stackoverflow.com/questions/29221645/cant-autowire-repository-annotated-interface-in-spring-boot) Upvotes: 4 [selected_answer]<issue_comment>username_2: Just remove the `@ComponentScan` annotation altogether.The `@SpringBootApplication` annotation already includes the component scan as specified [here](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html). Upvotes: 0 <issue_comment>username_3: Remove the annotation @Repository from the dao interface. That annotation must be put only on implented classes. Be careful also to implement both the empty constructor than the all args constructor of the Customer class. Upvotes: 1
2018/03/18
553
1,578
<issue_start>username_0: I have configuration: * Open Server 5.2.8 (WAMP) * PhpStorm 2017.3.4 * Yii 2.0.14 basic I added to the `%PATH%` path to PHP and to the Codeception folder: [![Path to PHP](https://i.stack.imgur.com/ug2jo.png)](https://i.stack.imgur.com/ug2jo.png) [![Path to Codeception](https://i.stack.imgur.com/PcfN8.png)](https://i.stack.imgur.com/PcfN8.png) In the PhpStorm terminal I launched the `codecept run` command and everything looks good. But the Windows terminal does not maintain colors therefore I wanted to launch tests through PhpStorm. [![PhpStorm Terminal](https://i.stack.imgur.com/qMbsS.png)](https://i.stack.imgur.com/qMbsS.png) I made such settings for PHPUnit and Codeception (from Yii2\vendor): [![PHPUnit Settings](https://i.stack.imgur.com/pt4C3.png)](https://i.stack.imgur.com/pt4C3.png) [![Codeceptiont Settings](https://i.stack.imgur.com/FTyFd.png)](https://i.stack.imgur.com/FTyFd.png) But for some reason I receive such error: [![Error](https://i.stack.imgur.com/4PLLt.png)](https://i.stack.imgur.com/4PLLt.png)<issue_comment>username_1: You are missing the dependency for `phpunit`, add the following to your `composer.json` ``` "require-dev": { "phpunit/phpunit": "3.7.*" }, ``` and run ``` composer update ``` Upvotes: 2 <issue_comment>username_2: Answers [here](https://stackoverflow.com/questions/49059726/phpstorm-v2017-3-4-codeception-v2-4-0-incompatibility) and [here](https://youtrack.jetbrains.com/issue/WI-40950). Thanks to @panosru. Just download new version PHPStorm 2017.3.6. Upvotes: 2 [selected_answer]
2018/03/18
640
2,023
<issue_start>username_0: I have a bytes variable in Python that I want to pass to a C++ function, and then want to return the bytes later on, also via a C++ function. The C++ code is wrapped in Swig. Does anyone know how I can do this or have a basic example? I have tried using void\* as the type in C++, but I can't get it to work. C++ example.hpp code: ``` class MyTestClass { public: void set_data(void* data); void* get_data(); private: void* data; }; ``` C++ example.cpp code: ``` void MyTestClass::set_data(void* data) { this->data = data; } void* MyTestClass::get_data() { return data; } ``` Swig interface file: ``` /* File : example.i */ %module example %include %{ #include "example.hpp" %} %include "example.hpp" ``` Test Python code: ``` from example import MyTestClass test_class = MyTestClass() data1 = b"test" test_class.set_data(data1) data2 = test_class.get_data() print(data2) ``` Compilation: ``` swig -c++ -python -modern -py3 example.i export CC=g++ python setup.py build_ext --inplace ``` Error: ``` Traceback (most recent call last): File "./test.py", line 6, in test\_class.set\_data(data\_1) File "example.py", line 119, in set\_data return \_example.MyTestClass\_set\_data(self, data) TypeError: in method 'MyTestClass\_set\_data', argument 2 of type 'void \*' ```<issue_comment>username_1: You should use char\* instead of void\*. In addition, you should not use the ``` %include ``` in the example.i file, as that has the typemap definition converting char \* to a string. Minor issue: you example.cpp shall #include "example.hpp" to have a definition for MyTestCLass. Upvotes: 1 <issue_comment>username_2: I managed to get it working with a cstring.i template: %cstring\_output\_allocate\_size(char\*\* data\_out, int\* maxdata, NULL) When I set the data I also set the size, which I use to set maxdata. The third parameter is NULL and not free because the data is meant to be a reference only. Upvotes: 1 [selected_answer]
2018/03/18
1,494
4,409
<issue_start>username_0: I am trying to start up a Spring Boot application but it is failing to start up. This is my stack trace: ``` 11:27:59.772 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : [] 11:27:59.775 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring- boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/] 11:27:59.776 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Users/Bobi/Documents/workspace-sts- 3.9.2.RELEASE/springproject/target/classes/] . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.0.M7) 2018-03-18 11:28:00.308 INFO 5048 --- [ restartedMain] o.s.boot.SpringApplication : Starting SpringApplication v2.0.0.M7 on DESKTOP-MFS6ORP with PID 5048 (C:\Users\Bobi\.m2\repository\org\springframework\boot\spring- boot\2.0.0.M7\spring-boot-2.0.0.M7.jar started by Bobi in C:\Users\Bobi\Documents\workspace-sts-3.9.2.RELEASE\springproject) 2018-03-18 11:28:00.313 INFO 5048 --- [ restartedMain] o.s.boot.SpringApplication : No active profile set, falling back to default profiles: default 2018-03-18 11:28:01.410 ERROR 5048 --- [ restartedMain] o.s.boot.SpringApplication : Application startup failed java.lang.IllegalArgumentException: Sources must not be empty at org.springframework.util.Assert.notEmpty(Assert.java:450) ~[spring- core-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:381) [spring-boot-2.0.0.M7.jar:2.0.0.M7] at org.springframework.boot.SpringApplication.run(SpringApplication.java:325) [spring-boot-2.0.0.M7.jar:2.0.0.M7] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1245) [spring-boot-2.0.0.M7.jar:2.0.0.M7] at org.springframework.boot.SpringApplication.main(SpringApplication.java:1261) [spring-boot-2.0.0.M7.jar:2.0.0.M7] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher .java:49) [spring-boot-devtools-2.0.0.M7.jar:2.0.0.M7] ``` This is my main class: ``` package com.example.a; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main( String[] args ) { SpringApplication.run(App.class, args); } } ``` This is my pom.xml ``` 4.0.0 com.example a 0.0.1-SNAPSHOT jar a http://maven.apache.org UTF-8 org.springframework.boot spring-boot-starter-parent 2.0.0.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-devtools true org.springframework.boot spring-boot-maven-plugin ``` I am using Spring Tool Suite and I created the project by File->New->Maven Project. I added some dependencies and added the `SpringApplication.run(App.class, args);` row in the main class and that's it. I tried other similar suggestions on StackOverflow but nothing worked for me. What do I have to do or change in order to get the application to start up correctly?<issue_comment>username_1: I solved the problem. I don't know how I was running the project before, but I just went *Right Click->Run As->Spring Boot App* and it worked properly. Upvotes: 1 <issue_comment>username_2: In Eclipse, when I was running it as a spring boot app, it showed the error, but when I ran it as Java Application from Right-click-> run as -> Java Application, it worked completely fine. Upvotes: 0
2018/03/18
602
2,162
<issue_start>username_0: I've gone over a ton of documentation on this topic and still aren't sure if the 25 custom params/property limit in Firebase is per app or per event name? Say I have 50 different events with 5 unique property names each, that would be a total of 250 unique property names. Is such a thing supported or do I start with a limit of 25 across all events? I have Firebase hooked up to Bigquery so I'm less concerned about the limitations in the Firebase reporting admin. Thanks.<issue_comment>username_1: The limits are [documented here](https://support.google.com/firebase/answer/7397304?hl=en). > > Google Analytics for Firebase lets you specify up to 25 custom > parameters per event (Android or iOS). > > > You can also identify up to 50 of those custom event parameters per > [project](https://support.google.com/firebase/answer/7397304?hl=en) (40 numeric and 10 textual) to include in reporting by registering > those parameters with their corresponding events. Once you register > your custom parameters, Google Analytics for Firebase displays a > corresponding card showing the data in each related event-detail > report. > > > The [javadoc for logEvent](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.html#logEvent(java.lang.String,%20android.os.Bundle)) gets more specific: > > The event can have up to 25 parameters. Events with the same name must > have the same parameters. Up to 500 event names are supported. Using > predefined FirebaseAnalytics.Event and/or FirebaseAnalytics.Param is > recommended for optimal reporting. > > > Upvotes: 1 <issue_comment>username_2: **Limitations for each Firebase project:** Limit for 25 params is per [logEvent](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics#logEvent(java.lang.String,%20android.os.Bundle)) call. Limit for 500 events is per app instance. Limit for 50 custom parameter (40 numeric and 10 texts) is the global limit in Google Analytics for Firebase dashboard. No limit for custom parameters in Big Query. This is as of 03/20/2018. Upvotes: 3
2018/03/18
918
3,472
<issue_start>username_0: So I have the following user registration form which I want to style. My forms.py look something like this. : ``` from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['username','email','password'] ``` Now this is my views.py: ``` class UserFormView(View): form_class =UserForm template_name = 'visit/registration/register.html' def get(self,request): form = self.form_class(None) return render(request,self.template_name,{'form':form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user =form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(<PASSWORD>) user.save() user = authenticate(username=username, password=<PASSWORD>) if user is not None: if user.is_active: login(request,user) return redirect('visit:index') return render(request, 'visit/registration/register.html', {'form': form}) ``` Now What I am getting a bit confused in HTML, since there is only one line which passes all these fields in the page together. So how M I supposed to style these fields separately. ``` {% extends 'visit/base.html'%} {%block content%} {% load staticfiles %} {% csrf\_token %} {{ form.as\_p }} Submit {%endblock%} ```<issue_comment>username_1: You have multiple options, each one with its pros and cons: **1. Add custom css classes within `forms.py`** To use the simplicity of `{{ form.as_p }}` approach you could manually add classes to all your forms fields, e.g.: ``` class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput( attrs={'class' : 'your-custom-class'}) ) ``` Note that it could be a challenge to render the form to be perfectly aligned with Bootstrap's style. **2. Render the form manually** You could write your form by hand within your template, e.g.: ``` {% trans 'Password' %} {% if form.password.help\_text %} {{ form.password.help\_text }} {% endif %} {% for err in form.password.errors %} {{ err }} {% endfor %} ``` More info on rendering form fields manually can be found [here](https://docs.djangoproject.com/en/2.0/topics/forms/#rendering-fields-manually). The above snippet will use most of the functionality existing in the default django [form renders methods](https://docs.djangoproject.com/en/2.0/topics/forms/#working-with-form-templates), but on the other hand forces you to write a lot of boilerplate code which is harden to maintain in the long run. **3. Use 3rd party app as a mix of the first two options** You could use custom app to handle the rendering of the forms, a good example would be [django-crispy-forms](http://django-crispy-forms.readthedocs.io/en/latest/). Upvotes: 1 [selected_answer]<issue_comment>username_2: You can simply use [django-bootstrap](https://github.com/dyve/django-bootstrap3) This will automatically render the bootstrap form for you. ``` {% extends 'visit/base.html'%} {% load bootstrap3 %} {%block content%} {% load staticfiles %} {% csrf\_token %} {% bootstrap\_form form %} Submit {%endblock%} ``` Upvotes: 1
2018/03/18
792
3,037
<issue_start>username_0: This is my first development using html/javascript and since my previous career was programming aircraft, it all seems very strange! So ... I picked up a Raspberry Pi and decided to develop server/client software so I can control my garden lighting and water features from my mobile using my wifi system. I can now turn on and off all my lights and pumps in the garden from any mobile. I am now refining the software and this simple item has me stumped. When the user switches on a water feature, I want the server to switch off the water feature when the minutes set by the user has expired. The html has: ``` Water Feature Zen Garden ``` my Java Script on the html page has:<issue_comment>username_1: When you access `this.value` inside of the listener, `this` refers to: ``` ``` And that has no value. You might wanna get the timer: ``` var timer = document.getElementById("WaterFeatureZenGardenTimer"); ``` And then take the timers value: ``` socket.emit("timer", timer.value); ``` --- Now on the serverside you could define a global variable that holds your timer: ``` let timer; ``` Then when you receive the clients timing request, you could kill the ongoing timeout and set a new one: ``` if(timer) clearTimeout(timer); timer = setTimeout(function(){ onWFZG.writeSync("0"); }, +userValue * 60 * 1000); ``` Upvotes: 2 <issue_comment>username_2: In your window.addEventListener you need to get input value like ``` var timerValue = document.getElementById("waterFeatureZenGardenTimer").value; ``` and then pass this timerValue as ``` socket.emit("WaterFeatureZenGardenTimer", timerValue); ``` Upvotes: 0 <issue_comment>username_3: Cool project! A few things. Since you are just starting to learn JS, it might be better to immediately hop on the ES6 boat - it is the newest iteration in Javascript and it introduces some cool stuff such as arrow functions, constants, OO, and so on. In addition, if you want to run code when DOM is loaded, use `document.addEventListener("DOMContentLoaded")`. Finally, in JS it is common to use lowerCamelCase names for functions and variables. On to your code, it seems you want the value of the timer - and not of the checkbox, which `this` refers to, so add a variable for that as well. I'm not sure why you are parsing the checkbox checked as a Number(), though, but I left it there because I'm not sure why you want that. ``` const socket = io(); document.addEventListener("DOMContentLoaded", () => { const gateStatus = document.querySelector("#gate"), wfzg = document.querySelector("#WaterFeatureZenGarden"), wfzgt = document.querySelector("#WaterFeatureZenGardenTimer"), wlzg = document.querySelector("#WallLightsZenGarden"), llzg = document.querySelector("#LanternLightsZenGarden"); getWFZG.addEventListener("change", function() { socket.emit("WaterFeatureZenGarden", Number(this.checked)); socket.emit("WaterFeatureZenGardenTimer", wfzgt.value); }); }); ``` Upvotes: 0
2018/03/18
773
1,823
<issue_start>username_0: I have a DataFrame, `df`, in pandas with series `df.A` and `df.B` and am trying to create a third series, `df.C` that is dependent on A and B as well as the previous result. That is: `C[0]=A[0]` `C[n]=A[n] + B[n]*C[n-1]` what is the most efficient way of doing this? Ideally, I wouldn't have to fall back to a `for` loop. --- **Edit** This is the desired output for C given A and B. Now just need to figure out how... ``` import pandas as pd a = [ 2, 3,-8,-2, 1] b = [ 1, 1, 4, 2, 1] c = [ 2, 5,12,22,23] df = pd.DataFrame({'A': a, 'B': b, 'C': c}) df ```<issue_comment>username_1: try this: `C[0]=A[0] C=[A[i]+B[i]*C[i-1] for i in range(1,len(A))]` very much quicker than a loop. Upvotes: -1 <issue_comment>username_2: You can vectorize this with obnoxious cumulative products and zipping together of other vectors. But it won't end up saving you time. As a matter of fact, it will likely be numerically unstable. Instead, you can use `numba` to speed up your loop. ``` from numba import njit import numpy as np import pandas as pd @njit def dynamic_alpha(a, b): c = a.copy() for i in range(1, len(a)): c[i] = a[i] + b[i] * c[i - 1] return c df.assign(C=dynamic_alpha(df.A.values, df.B.values)) A B C 0 2 1 2 1 3 1 5 2 -8 4 12 3 -2 2 22 4 1 1 23 ``` --- For this simple calculation, this will be about as fast as a simple ``` df.assign(C=np.arange(len(df)) ** 2 + 2) ``` --- ``` df = pd.concat([df] * 10000) %timeit df.assign(C=dynamic_alpha(df.A.values, df.B.values)) %timeit df.assign(C=np.arange(len(df)) ** 2 + 2) ``` --- > > > ``` > 337 µs ± 5.87 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) > 333 µs ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) > > ``` > > Upvotes: 4 [selected_answer]
2018/03/18
711
1,730
<issue_start>username_0: i want to put comma's in numbers The output is this which is encoded in json array ``` [{"total2":"7619627.0000"}] ``` I want to change the number in this format ``` [{"total2":"7,619,627"}] ``` heres the php code ``` $sql2 = "SELECT SUM(NettoPrice) AS total2 FROM Sales WHERE OrderType = 8"; $result2 = $conn->query($sql2); // output data of each row while($row[] = $result2->fetch_assoc()) { $json = json_encode($row); } echo $json; $conn->close(); ?> ```<issue_comment>username_1: try this: `C[0]=A[0] C=[A[i]+B[i]*C[i-1] for i in range(1,len(A))]` very much quicker than a loop. Upvotes: -1 <issue_comment>username_2: You can vectorize this with obnoxious cumulative products and zipping together of other vectors. But it won't end up saving you time. As a matter of fact, it will likely be numerically unstable. Instead, you can use `numba` to speed up your loop. ``` from numba import njit import numpy as np import pandas as pd @njit def dynamic_alpha(a, b): c = a.copy() for i in range(1, len(a)): c[i] = a[i] + b[i] * c[i - 1] return c df.assign(C=dynamic_alpha(df.A.values, df.B.values)) A B C 0 2 1 2 1 3 1 5 2 -8 4 12 3 -2 2 22 4 1 1 23 ``` --- For this simple calculation, this will be about as fast as a simple ``` df.assign(C=np.arange(len(df)) ** 2 + 2) ``` --- ``` df = pd.concat([df] * 10000) %timeit df.assign(C=dynamic_alpha(df.A.values, df.B.values)) %timeit df.assign(C=np.arange(len(df)) ** 2 + 2) ``` --- > > > ``` > 337 µs ± 5.87 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) > 333 µs ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) > > ``` > > Upvotes: 4 [selected_answer]
2018/03/18
969
2,783
<issue_start>username_0: In section 9.2 of the book *The C++ Programming Language*, <NAME> wrote: > > Note that a variable defined without an initializer in the global or a namespace scope is initialized by default. This is not the case for local variables or objects created on the free store. > > > But the following program prints a value of 0: ``` #include using namespace std; int main() { int x; cout << x << endl; return 0; } ``` Shouldn't it be returning some kind of error? I use `g++` to compile.<issue_comment>username_1: **`x` is uninitialized, so your snippet actually has an [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior).** --- > > Shouldn't it be returning some kind of error? > > > **`g++` doesn't warn of uninitialized values by default.** You need the `-Wuninitialized` option if you want your compiler to show a warning: ``` g++ -Wuninitialized your_file.c ``` You should probably use the `-Wall` option instead to enable this warning alongside lots of other useful warnings. More information on warning options [**here**](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html) Upvotes: 3 <issue_comment>username_2: > > But the following program prints a value of 0 on my terminal. > > > It has undefined behaviour because the `cout` line tries to read from an uninitialised `int`. Any output you see, and in fact any behaviour at all, is not guaranteed. > > Shouldn't it be returning some kind of error? > > > No, that's not how undefined behaviour works. You may or may not see an error. Upvotes: 4 [selected_answer]<issue_comment>username_3: > > Shouldn't it be returning some kind of error? > > > No, it should not, but this error is detectable by [**Valgrind**](http://valgrind.org/): ``` $ valgrind --track-origins=yes ./a.out ==4950== Memcheck, a memory error detector ==4950== Copyright (C) 2002-2017, and GNU GPL'd, by <NAME> et al. ==4950== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info ==4950== Command: ./a.out ==4950== ==4950== Conditional jump or move depends on uninitialised value(s) ==4950== at 0x4F4444A: std::ostreambuf_iterator > std::num\_put > >::\_M\_insert\_int(std::ostreambuf\_iterator >, std::ios\_base&, char, long) const (locale\_facets.tcc:874) ==4950== by 0x4F504C4: put (locale\_facets.h:2371) ==4950== by 0x4F504C4: std::ostream& std::ostream::\_M\_insert(long) (ostream.tcc:73) ==4950== by 0x40076D: main (t.cpp:5) ==4950== Uninitialised value was created by a stack allocation ==4950== at 0x400757: main (t.cpp:3) ==4950== ``` This part of Valgrind output clearly states that: ``` ==4950== Uninitialised value was created by a stack allocation ==4950== at 0x400757: main (t.cpp:3) ==4950== ``` Upvotes: 2
2018/03/18
1,048
3,225
<issue_start>username_0: I have a page with absolutely no interface at all. It is literally just a string of text (it grabs text every X seconds that could be of various lengths in terms of characters and words.) I need this text to fill exactly 100% of the browser window height and width. Basically the window would be just this string (using whatever Google Font I need) and nothing else (I suppose it could have a bit of a margin but not much) The text cannot spill over length-wise or height-wise to where scrolling is needed, as there is not user interface to scroll (this is being displayed on a monitor with no keyboard or mouse)... sort of like a sign, but digital. I have tried everything I know, I am not a UI person, I know very generally how to make a page responsive. I also can use a lot of JQuery if needed. No Angular, etc. (This will be on a desktop browser, but I assume it would work on mobile too. Again, 100% height and width and no more or no less)<issue_comment>username_1: **`x` is uninitialized, so your snippet actually has an [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior).** --- > > Shouldn't it be returning some kind of error? > > > **`g++` doesn't warn of uninitialized values by default.** You need the `-Wuninitialized` option if you want your compiler to show a warning: ``` g++ -Wuninitialized your_file.c ``` You should probably use the `-Wall` option instead to enable this warning alongside lots of other useful warnings. More information on warning options [**here**](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html) Upvotes: 3 <issue_comment>username_2: > > But the following program prints a value of 0 on my terminal. > > > It has undefined behaviour because the `cout` line tries to read from an uninitialised `int`. Any output you see, and in fact any behaviour at all, is not guaranteed. > > Shouldn't it be returning some kind of error? > > > No, that's not how undefined behaviour works. You may or may not see an error. Upvotes: 4 [selected_answer]<issue_comment>username_3: > > Shouldn't it be returning some kind of error? > > > No, it should not, but this error is detectable by [**Valgrind**](http://valgrind.org/): ``` $ valgrind --track-origins=yes ./a.out ==4950== Memcheck, a memory error detector ==4950== Copyright (C) 2002-2017, and GNU GPL'd, by <NAME> et al. ==4950== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info ==4950== Command: ./a.out ==4950== ==4950== Conditional jump or move depends on uninitialised value(s) ==4950== at 0x4F4444A: std::ostreambuf_iterator > std::num\_put > >::\_M\_insert\_int(std::ostreambuf\_iterator >, std::ios\_base&, char, long) const (locale\_facets.tcc:874) ==4950== by 0x4F504C4: put (locale\_facets.h:2371) ==4950== by 0x4F504C4: std::ostream& std::ostream::\_M\_insert(long) (ostream.tcc:73) ==4950== by 0x40076D: main (t.cpp:5) ==4950== Uninitialised value was created by a stack allocation ==4950== at 0x400757: main (t.cpp:3) ==4950== ``` This part of Valgrind output clearly states that: ``` ==4950== Uninitialised value was created by a stack allocation ==4950== at 0x400757: main (t.cpp:3) ==4950== ``` Upvotes: 2
2018/03/18
929
2,670
<issue_start>username_0: I interchanged the positions of map and filter. Does it make any difference related to number of iterations done by code ? ``` List Aname3 =names.stream() .map(name->name.toUpperCase()) .filter(name->name.startsWith("A")) .collect(Collectors.toList()); List Aname4 =names.stream() .filter(name->!name.startsWith("A")) .map(name->name.toLowerCase()) .collect(Collectors.toList()); ```<issue_comment>username_1: **`x` is uninitialized, so your snippet actually has an [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior).** --- > > Shouldn't it be returning some kind of error? > > > **`g++` doesn't warn of uninitialized values by default.** You need the `-Wuninitialized` option if you want your compiler to show a warning: ``` g++ -Wuninitialized your_file.c ``` You should probably use the `-Wall` option instead to enable this warning alongside lots of other useful warnings. More information on warning options [**here**](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html) Upvotes: 3 <issue_comment>username_2: > > But the following program prints a value of 0 on my terminal. > > > It has undefined behaviour because the `cout` line tries to read from an uninitialised `int`. Any output you see, and in fact any behaviour at all, is not guaranteed. > > Shouldn't it be returning some kind of error? > > > No, that's not how undefined behaviour works. You may or may not see an error. Upvotes: 4 [selected_answer]<issue_comment>username_3: > > Shouldn't it be returning some kind of error? > > > No, it should not, but this error is detectable by [**Valgrind**](http://valgrind.org/): ``` $ valgrind --track-origins=yes ./a.out ==4950== Memcheck, a memory error detector ==4950== Copyright (C) 2002-2017, and GNU GPL'd, by <NAME> et al. ==4950== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info ==4950== Command: ./a.out ==4950== ==4950== Conditional jump or move depends on uninitialised value(s) ==4950== at 0x4F4444A: std::ostreambuf_iterator > std::num\_put > >::\_M\_insert\_int(std::ostreambuf\_iterator >, std::ios\_base&, char, long) const (locale\_facets.tcc:874) ==4950== by 0x4F504C4: put (locale\_facets.h:2371) ==4950== by 0x4F504C4: std::ostream& std::ostream::\_M\_insert(long) (ostream.tcc:73) ==4950== by 0x40076D: main (t.cpp:5) ==4950== Uninitialised value was created by a stack allocation ==4950== at 0x400757: main (t.cpp:3) ==4950== ``` This part of Valgrind output clearly states that: ``` ==4950== Uninitialised value was created by a stack allocation ==4950== at 0x400757: main (t.cpp:3) ==4950== ``` Upvotes: 2
2018/03/18
1,242
2,121
<issue_start>username_0: gurus, i stumbled in hive rank process, i woluld like to rank transaction in each day (with no repeating rank value for the same trx value) ``` date hour trx rnk 18/03/2018 0 1 24 18/03/2018 1 2 23 18/03/2018 2 3 22 18/03/2018 3 4 21 18/03/2018 4 5 20 18/03/2018 5 6 19 18/03/2018 6 7 18 18/03/2018 7 8 17 18/03/2018 8 9 16 18/03/2018 9 10 15 18/03/2018 10 11 14 18/03/2018 11 12 13 18/03/2018 12 13 12 18/03/2018 13 14 11 18/03/2018 14 15 10 18/03/2018 15 16 9 18/03/2018 16 17 8 18/03/2018 17 18 7 18/03/2018 18 19 6 18/03/2018 19 20 5 18/03/2018 20 21 4 18/03/2018 21 22 3 18/03/2018 22 23 2 18/03/2018 23 24 1 17/03/2018 0 1 24 17/03/2018 1 2 23 17/03/2018 2 3 22 17/03/2018 3 4 21 17/03/2018 4 5 20 17/03/2018 5 6 19 17/03/2018 6 7 18 17/03/2018 7 8 17 17/03/2018 8 9 16 17/03/2018 9 10 15 17/03/2018 10 11 14 17/03/2018 11 12 13 17/03/2018 12 13 12 17/03/2018 13 14 11 17/03/2018 14 15 10 17/03/2018 15 16 9 17/03/2018 16 17 8 17/03/2018 17 18 7 17/03/2018 18 19 6 17/03/2018 19 20 5 17/03/2018 20 21 4 17/03/2018 21 22 3 17/03/2018 22 23 2 17/03/2018 23 24 1 ``` here is my code ``` select a.date, a.hour, trx, rank() over (order by a.trx) as rnk from( select date,hour, count(*) as trx from smy_tb group by date, hour )a limit 100; ``` the problem is: 1. rank value repeated with the same trx value 2. rank value continued to next date (it should be grouped for date and hour, so each date will only return 24 rank value) need advice, thank you<issue_comment>username_1: You should `partition by` date column and use a specific ordering. ``` rank() over (partition by a.date order by a.hour desc) ``` Upvotes: 1 <issue_comment>username_2: as explained by @BKS this is the resolved code ``` select a.date, a.hour, trx, row_number() over (partition by a.date order by a.trx desc) as rnk from( select date,hour, count(*) as trx from smy_tb group by date, hour )a limit 100; ``` Upvotes: 0
2018/03/18
434
1,512
<issue_start>username_0: Is Docker Swarm supported on Docker for Mac? When I try to use Docker Swarm I get an error: ``` $ docker swarm init docker swarm init is only supported on a Docker cli with swarm features enabled ``` I need Docker Swarm on my local Mac to test Docker features which are only available for Docker Swarm (e.g. [Config Maps](https://docs.docker.com/engine/swarm/configs/)). This question is also asked in the [docker community forum](https://forums.docker.com/t/docker-swarm-init-is-only-supported-on-a-docker-cli-with-swarm-features-enabled/44422). But no answer is provided there.<issue_comment>username_1: It should work in current versions of Docker for Mac. Check the "About Docker" view to make sure you have a version that supports it (Docker engine >= 1.13 or Docker CE). It appears right now that you need Kubernetes support turned *off* ([see forum post](https://forums.docker.com/t/docker-swarm-init-is-only-supported-on-a-docker-cli-with-swarm-features-enabled/44422)), so check that in the settings as well. Upvotes: 3 [selected_answer]<issue_comment>username_2: 1. You may disable Kubernetes by navigating to the Preferences pane [![enter image description here](https://i.stack.imgur.com/b56F1.png)](https://i.stack.imgur.com/b56F1.png) 2. If you would like to use Swarm simultaneously with Kubernetes, you need to set the DOCKER\_ORCHESTRATOR env variable to switch to Swarm. So open a new terminal, `export DOCKER_ORCHESTRATOR=swarm` `docker swarm init` Upvotes: 2
2018/03/18
1,583
5,396
<issue_start>username_0: Recently I have been learning more about hashing in Python and I came around this [blog](https://www.journaldev.com/17357/python-hash-function) where it states that: > > Suppose a Python program has 2 lists. If we need to think about > comparing those two lists, what will you do? Compare each element? > Well, that sounds fool-proof but slow as well! > > > Python has a much smarter way to do this. When a tuple is constructed > in a program, Python Interpreter calculates its hash in its memory. If > a comparison occurs between 2 tuples, it simply compares the hash > values and it knows if they are equal! > > > So I am really confused about these statements. First when we do: `[1, 2, 3] == [1, 2, 3]` then how does this equality works ? Does it calculate the hash value and then compare it ? Second what's the difference when we do: `[1, 2, 3] == [1, 2, 3]` and `(1, 2, 3) == (1, 2, 3)` ? Because when I tried to find time of execution with timeit then I got this result: ``` $ python3.5 -m timeit '[1, 2, 3] == [1, 2, 3]' 10000000 loops, best of 3: 0.14 usec per loop $ python3.5 -m timeit '(1, 2, 3) == (1, 2, 3)' 10000000 loops, best of 3: 0.0301 usec per loop ``` So why there is difference in time from `0.14` for list to `0.03` for tuple which is faster than list.<issue_comment>username_1: The answer was given in that article too :) here is the demonstrated : ``` >>> l1=[1,2,3] >>> l2=[1,2,3] >>> >>> hash(l1) #since list is not hashable Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' >>> t=(1,2,3) >>> t2=(1,2,3) >>> hash(t) 2528502973977326415 >>> hash(t2) 2528502973977326415 >>> ``` in above when you call hash on list it will give you TypeError as it is not hashable and for equality of two list python check its inside value that will lead to take much time in case of tuple it calculates the hash value and for two similar tuplle having the same hash value so python only compared the hashvalue of tuple so it us much fast than list from given article > > Python has a much smarter way to do this. When a tuple is constructed > in a program, Python Interpreter calculates its hash in its memory. If > a comparison occurs between 2 tuples, it simply compares the hash > values and it knows if they are equal! > > > Upvotes: 0 <issue_comment>username_2: Well, part of your confusion is that the blog post you're reading is just wrong. About multiple things. Try to forget that you ever read it (except to remember the site and the author's name so you'll know to avoid them in the future). It is true that tuples are hashable and lists are not, but that isn't relevant to their equality-testing functions. And it's certainly not true that "it simply compares the hash values and it knows if they are equal!" Hash collisions happen, and ignoring them would lead to horrible bugs, and fortunately Python's developers are not that stupid. In fact, it's not even true that Python computes the hash value at initialization time.\* There actually *is* one significant difference between tuples and lists (in CPython, as of 3.6), but it usually doesn't make much difference: Lists do an extra check for unequal length at the beginning as an optimization, but the same check turned out to be a pessimization for tuples,\*\* so it was removed from there. Another, often much more important, difference is that tuple literals in your source get compiled into constant values, and separate copies of the same tuple literal get folded into the same constant object; that doesn't happen with lists, for obvious reasons. In fact, that's what you're really testing with your `timeit`. On my laptop, comparing the tuples takes 95ns, while comparing the lists takes 169ns—but breaking it down, that's actually 93ns for the comparison, plus an extra 38ns to create each list. To make it a fair comparison, you have to move the creation to a setup step, and then compare already-existing values inside the loop. (Or, of course, you may not *want* to be fair—you're discovering the useful fact that every time you use a tuple constant instead of creating a new list, you're saving a significant fraction of a microsecond.) Other than that, they basically do the same thing. Translating [the C source](https://github.com/python/cpython/blob/master/Objects/tupleobject.c#L604) into Python-like pseudocode (and removing all the error handling, and the stuff that makes the same function work for `<`, and so on): ``` for i in range(min(len(v), len(w))): if v[i] != w[i]: break else: return len(v) == len(w) return False ``` The [list equivalent](https://github.com/python/cpython/blob/master/Objects/listobject.c#L2578) is like this: ``` if len(v) != len(w): return False for i in range(min(len(v), len(w))): if v[i] != w[i]: break else: return True return False ``` --- \* In fact, unlike strings, tuples don't even cache their hashes; if you call `hash` over and over, it'll keep re-computing it. See [issue 9685](https://bugs.python.org/issue9685), where a patch to change that was rejected because it slowed down some benchmarks and didn't speed up anything anyone could find. \*\* Not because of anything inherent about the implementation, but because people often compare lists of different lengths, but rarely do with tuples. Upvotes: 3
2018/03/18
1,290
4,636
<issue_start>username_0: Problem: -------- Vulkan right handed coordinate system became left handed coordinate system after applying projection matrix. How can I make it consistent with Vulkan coordinate system? Details: -------- I know that Vulkan is right handed coordinate system where * **X+** points toward right * **Y+** points toward down * **Z+** points toward inside the screen I've this line in the vertex shader: <https://github.com/AndreaCatania/HelloVulkan/blob/master/shaders/shader.vert#L23> ``` gl_Position = scene.cameraProjection * scene.cameraView * meshUBO.model * vec4(vertexPosition, 1.0); ``` At this point: <https://github.com/AndreaCatania/HelloVulkan/blob/master/main.cpp#L62-L68> I'm defining the position of camera at center of scene and the position of box at (4, 4, -10) World space The result is this: [![enter image description here](https://i.stack.imgur.com/IJ6Ci.png)](https://i.stack.imgur.com/IJ6Ci.png) As you can see in the picture above I'm getting **Z-** that point inside the screen but it should be positive. Is it expected and I need to add something more or I did something wrong? Useful part of code: -------------------- Projection calculation: <https://github.com/AndreaCatania/HelloVulkan/blob/master/VisualServer.cpp#L88-L98> ``` void Camera::reloadProjection(){ projection = glm::perspectiveRH_ZO(FOV, aspect, near, far); isProjectionDirty = false; } ``` Camera UBO fill: <https://github.com/AndreaCatania/HelloVulkan/blob/master/VisualServer.cpp#L403-L414> ``` SceneUniformBufferObject sceneUBO = {}; sceneUBO.cameraView = camera.transform; sceneUBO.cameraProjection = camera.getProjection(); ```<issue_comment>username_1: I do not use or know Vulcan but **perspective projection matrix** (at lest in **OpenGL**) is looking in the `Z-` direction which inverts one axis of your coordinate system. That inverts the winding rule of the coordinate system. If you want to preserve original winding than just invert `Z` axis vector in the matrix for more info see: * [Understanding 4x4 homogenous transform matrices](https://stackoverflow.com/a/28084380/2521214) So just scale the `Z` axis by `-1` either by some analogy to `glScale(1.0,1.0,-1.0);` or by direct matrix cells access. Upvotes: 3 [selected_answer]<issue_comment>username_2: All the OpenGL left coordinate system vs Vulkan right coordinate system happens during the fragment shader in NDC space, it means your view matrix doesn't care. If you are using glm, everything you do in world space or view space is done via a right handed coordinate system. *GLM, a very popular math library that every beginner uses, uses right-handed coordinate system by default.* Your view matrix must be set accordingly, the only way to get a right handed system with x from left to right and y from bottom to top is if to set your z looking direction looking down at the negative values. If you don't provide a right handed system to your `glm::lookat` call, glm will convert it with one of your axis getting flipped via a series of `glm::cross` see *glm source code* the proper way: ``` glm::vec3 eye = glm::vec3(0, 0, 10); glm::vec3 up = glm::vec3(0, 1, 0); glm::vec3 center = glm::vec3(0, 0, 0); // looking in the negative z direction glm::mat4 viewMat = glm::lookAt(eye, up, center); ``` Personnaly I store all information for coordinate system conversion in the projection matrix because **by default glm doest it for you for the z coordinate** from songho: <http://www.songho.ca/opengl/gl_projectionmatrix.html> *Note that the eye coordinates are defined in the right-handed coordinate system, but NDC uses the left-handed coordinate system. That is, the camera at the origin is looking along -Z axis in eye space, but it is looking along +Z axis in NDC. Since glFrustum() accepts only positive values of near and far distances, we need to NEGATE them during the construction of GL\_PROJECTION matrix.* Because we are looking at the negative z direction glm by default negate the sign. It turns out that the y coordinate is flipped between vulkan and openGL so everything will get turned upside down. One way to resolve the problem is to negate the y values aswell: ``` glm::mat4 projection = glm::perspective(glm::radians(verticalFov), screenDimension.x / screenDimension.y, near, far); // Vulkan NDC space points downward by default everything will get flipped projection[1][1] \*= -1.0f; ``` If you follow the above step you must end up with something very similar to old openGL applications and with the up vector of your camera with the same sign than most 3D models. Upvotes: 0
2018/03/18
617
2,142
<issue_start>username_0: I am experiencing a problem with debugging in vscode just after the last update. There's something going on (<https://github.com/Microsoft/vscode/issues/45657>) I'd like to check the previous version to see if my case is a problem here or in vscode but I can not find instructions on how to downgrade (I suppose it's possible)<issue_comment>username_1: Previous versions of Visual Studio Code can be downloaded here: <https://code.visualstudio.com/updates/> **Pick the version you want from the list on the left**, and then click on the download link for your OS as shown here: [![enter image description here](https://i.stack.imgur.com/G2fEs.png)](https://i.stack.imgur.com/G2fEs.png) **You should disable auto update** (as mentioned by Gregory in the comment) to **prevent it from auto updating itself** later upon restart. To do this, go to *Preferences*, *Settings* and then search for 'update'. Set it to 'none' as shown below: [![Disable auto update](https://i.stack.imgur.com/0acuR.png)](https://i.stack.imgur.com/0acuR.png) Upvotes: 9 [selected_answer]<issue_comment>username_2: <https://code.visualstudio.com/updates/> site is only Windows Installer. If you want to download Zip Executable, you can download like this url pattern. ``` # is like 1.44.0 https://vscode-update.azurewebsites.net//win32-x64-archive/stable ``` reference is this site. <https://github.com/Microsoft/vscode/issues/60933> And I try to download another site, and success to download. this site is linked in <https://code.visualstudio.com/updates/> ``` https://update.code.visualstudio.com//win32-x64-archive/stable ``` Upvotes: 1 <issue_comment>username_3: Visual studio docs now have a [section](https://code.visualstudio.com/docs/supporting/faq#_previous-release-versions) documenting all Url endpoints for downloading platform and archive specific downloads. For ex. for `Windows 64 bit zip` the download endpoint is : `https://update.code.visualstudio.com/{version}/win32-x64-archive/stable` [![enter image description here](https://i.stack.imgur.com/u8YvF.jpg)](https://i.stack.imgur.com/u8YvF.jpg) Upvotes: 3
2018/03/18
1,150
4,179
<issue_start>username_0: I have been trying to extract array elements from my JSON, but unable to, so far. I have the following JSON: ``` { "Sample JSON": [{ "Title": "Title1", "Audit": [{ "auditId": "01", "type": "sampleType", "auditText": "sampleText", "answer": ["Ans1", "Ans2"] }, { "auditId": "02", "type": "sampleType2", "auditText": "sampleText2", "answer": ["Ans1", "Ans2", "Ans3", "Ans4"] } ] }, { "Title": "Title2", "Audit": [{ "auditId": "03", "type": "sampleType3", "auditText": "sampleText3", "answer": ["Ans1", "Ans2"] }, { "auditId": "04", "type": "sampleType4", "auditText": "sampleText4", "answer": ["Ans1", "Ans2", "Ans3", "Ans4"] } ] } ] } ``` I want to extract the array elements of the array 'answer'. I get exception in the line indicated in comment in the method below: ``` public void getAudit(String myJSON) { auditList = new ArrayList(); String title; String auditId; String type; String auditText; ArrayList answer = new ArrayList<>(); try { JSONObject jsonObj = new JSONObject(myJSON); JSONArray jssArray = jsonObj.getJSONArray("Sample JSON"); int jsonArrLength = jssArray.length(); for (int i = 0; i < jsonArrLength; i++) { JSONObject jsonChildObj = jssArray.getJSONObject(i); title = jsonChildObj.getString("Title"); JSONArray jssArray1 = jsonChildObj.getJSONArray("Audit"); for (int i1 = 0; i1 < jssArray1.length(); i1++) { JSONObject jsonChildObj1 = jssArray1.getJSONObject(i1); type = jsonChildObj1.optString("type"); auditText = jsonChildObj1.optString("auditText"); auditId = jsonChildObj1.optString("auditId"); JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer"); //Getting exception in above line for (int j=0; j ``` I found the exception occurring in the line indicated above using the debugger. Couldn't find a way to extract array elements of the array 'answer'. Please help.<issue_comment>username_1: Previous versions of Visual Studio Code can be downloaded here: <https://code.visualstudio.com/updates/> **Pick the version you want from the list on the left**, and then click on the download link for your OS as shown here: [![enter image description here](https://i.stack.imgur.com/G2fEs.png)](https://i.stack.imgur.com/G2fEs.png) **You should disable auto update** (as mentioned by Gregory in the comment) to **prevent it from auto updating itself** later upon restart. To do this, go to *Preferences*, *Settings* and then search for 'update'. Set it to 'none' as shown below: [![Disable auto update](https://i.stack.imgur.com/0acuR.png)](https://i.stack.imgur.com/0acuR.png) Upvotes: 9 [selected_answer]<issue_comment>username_2: <https://code.visualstudio.com/updates/> site is only Windows Installer. If you want to download Zip Executable, you can download like this url pattern. ``` # is like 1.44.0 https://vscode-update.azurewebsites.net//win32-x64-archive/stable ``` reference is this site. <https://github.com/Microsoft/vscode/issues/60933> And I try to download another site, and success to download. this site is linked in <https://code.visualstudio.com/updates/> ``` https://update.code.visualstudio.com//win32-x64-archive/stable ``` Upvotes: 1 <issue_comment>username_3: Visual studio docs now have a [section](https://code.visualstudio.com/docs/supporting/faq#_previous-release-versions) documenting all Url endpoints for downloading platform and archive specific downloads. For ex. for `Windows 64 bit zip` the download endpoint is : `https://update.code.visualstudio.com/{version}/win32-x64-archive/stable` [![enter image description here](https://i.stack.imgur.com/u8YvF.jpg)](https://i.stack.imgur.com/u8YvF.jpg) Upvotes: 3
2018/03/18
1,237
3,146
<issue_start>username_0: I have some trouble with a drop-down menu (Bootstrap 4). So I have a table: [![enter image description here](https://i.stack.imgur.com/AbqTX.png)](https://i.stack.imgur.com/AbqTX.png) When I'm clicking on settings in first row I have a drop-down: [![enter image description here](https://i.stack.imgur.com/xSfli.png)](https://i.stack.imgur.com/xSfli.png) But when I'm clicking on settings in second row, I have a drop-down in same place as the first. How I can solve it? [![enter image description here](https://i.stack.imgur.com/3AtMa.png)](https://i.stack.imgur.com/3AtMa.png) Here is a codepen same troubles there: [CodePen](https://codepen.io/WhoIsDT/pen/RMoNEL) HTML: ``` | Фио сотрудника | Должность | Телефон | Ломбард | Профиль доступа | | | --- | --- | --- | --- | --- | --- | | hC <NAME> | Разработчик | +7 (921) 030-33-32 | Южный | Администратор | [Action](#) [Another action](#) [Something else here](#) | | Разработчик | Moe | +7 (921) 030-33-32 | Dooley | +7 (921) 030-33-32 | [Action2](#) [Another action](#) [Something else here](#) | ```<issue_comment>username_1: Here is the Working fiddle ``` | Фио сотрудника | Должность | Телефон | Ломбард | Профиль доступа | | | --- | --- | --- | --- | --- | --- | | hC <NAME> | Разработчик | +7 (921) 030-33-32 | Южный | Администратор | [Action](#) [Another action](#) [Something else here](#) | | Разработчик | Moe | +7 (921) 030-33-32 | Dooley | +7 (921) 030-33-32 | [Action2](#) [Another action](#) [Something else here](#) | | Разработчик | Moe | +7 (921) 030-33-32 | Dooley | +7 (921) 030-33-32 | [Action2](#) [Another action](#) [Something else here](#) | | Разработчик | Moe | +7 (921) 030-33-32 | Dooley | +7 (921) 030-33-32 | [Action2](#) [Another action](#) [Something else here](#) | | Разработчик | Moe | +7 (921) 030-33-32 | Dooley | +7 (921) 030-33-32 | [Action2](#) [Another action](#) [Something else here](#) | ``` [Working Fiddle](https://jsfiddle.net/LSKhan/yopp45kq/) Upvotes: 0 <issue_comment>username_2: As stated in the [Bootstrap docs](https://getbootstrap.com/docs/4.0/content/tables/#responsive-tables)... > > **Vertical clipping/truncation** > > Responsive tables make use of overflow-y: > hidden, which clips off any content that goes beyond the bottom or top > edges of the table. In particular, this can clip off dropdown menus > and other third-party widgets. > > > It's happening because the **`table-responsive` doesn't have enough vertical height**. Give the `table-responsive` a min height, for example... ``` .vh-100 { min-height: 100vh; } ``` <https://codepen.io/anon/pen/VXmLqG?editors=1100> Upvotes: 4 [selected_answer]<issue_comment>username_3: Define this properties for Bootstrap 4. Good Luck! ``` data-toggle="dropdown" data-boundary="window" ``` Upvotes: 2 <issue_comment>username_4: `data-toggle="dropdown" data-boundary="window"` The code above did the trick for me! Here is my complete dropdown in table cell code: ```html Actions [Dropdown item](#) ``` Upvotes: 3
2018/03/18
573
2,108
<issue_start>username_0: I am building a Nodejs Note app and I am very new at this, so here the delete function doesn't work it, deletes everything from the array and I want to delete only title There are two file app.js and note.js. Here's the content of app.js file ``` if (command === "add") { var note = notes.addNote(argv.title, argv.body); if (note) { console.log("Note created"); console.log("__"); console.log(`Title: ${note.title}`); console.log(`Body: ${note.body}`); } else { console.log("The title has already exist") } } else if (command === "delete") { var noteRemoved = notes.delNote(argv.title) var message = noteRemoved ? "Note has been removed" : "Note not found"; console.log(message) } ``` Here's the note.js content ``` var fetchNotes = function () { try { var noteString = fs.readFileSync("notes-data.json") return JSON.parse(noteString); } catch (e) { return []; } }; var saveNotes = function (notes) { fs.writeFileSync("notes-data.json", JSON.stringify(notes)); }; var addNote = function (title, body) { var notes = fetchNotes(); var note = { title, body }; var duplicateNotes = notes.filter(function (note) { return note.title === title; }); if (duplicateNotes.length === 0) { notes.push(note); saveNotes(notes); return note; }; } var delNote = function (title) { var notes = fetchNotes(); var filteredNotes = notes.filter(function (note) { note.title !== title; }); saveNotes(filteredNotes); return notes.length !== filteredNotes.length } ```<issue_comment>username_1: You need to add `return note.title !== title;` in delNote function. Upvotes: 1 <issue_comment>username_2: You miss return statement in delNote filter function ``` var filteredNotes = notes.filter(function (note) { return note.title !== title; }); ``` or we can use es6 syntax: ``` const filteredNotes = notes.filter(note => note.title !== title); ``` Upvotes: 3 [selected_answer]
2018/03/18
1,525
5,266
<issue_start>username_0: Let us say i have following main menu structure for which i need to add class active class to nav if part of url matches the menu link for example `www.domain.com/en/blog/this-is-firt-blog` in this case i need to add `active` class to second item in name `/blog` ``` * [Home](/en/) * [All Blogs](/en/blogs/) * [All Videos](/en/videos/) * [Contact Us](/en/contact/) ``` <https://codepen.io/anon/pen/aYBzRd> I use below code to match the part of url which is `/blog` but this code adds active class to all menu items ``` $(".wrapper li a").first().removeClass("active-menu"); var pathnameurl = window.location.pathname; if (pathnameurl.indexOf('/blog') != -1) { // alert("match"); $(".wrapper li a").each(function (index, element) { $(element).addClass("active"); }); } else { alert("nomatch"); } ``` I tried using `$(this).addClass("active");` but that also adds active class to all menu items<issue_comment>username_1: Try doing this to your code: ``` * [Home](/en/) * [All Blogs](/en/blogs/) * [All Videos](/en/videos/) * [Contact Us](/en/contact/) ``` Then in the javaScript code try this: ``` var pathname = window.location.href; if (pathname.indexof("/blogs") > -1){ document.getElementById("y").classlist.add("active"); document.getElementById("z").classlist.remove("active"); document.getElementById("w").classlist.remove("active"); }else if(pathname.indexof("/videos") > -1){ document.getElementById("z").classlist.add("active"); document.getElementById("").classlist.remove("active"); document.getElementById("w").classlist.remove("active"); }else if(pathname.indexof("/contact") > -1){ document.getElementById("w").classlist.add("active"); document.getElementById("y").classlist.remove("active"); document.getElementById("z").classlist.remove("active"); } ``` if you are using word press try: ``` * [Home](/en/) * [All Blogs](/en/blogs/) * [All Videos](/en/videos/) * [Contact Us](/en/contact/) ``` and your js will be: ``` var pathname = window.location.href; if (pathname.indexof("/blogs") > -1){ var li = document.getElementsByTagName("li"); for(var i = 0;i ``` This must fix your problem obviously and Good Luck. Upvotes: 1 <issue_comment>username_2: ``` $(document).ready(function(){ var pathnameurl = window.location.pathname; if (pathnameurl.indexOf('/blog') != -1) { $('a').each(function() { if($(this).attr("href") == "/en/blogs/") { $(this).parent().addClass("active") } }); } else { alert("nomatch"); } }); ``` try this Upvotes: 1 <issue_comment>username_3: make sure to remove all the classes from *a* tag ``` var pathnameurl = window.location.pathname; if (pathnameurl.indexOf('/blog') != -1) { var elements = document.querySelectorAll(".wrapper li a"); for(var i = 0; i < elements.length; i++) { if(elements[i].getAttribute("href").indexOf("/blog") > -1) { elements[i].className = "active"; } } } else { alert("nomatch"); } ``` or using jquery ``` $(".wrapper li a").first().removeClass("active-menu"); var pathnameurl = window.location.pathname; if (pathnameurl.indexOf('/blog') != -1) { // alert("match"); $(".wrapper li a").each(function (index, element) { if($(element).attr("href").indexOf("/blog") > -1) $(element).addClass("active"); }); } else { alert("nomatch"); } ``` Upvotes: 1 <issue_comment>username_4: Use This ``` $(".wrapper li a").removeClass("active"); var pathnameurl = window.location.pathname; //'someurl/en/blogs/' $(".wrapper li a").each(function (index, element) { var $el = $(this); var href = $el.attr('href'); if (pathnameurl.indexOf(href) >= 0) $el.addClass("active"); }); ``` <https://codepen.io/anon/pen/eMBNMB> Upvotes: 2 <issue_comment>username_5: Try this ``` $(".wrapper li a").first().removeClass("active-menu"); var pathnameurl = window.location.pathname; $(".wrapper li a").each(function() { if(pathnameurl.indexOf($(this).attr("href")) != -1) { $(this).addClass("active"); break; } else { alert("nomatch"); } }); ``` Upvotes: 1 <issue_comment>username_6: Why don't you try something like this: ``` $('[href*=blog]').addClass('active') ``` <https://codepen.io/username_6novic/pen/pLNJNo?editors=1111> p.s. your css also required change to work EDIT: If you need to add slash to css selector: ``` $('[href*="/blog"]').addClass('active') ``` Upvotes: 3 [selected_answer]<issue_comment>username_7: This code should work for any URL starting with /xy/type where xy is a 2 letter code (e.g. /en/blog..., /es/video...). It should be easily modifiable for similar forms. ``` // get the path name var pathnameurl = window.location.pathname; // extract the path type - assumes path is of the form /xy/type/... var pathtype = pathnameurl.replace(/^\/..\/([a-z]+).*$/, '$1'); // now set the corresponding menu item active $('[href*=' + pathtype + ']').addClass('active'); ``` Upvotes: 1
2018/03/18
663
2,495
<issue_start>username_0: Just discovered that I can use the getState() to pass state values to action creators. However I am noticing that getState() is returning all the combined states rather than the one specified in the argument. What am I doing wrong, as I don't suppose this is the correct behavior? Reducer: ``` import { combineReducers } from "redux"; import { reducer as reduxForm } from "redux-form"; import authReducer from "./authReducer"; export default combineReducers({ auth: authReducer, form: reduxForm }); ``` Action creator snippet: ``` export const handleProviderToken = token => async (dispatch, getState) => { let testState = getState("auth"); console.log(testState); const res = await axios.get(`${API_URL}/api/testEndpoint`); dispatch({ type: FETCH_USER, payload: res.data }); }; ``` The **console.log(testState)** is showing me the entire state tree object (auth and form, rather than just auth).<issue_comment>username_1: It is the correct behavior. [From docs](https://redux.js.org/api-reference/store#getstate()): > > Returns the current state tree of your application. It is equal to the > last value returned by the store's reducer. > > > Upvotes: 1 <issue_comment>username_2: It is correct behavior. You will need to pick the reducer key from the complete state. ``` export const handleProviderToken = token => async (dispatch, getState) => { let testState = getState(); let authReducer = testState.auth; const res = await axios.get(`${API_URL}/api/testEndpoint`); dispatch({ type: FETCH_USER, payload: res.data }); }; ``` Upvotes: 1 <issue_comment>username_3: Quoting redux-thunk documentation > > The inner function receives the store methods dispatch and getState as > parameters. > > > and quoting from redux's documentation > > getState()  Returns the current state tree of your application. It is > equal to the last value returned by the store's reducer. > > > So the getState you pass thanks to redux-thunk, is actually redux's getState() function itself and thus it is the default behavior. To get a specific value from your state tree, you can either use one of the following ``` const { auth } = getState() // OR const testState = getState() const auth = testState.auth ``` Upvotes: 4 [selected_answer]<issue_comment>username_4: What works in similar case for me is ``` const lastFetchedPage =getState().images.lastFetchedPage; ``` I do not know how it goes with guidelines, however. Upvotes: 1
2018/03/18
731
2,777
<issue_start>username_0: I'm calling native function from Java: ``` String pathTemp = Environment.getExternalStorageDirectory().getAbsolutePath()+Const.PATH_TEMP String pathFiles = Environment.getExternalStorageDirectory().getAbsolutePath()+Const.PATH_FILES engine.init(someInt, pathTemp, pathFiles); ``` And I have the native function: ``` extern "C" JNIEXPORT void Java_com_engine_init(JNIEnv *env, jobject __unused obj, jint someInt, jstring pathTemp, jstring pathFiles) { const char *pathTemp_ = env->GetStringUTFChars(pathTemp, JNI_FALSE); const char *pathFiles_ = env->GetStringUTFChars(pathFiles, JNI_FALSE); // <-- CRASH // More init code env->ReleaseStringUTFChars(pathTemp, pathTemp_); env->ReleaseStringUTFChars(pathRecording, pathRecording_); ``` } The problem: pathTemp is arriving good, but pathFiles==NULL in native function. Rechecked, and confirmed - both strings are non NULL in java. One more strange thing - The problem is on LG-G3 (android 6.0). On Meizu PRO 5 (android 7.0) - everything works good - both strings are intact. What is this JNI magic? Any clue?<issue_comment>username_1: Not an answer, but workaround. Moved the strings (in parameters) to be before int parameter. Now it's working. I have no idea why is this. Upvotes: -1 <issue_comment>username_2: I had the same problem as this and while I can't guarantee this is the same, I found a better solution than re-ordering the parameters. tldr; Ensure the code works for 32bit and 64bit platforms as pointers have different sizes. I was running 32bit native code and passed `nullptr` as a parameter and java expected a `long` which resulted in all parameters after the `nullptr` to be invalid. `(JJLjava/lang/String;Z)V` -> `(final long pCallback, final long pUserPointer, final String id, final boolean b)` pCallback was always set to a valid value (pointer casted to `jlong` in c++) and pUserPointer was always `nullptr`. I found this answer and tried switching the order around and it 'just worked' but I knew that fix was never going to be approved. After looking at the JNI documentation on the Android website again (<https://developer.android.com/training/articles/perf-jni>) I took note of the "64-bit considerations" section and took a stab at my assumption of the data size. This feature was developed with a 64bit device (Pixel 3) but issues had been reported on a 32bit device (Amazon Fire Phone) so `nullptr` would be 32bit but the java function still expected a long (64bit). In my situation the offending parameter was always unused so I could safely remove it and everything "just worked" (including some other parameters which were broken). An alternative would be to have a define/function/macro for JniLongNullptr which is just 0 casted to jlong. Upvotes: 0
2018/03/18
423
1,621
<issue_start>username_0: I'm creating (for the first time) a small Mac only app using Electron. I am trying to use ipcRenderer to communicate between my app menu and the content in the main BrowserWindow. I have the menu set up as follows to send the message 'select-active': ``` const {Menu} = require('electron') const electron = require('electron') const app = electron.app const BrowserWindow = electron.BrowserWindow const template = [ { label: 'Fonts', submenu: [ { label: 'Select All Acitve Fonts', accelerator: 'Command+A', click (item, focusedWindow) { if(focusedWindow) focusedWindow.webContents.send('select-active') } },... ``` which I am then receiving as follows: ``` const ipcRenderer = require('electron').ipcRenderer; ipcRenderer.on('select-active', function () { console.log('SELECTED'); }) ``` The problem I have is that every time the menu command is selected the message is logged twice in the console. Where am I going wrong?<issue_comment>username_1: How about using .once instead ``` ipcRenderer.once('select-active', function () { console.log('SELECTED'); ``` }) Upvotes: 1 <issue_comment>username_2: You are subscribing to `ipcRenderer.on` after React component rerendering (React calls your function every time it needs to get rendered version of it). Try to define the `ipcRenderer.on` event handler outside of React component function. ``` function yourFunction(){ return(){} } export default yourFunction; ipcRenderer.send(); ``` Place your `ipcRenderer.send();` under the `export default yourFunction;` It`s works for me! Upvotes: 0
2018/03/18
1,048
2,680
<issue_start>username_0: ionic build android error gradle error > > Exception in thread "main" > > > java.lang.RuntimeException: java.util.zip.ZipException: error in > opening zip file > > > at > org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:78) > > > at org.gradle.wrapper.Install.createDist(Install.java:47) > > > at > org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129) > > > at > org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48) > > > Caused by: java.util.zip.ZipException: error in opening zip file > > > at java.util.zip.ZipFile.open(Native Method) > > > at java.util.zip.ZipFile.(ZipFile.java:219) > > > at java.util.zip.ZipFile.(ZipFile.java:149) > > > at java.util.zip.ZipFile.(ZipFile.java:163) > > > at org.gradle.wrapper.Install.unzip(Install.java:160) > > > at org.gradle.wrapper.Install.access$400(Install.java:29) > > > at org.gradle.wrapper.Install$1.call(Install.java:70) > > > at org.gradle.wrapper.Install$1.call(Install.java:47) > > > at > org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) > > > ... 3 more > > > Failed to install 'cordova-plugin-console':Error: > /node/Palaroo/platforms/android/gradlew: Command failed with exit code > 1 > > > at ChildProcess.whenDone > (/node/Palaroo/platforms/android/cordova/node\_modules/cordova-common/src/superspawn.js:169:23) > > > at emitTwo (events.js:106:13) > > > at ChildProcess.emit (events.js:191:7) > > > at maybeClose (internal/child\_process.js:877:16) > > > at Process.ChildProcess.\_handle.onexit > (internal/child\_process.js:226:5) > > > Error: /node/Palaroo/platforms/android/gradlew: Command failed with > exit code 1 > > > **Can any one provide solution for this**<issue_comment>username_1: If faced error while building ionic build android then got to this path on mac and delete everything ``` /var/root/.gradle/wrapper/dists/gradle-2.14.1-all/ ``` If faced error while building ionic build android then got to this path on mac and delete everything ``` /var/root/.gradle/wrapper/dists/gradle-2.14.1-all/ /var/root/.gradle/wrapper/dists/gradle-2.14.1-all/nzipping /var/root/.gradle/wrapper/dists/gradle-2.14.1-all/53l0mv9mggp9q5m2ip574m21oh/gradle-2.14.1-all.zip ``` to ``` /var/root/.gradle/wrapper/dists/gradle-2.14.1-all/53l0mv9mggp9q5m2ip574m21oh ``` This solves the problem Upvotes: 0 <issue_comment>username_2: Just delete the folder /**home/USER-NAME/.gradle/wrapper/dists/** Its happening because your gradle zip file has not downloaded correctly delete it and run the command again. Upvotes: 1
2018/03/18
1,660
5,759
<issue_start>username_0: I am new to Spring Boot and following some video tutorials to get started. I created a Maven project, added a parent dependency of artifact id `spring-boot-starter-parent`, added dependency for `spring-boot-starter-web` and `spring-boot-starter-test`. This is the `Application.java`: ``` @RestController @EnableAutoConfiguration public class Application { @RequestMapping("/") public String home() { return "Hello World"; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` **Note:** `src/test/java` and `src/test/resources` packages are empty. This is a Maven Project, I am using STS, performed "Maven -> Update Project..." and cleaned/build the entire project multiple times using STS IDE and I am getting the following error. Also, I tried to create a new project in STS and still I am getting the following error: I am getting this error when I run this as a `Spring Boot App`: ``` Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/util/Assert at org.springframework.boot.SpringApplication.(SpringApplication.java:263) at org.springframework.boot.SpringApplication.(SpringApplication.java:247) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) at com.boot.Application.main(Application.java:18) Caused by: java.lang.ClassNotFoundException: org.springframework.util.Assert at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 5 more ``` Please help me in resolving this issue. **EDIT:** This is my pom.xml: ``` 4.0.0 com.deloitte.boot boot-test 0.0.1-SNAPSHOT boot-test org.springframework.boot spring-boot-starter-parent 2.0.0.RELEASE org.springframework.boot spring-boot-starter-web ``` This is my project directory stricture: [![enter image description here](https://i.stack.imgur.com/RRLFM.png)](https://i.stack.imgur.com/RRLFM.png)<issue_comment>username_1: It is better to follow software principles while you are learning and making projects. Try to make project in a way that *separation of concern* is always achieved, that will make your code not just easy to understand, but to debug and fix too. Change your application class like this: ``` import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` Now make another package **controller** and make class in it for your testing ``` @RestController //You can add this if you want or remove this class level mapping @RequestMapping("/testApp") public class TestController { @RequestMapping("/") public String home() { return "Hello World"; } } ``` For further help. please check [this (official spring.io tutorial)](https://spring.io/blog/2015/03/18/spring-boot-support-in-spring-tool-suite-3-6-4) simple example of Spring Boot App in STS. And another one is this [very simple and straightforward](http://blog.netgloo.com/2014/05/18/very-basic-web-application-with-spring-mvc-spring-boot-and-eclipse-sts/) to get Spring Boot App up and running. **Edit**: please add starter test in pom.xml as well. ``` org.springframework.boot spring-boot-starter-test 1.5.10.RELEASE test ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I have fixed that issue like this, first I removed my folder .m2 and then I run mvn clean install into my directory spring boot project. that's all! Upvotes: 2 <issue_comment>username_3: Had the same issue, after I installed STS (before that, everything in Eclipse was going ok). I removed the springframework folder that was inside the .m2 folder, then ran 'mvn clean install' in my project directory. After that I encountered an issue with my assertj-core-3.11.1.jar and mockito-core-2.23.0.jar (ZipFile invalid LOC header (bad signature)), so I also removed them and ran "mvn spring-boot:run". Now it works (but I can't really explain why). Upvotes: 0 <issue_comment>username_4: Had the same issue with IntelliJ and a brand new project created from Spring Initializer. Saw this message when trying to compile manually: ``` [ERROR] error reading /Users/mike/.m2/repository/org/springframework/spring-core/5.1.4.RELEASE/spring-core-5.1.4.RELEASE.jar; zip file is empty ``` Turns out the files downloaded from maven central were corrupt: ``` ls -al /Users/mike/.m2/repository/org/springframework/spring-core/5.1.4.RELEASE/spring-core-5.1.4.RELEASE.jar -rw-r--r-- 1 mike staff 0 Jan 16 20:55 /Users/mike/.m2/repository/org/springframework/spring-core/5.1.4.RELEASE/spring-core-5.1.4.RELEASE.jar ``` Removing the entire directory and rebuilding forced it to download a new copy of of the missing library: ``` ./mvnw compile Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/spring-core/5.1.4.RELEASE/spring-core-5.1.4.RELEASE.pom Downloaded from central: https://repo.maven.apache.org/maven2/org/springframework/spring-core/5.1.4.RELEASE/spring-core-5.1.4.RELEASE.pom (3.6 kB at 7.6 kB/s) Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/spring-core/5.1.4.RELEASE/spring-core-5.1.4.RELEASE.jar Downloaded from central: https://repo.maven.apache.org/maven2/org/springframework/spring-core/5.1.4.RELEASE/spring-core-5.1.4.RELEASE.jar (1.3 MB at 3.6 MB/s) ``` Upvotes: 1
2018/03/18
432
1,311
<issue_start>username_0: I've got a string like: "The delivery time will be 3-4 days. If you choose 'express' the delivery time will be 1-2 days. Pay within 30 days.". How can I add 1 day to every number in the string without re-creating the string? The result should be: "The delivery time will be 4-5 days. If you choose 'express' the delivery time will be 2-3 days. Pay within 31 days.".<issue_comment>username_1: You can use [`preg_replace_callback`](http://php.net/manual/de/function.preg-replace-callback.php) to do that: ``` php $s = "The delivery time will be 3-4 days. If you choose 'express' the delivery time will be 1-2 days. Pay within 30 days."; function callback($matches) { return $matches[0] + 1; } $pattern = '~([0-9]+)~'; $r = preg_replace_callback($pattern, 'callback', $s); echo $r; ? ``` [Here's a demo](http://rextester.com/QIOD54543) Upvotes: 4 [selected_answer]<issue_comment>username_2: [`preg_replace_callback()`](http://php.net/manual/en/function.preg-replace-callback.php) ``` php $str = "The delivery time will be 3-4 days. If you choose 'express' the delivery time will be 1-2 days. Pay within 30 days"; $str = preg_replace_callback( '([0-9]+)', function ($matches) { return $matches[0]+1; }, $str ); echo $str; ? ``` Upvotes: 2
2018/03/18
336
1,062
<issue_start>username_0: I have an HTML5 date input element like this: if you choose a date in this input a string will be the value, for example: `"2018-12-31"` In my model I want the date to be presented as the following string: `"2018-12-31T00:00:00.000Z"` and not the simplified string. How do I make sure that the date in my model keeps the correct format? I tried using a computed but since I am in a loop this time I cannot use them. ``` {{eventDate.date}} ``` As you can see here the eventDate.date is a long string but the input needs the format YYYY-MM-DD. I need to convert it to and from this format some way. [![enter image description here](https://i.stack.imgur.com/mrFnd.png)](https://i.stack.imgur.com/mrFnd.png)<issue_comment>username_1: You could use a filter: ``` filter: { dateToString(date) { return date.toString().substr(0,10) } } ``` and then update your template ``` :value="eventDate.date | dateToString" ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: This is what I ended up using: ``` ``` Upvotes: 0
2018/03/18
1,115
4,179
<issue_start>username_0: I'm trying to get the element density from the abaqus output database. I know you can request a field output for the volume using 'EVOL', is something similar possible for the density? I'm afraid it's not because of this: [Getting element mass in Abaqus postprocessor](https://stackoverflow.com/questions/31671101/getting-element-mass-in-abaqus-postprocessor) What would be the most efficient way to get the density? Look for every element in which section set it is?<issue_comment>username_1: Found a solution, I don't know if it's the fastest but it works: ``` odb_file_path=r'your_path\file.odb' odb = session.openOdb(name=odb_file_path) instance = odb.rootAssembly.instances['MY_PART'] material_name = instance.elements[0].sectionCategory.name[8:-2] density=odb.materials[material_name].density.table[0][0]) ``` note: the 'name' attribute will give you a string like, 'solid MATERIALNAME'. So I just cut out the part of the string that gave me the real material name. So it's the sectionCategory attribute of an OdbElementObject that is the answer. EDIT: This doesn't seem to work after all, it turns out that it gives all elements the same material name, being the name of the first material. Upvotes: 1 <issue_comment>username_2: The properties are associated something like this: * `sectionAssignment` connects `section` to `set` * `set` is the container for `element` * `section` connects `sectionAssignment` to `material` * `instance` is connected to `part` (could be from a part from another model) * `part` is connected to `model` * `model` is connected to `section` Use the `.inp` or `.cae` file if you can. The following gets it from an opened `cae` file. To thoroughly get `elements` from `materials`, you would do something like the following, assuming you're starting your search in `rootAssembly.instances`: 1. Find the `parts` which the `instances` were created from. 2. Find the `models` which contain these `parts`. 3. Look for all `sections` with `material_name` in these `parts`, and store all the `sectionNames` associated with this section 4. Look for all `sectionAssignments` which references these `sectionNames` 5. Under each of these `sectionAssignments`, there is an associated `region` object which has the name (as a string) of an `elementSet` and the name of a `part`. Get all the `elements` from this `elementSet` in this `part`. Cleanup: 5. Use the Python `set` object to remove any multiple references to the same element. 6. Multiply the number of elements in this set by the number of identical part instances that refer to this material in `rootAssembly`. E.g., for some `cae` model variable called `model`: ``` model_part_repeats = {} model_part_elemLabels = {} for instance in model.rootAssembly.instances.values(): p = instance.part.name m = instance.part.modelName try: model_part_repeats[(m, p)] += 1 continue except KeyError: model_part_repeats[(m, p)] = 1 # Get all sections in model sectionNames = [] for s in mdb.models[m].sections.values(): if s.material == material_name: # material_name is already known # This is a valid section - search for section assignments # in part for this section, and then the associated set sectionNames.append(s.name) if sectionNames: labels = [] for sa in mdb.models[m].parts[p].sectionAssignments: if sa.sectionName in sectionNames: eset = sa.region[0] labels = labels + [e.label for e in mdb.models[m].parts[p].sets[eset].elements] labels = list(set(labels)) model_part_elemLabels[(m,p)] = labels else: model_part_elemLabels[(m,p)] = [] num_elements_with_material = sum([model_part_repeats[k]*len(model_part_elemLabels[k]) for k in model_part_repeats]) ``` Finally, grab the material density associated with `material_name` then multiply it by `num_elements_with_material`. Of course, this method will be extremely slow for larger models, and it is more advisable to use string techniques on the `.inp` file for faster performance. Upvotes: 1 [selected_answer]
2018/03/18
1,547
4,208
<issue_start>username_0: [![enter image description here](https://i.stack.imgur.com/q0A1y.png)](https://i.stack.imgur.com/q0A1y.png) [![enter image description here](https://i.stack.imgur.com/qxb9j.png)](https://i.stack.imgur.com/qxb9j.png) I would like to ask how to shorten the code below? Have any other ways to achieve the same result? ``` Option Explicit Sub test() Dim i As Integer Dim nRow As Integer: nRow = Cells(Rows.Count, 1).End(xlUp).Row For i = 2 To nRow If Cells(i, 1) <> "" And Cells(i, 1) = Cells(i + 1, 1) And Cells(i + 1, 1) = Cells(i + 2, 1) And Cells(i + 2, 1) = Cells(i + 3, 1) And Cells(i + 3, 1) = Cells(i + 4, 1) Then Cells(i, 2) = Cells(i, 2) & "/" & Cells(i + 1, 2) & "/" & Cells(i + 2, 2) & "/" & Cells(i + 3, 2) & "/" & Cells(i + 4, 2) Rows(i + 1 & ":" & i + 4).Delete Shift:=xlShiftUp ElseIf Cells(i, 1) <> "" And Cells(i, 1) = Cells(i + 1, 1) And Cells(i + 1, 1) = Cells(i + 2, 1) And Cells(i + 2, 1) = Cells(i + 3, 1) Then Cells(i, 2) = Cells(i, 2) & "/" & Cells(i + 1, 2) & "/" & Cells(i + 2, 2) & "/" & Cells(i + 3, 2) Rows(i + 1 & ":" & i + 3).Delete Shift:=xlShiftUp ElseIf Cells(i, 1) <> "" And Cells(i, 1) = Cells(i + 1, 1) And Cells(i + 1, 1) = Cells(i + 2, 1) Then Cells(i, 2) = Cells(i, 2) & "/" & Cells(i + 1, 2) & "/" & Cells(i + 2, 2) Rows(i + 1 & ":" & i + 2).Delete Shift:=xlShiftUp ElseIf Cells(i, 1) <> "" And Cells(i, 1) = Cells(i + 1, 1) Then Cells(i, 2) = Cells(i, 2) & "/" & Cells(i + 1, 2) Rows(i + 1 & ":" & i + 1).Delete Shift:=xlShiftUp ElseIf Cells(i, 1) = "" Then Exit For End If Next i End Sub ``` Thank you!<issue_comment>username_1: Here's `Dictionary` based approach which should work for you. ``` Public Sub RearrangeData() Dim objDic As Object Dim varRng Dim i As Long Set objDic = CreateObject("Scripting.Dictionary") objDic.CompareMode = vbTextCompare '\\ change this if you need it case sensitive varRng = Range("A2:B" & Range("A" & Rows.Count).End(xlUp).Row).Value For i = LBound(varRng) To UBound(varRng) If objDic.Exists(varRng(i, 1)) Then objDic.Item(varRng(i, 1)) = objDic.Item(varRng(i, 1)) & "/" & varRng(i, 2) Else objDic.Add varRng(i, 1), varRng(i, 2) End If Next i Range("A2:B" & Range("A" & Rows.Count).End(xlUp).Row).ClearContents Range("A2").Resize(objDic.Count, 1).Value = Application.Transpose(objDic.Keys) Range("B2").Resize(objDic.Count, 1).Value = Application.Transpose(objDic.Items) Set objDic = Nothing End Sub ``` Upvotes: 2 <issue_comment>username_2: here's another dictionary approach (no reference adding required) ``` Sub strings() Dim data As Variant, key As Variant Dim i As Long data = Range("B2", Cells(Rows.Count, 1).End(xlUp)).Value With CreateObject("Scripting.Dictionary") For i = 1 To UBound(data) .Item(data(i, 1)) = .Item(data(i, 1)) & "/" & data(i, 2) Next Range("A1").CurrentRegion.Resize(Range("A1").CurrentRegion.Rows.Count - 1).Offset(1).ClearContents i = 1 For Each key In .Keys i = i + 1 Cells(i, 1) = key Cells(i, 2) = Mid(.Item(key), 2) Next End With End Sub ``` *BTW*, should you *ever* need to combine strings from more columns, you could use ``` Option Explicit Sub strings() Dim data As Variant, key As Variant Dim i As Long, iCol As Long With Range("A1").CurrentRegion With .Resize(.Rows.Count - 1).Offset(1) data = .Value .ClearContents End With End With With CreateObject("Scripting.Dictionary") For iCol = 2 To UBound(data, 2) For i = 1 To UBound(data) .Item(data(i, 1)) = Trim(.Item(data(i, 1)) & " " & data(i, iCol)) Next Range("A2").Resize(.Count) = Application.Transpose(.Keys) Range("A2").Resize(.Count).Offset(, iCol - 1) = Application.Transpose(.Items) .RemoveAll Next End With Range("a1").CurrentRegion.Replace what:=" ", replacement:="/", lookat:=xlPart End Sub ``` Upvotes: 3 [selected_answer]
2018/03/18
1,192
4,584
<issue_start>username_0: I want to an image while I hit an API like `localhost:8080:/getImage/app/path={imagePath}` While I hit this API it will return me an Image. Is this possible? Actually, I have tried this but it is giving me an ERROR. Here is my code, ``` @GET @Path("/app") public BufferedImage getFullImage(@Context UriInfo info) throws MalformedURLException, IOException { String objectKey = info.getQueryParameters().getFirst("path"); return resizeImage(300, 300, objectKey); } public static BufferedImage resizeImage(int width, int height, String imagePath) throws MalformedURLException, IOException { BufferedImage bufferedImage = ImageIO.read(new URL(imagePath)); final Graphics2D graphics2D = bufferedImage.createGraphics(); graphics2D.setComposite(AlphaComposite.Src); // below three lines are for RenderingHints for better image quality at cost of // higher processing time graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.drawImage(bufferedImage, 0, 0, width, height, null); graphics2D.dispose(); System.out.println(bufferedImage.getWidth()); return bufferedImage; } ``` My ERROR, ``` java.io.IOException: The image-based media type image/webp is not supported for writing ``` Is there any way to return an Image while hitting any URL in java?<issue_comment>username_1: i didn't test it due to i don't have the environment in this machine, but logically it should work like the following, read it as input stream and let your method returns @ResponseBody byte[] ``` @GET @Path("/app") public @ResponseBody byte[] getFullImage(@Context UriInfo info) throws MalformedURLException, IOException { String objectKey = info.getQueryParameters().getFirst("path"); BufferedImage image = resizeImage(300, 300, objectKey); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", os); InputStream is = new ByteArrayInputStream(os.toByteArray()); return IOUtils.toByteArray(is); } ``` **UPDATE** depending on @Habooltak Ana suggestion there is no need to create an input stream, the code should be look like the following ``` @GET @Path("/app") public @ResponseBody byte[] getFullImage(@Context UriInfo info) throws MalformedURLException, IOException { String objectKey = info.getQueryParameters().getFirst("path"); BufferedImage image = resizeImage(300, 300, objectKey); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", os); return os.toByteArray(); } ``` Upvotes: 2 <issue_comment>username_2: Just return a file object with correct HTTP-Headers ([Content-Type](https://en.wikipedia.org/wiki/MIME#Content-Type) and [Content-Disposition](https://en.wikipedia.org/wiki/MIME#Content-Disposition)) will work in most cases/environments. Pseudocode ``` File result = createSomeJPEG(); /* e.g. RenderedImage rendImage = bufferedImage; File file = new File("filename.jpg"); ImageIO.write(rendImage, "jpg", file); */ response().setHeader("Content-Disposition", "attachment;filename=filename.jpg;"); response().setHeader("Content-Type", "image/jpeg"); return ok(result); ``` See also: * [file downloading in restful web services](https://stackoverflow.com/questions/10100936/file-downloading-in-restful-web-services) * [what's the correct way to send a file from REST web service to client?](https://stackoverflow.com/questions/12239868/whats-the-correct-way-to-send-a-file-from-rest-web-service-to-client) Upvotes: 1 <issue_comment>username_3: You can use [IOUtils](https://mvnrepository.com/artifact/org.apache.commons/commons-io/1.3.2). Here is code sample. ``` @RequestMapping(path = "/getImage/app/path/{filePath}", method = RequestMethod.GET) public void getImage(HttpServletResponse response, @PathVariable String filePath) throws IOException { File file = new File(filePath); if(file.exists()) { String contentType = "application/octet-stream"; response.setContentType(contentType); OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(file); // copy from in to out IOUtils.copy(in, out); out.close(); in.close(); }else { throw new FileNotFoundException(); } } ``` Upvotes: 3 [selected_answer]
2018/03/18
760
2,479
<issue_start>username_0: How to collect to Map from List where null values are excluded/skipped? This code doesn't skip null values: ``` val map = listOf(Pair("a", 1), Pair("b", null), Pair("c", 3), Pair("d", null)) .associateBy({ it.first }, { it.second }) println(map) ``` Workaround solution. But collects into mutable map: ``` val map2 = listOf(Pair("a", 1), Pair("b", null), Pair("c", 3), Pair("d", null)) .mapNotNull { if (it.second != null) it else null }.toMap() println(map2) ``` So is there more convenient way to do this? Also I want to get `Map` type, not `Map`<issue_comment>username_1: You want to filter out `null` values, then you should use `filter` method: ``` val map = listOf(Pair("a", 1), Pair("b", null), Pair("c", 3), Pair("d", null)) .filter { it.second != null } .toMap() println(map) ``` Upvotes: 3 <issue_comment>username_2: Actually, a slight change to username_1's answer guarantees that the second item is non-nullable: ``` val map = listOf(Pair("a", 1), Pair("b", null), Pair("c", 3), Pair("d", null)) .mapNotNull { p -> p.second?.let { Pair(p.first, it) } } .toMap() println(map) ``` This will give you a `Map`, since `mapNotNull` ignores anything that maps to `null`, and using `let` with the safe call operator `?.` returns null if its receiver (`p.second`) is `null`. This is basically what you stated in your question, made shorter with `let`. Upvotes: 6 [selected_answer]<issue_comment>username_3: A more readable solution might be using the associateBy function with the double bang expression (!!): ``` val map: Map = listOf( Pair("a", 1), Pair("b", null), Pair("c", 3), Pair("d", null) ) .filter { it.first != null && it.second != null } .associateBy({ it.first!! }, { it.second!! }) println(map) ``` Upvotes: 2 <issue_comment>username_4: Since Kotlin 1.6, there is also a stable [buildMap](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/build-map.html) function that can be used to write custom helper functions that are performant without sacrificing readability: ``` fun Iterable.associateByNotNull( keySelector: (T) -> K?, valueTransform: (T) -> V?, ): Map = buildMap { for (item in this@associateByNotNull) { val key = keySelector(item) ?: continue val value = valueTransform(item) ?: continue this[key] = value } } ``` Note that writing this as a "low-level" for loop eliminates the need for the creation of intermediate collections. Upvotes: 2
2018/03/18
1,730
6,952
<issue_start>username_0: I have TableView with customs cell representing events. It looks very close to first and third image here. [![enter image description here](https://i.stack.imgur.com/3yUNd.jpg)](https://i.stack.imgur.com/3yUNd.jpg) As you can see (sorry for small resolution) on some events there are photos of friends that are going to participate. Unfortunately information about friends is not loaded with other information about events. So after I got list of events I can make request to load list of friends that are going to participate in each event. Right now I use code like ``` class EventCell : UITableViewCell { var eventForCell : Event? { didSet { eventTitleLabel.text = eventForCell.title eventDateLabel.text = eventForCell.date presentFriends(eventID : eventForCell.id) } } func presentFriends(eventID : Int) { //searching for friends for event with specific eventID ....... ....... //for every friend found adding UIImageView in cell for friend in friendsOnEvent { let avatar = UIImageView(....) self.addSubview(avatar) } } } ``` This code works but photos are not presented in smooth way. Also if you scroll list fast they start to blink. Maybe it is even not necessary to load them if user scrolls fast list of events. So I have two questions: 1. How can I make smooth scrolling experience taking in consideration that presenting friends for every event can take time and sometimes it finishes after cell was scrolled away. 2. If I had loaded list of events and already presenting cells with them. How can I update those cells after I get information about friends that are going to participate? 3. When user is scrolling and I am creating async tasks to display some images in cell I think I should use weak reference to self and maybe check it not to equal nil so task would be canceled if cell is not visible now. How should it be done? **Update:** I found info about **tableView(\_:prefetchRowsAt:)** method inside UITableViewPrefetchingDataSource protocol, should I use it for this case? Maybe someone has some experience with it?<issue_comment>username_1: **1.** (Re)creating a view objects during `cellForRowAt` is generally a bad practice. From the screenshot I assume that there is a limit to how many avatars are there on a single cell - I would recommend creating all the `UIImageView` objects in the cell initializer, and then in `presentFriends` just set images to them, and either hide the unused ones (`isHidden = true`) or set their alpha to 0 (of course, don't forget to unhide those that are used). **2.** If you are using SDWebImage to load images, implement `prepareForReuse` and cancel current downloads to get a bit of performance boost during scrolling, and prevent undefined behaviour (when you try to set another image while the previous one was not yet downloaded). Based on [this question](https://stackoverflow.com/questions/17222434/sdwebimage-cancel-download), [this one](https://stackoverflow.com/questions/22914624/how-to-cancel-download-with-sdwebimagedownloader) and [this one](https://stackoverflow.com/questions/17073240/is-there-any-way-to-stop-an-image-in-a-uiimageview-from-lazy-loading-with-sdwebi) I would expect something like: ``` override func prepareForReuse() { super.prepareForReuse() self.imageView.sd_cancelCurrentImageLoad() } Or you can use [this gist][4] for an inspiration. ``` **P.S.:** Also, you will have to count with some blinking, since the images are downloaded from web - there will always be some delay. By caching you can get instantly those that were already downloaded, but new ones will have delay - there is no way to prevent that (unless you preload all the images that can appear in tableView before presenting tableView). **P.S.2:** You can try to implement prefetching using `[UITableViewDataSourcePrefetching][6]`. This could help you out with blinking caused by downloading the avatars from web. This would make things a bit more complicated, but if you really want to remove that blinking you will have to get your hands dirty. First of all, as you can see from the documentation, `prefetchRowsAt` does not give you a cell object - thus you will have to prefetch images to your model object instead of simply using `sd_setImage` on the `UIImageView` object at a given cell. Maybe the aforementioned [gist](https://gist.github.com/keighl/6319942) would help you out with downloading images to model. Now also as the [documentation](https://developer.apple.com/documentation/uikit/uitableviewdatasourceprefetching) states: > > **Loading Data Asynchronously** > > > The `tableView(_:prefetchRowsAt:)` method is not necessarily called for every cell in the table view. Your implementation of `tableView(_:cellForRowAt:)` must therefore be able to cope with the following potential situations: > > > Data has been loaded via the prefetch request, and is ready to be displayed. > > > Data is currently being prefetched, but is not yet available. > > > Data has not yet been requested. > > > Simply said, when you are in `cellForRowAt`, you cannot rely on `prefetchRowsAt` being called - it might have been called, and it might not have been called (or maybe the call is in progress). Documentation continues to suggest using `Operation` as a backing tool for downloading the resources - `prefetchRowsAt` could create `Operation` objects that would be responsible for downloading avatars for a given row. `cellForRowAt` can then ask the model for the `Operation` objects for the given row - if there are not any, it means that `prefetchRowsAt` was not called for that row, and you have to create `Operation` objects at that point. Otherwise you can use the operations created by `prefetchRowsAt`. Anyway, if you decide that it is worth it, you can use this [tutorial](https://andreygordeev.com/2017/02/20/uitableview-prefetching/) as an inspiration for implementing prefetching. Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use [`UITableViewDataSourcePrefetching`](https://developer.apple.com/documentation/uikit/uitableviewdatasourceprefetching) as you mentioned. It's a protocol that calls your prefetch data source when some cells are going to be displayed but are not on the screen yet. This way you can prepare all the resources that takes time to load before they are presented. You just have to implement: ``` func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) ``` and fetch the data related to the cells from all of the `indexpaths`. Beware it's only available since **iOS10**. --- I personally use AlamofireImage with a cache so images that have already been downloaded aren't fetched twice, there's plenty of alternatives but it's a good practice to use cached images on this kind of scenario. Upvotes: 0
2018/03/18
1,303
5,049
<issue_start>username_0: I want to apply positive or negative class as per the value in element which is part of v-for loop. Below given is the template ``` | {{value}} | ``` I want to add class named 'positive' if 'value>0' , else apply class 'negative'. What is the best way to do this?<issue_comment>username_1: **1.** (Re)creating a view objects during `cellForRowAt` is generally a bad practice. From the screenshot I assume that there is a limit to how many avatars are there on a single cell - I would recommend creating all the `UIImageView` objects in the cell initializer, and then in `presentFriends` just set images to them, and either hide the unused ones (`isHidden = true`) or set their alpha to 0 (of course, don't forget to unhide those that are used). **2.** If you are using SDWebImage to load images, implement `prepareForReuse` and cancel current downloads to get a bit of performance boost during scrolling, and prevent undefined behaviour (when you try to set another image while the previous one was not yet downloaded). Based on [this question](https://stackoverflow.com/questions/17222434/sdwebimage-cancel-download), [this one](https://stackoverflow.com/questions/22914624/how-to-cancel-download-with-sdwebimagedownloader) and [this one](https://stackoverflow.com/questions/17073240/is-there-any-way-to-stop-an-image-in-a-uiimageview-from-lazy-loading-with-sdwebi) I would expect something like: ``` override func prepareForReuse() { super.prepareForReuse() self.imageView.sd_cancelCurrentImageLoad() } Or you can use [this gist][4] for an inspiration. ``` **P.S.:** Also, you will have to count with some blinking, since the images are downloaded from web - there will always be some delay. By caching you can get instantly those that were already downloaded, but new ones will have delay - there is no way to prevent that (unless you preload all the images that can appear in tableView before presenting tableView). **P.S.2:** You can try to implement prefetching using `[UITableViewDataSourcePrefetching][6]`. This could help you out with blinking caused by downloading the avatars from web. This would make things a bit more complicated, but if you really want to remove that blinking you will have to get your hands dirty. First of all, as you can see from the documentation, `prefetchRowsAt` does not give you a cell object - thus you will have to prefetch images to your model object instead of simply using `sd_setImage` on the `UIImageView` object at a given cell. Maybe the aforementioned [gist](https://gist.github.com/keighl/6319942) would help you out with downloading images to model. Now also as the [documentation](https://developer.apple.com/documentation/uikit/uitableviewdatasourceprefetching) states: > > **Loading Data Asynchronously** > > > The `tableView(_:prefetchRowsAt:)` method is not necessarily called for every cell in the table view. Your implementation of `tableView(_:cellForRowAt:)` must therefore be able to cope with the following potential situations: > > > Data has been loaded via the prefetch request, and is ready to be displayed. > > > Data is currently being prefetched, but is not yet available. > > > Data has not yet been requested. > > > Simply said, when you are in `cellForRowAt`, you cannot rely on `prefetchRowsAt` being called - it might have been called, and it might not have been called (or maybe the call is in progress). Documentation continues to suggest using `Operation` as a backing tool for downloading the resources - `prefetchRowsAt` could create `Operation` objects that would be responsible for downloading avatars for a given row. `cellForRowAt` can then ask the model for the `Operation` objects for the given row - if there are not any, it means that `prefetchRowsAt` was not called for that row, and you have to create `Operation` objects at that point. Otherwise you can use the operations created by `prefetchRowsAt`. Anyway, if you decide that it is worth it, you can use this [tutorial](https://andreygordeev.com/2017/02/20/uitableview-prefetching/) as an inspiration for implementing prefetching. Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use [`UITableViewDataSourcePrefetching`](https://developer.apple.com/documentation/uikit/uitableviewdatasourceprefetching) as you mentioned. It's a protocol that calls your prefetch data source when some cells are going to be displayed but are not on the screen yet. This way you can prepare all the resources that takes time to load before they are presented. You just have to implement: ``` func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) ``` and fetch the data related to the cells from all of the `indexpaths`. Beware it's only available since **iOS10**. --- I personally use AlamofireImage with a cache so images that have already been downloaded aren't fetched twice, there's plenty of alternatives but it's a good practice to use cached images on this kind of scenario. Upvotes: 0
2018/03/18
668
2,500
<issue_start>username_0: Let's say I have a vector of values, and a vector of probabilities. I want to compute the percentile over the values, but using the given vector of probabilities. Say, for example, ``` import numpy as np vector = np.array([4, 2, 3, 1]) probs = np.array([0.7, 0.1, 0.1, 0.1]) ``` Ignoring `probs`, `np.percentile(vector, 10)` gives me `1.3`. However, it's clear that the lowest 10% here have value of `1`, so that would be my desired output. **If the result lies between two data points, I'd prefer linear interpolation as [documented for the original percentile function](https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.percentile.html)**. How would I solve this in Python most conveniently? As in my example, `vector` will not be sorted. `probs` always sums to `1`. I'd prefer solutions that don't require "non-standard" packages, by any reasonable definition.<issue_comment>username_1: One solution would be to use sampling via numpy.random.choice and then numpy.percentile: ``` N = 50 # number of samples to draw samples = np.random.choice(vector, size=N, p=probs, replace=True) interpolation = "nearest" print("25th percentile",np.percentile(samples, 25, interpolation=interpolation),) print("75th percentile",np.percentile(samples, 75, interpolation=interpolation),) ``` Depending on your kind of data (discrete or continuous) you may want to use different values for the `interpolation` parameter. Upvotes: 1 <issue_comment>username_2: If you're prepared to sort your values, then you can construct an interpolating function that allows you to compute the inverse of the probability distribution. This is probably more easily done with `scipy.interpolate` than with pure `numpy` routines: ``` import scipy.interpolate ordering = np.argsort(vector) distribution = scipy.interpolate.interp1d(np.cumsum(probs[ordering]), vector[ordering], bounds_error=False, fill_value='extrapolate') ``` If you interrogate this distribution with the percentile (in the range 0..1), you should get the answers you want, e.g. `distribution(0.1)` gives 1.0, `distribution(0.5)` gives about 3.29. A similar thing can be done with numpy's `interp()` function, avoiding the extra dependency on scipy, but that would involve reconstructing the interpolating function every time you want to calculate a percentile. This might be fine if you have a fixed list of percentiles that is known before you estimate the probability distribution. Upvotes: 3 [selected_answer]
2018/03/18
1,149
2,811
<issue_start>username_0: I have one large dataframe `df1` with many observations including the date of the observation. There are multiple observations for each date. I also have another dataframe `df2` which contains two variables, a date and a new variable I would like to add to `df1`, which we'll call `VarC`. We can assume there is only one observation per date in `df2`. Here's some simple example code: ``` df1Date <- as.Date(c('2010-11-1', '2010-11-1', '2010-11-2', '2010-11-2', '2010-11-2', '2010-11-2')) VarA <- c("Red", "Blue", "Green", "Yellow", "Orange", "Black") VarB <- c(1, 2, 3, 4, 5, 6) df1 <- data.frame(df1Date, VarA, VarB) df2date <- as.Date(c('2010-11-1','2010-11-2')) VarC <- c("Good Day", "Bad Day") df2 <- data.frame(df2date, VarC) ``` I would like to find an efficient way to add a new Variable `DayType` in `df1` which would be equal to a value selected from `VarC` matching the date in `df1`. In other words, I would like to go through each observation in `df1`, look up the date `df1Date` for the matching `df2date` in `df2`, and append the analagous value of `VarC` to my `df1` dataframe under a new variable `DayType`. I'm familiar with the dplyr::mutate function, but I don't know how to appropriately index into the dataframes to accomplish what I'm trying to do. The new variable `DayType` should look like: ``` DayType <- c("Good Day", "Good Day", "Bad Day", "Bad Day", "Bad Day", "Bad Day") ```<issue_comment>username_1: Just use `left join()` from the`dplyr` library Method: ``` df3 <- df1 %>% left_join(df2, by = c("df1Date" = "df2date")) ``` Output: ``` df3 df1Date VarA VarB VarC 1 2010-11-01 Red 1 Good Day 2 2010-11-01 Blue 2 Good Day 3 2010-11-02 Green 3 Bad Day 4 2010-11-02 Yellow 4 Bad Day 5 2010-11-02 Orange 5 Bad Day 6 2010-11-02 Black 6 Bad Day ``` Upvotes: 1 <issue_comment>username_2: Here is a base R solution using `merge`: ``` merge(df1, df2, by.x = "df1Date", by.y = "df2date"); # df1Date VarA VarB VarC #1 2010-11-01 Red 1 Good Day #2 2010-11-01 Blue 2 Good Day #3 2010-11-02 Green 3 Bad Day #4 2010-11-02 Yellow 4 Bad Day #5 2010-11-02 Orange 5 Bad Day #6 2010-11-02 Black 6 Bad Day ``` Upvotes: 1 <issue_comment>username_3: Since `OP` is looking for an `efficient` and `fast` way to get result hence my suggestion would be to use `left_join` approach using `data.table`. ``` library(data.table) setDT(df1) setDT(df2) #left_join in data.table way df1[df2, on=.(df1Date = df2date)] # df1Date VarA VarB VarC # 1: 2010-11-01 Red 1 Good Day # 2: 2010-11-01 Blue 2 Good Day # 3: 2010-11-02 Green 3 Bad Day # 4: 2010-11-02 Yellow 4 Bad Day # 5: 2010-11-02 Orange 5 Bad Day # 6: 2010-11-02 Black 6 Bad Day ``` Upvotes: 0
2018/03/18
299
1,212
<issue_start>username_0: I am doing a course in regression and I have to edit a certain jupyter notebook file as an assignment. However, at the end of each cell, they have put 'raise NotImplementedError()'. If I remove it, everything seems to work according to instruction. But if I leave it, naturally, I get an error. I'm not sure why they have done that. For example, this is the column where I have to separate my data: ``` bank_features = None # explanatory features - 16 total bank_output = None # output feature # YOUR CODE HERE raise NotImplementedError() ``` If I separate it without the error line, it works. But the error like breaks it. What should I do, should I just remove it? It's at the end of EVERY cell.<issue_comment>username_1: You have to remove it, it is a placeholder for you. If you forget to implement a part of the assignment, it will be obvious for you and the examiner to spot. Upvotes: 1 <issue_comment>username_2: ``` raise NotImplementedError() ``` is just there so you're reminded to *implement* the method (an empty stub would just do nothing and there would be bugs because some features aren't implemented) Of course, when you're done, remove this statement. Upvotes: 3
2018/03/18
902
3,530
<issue_start>username_0: I am using httpclient 4.5.5 i want to get large files upto 1 gb in response. But it seems like > > `CloseableHttpResponse response = httpClient.execute(httpGet); > HttpEntity entity = response.getEntity();` > > > This returns whole response so its not good to have whole response in memory. Is there any way to get response as stream?<issue_comment>username_1: Use `HttpURLConnection` instead of `httpClient`. ``` final HttpURLConnection conn = (HttpURLConnection)url.openConnection(); final int bufferSize = 1024 * 1024; conn.setChunkedStreamingMode(bufferSize); final OutputStream out = conn.getOutputStream(); ``` Upvotes: 0 <issue_comment>username_2: You need Apache Async Client. HttpAsyncClient is the ASYNC version of Apache HttpClient. Apache HttpClient construct the whole response in memory, while with HttpAsyncClient, you can define a Handler (Consumer) to process the response while receiving data. ``` https://hc.apache.org/httpcomponents-asyncclient-4.1.x/index.html ``` Here is an example from their official example code ``` package org.apache.http.examples.nio.client; import java.io.IOException; import java.nio.CharBuffer; import java.util.concurrent.Future; import org.apache.http.HttpResponse; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.nio.IOControl; import org.apache.http.nio.client.methods.AsyncCharConsumer; import org.apache.http.nio.client.methods.HttpAsyncMethods; import org.apache.http.protocol.HttpContext; /** * This example demonstrates an asynchronous HTTP request / response exchange with * a full content streaming. */ public class AsyncClientHttpExchangeStreaming { public static void main(final String[] args) throws Exception { CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try { httpclient.start(); Future future = httpclient.execute( HttpAsyncMethods.createGet("http://httpbin.org/"), new MyResponseConsumer(), null); Boolean result = future.get(); if (result != null && result.booleanValue()) { System.out.println("Request successfully executed"); } else { System.out.println("Request failed"); } System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); } static class MyResponseConsumer extends AsyncCharConsumer { @Override protected void onResponseReceived(final HttpResponse response) { } @Override protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException { while (buf.hasRemaining()) { System.out.print(buf.get()); } } @Override protected void releaseResources() { } @Override protected Boolean buildResult(final HttpContext context) { return Boolean.TRUE; } } } ``` Upvotes: 3 <issue_comment>username_3: Apache HttpClient as of version 4.0 (as well as Apache HttpAsyncClient) supports full content streaming for both incoming and outgoing HTTP messages. Use `HttpEntity` to get access to the underling content input stream ``` CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://myhost/tons-of-stuff"); try (CloseableHttpResponse response1 = client.execute(httpGet)) { final HttpEntity entity = response1.getEntity(); if (entity != null) { try (InputStream inputStream = entity.getContent()) { // do something useful with the stream } } } ``` Upvotes: 4
2018/03/18
347
1,200
<issue_start>username_0: What I am trying to do is to count all the files in a directory using shell script. For example, when execute the program, ``` ./test.sh project ``` it should count all the files in the folder called "project". But I am having trouble with the directory part. What I have done so far is, ``` #!/bin/bash directory=$1 count=ls $directory | wc -l echo "$folder has $count files" ``` but it does not work... Can anyone blow up my confusion please? Thanks!<issue_comment>username_1: You have an incorrect syntax while setting the count, for running nested commands in `bash` you need to use command-substitution using `$(..)` which runs the commands in a sub-shell and returns the restult ``` count=$(ls -- "$directory" | wc -l) ``` But never parse `ls` output in scripts for any purpose, use the more general purpose `find` command ``` find "$1" -maxdepth 1 -type f | wc -l ``` Check more about what `$(..)` form [Wiki Bash Hackers - Command substitution](http://wiki.bash-hackers.org/syntax/expansion/cmdsubst) Upvotes: 1 <issue_comment>username_2: ``` #!/bin/bash directory=$1 count=`ls $directory | wc -l` echo "$folder has $count files" ``` Upvotes: 0
2018/03/18
1,320
4,454
<issue_start>username_0: Have been suffering with this error the whole day. **Please don't mark this question as a duplicate.I have gone through many similar questions and none of the answers worked for me.** Full error : ``` Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'. > java.io.IOException: Can't write [E:\Educational\Career\Android\Projects \FirebaseTutorial\app\build\intermediates\multi-dex\debug\componentClasses.jar] (Can't read [C:\Users\Abhi\.gradle\caches\transforms-1\files-1.1\support-core-ui- 27.1.0.aar\167562b027fa4c1af2f69bce0de3dd43\jars\classes.jar(;;;;;;**.class)] (Duplicate zip entry [classes.jar:android/support/design/widget/CoordinatorLayout $Behavior.class])) ``` **Things I have already tried :** 1. Clean and Rebuild 2. Invalidate Caches and Restart 3. Deleted .gradle in my project folder and resynced the project. 4. Deleted whole .gradle of android studio (In Users/Username/.gradle) *almost 2.5Gb of data* and tried syncing again. 5. Added : `android {` `defaultConfig {` `multiDexEnabled true` `}}` to gradle file: **My full gradle files :** **app :** ``` apply plugin: 'com.android.application' android { compileSdkVersion 27 defaultConfig { applicationId "com.appz.abhi.firebasetutorial" minSdkVersion 19 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:27.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' implementation 'com.google.firebase:firebase-database:11.8.0' implementation 'com.google.firebase:firebase-storage:11.8.0' implementation 'com.google.firebase:firebase-auth:11.8.0' implementation 'com.firebaseui:firebase-ui-auth:3.2.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' } apply plugin: 'com.google.gms.google-services' ``` **Top level gradle :** ``` // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.google.gms:google-services:3.2.0' } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } ``` **This error occurred after adding firebase auth.** P.S : Removing firebase auth dependencies and rebuilding the project doesn't show any error. i.e Removing ``` implementation 'com.google.firebase:firebase-auth:11.8.0' implementation 'com.firebaseui:firebase-ui-auth:3.2.2' ``` removes the error, but i want firebase Auth in my project.<issue_comment>username_1: The supported Support library for `firebase-ui-auth:3.2.2` is 27.0.2 not 27.1.0 So change: ``` implementation 'com.android.support:appcompat-v7:27.1.0' ``` To ``` implementation 'com.android.support:appcompat-v7:27.0.2' ``` [FirebaseUi-Android releases](https://github.com/firebase/FirebaseUI-Android/releases) Upvotes: 2 [selected_answer]<issue_comment>username_2: As @Jagar explains in his answer, FirebaseUI 3.2.2 has [transitive dependencies](https://github.com/firebase/FirebaseUI-Android/releases) on Support Library 27.0.2. If you want to build with a different version of the Support Libraries, such as 27.1.0, you must follow the [instructions described in the documentation](https://github.com/firebase/FirebaseUI-Android#upgrading-dependencies) to add the appropriate libraries in your dependencies. In your case, for FirebaseUI Auth, these are: ``` implementation 'com.android.support:design:27.1.0' implementation 'com.android.support:customtabs:27.1.0' implementation 'com.android.support:cardview-v7:27.1.0' ``` Upvotes: 0
2018/03/18
681
1,467
<issue_start>username_0: Can someone please let me know how can I use Indian currency symbol in SAS program? Like we do for dollar as below ``` format Salary :dollar8.; ```<issue_comment>username_1: A similar format can be built like this: ``` %let inr=%sysfunc(unicode(\u20B9)); proc format; picture rupee low - <0 = '00,000,000,000,009.99)' (prefix="(&inr") 0 - high = '00,000,000,000,009.99 ' (prefix="&inr") ; run; ``` Which, applied as follows: ``` data test; format x rupee.; x=34341.12; output; x=-12343452435.44;output; x=0; output; run; ``` Gives: [![enter image description here](https://i.stack.imgur.com/2h9nA.png)](https://i.stack.imgur.com/2h9nA.png) Upvotes: 1 <issue_comment>username_2: **Using ASCII in HTML** ``` Rupee sign: ₹ ``` **Using UNICODE character in HTML** ``` Rupee sign: ₹ ``` **Using CSS** ``` .inr-sign::before{ content:"\20B9"; } // Or use with ::after .inr-sign::after{ content:"\20B9"; } ``` **Using Font Awesome** The icon name for rupee symbol is “fa-rupee-sign” ``` ``` **More Options** **Encoding** ``` HTML Entity: ₹ HTML Entity (hex): ₹ URL Escape Code: %E2%82%B9 UTF-8 (hex): 0xE2 0x82 0xB9 UTF-8 (binary): 11100010:10000010:10111001 UTF-16: 0x20B9 UTF-32: 0x000020B9 ``` **Source Code** ``` C, C++, and Java: "\u20B9" CSS Code: \20B9 JavaScript: "\u20B9" Perl: \x{20B9} Python 2: u"\u20B9" Python 3: \u20B9 Ruby: \u{20B9} ``` Upvotes: 0
2018/03/18
879
2,112
<issue_start>username_0: ``` import pandas as pd d = [{'col1' : ' B', 'col2' : '2015-3-06 01:37:57'}, {'col1' : ' A', 'col2' : '2015-3-06 01:39:57'}, {'col1' : ' A', 'col2' : '2015-3-06 01:45:28'}, {'col1' : ' B', 'col2' : '2015-3-06 02:31:44'}, {'col1' : ' B', 'col2' : '2015-3-06 03:55:45'}, {'col1' : ' B', 'col2' : '2015-3-06 04:01:40'}] df = pd.DataFrame(d) df['col2'] = pd.to_datetime(df['col2']) ``` For each row I want to count number of rows with same values of 'col1' and time within window of past 10 minutes before time of this row(include). I'm interested in **implementation** which work **fast** this source work very **slow** on big dataset: ``` dt = pd.Timedelta(10, unit='m') def count1(row): id1 = row['col1'] start_time = row['col2'] - dt end_time = row['col2'] mask = (df['col1'] == id1) & ((df['col2'] >= start_time) & (df['col2'] <= end_time)) return df.loc[mask].shape[0] df['count1'] = df.apply(count1, axis=1) df.head(6) col1 col2 count1 0 B 2015-03-06 01:37:57 1 1 A 2015-03-06 01:39:57 1 2 A 2015-03-06 01:45:28 2 3 B 2015-03-06 02:31:44 1 4 B 2015-03-06 03:55:45 1 5 B 2015-03-06 04:01:40 2 ``` Notice: column 'col2' is date sensitive, not only time<issue_comment>username_1: The problem is, that `apply` is very expensive. One option is to optimize the code via cython or with the use of numba. [This](https://pandas.pydata.org/pandas-docs/stable/enhancingperf.html) might be helpful. Another option is the following: 1. Create a column with timestamps from col2 2. Create a column with ids which group the timestamps by your 10 min criterium 3. Create a combined column with the previous created ids and col1 as in `df['time_ids'].map(str) + df['col1']` 4. Use `groupby` to determine the number of equal rows. Something like: `df.groupby(df['combined_ids']).size()` Upvotes: 2 <issue_comment>username_2: Try to use ``` df.col2=pd.to_datetime(df.col2) df.groupby([pd.Grouper(key='col2',freq='H'),df.col1]).size().reset_index(name='count') ``` Upvotes: 0
2018/03/18
2,476
6,685
<issue_start>username_0: I have used Embedded derby earlier in my spring boot projects. But now when i created the project through Spring Initializr with the derby dependency. I get the below error : **Schema 'SA' does not exist** followed by **org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement** When i tried running the earlier project that i had created, the Derby is working just fine. PFB the console for the earlier project : > > 2018-03-18 15:34:44.346 INFO 16560 --- [ restartedMain] > org.hibernate.cfg.Environment : HHH000021: Bytecode > provider name : javassist 2018-03-18 15:34:44.391 INFO 16560 --- [ > restartedMain] o.hibernate.annotations.common.Version : HCANN000001: > Hibernate Commons Annotations {5.0.1.Final} 2018-03-18 15:34:44.490 > \*\*INFO 16560 --- [ restartedMain] org.hibernate.dialect.Dialect > > : HHH000400: Using dialect: org.hibernate.dialect.DerbyDialect > 2018-03-18 15:34:44.497 WARN 16560 --- [ restartedMain] > org.hibernate.dialect.DerbyDialect : HHH000430: The DerbyDialect > dialect has been deprecated; use one of the version-specific dialects > \*\* instead 2018-03-18 15:34:45.094 INFO 16560 --- [ restartedMain] > org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl > schema export 2018-03-18 15:34:45.099 ERROR 16560 --- [ > restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: > Unsuccessful: drop table book 2018-03-18 15:34:45.099 ERROR 16560 --- > [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Schema > 'SA' does not exist 2018-03-18 15:34:45.129 WARN 16560 --- [ > restartedMain] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning > Code: 10000, SQLState: 01J01 2018-03-18 15:34:45.129 WARN 16560 --- [ > restartedMain] o.h.engine.jdbc.spi.SqlExceptionHelper : Database > 'memory:testdb' not created, connection made to existing database > instead. 2018-03-18 15:34:45.129 INFO 16560 --- [ restartedMain] > org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export > complete 2018-03-18 15:34:45.152 INFO 16560 --- [ restartedMain] > j.LocalContainerEntityManagerFactoryBean : Initialized JPA > EntityManagerFactory for persistence unit 'default' > > > The Console Log for my current spring boot with embedded derby : > > 2018-03-18 15:42:23.234 INFO 11312 --- [ main] > com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... > 2018-03-18 15:42:23.237 WARN 11312 --- [ main] > \*\*com.zaxxer.hikari.util.DriverDataSource : Registered driver with > driverClassName=org.apache.derby.jdbc.EmbeddedDriver was not found, > trying direct instantiation. 2018-03-18 15:42:23.844 INFO 11312 --- [ > \*\* main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver > does not support get/set network timeout for connections. (Feature not > implemented: No details.) 2018-03-18 15:42:23.847 INFO 11312 --- [ > > main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start > completed. 2018-03-18 15:42:23.937 INFO 11312 --- [ main] > j.LocalContainerEntityManagerFactoryBean : Building JPA container > EntityManagerFactory for persistence unit 'default' 2018-03-18 > 15:42:23.969 INFO 11312 --- [ main] > o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing > PersistenceUnitInfo [ name: default ...] 2018-03-18 15:42:24.136 > INFO 11312 --- [ main] org.hibernate.Version > > : HHH000412: Hibernate Core {5.2.14.Final} 2018-03-18 15:42:24.138 > INFO 11312 --- [ main] org.hibernate.cfg.Environment > > : HHH000206: hibernate.properties not found 2018-03-18 15:42:24.199 > INFO 11312 --- [ main] > o.hibernate.annotations.common.Version : HCANN000001: Hibernate > Commons Annotations {5.0.1.Final} 2018-03-18 15:42:24.380 INFO 11312 > --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.DerbyTenSevenDialect > 2018-03-18 15:42:25.572 WARN 11312 --- [ main] > o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget > encountered exception accepting command : Error executing DDL via JDBC > Statement > > > org.hibernate.tool.schema.spi.CommandAcceptanceException: Error > executing DDL via JDBC Statement at > org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) > ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final] at > org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:375) > [hibernate-core-5.2.14.Final.jar:5.2.14.Final] > > > The difference i can find between the two is that in the current log(abv log) it says that the **com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=org.apache.derby.jdbc.EmbeddedDriver was not found, trying direct instantiation.** Let me know if we need to configure something apart from the below dependency for enabling this derby. Note- I dint do anything apart from maven dependency in the previous project. Maven dependency : ``` org.apache.derby derby runtime ```<issue_comment>username_1: Please configure you JPA Configuration as per your requirement. I've configured as below. You need to add below configuration in application.properties file. ``` # PROFILES spring.profiles.active=dev # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error=false spring.datasource.generate-unique-name=false ``` Upvotes: 3 <issue_comment>username_2: The default driver used by derby is `org.apache.derby.jdbc.AutoloadedDriver`, but springboot and other framework choice `org.apache.derby.jdbc.EmbeddedDriver`. It causes the driver to be unable to find the driver when using the datasource for the first time. About `Schema 'SA' does not exist`. I think that you use the other tool connect the derby, such as **ij**. And the jdbc url they use is the same. It looks like the same database connected, but it's not actually. This is the key to the problem. Upvotes: 0 <issue_comment>username_3: add ```sh spring.jpa.hibernate.ddl-auto=update ``` to your ***`application.properties`*** it is by default create-drop. Upvotes: 2 <issue_comment>username_4: Added this in appplication.properties and worked ``` spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true ``` Upvotes: 0 <issue_comment>username_5: I've added below property in application.properties, it worked! ``` spring.jpa.hibernate.ddl-auto=update ``` Upvotes: 0
2018/03/18
681
2,325
<issue_start>username_0: I have the following code: ``` x = range(100) M = len(x) sample=np.zeros((M,41632)) for i in range(M): lista=np.load('sample'+str(i)+'.npy') for j in range(41632): sample[i,j]=np.array(lista[j]) print i ``` to create an array made of sample\_i numpy arrays. sample0, sample1, sample3, etc. are numpy arrays and my expected output is a Mx41632 array like this: ``` sample = [[sample0],[sample1],[sample2],...] ``` How can I compact and make more quick this operation without loop for? M can reach also 1 million. Or, how can I append my sample array if the starting point is, for example, 1000 instead of 0? Thanks in advance<issue_comment>username_1: Please configure you JPA Configuration as per your requirement. I've configured as below. You need to add below configuration in application.properties file. ``` # PROFILES spring.profiles.active=dev # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error=false spring.datasource.generate-unique-name=false ``` Upvotes: 3 <issue_comment>username_2: The default driver used by derby is `org.apache.derby.jdbc.AutoloadedDriver`, but springboot and other framework choice `org.apache.derby.jdbc.EmbeddedDriver`. It causes the driver to be unable to find the driver when using the datasource for the first time. About `Schema 'SA' does not exist`. I think that you use the other tool connect the derby, such as **ij**. And the jdbc url they use is the same. It looks like the same database connected, but it's not actually. This is the key to the problem. Upvotes: 0 <issue_comment>username_3: add ```sh spring.jpa.hibernate.ddl-auto=update ``` to your ***`application.properties`*** it is by default create-drop. Upvotes: 2 <issue_comment>username_4: Added this in appplication.properties and worked ``` spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true ``` Upvotes: 0 <issue_comment>username_5: I've added below property in application.properties, it worked! ``` spring.jpa.hibernate.ddl-auto=update ``` Upvotes: 0
2018/03/18
650
2,420
<issue_start>username_0: Actually i want to return true if set1 contains some values(b and d) of set2. If any one value exist in any of the set then it should return true ``` class TreeSetExample{ public static void main(String[] args){ TreeSet set1 = new TreeSet(); TreeSet set2 = new TreeSet(); set1.add("a"); set1.add("b"); set1.add("d"); set1.add("e"); set2.add("c"); set2.add("b"); set2.add("d"); set2.add("g"); boolean b1 = set1.contains(set2);// here i am getting classCastException } } ``` I know that contains will accept only object not collection. So is there any way to check the values between two treeset.<issue_comment>username_1: Please configure you JPA Configuration as per your requirement. I've configured as below. You need to add below configuration in application.properties file. ``` # PROFILES spring.profiles.active=dev # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error=false spring.datasource.generate-unique-name=false ``` Upvotes: 3 <issue_comment>username_2: The default driver used by derby is `org.apache.derby.jdbc.AutoloadedDriver`, but springboot and other framework choice `org.apache.derby.jdbc.EmbeddedDriver`. It causes the driver to be unable to find the driver when using the datasource for the first time. About `Schema 'SA' does not exist`. I think that you use the other tool connect the derby, such as **ij**. And the jdbc url they use is the same. It looks like the same database connected, but it's not actually. This is the key to the problem. Upvotes: 0 <issue_comment>username_3: add ```sh spring.jpa.hibernate.ddl-auto=update ``` to your ***`application.properties`*** it is by default create-drop. Upvotes: 2 <issue_comment>username_4: Added this in appplication.properties and worked ``` spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true ``` Upvotes: 0 <issue_comment>username_5: I've added below property in application.properties, it worked! ``` spring.jpa.hibernate.ddl-auto=update ``` Upvotes: 0
2018/03/18
640
2,257
<issue_start>username_0: I am trying to auto update a website from remote git repo. As it's on a shared hosting i use a webhook on github & phpseclib 1.0. Here is my code: ``` $ssh = new Net_SSH2(SITE_DOMAIN); $key = new Crypt_RSA(); $key->loadKey(file_get_contents('/home/'.SSH_USERNAME.'/.ssh/'.KEYPAIR_NAME)); if (!$ssh->login(SSH_USERNAME, $key)) { throw new Exception('Failed to login'); exit('Login Failed'); } echo $ssh->write("cd ~/source\n"); echo $ssh->write("git pull origin master\n"); ``` the git command won't run. but when i do a git pull manually from terminal it works Thanks for your help<issue_comment>username_1: Please configure you JPA Configuration as per your requirement. I've configured as below. You need to add below configuration in application.properties file. ``` # PROFILES spring.profiles.active=dev # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error=false spring.datasource.generate-unique-name=false ``` Upvotes: 3 <issue_comment>username_2: The default driver used by derby is `org.apache.derby.jdbc.AutoloadedDriver`, but springboot and other framework choice `org.apache.derby.jdbc.EmbeddedDriver`. It causes the driver to be unable to find the driver when using the datasource for the first time. About `Schema 'SA' does not exist`. I think that you use the other tool connect the derby, such as **ij**. And the jdbc url they use is the same. It looks like the same database connected, but it's not actually. This is the key to the problem. Upvotes: 0 <issue_comment>username_3: add ```sh spring.jpa.hibernate.ddl-auto=update ``` to your ***`application.properties`*** it is by default create-drop. Upvotes: 2 <issue_comment>username_4: Added this in appplication.properties and worked ``` spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true ``` Upvotes: 0 <issue_comment>username_5: I've added below property in application.properties, it worked! ``` spring.jpa.hibernate.ddl-auto=update ``` Upvotes: 0
2018/03/18
499
1,859
<issue_start>username_0: How could I show a `JOptionPane` at the beginning of a certain function, by having for example, "Working...", and then programmatically dismiss it at the end of said function/piece of code?<issue_comment>username_1: Please configure you JPA Configuration as per your requirement. I've configured as below. You need to add below configuration in application.properties file. ``` # PROFILES spring.profiles.active=dev # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error=false spring.datasource.generate-unique-name=false ``` Upvotes: 3 <issue_comment>username_2: The default driver used by derby is `org.apache.derby.jdbc.AutoloadedDriver`, but springboot and other framework choice `org.apache.derby.jdbc.EmbeddedDriver`. It causes the driver to be unable to find the driver when using the datasource for the first time. About `Schema 'SA' does not exist`. I think that you use the other tool connect the derby, such as **ij**. And the jdbc url they use is the same. It looks like the same database connected, but it's not actually. This is the key to the problem. Upvotes: 0 <issue_comment>username_3: add ```sh spring.jpa.hibernate.ddl-auto=update ``` to your ***`application.properties`*** it is by default create-drop. Upvotes: 2 <issue_comment>username_4: Added this in appplication.properties and worked ``` spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true ``` Upvotes: 0 <issue_comment>username_5: I've added below property in application.properties, it worked! ``` spring.jpa.hibernate.ddl-auto=update ``` Upvotes: 0
2018/03/18
572
2,070
<issue_start>username_0: I have this form ```html ``` and this validation ```js if ($("#name").val() == "") { return false; } return true; ``` what I am trying to do, is to disable the submit button, I tried to use submit function for the form but its not triggered, the problem is I don't have access to html or js files, only one custom.js file I can add or override other functions. anyone can help me ? Thanks<issue_comment>username_1: Please configure you JPA Configuration as per your requirement. I've configured as below. You need to add below configuration in application.properties file. ``` # PROFILES spring.profiles.active=dev # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error=false spring.datasource.generate-unique-name=false ``` Upvotes: 3 <issue_comment>username_2: The default driver used by derby is `org.apache.derby.jdbc.AutoloadedDriver`, but springboot and other framework choice `org.apache.derby.jdbc.EmbeddedDriver`. It causes the driver to be unable to find the driver when using the datasource for the first time. About `Schema 'SA' does not exist`. I think that you use the other tool connect the derby, such as **ij**. And the jdbc url they use is the same. It looks like the same database connected, but it's not actually. This is the key to the problem. Upvotes: 0 <issue_comment>username_3: add ```sh spring.jpa.hibernate.ddl-auto=update ``` to your ***`application.properties`*** it is by default create-drop. Upvotes: 2 <issue_comment>username_4: Added this in appplication.properties and worked ``` spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true ``` Upvotes: 0 <issue_comment>username_5: I've added below property in application.properties, it worked! ``` spring.jpa.hibernate.ddl-auto=update ``` Upvotes: 0
2018/03/18
685
2,413
<issue_start>username_0: I am trying to load images from folder via jquery and ajax and I'm using the solution provided [here](https://stackoverflow.com/questions/18480550/how-to-load-all-the-images-from-one-of-my-folder-into-my-web-page-using-jquery). However, this throws a 404 error - even though the directory definitely exists, and I even can access the files in it. Here's the jquery code: ``` $(document).ready(function () { var folder = "images/"; $.ajax({ url: folder, success: function (data) { $(data).find("a").attr("href", function (i, val) { if (val.match(/\.(jpe?g|png|gif)$/)) { $('#galerie').append('[![](' + folder + val + ')](resources/img/header_bg.jpg)') } }); } }); }); ```<issue_comment>username_1: Please configure you JPA Configuration as per your requirement. I've configured as below. You need to add below configuration in application.properties file. ``` # PROFILES spring.profiles.active=dev # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error=false spring.datasource.generate-unique-name=false ``` Upvotes: 3 <issue_comment>username_2: The default driver used by derby is `org.apache.derby.jdbc.AutoloadedDriver`, but springboot and other framework choice `org.apache.derby.jdbc.EmbeddedDriver`. It causes the driver to be unable to find the driver when using the datasource for the first time. About `Schema 'SA' does not exist`. I think that you use the other tool connect the derby, such as **ij**. And the jdbc url they use is the same. It looks like the same database connected, but it's not actually. This is the key to the problem. Upvotes: 0 <issue_comment>username_3: add ```sh spring.jpa.hibernate.ddl-auto=update ``` to your ***`application.properties`*** it is by default create-drop. Upvotes: 2 <issue_comment>username_4: Added this in appplication.properties and worked ``` spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true ``` Upvotes: 0 <issue_comment>username_5: I've added below property in application.properties, it worked! ``` spring.jpa.hibernate.ddl-auto=update ``` Upvotes: 0
2018/03/18
666
2,347
<issue_start>username_0: I'm doing a lot of calculations writing the results to a file. Using multiprocessing I'm trying to parallelise the calculations. Problem here is that I'm writing to one output file, which all the workers are writing too. I'm quite new to multiprocessing, and wondering how I could make it work. A very simple concept of the code is given below: ``` from multiprocessing import Pool fout_=open('test'+'.txt','w') def f(x): fout_.write(str(x) + "\n") if __name__ == '__main__': p = Pool(5) p.map(f, [1, 2, 3]) ``` The result I want would be a file with: > > 1 2 3 > > > However now I get an empty file. Any suggestions? I greatly appreciate any help :)!<issue_comment>username_1: Please configure you JPA Configuration as per your requirement. I've configured as below. You need to add below configuration in application.properties file. ``` # PROFILES spring.profiles.active=dev # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error=false spring.datasource.generate-unique-name=false ``` Upvotes: 3 <issue_comment>username_2: The default driver used by derby is `org.apache.derby.jdbc.AutoloadedDriver`, but springboot and other framework choice `org.apache.derby.jdbc.EmbeddedDriver`. It causes the driver to be unable to find the driver when using the datasource for the first time. About `Schema 'SA' does not exist`. I think that you use the other tool connect the derby, such as **ij**. And the jdbc url they use is the same. It looks like the same database connected, but it's not actually. This is the key to the problem. Upvotes: 0 <issue_comment>username_3: add ```sh spring.jpa.hibernate.ddl-auto=update ``` to your ***`application.properties`*** it is by default create-drop. Upvotes: 2 <issue_comment>username_4: Added this in appplication.properties and worked ``` spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.database=default spring.jpa.show-sql=true ``` Upvotes: 0 <issue_comment>username_5: I've added below property in application.properties, it worked! ``` spring.jpa.hibernate.ddl-auto=update ``` Upvotes: 0
2018/03/18
784
2,118
<issue_start>username_0: I have a data frame consisting of 400 rows of x, y and z values, and I would like to plot the x column against the y column. This is what I have got so far: ``` sample3d = function(n) { df = data.frame() while(n>0) { X = runif(1,-1,1) Y = runif(1,-1,1) Z = runif(1,-1,1) a = X^2 + Y^2 + Z^2 if( a < 1 ) { b = (X^2+Y^2+Z^2)^(0.5) vector = data.frame(X = X/b, Y = Y/b, Z = Z/b) df = rbind(vector,df) n = n- 1 } } df } sample3d(400) ```<issue_comment>username_1: I named the dataframe your function creates `data` (`data <- sample3d(400)`). Then, if you need a scatterplot (points at x and y coordinates) of the X and Y column, you can use base R's function `plot()`. e.g. `plot(x = data$X, y = data$Y)`. If you are like me and don't want to type `data$` before every column you can make the columns available to functions as vectors by wrapping everything inside `with(data = data, {...})`. If you want to create a scatterplot of all three coordinates, you might want to check out the packages in the following two examples: ``` library(scatterplot3d) with(data = data, { scatterplot3d(x = X, y = Y, z = Z) }) library(rgl) with(data, { plot3d(X, Y, Z) }) ``` Upvotes: 0 <issue_comment>username_2: If you need to draw random points on the surface of a sphere, you need just to extract the polar coordinates. Something like that: ``` sample3d_v2 <- function(n) { phi<-runif(n,0,2*pi) cost<-runif(n,-1,1) sint<-sqrt(1-cost^2) data.frame(X=sint*cos(phi),Y=sint*sin(phi),Z=cost) } ``` Just some tests: ``` system.time(old<-sample3d(4000)) # user system elapsed # 3.895 0.000 3.879 system.time(new<-sample3d_v2(4000)) # user system elapsed # 0.000 0.000 0.002 ``` As you can see, a gain of thousands of times. Test the results are correct: ``` require(rgl) plot3d(old) open3d();plot3d(new) ``` Regarding your question: just name the object resulting for your function and plot the X and Y components. ``` data<-sample3d_v2(400) plot(data$X,data$Y) ``` Upvotes: 2 [selected_answer]
2018/03/18
809
2,483
<issue_start>username_0: i'm trying to make right click> search by image for website, but source images will be 1 specific website only, so website needs only "images1/image1" from "<http://example.com/images1/img1.jpg>" ``` var url = 'example.com/search/'; chrome.contextMenus.onClicked.addListener(function(info, tab){ chrome.tabs.create({ url: url + encodeURIComponent(info.srcUrl), index: tab.index + 1 }) }); var onInitialize = function(){ chrome.contextMenus.create({ title: 'Search by image', contexts: ['image'], targetUrlPatterns: ['https://*/*', 'http://*/*'], id: 'contextMenu' }); }; ``` this code results in "example.com/search/<https://sourceimageexample.com/images/img1.jpg>" it should look like "example.com/search/images1/img1/ solutions i found online didn't work or i couldn't make it work, any help? xD<issue_comment>username_1: I named the dataframe your function creates `data` (`data <- sample3d(400)`). Then, if you need a scatterplot (points at x and y coordinates) of the X and Y column, you can use base R's function `plot()`. e.g. `plot(x = data$X, y = data$Y)`. If you are like me and don't want to type `data$` before every column you can make the columns available to functions as vectors by wrapping everything inside `with(data = data, {...})`. If you want to create a scatterplot of all three coordinates, you might want to check out the packages in the following two examples: ``` library(scatterplot3d) with(data = data, { scatterplot3d(x = X, y = Y, z = Z) }) library(rgl) with(data, { plot3d(X, Y, Z) }) ``` Upvotes: 0 <issue_comment>username_2: If you need to draw random points on the surface of a sphere, you need just to extract the polar coordinates. Something like that: ``` sample3d_v2 <- function(n) { phi<-runif(n,0,2*pi) cost<-runif(n,-1,1) sint<-sqrt(1-cost^2) data.frame(X=sint*cos(phi),Y=sint*sin(phi),Z=cost) } ``` Just some tests: ``` system.time(old<-sample3d(4000)) # user system elapsed # 3.895 0.000 3.879 system.time(new<-sample3d_v2(4000)) # user system elapsed # 0.000 0.000 0.002 ``` As you can see, a gain of thousands of times. Test the results are correct: ``` require(rgl) plot3d(old) open3d();plot3d(new) ``` Regarding your question: just name the object resulting for your function and plot the X and Y components. ``` data<-sample3d_v2(400) plot(data$X,data$Y) ``` Upvotes: 2 [selected_answer]
2018/03/18
695
2,431
<issue_start>username_0: I know variations of this have been asked hundreds of times, but after searching and reading dozens of similar questions am being particularly thick and i can't come close to working out the whys and hows of it happening, so at the risk of being shot down in flames... Troubleshooting it i trimmed down everything to the most basic, so i got a html of the form ``` - ``` if i put down a jquery function as ``` $('.field').on('mouseenter',function(){console.log(this.id)}); ``` it returns the id fine, but if i declare and call a function such as ``` function shade(){ console.log(this.id); }; $('.field').on('mouseenter',function(){shade()}); ``` it returns 'undefined'. Also tried within shade() passing the id as a 'var', using .attr(), etc. in case it made a difference to no avail. Anyone can point me on what i'm doing wrong 'for dummies' before i just give up and declare the id as a global variable within the mouseenter would be much appreciated. Thanks!<issue_comment>username_1: You should use [call()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) ```js function shade(){ console.log(this.id); }; $('.field').on( 'mouseenter', function(){ shade.call(this) } ); ``` ```html - hover me ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I see a big problem : `this` seems to be the current item in jQuery. Here are 2 solutions : 1- You can set a `this` var : var this = $('.field'); this.on('mouseenter',function(){console.log(this.id)}); 2- when you want to use the current DOM cibling item in jQuery, do not user `this`, but use `$(this)` instead, with the `$`. Upvotes: 0 <issue_comment>username_3: **jQuery**: The reason for this is when your using jQuery your using a function that is settings this as the event rather than the DOM Element. See the following output: ```js function shade(){ console.log(this); }; $('.field').on('mouseenter',function(){shade()}); ``` ```html - ``` You will need to use the traditional JavaScript as a work around. ```js function myId(el){ console.log (el.id); } ``` ```css .area{ width: 50%; height: 5em; background: lime; margin: 0 auto} ``` Or refer to the class item as others have suggested (I will not add that to my answer as I feel others should be given credit for providing you with the solution) Upvotes: 0
2018/03/18
980
3,289
<issue_start>username_0: This is the task: * Display the usage message "Please input test scores with values between 0-100. * Enter 999 to finish." * Accept test scores within the range 0-100. If the number is out of range, display the message "Invalid Test Score", disregard that input and continue collecting values * Stop collecting test scores when the user inputs the number 999 * Once all values have been entered, display the number of scores entered, the lowest score, the highest score, and the average. Sample output for input: `57 -2 98 13 85 77 999` And this is my solution: ``` import java.util.Scanner; public class TestScoreStatistics { public static void main(String[] args) { int max=0; int min=999; int avg=0; int count=0; int sum=0; int num; Scanner scan=new Scanner(System.in); System.out.println("Please input test scores with values between 0-100.\nEnter 999 to finish."); num=scan.nextInt(); int temp=num; do { if(num==999) System.exit(0); if(num>=0 && num<=100) { count++; sum+=num; if(num>max ) max=num; if(num ``` but when input is 999 the output should be Test Statistics: Number of Tests: 0 Lowest: 0 Highest: 0 Average: 0 how do I do that?<issue_comment>username_1: You might want to consider changing: ``` if(num==999) System.exit(0); ``` to: ``` if(num==999) break; ``` It will cause exiting `do-while` loop instead of finishing a program when your first input is "`999`". The problem you will need to solve then is dividing by 0 here: ``` System.out.printf("Average: " + sum/count); ``` You can change it to something like this: ``` if (count == 0) { System.out.printf("Average: 0"); // Show average as 0 here, when count is equal to 0. } else { System.out.printf("Average: " + sum / count); } ``` or something similar what you need to perform instead of dividing by 0 there. Upvotes: 0 <issue_comment>username_2: This is what i would do. If it is as assigment for your programming classes, I would suggest replacing the lines with collections etc. with some other code (you can find that on stackoverflow) ``` List scores = new ArrayList<>(); Scanner scan = new Scanner(System.in); System.out.println("Please input test scores with values between 0-100. Enter 999 to finish."); int num = scan.nextInt(); do { if (num == 999) break; if (num >= 0 && num <= 100) { scores.add(num); } } while ((num = scan.nextInt()) != 999); if (scores.size() != 0) { System.out.println("Test Statistics:"); System.out.println("Number of tests: " + scores.size()); System.out.println("Lowest: " + scores.indexOf(Collections.min(scores))); System.out.println("Highest: " + scores.indexOf(Collections.max(scores))); System.out.printf("Average: " + scores.stream().mapToInt(Integer::intValue).sum() / scores.size()); } else { System.out.println("Test Statistics:"); System.out.println("Number of tests: 0"); System.out.println("Lowest: 0 \*or write whatever you want here"); System.out.println("Highest: 0"); System.out.printf("Average: 0"); } ``` Upvotes: 2
2018/03/18
1,084
3,726
<issue_start>username_0: Im trying to create a Login but everytime I type my credentials and click on Login, I get "No database selected" Here is my PHP code ``` php define('DB_HOST', 'localhost'); define('DB_NAME', 'phplogin'); define('DB_USER','adminuser'); define('DB_PASSWORD','<PASSWORD>'); $con=mysql_connect(DB_HOST,DB_USER, "") //$mysql_select_db = 'phplogin' //or die("Failed to connect to MySQL: " . mysql_error()); //$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error()); $ID = $_POST['user']; $Password = $_POST['pass']; function SignIn() { session_start(); if(!empty($_POST['user'])) { $query = mysql_query("SELECT * FROM phplogin where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error()); $row = mysql_fetch_array($query) or die(mysql_error()); if(!empty($row['userName']) AND !empty($row['pass'])) { $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; } else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY..."; } } } if(isset($_POST['submit'])) { SignIn(); } ? ``` Where is the mistake? Kind regards newbie<issue_comment>username_1: Use pdo for prevent sql injection. **You mistake this** ``` mysql_select_db('database', $con) or die(mysql_error()); ``` **`Mysql` not available in php7. You can use mysqli or pdo.** ``` $servername = "localhost"; $username = "username"; $password = "<PASSWORD>"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ``` Upvotes: 0 <issue_comment>username_2: You forgot to pass the variable $con as the link parameter. ``` mysql_select_db('database', $con) or die(mysql_error()); ``` Upvotes: 1 <issue_comment>username_3: I would really recommend you to use classes, methods and most importantly **PDOs**. The use of "unescaped" mysqli is very insecure and vulnerable due to SQL injections. Also, when storing passwords into your DB, hash them using the PHP function `password_hash($password, PASSWORD_DEFAULT)`; This will generate a hash string that you can store in your DB. That SignIn with the use of PDO and `password_hash()` and `password_verify()` *to verify the password* would look the following: **Class DataBase (DB)** (db.php) ``` class DB { private $error; private $db; function Conn() { try { $this->db = new PDO('mysql:host=localhost;dbname=phplogin;', 'adminuser', 'adminuser'); //second adminuser is password return $this->db; //Returns PDO object } catch(PDOException $ex){ return $ex->getMessage(); } } } ``` **Your login.php** (login.php) ``` require_once('db.php'); $db = new DB(); //Create instance of DB class $conn = $db->Conn(); //Call Conn() method of DB class $username = $_POST["user"]; $password = $_POST["<PASSWORD>"]; $statement = $conn->prepare("SELECT * FROM phplogin where userName = :user"); $statement->execute(array(":user"=>$username)); //For :user in SQL query it enters the username you entered in the login form (bind param) $row = $statement->fetch(); //Returns the row from DB //password_verify() checks if the password you've enteres matches the hash in the DB //$row["pass"] is the hash you get returned from the SQL query aboth if(password_verify($password, $row["pass"])){ return true; //Or echo "success" } else{ return false; //Or echo "Wrong username/password" } ``` I hope I was able to help you :) Upvotes: 0
2018/03/18
721
2,898
<issue_start>username_0: I am trying to get some data from my server via HttpClient Post request. the request completes well. it returns the desired data. this process is handled by a service. this service in turn returns the data to the method calling from a component. the problem here is the service receives the data successfully but the method calling the service does not receive the data in the first request. it does receive the data from the second request onwards. I dont understand why. can someone make the component receive the data in the very first request? Here is the code **AuthorizationService.ts** ``` import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { ServerResponse } from './login/server-repsonse'; import { Observable } from 'rxjs/Observable'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable() export class AuthenticationService { constructor(private http:HttpClient) { } response:ServerResponse; public obtainAccessToken(user):ServerResponse{ this.http.post("/login",user,httpOptions).subscribe( data=> { this.response= data; console.log("In the service...."); console.log(this.response); }, err=>{ console.log(err)}, ()=>{console.log("Success")} ); return this.response; } } ``` **LoginComponent.ts** ``` @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { private user = new User(); private serverResponse: ServerResponse; constructor(private authenticationService: AuthenticationService) { } ngOnInit() { } login() { this.serverResponse = this.authenticationService.obtainAccessToken(this.user); console.log("In the login component...."); console.log(this.serverResponse); } } ``` **[Here is a screenshot](https://i.stack.imgur.com/PAD8h.png)**<issue_comment>username_1: it's because of javascript's asynchronous functions, your `obtainAccessToken` called before getting response from server, you should use [promises](https://codecraft.tv/courses/angular/es6-typescript/promises/) for your services . Upvotes: 0 <issue_comment>username_2: @Arul, In general, the services must be return only an observable (we not subscribe in the service, we subscribe in the component) ``` //your service public obtainAccessToken(user):ServerResponse{ //just return a "observable" return this.http.post("/login",user,httpOptions) } //Your component //Your component is who take account of the observable login() { this.authenticationService.obtainAccessToken(this.user).subscribe(res=>{ this.serverResponse=res; console.log(this.serverResponse) //<--here have value }); console.log(this.serverResponse); //Outside subscribe have NO value } ``` Upvotes: 2