date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/16
559
2,045
<issue_start>username_0: I purchased a wordpress theme, which came with custom plugin, that allows custom posts, which is titled 'tour'. The permalink to view the custom post currently is site.com/tour/post-name I am trying to change the /tour/ so I have updated all the code in the files of the plugin folder from 'tour' to 'visa'. I also went to my database and changed all my posts from wp\_posts and updated the post\_type from `tour` to `visa`. Now the custom posts show in my posts section as it should, but when i go to mysite.com/visa/post-name it goes to my 404 page. Am i missing something? do i need to change anything else? thanks<issue_comment>username_1: You need to import the projects into Eclipse, regardless of whether you pasted the files into the work space. Go to File>Import, choose the type of project it is that you want to import, and follow the prompts. [Here is a simple tutorial.](http://help.eclipse.org/kepler/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Ftasks%2Ftasks-importproject.htm) Also, maybe look into using version control such as git. Here are some resources on that. I really like TortoiseGit. [Git for Beginners](https://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) [TortoiseGit](https://tortoisegit.org/) Upvotes: 1 <issue_comment>username_2: 1. *Paste* your Java folder/directory that contain the source code in your home folder. 2. *Create* a new project in Eclipse, or simply *use an existing project.* 3. *Right-click* on the project tag. Or simply click on **File** and then **Import**. 4. *Select Import*, and follow up until you reach your saved Java folder/directory with the source code. Upvotes: 0 <issue_comment>username_3: you can follow the below steps. a. Right click on your project and click **export**. b. select **file system** and save in desktop or u r preferred loc. c. In Linux eclipse menu click **file** and select **import** option. d. select **existing projects in to workspace** and give the project path. Upvotes: 1 [selected_answer]
2018/03/16
1,092
3,760
<issue_start>username_0: **for those not into reading 20 comments to look for the answer. here is what worked for me:** 1. the tableView is View Based, not Cell Based (attributes inspector) 2. tableView.reloadData() wasn’t fast enough. using insertRow(at[0]:withAnimation:.leftSlide) instead worked fine 3. make sure that the NSTextField as well as the NSTextFieldCell are editable (attributes inspector) the final code: ``` tableViewAlarms.insertRows(at: [0], withAnimation: .effectFade) let keyView = tableViewAlarms.view(atColumn: 0, row: 0, makeIfNecessary: false) as! NSTableCellView self.view.window!.makeFirstResponder(keyView.textField) ``` **the question:** got one question. I have been stuck for some time making my NSTableView work the way I want it to. I'm a beginner and working with classes, inheritance, and views is giving me a lot of trouble. [screenshot, the NSTextField is activated](https://i.stack.imgur.com/Si3mm.png) you add a row to the NSTableView by pushing the '+' button. the NSTextField in the first tableColumn is editable and begins editing when double-clicked now I want the NSTextField in the first column to be activated automatically (show cursor, responding to text input via keyboard) when a row is added. so far i have tried: ``` class NSTextFieldSubClass: NSTextField { override func becomeFirstResponder() -> Bool { return true } } ``` I also played around with the bindings of the cell (or the NSTextField itself to be precise), but since I don't really know my way around those it went nowhere what I think is the way to go: make the NSTextField the firstResponder when the cell is created, but I don't know how. Any help is greatly appreciated!! also: how exactly is the state of an NSTextField called when the cursor is blinking? edit: as for the subclass, this is all I tried: ``` class NSTextFieldSubClass: NSTextField { override func becomeFirstResponder() -> Bool { return true } } ``` edit screenshot: [![these are the connections](https://i.stack.imgur.com/UHBF3.png)](https://i.stack.imgur.com/UHBF3.png) edit2: [![edit2: attributes inspector tableView](https://i.stack.imgur.com/pipHO.png)](https://i.stack.imgur.com/pipHO.png) edit3: [![edit3: bindings NSTextField](https://i.stack.imgur.com/vpdvE.png)](https://i.stack.imgur.com/vpdvE.png) edit4: [![edit4: error](https://i.stack.imgur.com/kgPPY.png)](https://i.stack.imgur.com/kgPPY.png)<issue_comment>username_1: At the end of the action method of the '+' button, after adding the row do: ``` DispatchQueue.main.async(execute: { // get the cell view let view = self.tableView.view(atColumn: 0, row: row, makeIfNecessary: false) if let cellView = view as? NSTableCellView { // get the text field if let textField = cellView.textField { // make the text field first responder if textField.acceptsFirstResponder { self.tableView.selectRowIndexes(IndexSet(integer:row), byExtendingSelection: false) self.tableView.window?.makeFirstResponder(textField) } } } }) ``` Upvotes: 2 <issue_comment>username_2: Don't subclass `NSTextField`. You can make the text field in a view based table view first responder right out of the box. It's pretty easy. Assuming you know `row` and `column` (in your example row 0 and column 0) get the table cell view with `view(atColumn: 0, row` and make the text field first responder. ``` let keyView = tableView.view(atColumn: 0, row: 0, makeIfNecessary: false) as! NSTableCellView view.window!.makeFirstResponder(keyView.textField) ``` And what is the second outlet for? Just use the standard default `textField`. Upvotes: 3 [selected_answer]
2018/03/16
826
2,661
<issue_start>username_0: I wish to put an image after a few items in a Wordpress site. I don't want to place an image after all similar items, only specific ones. Thankfully each specific item generates it's own css class. I thought using `:after` would be the answer but i'm failing somewhere. ``` ##### Onion Soup €4.50 ``` I want to place the image after "Onion Soup" So I tried this approach to target specifically `#menu_4212`: ``` #menu_4212.menu_post.menu_title::after { content: url('..images/gluten_free.png') } ``` I think i may have got the div hierarchy wrong, any ideas would be great.<issue_comment>username_1: If you want to do this, you can give your `:after` pseudo-element some `display` property and also specify it's dimensions. Then put image on the background. It will give you some flexibility for styling the image. Something like this (style to your own needs): ``` #menu_4212 .menu_post .menu_title::after { content: ''; display: block; width: 30px; height: 30px; background: url('..images/gluten_free.png') no-repeat center center; background-size: cover; } ``` Upvotes: 0 <issue_comment>username_2: Try: ``` #menu_4212 .menu_post .menu_title::after { content: url('..images/gluten_free.png') } ``` Your current code assumes the ID & 2 classes are all on the same element. You want to use the "[descendant](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_selectors)" syntax instead. Upvotes: 1 <issue_comment>username_3: Technically you cannot insert an image tag in between the two tags via CSS, let's say: ``` .menu_title::after { content: "NEW"; } ``` That will insert it to `Onion SoupNEW` It will be the same if you're trying to insert an image: ``` .menu_title::after { content: url('..images/gluten_free.png'); } ``` The problem is your selectors `#menu_4212.menu_post.menu_title::after`, it targets everything is on the same element, e.g. With your markup you should do this, mind the gap. ``` #menu_4212. menu_post. menu_title::after { content: url('..images/gluten_free.png') } ``` And be aware, with this method, you won't be able to control the size of the image via CSS. You can however use background images. ``` #menu_4212. menu_post. menu_title::after { content: ""; display: inline-block; vertical-align: middle; width: 20px; height: 20px; background: url('..images/gluten_free.png') 0 0 no-repeat; background-size: contain; } ``` In addition, you can also insert the image via `.menu_post::after {...}`, then use flexbox `order` property to reorder them, make the image to show in the middle of the spans visually. Upvotes: 3
2018/03/16
963
3,150
<issue_start>username_0: Is it possible to make an API which prints database records like this: `http://localhost:8000/products/?compare=1-2-N...(1,2,N) product id's.` I have succeeded printing only one record. My route: ``` $router->get('products/{id}','ProductController@getProduct'); ``` and my controller: ``` public function getProduct($id){ $tlt_products = DB::table('tlt_products')->find($id); $tlt_products_features_id = DB::table('tlt_product_features')->where('product_id', $id)->get()->pluck('feature_id'); $tlt_features = DB::table('tlt_features')->whereIn('id', $tlt_products_features_id)->get()->groupBy('feature_group'); $tlt_feature_groups = DB::table('tlt_features')->groupBy('feature_group')->get()->toArray(); return response()->json([ 'product' => $tlt_products, 'product_features' => $tlt_features, 'feature_groups' => $tlt_feature_groups ]); } ``` could you please help me printing array of records using route like this: ``` http://localhost:8000/products/?compare=1-2-3...-N ```<issue_comment>username_1: If you want to do this, you can give your `:after` pseudo-element some `display` property and also specify it's dimensions. Then put image on the background. It will give you some flexibility for styling the image. Something like this (style to your own needs): ``` #menu_4212 .menu_post .menu_title::after { content: ''; display: block; width: 30px; height: 30px; background: url('..images/gluten_free.png') no-repeat center center; background-size: cover; } ``` Upvotes: 0 <issue_comment>username_2: Try: ``` #menu_4212 .menu_post .menu_title::after { content: url('..images/gluten_free.png') } ``` Your current code assumes the ID & 2 classes are all on the same element. You want to use the "[descendant](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_selectors)" syntax instead. Upvotes: 1 <issue_comment>username_3: Technically you cannot insert an image tag in between the two tags via CSS, let's say: ``` .menu_title::after { content: "NEW"; } ``` That will insert it to `Onion SoupNEW` It will be the same if you're trying to insert an image: ``` .menu_title::after { content: url('..images/gluten_free.png'); } ``` The problem is your selectors `#menu_4212.menu_post.menu_title::after`, it targets everything is on the same element, e.g. With your markup you should do this, mind the gap. ``` #menu_4212. menu_post. menu_title::after { content: url('..images/gluten_free.png') } ``` And be aware, with this method, you won't be able to control the size of the image via CSS. You can however use background images. ``` #menu_4212. menu_post. menu_title::after { content: ""; display: inline-block; vertical-align: middle; width: 20px; height: 20px; background: url('..images/gluten_free.png') 0 0 no-repeat; background-size: contain; } ``` In addition, you can also insert the image via `.menu_post::after {...}`, then use flexbox `order` property to reorder them, make the image to show in the middle of the spans visually. Upvotes: 3
2018/03/16
686
2,304
<issue_start>username_0: I'd like to apply `text-overflow: ellipsis;` to the [mat-panel-description](https://material.angular.io/components/expansion/api#MatExpansionPanelDescription) of a [mat-expansion-panel](https://material.angular.io/components/expansion/overview): ``` .mat-expansion-panel-header-description { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100%; } ``` While the overflow is hidden, there are no ellipsis. See the following screenshot of [this stackblitz](https://stackblitz.com/edit/angular-gsxyhn?embed=1&file=app/expansion-overview-example.css&view=preview): [![enter image description here](https://i.stack.imgur.com/nlodw.png)](https://i.stack.imgur.com/nlodw.png) Wrapping is intentionally prevented since I don't want the description to wrap onto a second line. The long URL is also intentional: ``` Panel Title https://stackblitz.com/edit/angular-gsxyhn?file=app%2Fexpans ion-overview-example.html ```<issue_comment>username_1: I think you will come to find out that if you just put text in flex containers you can run into problems. I think it is best if you have a container element to hold your text and will help you in this case. Once the content is placed in some container, [there is one thing that needs to be done to get the ellipsis to show up](https://css-tricks.com/flexbox-truncated-text/)... add `min-width: 0;` to the `mat-expansion-panel-header-description` class. ```html Panel Title https://stackblitz.com/edit/angular-gsxyhn?file=app%2Fexpans ion-overview-example.html ``` ```css .mat-expansion-panel-header-title { flex: 0 0 auto; /* make this not grow or shrink */ margin-right: 16px; } .mat-expansion-panel-header-description { flex: 1 1 auto; /* make this grow and shrink */ min-width: 0; /* see link to see why this is needed */ margin-right: 16px; } .mat-expansion-panel-header-description > div { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: I solved it changing the child's visibility property. Take a look [here](https://stackoverflow.com/a/53268674/5124373). Ellipsis won't work on a *visibility: hidden* element, or any of its children inheriting this property. Upvotes: 0
2018/03/16
1,021
3,400
<issue_start>username_0: I am trying to place two image buttons and some text on a single line. Here is the XML for the layout: ``` xml version="1.0" encoding="utf-8"? ``` The selector XML for each of the buttons in drawable: `button_delete.xml`: ``` xml version="1.0" encoding="utf-8"? ``` `button_add.xml`: ``` xml version="1.0" encoding="utf-8"? ``` In the builder all looks well: [![enter image description here](https://i.stack.imgur.com/KNiSi.png)](https://i.stack.imgur.com/KNiSi.png) But in the application the gray background is lost and the edges of the image (which are transparent) are shown, but only for the first image: [![enter image description here](https://i.stack.imgur.com/Zm8HA.jpg)](https://i.stack.imgur.com/Zm8HA.jpg) Strangely, the first image button is not recognizing the transparent background of the image. Additionally I needed to mess with the width and height of the RelativeLayout and the first ImageButton to even get it close to the right size. With the 2nd I did not have to do anything. There is nothing special with the first image. Here are the images from the directory: [![enter image description here](https://i.stack.imgur.com/ExA4i.jpg)](https://i.stack.imgur.com/ExA4i.jpg) One last issue - How do you make the text wrap before the 2nd image if it is too long for the space? Right now it writes under the 2nd image before wrapping: [![enter image description here](https://i.stack.imgur.com/pZorN.jpg)](https://i.stack.imgur.com/pZorN.jpg) Here are all the delete images. Seem to have transparent backgrounds, but I am far from a Gimp expert. Also not sure if StackOverflow keeps the original.. [![enter image description here](https://i.stack.imgur.com/m8ffL.png)](https://i.stack.imgur.com/m8ffL.png) [![enter image description here](https://i.stack.imgur.com/8nNyn.png)](https://i.stack.imgur.com/8nNyn.png) Update ------ I have verified the images are transparent. The image still has the white background. I have also updated the XML to look like this: ``` xml version="1.0" encoding="utf-8"? ```<issue_comment>username_1: I think you will come to find out that if you just put text in flex containers you can run into problems. I think it is best if you have a container element to hold your text and will help you in this case. Once the content is placed in some container, [there is one thing that needs to be done to get the ellipsis to show up](https://css-tricks.com/flexbox-truncated-text/)... add `min-width: 0;` to the `mat-expansion-panel-header-description` class. ```html Panel Title https://stackblitz.com/edit/angular-gsxyhn?file=app%2Fexpans ion-overview-example.html ``` ```css .mat-expansion-panel-header-title { flex: 0 0 auto; /* make this not grow or shrink */ margin-right: 16px; } .mat-expansion-panel-header-description { flex: 1 1 auto; /* make this grow and shrink */ min-width: 0; /* see link to see why this is needed */ margin-right: 16px; } .mat-expansion-panel-header-description > div { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: I solved it changing the child's visibility property. Take a look [here](https://stackoverflow.com/a/53268674/5124373). Ellipsis won't work on a *visibility: hidden* element, or any of its children inheriting this property. Upvotes: 0
2018/03/16
370
1,297
<issue_start>username_0: I use WebStorm for React JS and I'm getting this 'Unresolved variable warning' for all props. I searched for solution everywhere but couldn't find. Whenever i pass down prop value and then use it as this.props.something, that something is unresolved. App works fine and there is no problem, it's just that WebStorm makes this irritating. I installed typescript definitions and nothing. This is the code: ``` import React from 'react'; import ReactDOM from 'react-dom'; class A extends React.Component { render() { return ( {this.props.something} ); } } class B extends React.Component { render() { return( ) } } ReactDOM.render( , document.getElementById('root') ); ``` Here is screenshot of that: [Screenshot](https://i.stack.imgur.com/ifopx.png)<issue_comment>username_1: Known issue, please follow [WEB-31785](https://youtrack.jetbrains.com/issue/WEB-31785) for updates Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` npm install --save @types/react ``` Upvotes: 0 <issue_comment>username_3: use es6 destructuring to remove the warnings: eg : rather than ```js if (this.props.variableName) ... ``` use ```js const { variableName } = this.props; if (variableName) ... ``` Upvotes: 1
2018/03/16
878
2,666
<issue_start>username_0: I'm running a quick test to make sure I have my pointer arithmetic down: **main.c** ``` #include #include #define ADDRESS 0xC0DCA11501LL #define LENGTH 5 void print\_address( char \*, char ); /\* Main program \*/ int main( int argc, char \*argv[] ) { char nums[ LENGTH ]; /\* LSB first \*/ for( int i = 0; i < LENGTH; i++ ) { nums[ i ] = ( ADDRESS >> ( 8 \* i ) ) & 0xFF; } print\_address( nums, LENGTH ); system("PAUSE"); return 0; } void print\_address( char \*data, char len ) { char \*data\_ptr = data; while( len-- ) { printf( "%X\n", \*data\_ptr++ ); } } ``` What I expect is the bytes of `ADDRESS` to be printed out LSB first in hex format. But the last 3 bytes appear to be printed with 32-bit lengths: ``` 1 15 FFFFFFA1 FFFFFFDC FFFFFFC0 Press any key to continue . . . ``` Is this due to my bit-shifting arithmetic, something compiler-specific, some `printf()` behavior? (I'm using MinGW GCC v6.3.0 on Windows 10 to compile.)<issue_comment>username_1: I believe that your `char` is a being used as a signed value and that you are seeing the `FFFF`s because `0xA1` is greater than `0x80` and is therefore showing up signed. Try using unsigned char pointer (and for the `nums` array and `data` in your function prototype) and the problem should go away. Upvotes: 4 [selected_answer]<issue_comment>username_2: The problem is that printf does not know that the type of your data is char. Try this ``` void print_address( char *data, char len ) { char *data_ptr = data; while( len-- ) { printf( "%02X\n", *data_ptr++ &0xFF); } } ``` Result: ``` [jmgomez@d1 tmp]$ a.o 01 15 A1 DC C0 sh: PAUSE: command not found [jmgomez@d1 tmp]$ ``` Upvotes: 0 <issue_comment>username_3: Type `char` seems to be signed in your environment, such that `A1` as an 8 bit value actually represents a negative number. Note then that the `varargs` of `printf` are promoted to int type, and a negative number is filled up with leading `1`-bits. In other words, signed `A1` when promoted to 32 bit integer will give `FFFFFFA1`. That's why. Use `unsigned char` instead: ``` void print_address( unsigned char *, char ); /* Main program */ int main( int argc, char *argv[] ) { unsigned char nums[ LENGTH ]; /* LSB first */ for( int i = 0; i < LENGTH; i++ ) { nums[ i ] = ( ADDRESS >> ( 8 * i ) ) & 0xFF; } print_address( nums, LENGTH ); system("PAUSE"); return 0; } void print_address( unsigned char *data, char len ) { unsigned char *data_ptr = data; while( len-- ) { printf( "%X\n", *data_ptr++ ); } } ``` Upvotes: 2
2018/03/16
2,107
4,921
<issue_start>username_0: How can i divide a number multiple levels, i have a number and a list with 3 values, step 6 has the expected output, but i am not able to get it ``` Number = 500 Divide=[5,6,9] ``` **Step1:** Get the number and divide by sum of numbers in divide list ``` 500/ (5+6+9) = 25 ``` **Step 2:** Multiply the number we got as output with each number in divide list ``` 25 *5 = 125 25* 6 = 150 25* 9 = 225 ``` **Step 3:** print the number and the each of result we got in step 2 ``` 500 125 500 150 500 225 ``` **Step 4:** Take every number we got in step 2 and divide that as follows ``` 125 / (5+6+9) = 125/20 = 6.25 ``` **Step 5** ``` 6.25 * 5 = 31.25 6.25 * 6 = 37.50 6.25 * 9 = 56.25 ``` **Step 6:** Take 150 and 225 from step 3 and do the same thing from step 4 to step 6 and print as follows which is the final output, ``` 500 125 31.25 500 125 37.50 500 125 56.25 500 150 37.5 500 150 45 500 150 67.5 500 225 56.25 500 225 67.5 500 225 101.25 ``` For this i am able to get the first level with the following code ``` number = 500 divide=[5,6,9] for i in divide: j=(number/sum(divide))*i print (number, j) ``` **Output:** ``` 500 125.0 500 150.0 500 225.0 ``` How can i proceed to get the next level of numbers as displayed in Step 6 ``` **Expected Output 2** 500 125 31.25 500 125 68.75 #31.25+37.5 500 125 125 # 68.75+56.25 500 150 37.5 500 150 82.5 #37.5+45 500 150 150 # 67.5+82.5 500 225 56.25 500 225 123.75 #56.25+67.5 500 225 225 # 123.75+101.25 ``` **Output 3:** ``` 500 125 31.25 500 125 68.75 #31.25+37.5 500 125 125 # 68.75+56.25 500 150 45 # this is 2nd set and the multiplication should start from 2nd number in divide list 6 9 5 500 150 112.5 #45+67.5 500 150 150 # 112.5+.37.5 500 225 101.25 # this is 3rd set and the multiplication should start from 3rd number in divide list 9 5 6 500 225 157.5 #101.25+56.25 500 225 225 # 157.5+67.5 ```<issue_comment>username_1: You just need some nested loops and an interim list for your results from your first looping pass. ``` number = 500 divide=[5,6,9] interim = [] for i in divide: j=(number/sum(divide))*i interim.append(j) print (number, j) for j in interim: for i in divide: k = j/sum(divide)*i print (j, k) ``` This returned the following for me ``` 500 125.0 500 150.0 500 225.0 125.0 31.25 125.0 37.5 125.0 56.25 150.0 37.5 150.0 45.0 150.0 67.5 225.0 56.25 225.0 67.5 225.0 101.25 ``` Upvotes: 2 <issue_comment>username_2: Using a couple of `list` comprehensions, you could achieve what you want. Breaking down the code through **each step**: ``` Number = 500 Divide = [5,6,9] step1 = Number/sum(Divide) step2 = [step1 * i for i in Divide] for i in step2: # step3 print('{} {}'.format(Number, i)) step4 = [i / sum(Divide) for i in step2] step5 = [[i * j for i in step4] for j in Divide] k = 0 # step6 for i in step2: for j in step5[k]: print('{} {} {}'.format(Number, i, j)) k += 1 ``` Output: ``` 500 125.0 500 150.0 500 225.0 500 125.0 31.25 500 125.0 37.5 500 125.0 56.25 500 150.0 37.5 500 150.0 45.0 500 150.0 67.5 500 225.0 56.25 500 225.0 67.5 500 225.0 101.25 ``` Solution to the **updated** question: ``` Number = 500 Divide = [5,6,9] step1 = Number/sum(Divide) step2 = [step1 * i for i in Divide] for i in step2: # step3 print('{} {}'.format(Number, i)) step4 = [i / sum(Divide) for i in step2] step5 = [[i * j for i in step4] for j in Divide] k = 0 # step6 for i in step2: sum = 0 for j in step5[k]: sum = sum + j print('{} {} {}'.format(Number, i, sum)) k += 1 ``` Output (2): ``` 500 125.0 500 150.0 500 225.0 500 125.0 31.25 500 125.0 68.75 500 125.0 125.0 500 150.0 37.5 500 150.0 82.5 500 150.0 150.0 500 225.0 56.25 500 225.0 123.75 500 225.0 225.0 ``` Upvotes: 1
2018/03/16
1,007
3,812
<issue_start>username_0: I am trying to exclude some .swift and .storyboard files from my project (Xcode9) for release build using `EXCLUDED_SOURCE_FILE_NAMES`. But its not working for me. Is it possible to give any folder name to exclude it completely? How to give multiple files and folder name? It is not working if I give path like **`../ForlderName/*`**. Folder is at the same level as my project. Is it possible to exclude sub-folders files as well? I am able to exclude if my hierarchy is ``` MyProject Folder |_ MyProject Folder |_FolderToBeExcluded ``` If I gave FolderToBeExcluded/\* it is working but file in FolderToBeExcluded's subfolders are not getting excluded. If my heirachy is like this (ie folder to be excluded and project folder both at same level) ``` FolderToBeExcluded MyProject Folder |_ MyProject Folder ``` If I give **../FolderToBeExcluded/** or $(SRCROOT)**/../FolderToBeExcluded/** both are not working If I give directly any one of the file name which is to be excluded it is getting exclude without giving full path. Is it the limitation of `EXCLUDED_SOURCE_FILE_NAMES`?<issue_comment>username_1: For me it worked if I define the value of `EXCLUDED_SOURCE_FILE_NAMES` like this: ``` $(SRCROOT)/../FolderToBeExcluded/*.* ``` I am using Xcode 9.4.1 Upvotes: 0 <issue_comment>username_2: > > If I gave **FolderToBeExcluded/\*** it is working but file in FolderToBeExcluded's subfolders are not getting excluded. > > > The reason subfolders are not excluded is because of the **/\***. That tells it to look for files in FolderToBeExcluded. If you just give **FolderToBeExcluded** (no slash after) then it will exclude all files in that folder and all subfolders. At least that is what I found. Upvotes: 2 <issue_comment>username_3: An important gotcha I ran into today is that you can't exclude files within a folder reference, but you can exclude an entire referenced folder. When you add a folder to Xcode it will ask you if you want to create a group or create a folder reference. If you choose the second option, then you'll need to be aware that you can't exclude files within the folder, but you can exclude the entire folder. Upvotes: 1 <issue_comment>username_4: This seems to be the only solution: 1. Use groups without folders for every subfolder in excluded directory 2. Exclude `${PROJECT_DIR}/{Path to Excluded Folder}/*` in EXCLUDED\_SOURCE\_FILE\_NAMES settings Upvotes: 0 <issue_comment>username_5: My Findings ----------- Lets say ``` Project |_ Foo |_ Bar |_ ToBeExcluded | file.json |_ Sub |_ subfile.json ``` I tried `ToBeExcluded/*` which works excludes `file.json` but not `subfile.json` When trying `ToBeExcluded/` and `ToBeExcluded` the exclusions seems to be ignored as both files are still included `ToBeExcluded/**` excludes `file.json` but includes `subfile.json` (this is suppose to be recursive but hey) `ToBeExcluded/*/*` excludes `subfile.json` but includes `file.json` (makes sense I guess) Kamen suggested using `$(SRCROOT)` so I tried `$(SRCROOT)/Foo/Bar/ToBeExcluded/*.*` (which is the same as just `$(SRCROOT)/Foo/Bar/ToBeExcluded/*`) and it does the same as `ToBeExcluded/*`, same goes for all other variants and the behaving the same with full path versus without `${PROJECT_DIR}` (in my case) translated to the same thing as `$(SRCROOT)`so did the same thing sadly My Conclusion (For now) ----------------------- Sadly for now I think what Im going to do is just exclude `ToBeExcluded/*` and maybe `ToBeExcluded/*/*` (will think on this) then just make sure that whenever adding new files to it that preferably in that root folder and if need be grouped in xcode without creating a folder. Worst case a single level of subfolder can be added Upvotes: 1
2018/03/16
850
3,180
<issue_start>username_0: I want the data out of while or for loops in Stacked Sequence Structure after each iteration.. I want the data out of loops even if it is not stopped that is after each iteration.. to see the plot of data at each iteration and continue to the next loop in the same plot [![My code](https://i.stack.imgur.com/xZCy9.png)](https://i.stack.imgur.com/xZCy9.png) somebody please help me .. I want to send and get data from a device, the data will be plot each time. thanks..<issue_comment>username_1: For me it worked if I define the value of `EXCLUDED_SOURCE_FILE_NAMES` like this: ``` $(SRCROOT)/../FolderToBeExcluded/*.* ``` I am using Xcode 9.4.1 Upvotes: 0 <issue_comment>username_2: > > If I gave **FolderToBeExcluded/\*** it is working but file in FolderToBeExcluded's subfolders are not getting excluded. > > > The reason subfolders are not excluded is because of the **/\***. That tells it to look for files in FolderToBeExcluded. If you just give **FolderToBeExcluded** (no slash after) then it will exclude all files in that folder and all subfolders. At least that is what I found. Upvotes: 2 <issue_comment>username_3: An important gotcha I ran into today is that you can't exclude files within a folder reference, but you can exclude an entire referenced folder. When you add a folder to Xcode it will ask you if you want to create a group or create a folder reference. If you choose the second option, then you'll need to be aware that you can't exclude files within the folder, but you can exclude the entire folder. Upvotes: 1 <issue_comment>username_4: This seems to be the only solution: 1. Use groups without folders for every subfolder in excluded directory 2. Exclude `${PROJECT_DIR}/{Path to Excluded Folder}/*` in EXCLUDED\_SOURCE\_FILE\_NAMES settings Upvotes: 0 <issue_comment>username_5: My Findings ----------- Lets say ``` Project |_ Foo |_ Bar |_ ToBeExcluded | file.json |_ Sub |_ subfile.json ``` I tried `ToBeExcluded/*` which works excludes `file.json` but not `subfile.json` When trying `ToBeExcluded/` and `ToBeExcluded` the exclusions seems to be ignored as both files are still included `ToBeExcluded/**` excludes `file.json` but includes `subfile.json` (this is suppose to be recursive but hey) `ToBeExcluded/*/*` excludes `subfile.json` but includes `file.json` (makes sense I guess) Kamen suggested using `$(SRCROOT)` so I tried `$(SRCROOT)/Foo/Bar/ToBeExcluded/*.*` (which is the same as just `$(SRCROOT)/Foo/Bar/ToBeExcluded/*`) and it does the same as `ToBeExcluded/*`, same goes for all other variants and the behaving the same with full path versus without `${PROJECT_DIR}` (in my case) translated to the same thing as `$(SRCROOT)`so did the same thing sadly My Conclusion (For now) ----------------------- Sadly for now I think what Im going to do is just exclude `ToBeExcluded/*` and maybe `ToBeExcluded/*/*` (will think on this) then just make sure that whenever adding new files to it that preferably in that root folder and if need be grouped in xcode without creating a folder. Worst case a single level of subfolder can be added Upvotes: 1
2018/03/16
1,075
3,084
<issue_start>username_0: How can I rank a DataFrame based on 2 columns? On below example, `col_b` would the tie breaker for `col_a`. **DataFrame:** ``` df = pd.DataFrame({'col_a':[0,0,0,1,1,1], 'col_b':[5,2,8,3,7,4]}) df col_a col_b 0 0 5 1 0 2 2 0 8 3 1 3 4 1 7 5 1 4 ``` **Expected Output:** ``` col_a col_b Rank 0 0 5 2 1 0 2 1 2 0 8 3 3 1 3 4 4 1 7 6 5 1 4 5 ```<issue_comment>username_1: Found my own solution: Create a tuple with the columns and rank it. Won't handle different ascending/descending order, but it is good for my problem. ``` df['rank'] = df[['col_a','col_b']].apply(tuple, 1).rank() ``` Upvotes: 2 <issue_comment>username_2: Here is one way. Create a temp DataFrame by sorting the columns and re-indexing. Then use the new index as the rank and join back to the original df. ``` temp_df = df.sort_values(['col_a', 'col_b']).reset_index() temp_df['rank'] = temp_df.index + 1 print(temp_df) # index col_a col_b rank #0 1 0 2 1 #1 0 0 5 2 #2 2 0 8 3 #3 3 1 3 4 #4 5 1 4 5 #5 4 1 7 6 ``` The column `'index'` corresponds to the index in the original DataFrame. Use this to join `temp_df` back to `df` and select the columns you want: ``` df = df.join(temp_df.set_index('index'), rsuffix="_r")[['col_a', 'col_b', 'rank']] print(df) # col_a col_b rank #0 0 5 2 #1 0 2 1 #2 0 8 3 #3 1 3 4 #4 1 7 6 #5 1 4 5 ``` Upvotes: 2 <issue_comment>username_3: Here is a one-line approach using `sort_values`: ``` In [135]: df['rank'] = df.sort_values(['col_a', 'col_b'])['col_b'].index + 1 In [136]: df Out[136]: col_a col_b rank 0 0 5 2 1 0 2 1 2 0 8 3 3 1 3 4 4 1 7 6 5 1 4 5 ``` The logic behind this snippet: Basically, the `DataFrame.sort_values` function accepts multiple column names and returns a sorted copy of the dataframe based on the order of passed column names. The default sorting order is `ascending` which is what we want. If you wanted another order you could pass the order as an iterable of booleans to the `ascending` keyword argument. At the end the new indices of the `column_b` is what we want (plus one). Upvotes: 3 [selected_answer]<issue_comment>username_4: Using `numpy`'s [`argsort`](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.argsort.html#numpy.argsort) method. ``` df = pd.DataFrame({'col_a':[0,0,0,1,1,1], 'col_b':[5,2,8,3,7,4]}) df["rank"] = np.argsort( df.values.copy().view(dtype=[('x', int), ('y', int)]).flatten(), order=("x","y") ) + 1 col_a col_b rank 0 0 5 2 1 0 2 1 2 0 8 3 3 1 3 4 4 1 7 6 5 1 4 5 ``` Upvotes: 1
2018/03/16
3,116
9,396
<issue_start>username_0: Is there any way to add a label on or near the center of a geom\_curve line? Currently, I can only do so by labeling either the start or end point of the curve. ``` library(tidyverse) library(ggrepel) df <- data.frame(x1 = 1, y1 = 1, x2 = 2, y2 = 3, details = "Object Name") ggplot(df, aes(x = x1, y = y1, label = details)) + geom_point(size = 4) + geom_point(aes(x = x2, y = y2), pch = 17, size = 4) + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2)) + geom_label(nudge_y = 0.05) + geom_label_repel(box.padding = 2) ``` [![Labeling origin point with either geom_label or geom_label_repel](https://i.stack.imgur.com/d6oWv.jpg)](https://i.stack.imgur.com/d6oWv.jpg) I would love some way to automatically label the curve near coordinates x=1.75, y=1.5. Is there a solution out there I haven't seen yet? My intended graph is quite busy, and labeling the origin points makes it harder to see what's happening, while labeling the arcs would make a cleaner output. [![Sample of my current graph without labels](https://i.stack.imgur.com/vpaTF.jpg)](https://i.stack.imgur.com/vpaTF.jpg)<issue_comment>username_1: Maybe annotations would help here (see: <http://ggplot2.tidyverse.org/reference/annotate.html>) ``` library(tidyverse) library(ggrepel) df <- data.frame(x1 = 1, y1 = 1, x2 = 2, y2 = 3, details = "Object Name") ggplot(df, aes(x = x1, y = y1, label = details)) + geom_point(size = 4) + geom_point(aes(x = x2, y = y2), pch = 17, size = 4) + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2)) + geom_label(nudge_y = 0.05) + geom_label_repel(box.padding = 2) + annotate("label", x=1.75, y=1.5, label=df$details) ``` Upvotes: 1 <issue_comment>username_2: I've come to a solution for this problem. It's large and clunky, but effective. The core problem is that `geom_curve()` does not draw a set path, but it moves and scales with the aspect ratio of the plot window. So short of locking the aspect ratio with `coord_fixed(ratio=1)` there is no way I can easily find to predict where the midpoint of a `geom_curve()` segment will be. [![Plot exported at height = 4, width = 4](https://i.stack.imgur.com/q7zk1.jpg)](https://i.stack.imgur.com/q7zk1.jpg) [![Plot exported at height = 2, width = 4, same points plotted](https://i.stack.imgur.com/ShzXc.jpg)](https://i.stack.imgur.com/ShzXc.jpg) So instead I set about finding midpoint for a curve, and then forcing the curve to go through that point which I would later label. To find the midpoint I had to copy two functions from the [grid package](https://www.rdocumentation.org/packages/grid/versions/3.4.3/source): ``` library(grid) library(tidyverse) library(ggrepel) # Find origin of rotation # Rotate around that origin calcControlPoints <- function(x1, y1, x2, y2, curvature, angle, ncp, debug=FALSE) { # Negative curvature means curve to the left # Positive curvature means curve to the right # Special case curvature = 0 (straight line) has been handled xm <- (x1 + x2)/2 ym <- (y1 + y2)/2 dx <- x2 - x1 dy <- y2 - y1 slope <- dy/dx # Calculate "corner" of region to produce control points in # (depends on 'angle', which MUST lie between 0 and 180) # Find by rotating start point by angle around mid point if (is.null(angle)) { # Calculate angle automatically angle <- ifelse(slope < 0, 2*atan(abs(slope)), 2*atan(1/slope)) } else { angle <- angle/180*pi } sina <- sin(angle) cosa <- cos(angle) # FIXME: special case of vertical or horizontal line ? cornerx <- xm + (x1 - xm)*cosa - (y1 - ym)*sina cornery <- ym + (y1 - ym)*cosa + (x1 - xm)*sina # Debugging if (debug) { grid.points(cornerx, cornery, default.units="inches", pch=16, size=unit(3, "mm"), gp=gpar(col="grey")) } # Calculate angle to rotate region by to align it with x/y axes beta <- -atan((cornery - y1)/(cornerx - x1)) sinb <- sin(beta) cosb <- cos(beta) # Rotate end point about start point to align region with x/y axes newx2 <- x1 + dx*cosb - dy*sinb newy2 <- y1 + dy*cosb + dx*sinb # Calculate x-scale factor to make region "square" # FIXME: special case of vertical or horizontal line ? scalex <- (newy2 - y1)/(newx2 - x1) # Scale end points to make region "square" newx1 <- x1*scalex newx2 <- newx2*scalex # Calculate the origin in the "square" region # (for rotating start point to produce control points) # (depends on 'curvature') # 'origin' calculated from 'curvature' ratio <- 2*(sin(atan(curvature))^2) origin <- curvature - curvature/ratio # 'hand' also calculated from 'curvature' if (curvature > 0) hand <- "right" else hand <- "left" oxy <- calcOrigin(newx1, y1, newx2, newy2, origin, hand) ox <- oxy$x oy <- oxy$y # Calculate control points # Direction of rotation depends on 'hand' dir <- switch(hand, left=-1, right=1) # Angle of rotation depends on location of origin maxtheta <- pi + sign(origin*dir)*2*atan(abs(origin)) theta <- seq(0, dir*maxtheta, dir*maxtheta/(ncp + 1))[c(-1, -(ncp + 2))] costheta <- cos(theta) sintheta <- sin(theta) # May have BOTH multiple end points AND multiple # control points to generate (per set of end points) # Generate consecutive sets of control points by performing # matrix multiplication cpx <- ox + ((newx1 - ox) %*% t(costheta)) - ((y1 - oy) %*% t(sintheta)) cpy <- oy + ((y1 - oy) %*% t(costheta)) + ((newx1 - ox) %*% t(sintheta)) # Reverse transformations (scaling and rotation) to # produce control points in the original space cpx <- cpx/scalex sinnb <- sin(-beta) cosnb <- cos(-beta) finalcpx <- x1 + (cpx - x1)*cosnb - (cpy - y1)*sinnb finalcpy <- y1 + (cpy - y1)*cosnb + (cpx - x1)*sinnb # Debugging if (debug) { ox <- ox/scalex fox <- x1 + (ox - x1)*cosnb - (oy - y1)*sinnb foy <- y1 + (oy - y1)*cosnb + (ox - x1)*sinnb grid.points(fox, foy, default.units="inches", pch=16, size=unit(1, "mm"), gp=gpar(col="grey")) grid.circle(fox, foy, sqrt((ox - x1)^2 + (oy - y1)^2), default.units="inches", gp=gpar(col="grey")) } list(x=as.numeric(t(finalcpx)), y=as.numeric(t(finalcpy))) } calcOrigin <- function(x1, y1, x2, y2, origin, hand) { # Positive origin means origin to the "right" # Negative origin means origin to the "left" xm <- (x1 + x2)/2 ym <- (y1 + y2)/2 dx <- x2 - x1 dy <- y2 - y1 slope <- dy/dx oslope <- -1/slope # The origin is a point somewhere along the line between # the end points, rotated by 90 (or -90) degrees # Two special cases: # If slope is non-finite then the end points lie on a vertical line, so # the origin lies along a horizontal line (oslope = 0) # If oslope is non-finite then the end points lie on a horizontal line, # so the origin lies along a vertical line (oslope = Inf) tmpox <- ifelse(!is.finite(slope), xm, ifelse(!is.finite(oslope), xm + origin*(x2 - x1)/2, xm + origin*(x2 - x1)/2)) tmpoy <- ifelse(!is.finite(slope), ym + origin*(y2 - y1)/2, ifelse(!is.finite(oslope), ym, ym + origin*(y2 - y1)/2)) # ALWAYS rotate by -90 about midpoint between end points # Actually no need for "hand" because "origin" also # encodes direction # sintheta <- switch(hand, left=-1, right=1) sintheta <- -1 ox <- xm - (tmpoy - ym)*sintheta oy <- ym + (tmpox - xm)*sintheta list(x=ox, y=oy) } ``` With that in place, I calculated a midpoint for each record ``` df <- data.frame(x1 = 1, y1 = 1, x2 = 10, y2 = 10, details = "Object Name") df_mid <- df %>% mutate(midx = calcControlPoints(x1, y1, x2, y2, angle = 130, curvature = 0.5, ncp = 1)$x) %>% mutate(midy = calcControlPoints(x1, y1, x2, y2, angle = 130, curvature = 0.5, ncp = 1)$y) ``` I then make the graph, but draw two separate curves. One from the origin to the calculated midpoint, and another from the midpoint to the destination. The angle and curvature settings for both finding the midpoint and drawing these curves are tricky to keep the result from obviously looking like two different curves. ``` ggplot(df_mid, aes(x = x1, y = y1)) + geom_point(size = 4) + geom_point(aes(x = x2, y = y2), pch = 17, size = 4) + geom_curve(aes(x = x1, y = y1, xend = midx, yend = midy), curvature = 0.25, angle = 135) + geom_curve(aes(x = midx, y = midy, xend = x2, yend = y2), curvature = 0.25, angle = 45) + geom_label_repel(aes(x = midx, y = midy, label = details), box.padding = 4, nudge_x = 0.5, nudge_y = -2) ``` [![Final plot with label tied to invisible midpoint](https://i.stack.imgur.com/S2CwL.jpg)](https://i.stack.imgur.com/S2CwL.jpg) Though the answer isn't ideal or elegant, it scales with a large number of records. Upvotes: 3 [selected_answer]
2018/03/16
534
1,716
<issue_start>username_0: I'm trying to specify a variable for opening up a file with a particular app, but no matter how I attempt to reference it, it's not working. ``` sublime1=/Applications/Sublime\ Text.app/ sublime2="/Applications/Sublime\ Text.app/" sublime3="/Applications/Sublime Text.app/" ``` I've been trying different ways of setting the variable, but for each of the variations I've tried, it fails. ``` open ~/.zshrc -a $sublime1 open ~/.zshrc -a $sublime2 open ~/.zshrc -a $sublime3 ``` > > The file /Users/matthew/Text.app does not exist > > > It gives me the same error for each, so I assume they're equivalent. Even when I try `cd $sublime` it also fails, but slightly differently... > > bash: cd: /Applications/Sublime: No such file or directory > > > **Update**: It was suggested by [Charles](https://stackoverflow.com/users/14122/charles-duffy) to use a function to accomplish the task of quickly opening something in sublime. ``` sublime() { open "$@" -a "/Applications/Sublime Text.app/"; } ``` Will allow you to simply run ``` sublime ~/.zshrc ```<issue_comment>username_1: These assignments are correct: > > > ``` > sublime1=/Applications/Sublime\ Text.app/ > sublime3="/Applications/Sublime Text.app/" > > ``` > > The problem is with the invocation. Variables used as command line arguments are subject to word splitting and globbing. You need to double-quote them, like this: ``` open ~/.zshrc -a "$sublime1" open ~/.zshrc -a "$sublime3" ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: try using `sublime1=$(/Applications/Sublime/Text.app)` and using `chmod 770 Text.app` on Text.app in the command line sorry for my english... Upvotes: -1
2018/03/16
698
2,173
<issue_start>username_0: I'm using the following code, where month is the current month(where am I): ``` lastDayOfLastMonth = month === 0 ? new Date(year - 1, 11, 0).getDate() : new Date(year, month, 0).getDate(); ``` the idea, is if I'm on the first month of an year, the previous month is the last month of the previous year. If I'm on January 2018, is reporting that December 2017 last day was 30, which is not true, it was 31, but I don't figure why.<issue_comment>username_1: below also give you result you want ``` var LastDay = new Date(year-1, 12, 0); //new Date(year - 1, 11, 0).getDate() this line seems issue in your code ``` --- this one returns december 31 2017 for me ``` var month = 0;//this you will get when do dt.getMonth() in January month var year = 2018; var LastDay = new Date(year, month, 0); document.getElementById("demo").innerHTML = LastDay; ``` --- try this out its working for me ``` var dt = new Date(); var month = dt.getMonth(); var year = 2018; var LastDay = new Date(year, month, 0); console.log(LastDay); ``` Upvotes: 0 <issue_comment>username_2: ``` var d = new Date(); var n = d.getMonth(); // first month if(n == 0){ console.log(new Date(new Date().getFullYear(), 11, 31).getDate()); } ``` Upvotes: 0 <issue_comment>username_3: Try this instead: ``` lastDayOfLastMonth = month === 0 ? new Date(year - 1, 12, 0).getDate(): new Date(year, month, 0).getDate(); ``` Upvotes: 0 <issue_comment>username_4: The day part of the `Date` constructor is not 0-indexed, but the actual day of the month. In your first condition, `new Date(year - 1, 11, 0).getDate()`, you will first initialize your date to be December 0, 2017. The date constructor then corrects this as November 30, 2017. If you want the last day of the previous month, you can ignore the ternary operator and do the following, as the `Date` constructor will make the necessary conversions: ``` lastDayOfLastMonth = new Date(currentYear, currentMonth, 0).getDate(); ``` Note that `currentMonth` is still 0-indexed (i.e. January is month 0 and December is month 11) Upvotes: 2 [selected_answer]
2018/03/16
667
2,725
<issue_start>username_0: Context: We have Java application on Maven and Spring framework. We are using a third party library in our project where classes from the library have to be imported this way(for example): ``` import com.doodle.api.v201709.Class1; ``` As a result,whenever there is a version change , it is not only the pom.xml has to be changed but almost all of the classes has to be updated to change the version from v201709 to v201711 for example. I tried to handle this issue by putting all of these kinds of imports in one class and extending that class in those classes where these imports are required. Seems classes where the imports are required are not getting them and I am seeing compilation failure with "cannot find symbol" error msg. Any idea on how to handle this issue?<issue_comment>username_1: Half an answer: > > I tried to handle this issue by putting all of these kinds of imports in one class and extending that class in those classes where these imports are required. > > > Translates to: you don't know what import statements are and how they are used. Meaning: import statements are not something that you can pass down using inheritance. They are a purely syntactical thing for human programmers. You import a class such as x.y.Z ... so that you can use `Z` within your source code, instead of writing `x.y.Z` all the time. The compiled byte code knows **nothing** about imports - they are gone. Instead, the compiled byte code uses `x.y.Z` all the time. Therefore your idea to "import" names, and using inheritance to sneak the imports into other places, as said: does not work. And in that sense the real answer is: you have to look into proper tooling that makes it easy to change such things. You probably find such refactoring capabilities within IntelliJ or eclipse. Or, alternatively, you turn to sed/awk and command line magic (it shouldn't be to hard to search for `import x.y.v1.Z` patterns to replace them with `import x.y.v2.Z`. Upvotes: 3 [selected_answer]<issue_comment>username_2: Java doesn't give you that flexibility at compile time. Among alternative options that you have: 1. **Properly version your code**, that of your dependency, then use a build dependency management tool such as Maven. This is safer as it allows version control and possibility to revert to the previous version if the new one doesn't work. This option reduces coupling between the two code bases. 2. **Use scripting**: With something like Groovy, you can take advantage of AST transformations and add dynamic imports at runtime. Upvotes: 1 <issue_comment>username_3: I ended up creating a class with all the imports and then imported that class wherever required. Upvotes: 0
2018/03/16
380
1,288
<issue_start>username_0: I am writing a telegram bot in Python. I want to send messages with bold letters. I tried to inclose message inside both `*` and `**`, but it does not solve the problem. Is there a function for mark up or HTML formatting or a way to do it?<issue_comment>username_1: You should use: ``` bot.send_message(chat_id=chat_id, text="*bold* Example message", parse_mode=telegram.constants.ParseMode.MARKDOWN_V2) ``` Or: ``` bot.send_message(chat_id=chat_id, text='**Example message**', parse_mode=telegram.ParseMode.HTML) ``` [More info](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Code-snippets#message-formatting-bold-italic-code-) Upvotes: 6 [selected_answer]<issue_comment>username_2: This is a little bit late. But i hope to be helpful for others: ``` import telepot token = '<KEY>' # Your telegram token . receiver_id = yyyyyyyy # Bot id, you can get this by using the next link : https://api.telegram.org/bot/getUpdates. Note that you should replace with your token. bot = telepot.Bot(token) message = "\*YOUR MESSAGE YOU WENT TO SEND.\*" #Any characters between \*\* will be send in bold format. bot.sendMessage(receiver\_id, message , parse\_mode= 'Markdown' ) ``` Upvotes: 2
2018/03/16
328
1,390
<issue_start>username_0: I'm new to SLAM and I'm sure the question is dumb, but I'd really like to know how this pose and area data accumulation goes in SLAM. Once an algorithm initializes it starts to track pose (and write somewhere (where?) a sequence of coordinates) and recover a map (a point cloud stored somewhere (where?)). Am I correct? Then the algo iterates over all persisted points for loop closure purposes? Are the points stored in some DB? Or what data structure is used? Help me please to clarify the situation! (Since it's the head of yours that may occasionally get sliced by the drone's propellers, which is driven by my future SLAM!)) Thanks in advance!<issue_comment>username_1: What you are asking is an implementation detail. It depends on which SLAM algorithm you are planning to use and how you want to implement it considering the performance issues for your project setting. As far as I know, [rtabmap](http://introlab.github.io/rtabmap/) uses a database to store the features with estimated location information to detect a loop closure in real-time. Upvotes: 1 <issue_comment>username_2: I have the same curiosity.I found some people use a pre-defined grid and a reference point at which the robot start from and as the robot moves discrete steps,for example 10cm for each direction ,the robot sensors triggered and the mape (grid) is updated. Upvotes: -1
2018/03/16
770
2,722
<issue_start>username_0: I am trying to flatten a multidimensional array into a one dimensional array using a recursive function. My single dimension array `elements` is returning `undefined` JS Bin with my example, [here](http://jsbin.com/woxebozudo/edit?html,js,console,output). HTML: ``` ``` JS: ``` // elements collection var elementsCollection = []; var elements = []; /* toSingle * convert mutlidimensional array to one dimensional array (i.e. flatten) * * @param ec - array */ function toSingle (ec) { for (var i = 0; i < ec.length; i++) { if (ec[i].length) { toSingle(ec[i]) } else { elements.push(ec[i]); } } } // get elements by their HTML class name var buttons = [ 'one', 'two' ]; // collect elements from class names for (var i = 0; i < buttons.length; i++) { elementsCollection.push(document.getElementsByClassName(buttons[i])); } // convert multiDimensional array to one dimensional elements = toSingle(elementsCollection); // log console.log(elements); // undefined ```<issue_comment>username_1: You need to return the array `elements`. A recommendation is putting that array `elements` into the function `toSingle` ```js /* toSingle * convert mutlidimensional array to one dimensional array (i.e. flatten) * * @param ec - array */ function toSingle(ec) { var elements = []; for (var i = 0; i < ec.length; i++) { if (ec[i].length) { elements = elements.concat(toSingle(ec[i])); } else { elements.push(ec[i]); } } return elements } // get integers, first, previous, next, last buttons by their HTML class name var buttons = ['one', 'two']; // elements collection var elementsCollection = []; // collect elements from class names for (var i = 0; i < buttons.length; i++) { elementsCollection.push(document.getElementsByClassName(buttons[i])); } // convert multiDimensional array to one dimensional var elements = toSingle(elementsCollection); // log console.log(elements); ``` ```html ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: First point, you can use querySelectorAll() to avoid an useless loop (and pass an array as argument, as it will be coerced toString). Second, if you don't mind using es6's features, just spread the received object in an array. Only two lines left: (also be aware that, although this doesn't seem to be the case in your example, with @username_1's solution, you have to remove duplicates in case you have elements having both or more classes) ```js var buttons = ['.one', '.two','.three']; var elements =[...document.querySelectorAll(buttons)]; console.log(elements); ``` ```html ``` Upvotes: 0
2018/03/16
1,007
4,913
<issue_start>username_0: How do I access the activity instance from within a nested onclicklistener within an adapterview? I have tried all sorts of things (context/ getcontext()) but they do not work. I am having the issue in the check permission if statement below. ``` public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.delegate_access_listview_item, parent, false); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog = new Dialog(context); dialog.setTitle("Delegate"); dialog.setContentView(R.layout.dialog_deleagte_access_profile); final Button callBtn = (Button) dialog.findViewById(R.id.call_btn); //callBtn.setText(); Button emailBtn = (Button) dialog.findViewById(R.id.call_btn); //emailBtn.setText(); CircularImageView imgView = dialog.findViewById(R.id.imageView2); // TODO: set image drawable dialog.show(); callBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int checkPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE); if (checkPermission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( context, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL); } else { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("373548474")); context.startActivity(callIntent); } } }); } }); return new MyViewHolder(v); } ```<issue_comment>username_1: This is not how you should implement. Try the steps mentioned below: 1) Set on click listener in onCreateViewHolder, as you have done. 2) When onClick event is triggered, instead of implementing the dialog here, send a callback to the activity. 3) When the callback is invoked in activity show the dialog. In this way, you'll have the activity access plus a clean code Upvotes: 2 [selected_answer]<issue_comment>username_2: Please create the Application Class of your root source folder and add on the AndroidManifest.xml file. ApplicationClass.java ``` public class ApplicationClass extends Application { private static ApplicationClass getInstance; @Override public void onCreate() { super.onCreate(); getInstance = this; } public static synchronized ApplicationClass getInstance() { return getInstance; } public static Context getContext() { return getInstance; } } ``` AndroidManifest.xml ``` ``` AdapterClass.java ``` public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.delegate_access_listview_item, parent, false); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog = new Dialog(ApplicationClass.getInstance()); dialog.setTitle("Delegate"); dialog.setContentView(R.layout.dialog_deleagte_access_profile); final Button callBtn = (Button) dialog.findViewById(R.id.call_btn); //callBtn.setText(); Button emailBtn = (Button) dialog.findViewById(R.id.call_btn); //emailBtn.setText(); CircularImageView imgView = dialog.findViewById(R.id.imageView2); // TODO: set image drawable dialog.show(); callBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int checkPermission = ContextCompat.checkSelfPermission(ApplicationClass.getInstance(), Manifest.permission.CALL_PHONE); if (checkPermission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( context, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL); } else { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("373548474")); context.startActivity(callIntent); } } }); } }); return new MyViewHolder(v); } ``` Upvotes: 0
2018/03/16
1,120
3,734
<issue_start>username_0: I have a webpage with a button and a paragraph of text. A click on the button should show or hide the paragraph. When the paragraph is shown initially, everything works fine. But when the paragraph is hidden, the first click has no consequence - the code works fine from the second click on. Why? How can I fix it? Here is my code: ```js function show_hide(id) { var e = document.getElementById(id); if (e.style.display == 'block' || e.style.display == '') { e.style.display = 'none'; } else { e.style.display = 'block'; } } ``` ```css .hidden { display: none; } ``` ```html This is the text that I want to show/hide. ```<issue_comment>username_1: Try this: ```js function show_hide(id) { var e = document.getElementById(id); e.classList.toggle("hidden"); } ``` ```css .hidden{ display:none; } ``` ```html This is the text that I want to show/hide. ``` Upvotes: 1 <issue_comment>username_2: `style.display` object always check the inline style value The issue is you have used `e.style.display == ''` in the first condition which is making the condition true first time because there is no display value at the first DOM load Try to remove `e.style.display == ''` from your condition... ```js function show_hide(id) { var e = document.getElementById(id); if (e.style.display == 'block') { e.style.display = 'none'; } else { e.style.display = 'block'; } } ``` ```css .hidden { display: none; } ``` ```html This is the text that I want to show/hide. ``` Upvotes: 2 <issue_comment>username_3: Your logic is wrong. ```js function show_hide(id) { var e = document.getElementById(id); if (e.style.display == 'none' || e.style.display==''){ e.style.display = 'block'; } else{ e.style.display = 'none'; } } ``` ```css .hidden{ display:none; } ``` ```html This is the text that I want to show/hide. ``` Upvotes: -1 <issue_comment>username_4: You need consistency. you are starting off the paragragh with the class `hidden`, which keeps the paragraph hidden, but does not have the 'display' property on the inline style. either add and remove the hidden class: ```js function show_hide(id) { var e = document.getElementById(id); e.classList.toggle('hidden'); } ``` ```css .hidden{ display:none; } ``` ```html This is the text that I want to show/hide. ``` OR use only inline styles ```js function show_hide(id) { var e = document.getElementById(id); if (e.style.display == 'block' || e.style.display==''){ e.style.display = 'none'; } else { e.style.display = 'block'; } } ``` ```html This is the text that I want to show/hide. ``` Upvotes: 3 [selected_answer]<issue_comment>username_5: The other answers are correct that you're only checking the inline display value which is causing the issues, but there is a better way than forcing your element to only use inline styles. Just use getComputedStyle instead. ``` if (window.getComputedStyle(e, username_6).getPropertyValue("display") == 'none' || window.getComputedStyle(e, username_6).getPropertyValue("display") == ''){ e.style.display = 'block'; } else{ e.style.display = 'none'; } ``` Upvotes: 1 <issue_comment>username_6: You can also declare a boolean variable like below and based on its state simply show and hide the paragraph text. ``` var isShown = false; function show_hide(id) { var e = document.getElementById(id); if (isShown) { isShown = false; e.style.display = 'none'; } else { e.style.display = 'block'; isShown = true; } } ``` [JSFIDDLE](https://jsfiddle.net/8L9g6dsf/5/) Upvotes: 1
2018/03/16
1,199
3,805
<issue_start>username_0: I want to sort points in 2D coordinate system by their distance to the origin (0,0) in increasing order. I found [this](https://stackoverflow.com/questions/2531952/how-to-use-a-custom-comparison-function-in-python-3) and tried something, but still I could not get desired result. Here is my code: ``` from functools import cmp_to_key def my_comp(point1, point2): return point1[0]*point1[0] + point1[1]*point1[1] < point2[0]*point2[0] + point2[1]*point2[1] points = [ [3.1, 4.1], [0.9, 0.8], [1.0, 1.0] ] sorted(points, key=cmp_to_key(my_comp)) print(points) ``` Result: ``` [[3.1, 4.1], [0.9, 0.8], [1.0, 1.0]] ``` Expected: ``` [[0.9, 0.8], [1.0, 1.0], [3.1, 4.1]] ```<issue_comment>username_1: Does this do what you want? ``` sorted_points = sorted(points, key=lambda p: p[0]*p[0] + p[1]*p[1]) ``` Another thing to watch out for in your original code is that sorted does not sort the list in place, it creates a new list that is sorted. So when you do ``` points = [3,2,1] sorted(points) print(points) ``` It will appear that your code hasn't sorted anything because you are printing the original list not the newly created sorted one. You can perform a sort in place like so. ``` points = [3,2,1] points.sort() print(points) ``` Upvotes: 2 <issue_comment>username_2: You're confusing the `cmp` and `key` arguments. A `cmp` function accepts two arguments and returns `-1`, `0`, or `1`. A `key` function returns a proxy value that will be used to sort the list. `cmp` was removed as an argument to `sorted` in Python 3. Upvotes: -1 <issue_comment>username_3: 1) Your `my_cmp()` function is supposed to return one of three values (+, -, or 0 depending upon the compare), but you only return two (True and False). 2) You ingnore the return value from `sorted()`. `sorted()` doesn't modify its argument, it returns a sorted copy of it. 3) Don't use cmp functions. They are hard to describe and hard to implement. Instead use key functions. How about: ``` def my_key(point1): return point1[0]*point1[0] + point1[1]*point1[1] points = [ [3.1, 4.1], [0.9, 0.8], [1.0, 1.0] ] points = sorted(points, key=my_key) print(points) assert points == [ [0.9, 0.8], [1.0, 1.0], [3.1, 4.1] ] ``` Upvotes: 5 [selected_answer]<issue_comment>username_4: It looks like you are going through some extra hoops here. You have a quantity that is already a perfect key. Instead of just using it, you define a comparator that recomputes and compares two of these quantities for every pair of objects, and then convert that comparator back to a key. This seems very inefficient. Why not just define a simple key function and use it directly? ``` def distance_from_origin_squared(point): return point[0]**2 + point[1]**2 points = sorted(points, key=distance_from_origin_squared) ``` Keep in mind that `sorted` does not operate in-place, so you have to stash it somewhere. Replacing the original name if fine. If you want an in-place sort, use `list.sort` instead: ``` points.sort(key=distance_from_origin_squared) ``` From a practical point of view, keys offer a number of advantages over comparators. For one thing, a key function only needs to be called once per element, while a comparator is called `O(nlog(n))` times. Of course the keys are compared `O(nlog(n))` times, but the comparison is usually much simpler since the values of interest are computed up front. The main difficulty coming from C (in my case) is grasping the idea that keys do not have to be single integers, as is usually shown in examples. Keys can be **any** type that clearly defines the `<` (or `>`) operator. Lexicographical comparison of strings, lists and tuples makes it very easy to boil a complex chained comparator to a key that is just a short sequence of values. Upvotes: 2
2018/03/16
300
1,074
<issue_start>username_0: I have the root project-folder. Where each php files are in specific folder. For each nav items, I have passed the php page through href="" tag. When I click on the nav item it then takes me to the requested page as passed in href. But when from that page if i choose other nav items it says page not found. * Project * Categories 1. Page.php 2. NextPage.php * Extras 1. extra.php e.g `[Page](Categories/page.php)` `[Extra](Extras/extra.php)` When I am on extra.php and choose another nav items from navigation it says object not found. The URI becomes unreachable i.e `http://localhost/Project/Extras/extra.php/Categories/page.php`"Object Not Found" It should be like `http://localhost/Project/Categories/page.php`.<issue_comment>username_1: Just use absolute links ``` [Page](/Project/Categories/page.php) [Extra](/Project/Extras/extra.php) ``` Upvotes: 2 <issue_comment>username_2: You need to make your tags start from the project root by prefixing all the links with `/` `[Page](/Project/Categories/page.php)` Upvotes: 0
2018/03/16
405
1,462
<issue_start>username_0: My compiler gives me an error for the following code: ``` #include #include using namespace std; void test() { throw runtime\_error("Error"); } int main() { try { test(); } for (int i = 0; i < 10; i++) { } catch (exception& e) { cout << e.what(); } } ``` It says "error: expected 'catch' before '(' token", and it's referring to the '(' in the for loop initialization. Do I have to write the catch block immediately after the try block? I thought that if an error is thrown in the try block, the program will bubble out until it finds an appropriate catch block. Why doesn't that apply here?<issue_comment>username_1: Yes it does. And by yes, I mean it does. --- To be explicit, as some people seem to be confused by the above brief answer: **A** catch block **does** need to be written immediately after a try block. There is a secondary question: > > I thought that if an error is thrown in the try block, the program will bubble out until it finds an appropriate catch block. Why doesn't that apply here? > > > Because you can only write a catch block immediately after a try block. Anything else is an ill formed program. Upvotes: 3 <issue_comment>username_2: it should always similar to this pseudo code: [reference](http://www.cplusplus.com/doc/tutorial/exceptions/) ``` try { risky code block } catch (ExceptionClassName exceptionObjectName) { code to resolve problem } ``` Upvotes: 0
2018/03/16
405
1,438
<issue_start>username_0: ``` import smtplib sender = '<EMAIL>' receivers = ['<EMAIL>'] message = """From: User To: To user\_2 Subject: message this is a test megssage. """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print ("Successfully sent email") except smtplib.SMTPException: print ("Error: unable to send email") ``` When I try to run this program, it shows an error: ``` ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it ``` Moreover what do I have to put in `localhost`?<issue_comment>username_1: Yes it does. And by yes, I mean it does. --- To be explicit, as some people seem to be confused by the above brief answer: **A** catch block **does** need to be written immediately after a try block. There is a secondary question: > > I thought that if an error is thrown in the try block, the program will bubble out until it finds an appropriate catch block. Why doesn't that apply here? > > > Because you can only write a catch block immediately after a try block. Anything else is an ill formed program. Upvotes: 3 <issue_comment>username_2: it should always similar to this pseudo code: [reference](http://www.cplusplus.com/doc/tutorial/exceptions/) ``` try { risky code block } catch (ExceptionClassName exceptionObjectName) { code to resolve problem } ``` Upvotes: 0
2018/03/16
1,783
6,320
<issue_start>username_0: I really want to learn and understand how to concatenate strings with the cursor approach. Here is my table: ``` declare @t table (id int, city varchar(15)) insert into @t values (1, 'Rome') ,(1, 'Dallas') ,(2, 'Berlin') ,(2, 'Rome') ,(2, 'Tokyo') ,(3, 'Miami') ,(3, 'Bergen') ``` I am trying to create a table that has all cities for each ID within one line sorted alphabetically. ``` ID City 1 Dallas, Rome 2 Berlin, Rome, Tokyo 3 Bergen, Miami ``` This is my code so far but it is not working and if somebody could walk me through each step I would be very happy and eager to learn it! ``` set nocount on declare @tid int declare @tcity varchar(15) declare CityCursor CURSOR FOR select * from @t order by id, city open CityCursor fetch next from CityCursor into @tid, @tcity while ( @@FETCH_STATUS = 0) begin if @tid = @tid -- my idea add all cities in one line within each id print cast(@tid as varchar(2)) + ', '+ @tcity else if @tid <> @tid --when it reaches a new id and we went through all cities it starts over for the next line fetch next from CityCursor into @tid, @tcity end close CityCursor deallocate CityCursor select * from CityCursor ```<issue_comment>username_1: First, for future readers: A cursor, as <NAME> wrote in his comment, is the wrong tool for this job. The correct way to do it is using a subquery with `for xml`. However, since you wanted to know how to do it with a cursor, you where actually pretty close. Here is a working example: ``` set nocount on declare @prevId int, @tid int, @tcity varchar(15) declare @cursorResult table (id int, city varchar(32)) -- if you are expecting more than two cities for the same id, -- the city column should be longer declare CityCursor CURSOR FOR select * from @t order by id, city open CityCursor fetch next from CityCursor into @tid, @tcity while ( @@FETCH_STATUS = 0) begin if @prevId is null or @prevId != @tid insert into @cursorResult(id, city) values (@tid, @tcity) else update @cursorResult set city = city +', '+ @tcity where id = @tid set @prevId = @tid fetch next from CityCursor into @tid, @tcity end close CityCursor deallocate CityCursor select * from @cursorResult ``` results: ``` id city 1 Dallas, Rome 2 Berlin, Rome, Tokyo 3 Bergen, Miami ``` I've used another variable to keep the previous id value, and also inserted the results of the cursor into a table variable. Upvotes: 4 [selected_answer]<issue_comment>username_2: I have written nested cursor to sync with distinct city id. Although it has performance issue, you can try the following procedure ``` CREATE PROCEDURE USP_CITY AS BEGIN set nocount on declare @mastertid int declare @detailstid int declare @tcity varchar(MAX) declare @finalCity varchar(MAX) SET @finalCity = '' declare @t table (id int, city varchar(max)) insert into @t values (1, 'Rome') ,(1, 'Dallas') ,(2, 'Berlin') ,(2, 'Rome') ,(2, 'Tokyo') ,(3, 'Miami') ,(3, 'Bergen') declare @finaltable table (id int, city varchar(max)) declare MasterCityCursor CURSOR FOR select distinct id from @t order by id open MasterCityCursor fetch next from MasterCityCursor into @mastertid while ( @@FETCH_STATUS = 0) begin declare DetailsCityCursor CURSOR FOR SELECT id,city from @t order by id open DetailsCityCursor fetch next from DetailsCityCursor into @detailstid,@tcity while ( @@FETCH_STATUS = 0) begin if @mastertid = @detailstid begin SET @finalCity = @finalCity + CASE @finalCity WHEN '' THEN +'' ELSE ', ' END + @tcity end fetch next from DetailsCityCursor into @detailstid, @tcity end insert into @finaltable values(@mastertid,@finalCity) SET @finalCity = '' close DetailsCityCursor deallocate DetailsCityCursor fetch next from MasterCityCursor into @mastertid end close MasterCityCursor deallocate MasterCityCursor SELECT * FROM @finaltable END ``` If you will face any problem, feel free to write in comment section. Thanks Upvotes: 2 <issue_comment>username_3: Using a cursor for this is probably the slowest possible solution. If performance is important then there are three valid approaches. The first approach is FOR XML without special XML character protection. ``` declare @t table (id int, city varchar(15)) insert into @t values (1, 'Rome'),(1, 'Dallas'),(2, 'Berlin'),(2, 'Rome'),(2, 'Tokyo'), (3, 'Miami'),(3, 'Bergen'); SELECT t.id, city = STUFF(( SELECT ',' + t2.city FROM @t t2 WHERE t.id = t2.id FOR XML PATH('')),1,1,'') FROM @t as t GROUP BY t.id; ``` The drawback to this approach is when you add a reserved XML character such as &, <, or >, you will get an XML entity back (e.g. "&" for "&"). To handle that you have to modify your query to look like this: **Sample data** ``` IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t; CREATE TABLE #t (id int, words varchar(20)) INSERT #t VALUES (1, 'blah blah'),(1, 'yada yada'),(2, 'PB&J'),(2,' is good'); SELECT t.id, city = STUFF(( SELECT ',' + t2.words FROM #t t2 WHERE t.id = t2.id FOR XML PATH(''), TYPE).value('.','varchar(1000)'),1,1,'') FROM #t as t GROUP BY t.id; ``` The downside to this approach is that it will be slower. The good news (and another reason this approach is 100 times better than a cursor) is that both of these queries benefit greatly when the optimizer chooses a parallel execution plan. The best approach is a new fabulous function available in SQL Server 2017, [STRING\_AGG](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql). STRING\_AGG does not have the problem with special XML characters and is, by far the cleanest approach: ``` SELECT t.id, STRING_AGG(t.words,',') WITHIN GROUP (ORDER BY t.id) FROM #t as t GROUP BY t.id; ``` Upvotes: 1
2018/03/16
598
2,126
<issue_start>username_0: Getting a bit stuck trying to build this query. **(SQL SERVER)** I'm trying to join two tables on similar rows, but then stack the unique rows from both table 1 and table 2 on the result set. I was first shooting for a full outer join, but it leaves my key fields blank when the data comes from only one of the tables. **Example:** [Full Outer Join](http://sqlfiddle.com/#!18/576bc/4) Here's what I would like for the query to be able to do: [![Joining And Stacking Tables](https://i.stack.imgur.com/0angB.jpg)](https://i.stack.imgur.com/0angB.jpg) Essentially, I would like to have a result table where the key fields (Part and Operation) are all returned in two columns (so like a union), but the Estimated and Actual Rate columns returned side by side where there is a matching row between table 1 and table 2. I've also been trying to inner join the two tables to make a subquery, then using that inner join for except clause on each of the tables, then stacking the original inner join with the two except unions. **Current Attempt:** [One Join, Two Excepts, Two Unions](http://sqlfiddle.com/#!18/576bc/19) **UPDATE:** I got the current attempt to return values! It's a bit complicated though, Appreciate any advice or feedback though! Great answers below thanks, I will need to do some comparisons Thanks<issue_comment>username_1: ``` SELECT ISNULL(t1.part,t2.part) AS Part, ISNULL(t1.operation,t2.operation) AS Operation, ISNULL('Estimated Rate',0) AS 'Estimated Rate', ISNULL('Actual Rate',0) AS 'Actual Rate' FROM table1 t1 FULL OUTER JOIN table2 t2 ON t1.part = t2.part AND t1.operation = t2.operation ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: I would do this as a `union all` and `group by`: ``` select part, operation, sum(estimatedrate) as estimatedrate, sum(actualrate) as actualrate from ((select part, operation, estimatedrate, 0 as actualrate from table1 ) union all (select part, operation, 0 as estimatedrate, 0 actualrate from table1 ) ) er group by part, operation; ``` Upvotes: 0
2018/03/16
780
3,196
<issue_start>username_0: ViewToken.class: ``` spinnerGenre = (Spinner) findViewById(R.id.spinnerGenres); spinnerGenre1 = (Spinner) findViewById(R.id.spinner); docname = spinnerGenre1.getSelectedItem().toString(); session = spinnerGenre.getSelectedItem().toString(); next=(Button)findViewById(R.id.button4); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent next=new Intent(ViewToken.this,Tokens.class); next.putExtra("docname", docname.toString()); next.putExtra("session", session.toString()); startActivity(next); } }); ``` Tokens.class ``` Intent i2 = getIntent(); final String docname = i2.getStringExtra("docname"); final String session = i2.getStringExtra("session"); ``` The spinner value from ViewToken.class is not passed to Tokens.class<issue_comment>username_1: Change this in ViewToken.class ``` next.putExtra("docname", docname); next.putExtra("session", session); ``` You can do the following in your Tokens.class ``` Bundle extras = getIntent().getExtras(); String docname = extras.getString("docname"); String session = extras.getString("session"); ``` Upvotes: 1 <issue_comment>username_2: The calls to `getSelectedItem()` should be made in the `onClick` listener so that it gets the most up-to-date values selected. So instead the `onClick()` method will be: ``` @Override public void onClick(View v) { docname = spinnerGenre1.getSelectedItem().toString(); session = spinnerGenre.getSelectedItem().toString(); Intent next=new Intent(ViewToken.this,Tokens.class); next.putExtra("docname", docname); next.putExtra("session", session); startActivity(next); } ``` It is likely that the calls to `getSelectedItem()` where being made before anything was selected and therefore the values being `put()` inside the intent where incorrect. Upvotes: 1 <issue_comment>username_3: get the values from the spinners just before send them. ``` next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { docname = spinnerGenre1.getSelectedItem().toString(); session = spinnerGenre.getSelectedItem().toString(); Intent next=new Intent(ViewToken.this,Tokens.class); next.putExtra("docname", docname.toString()); next.putExtra("session", session.toString()); startActivity(next); } }); ``` Upvotes: 0 <issue_comment>username_4: ``` int positionOfSelectedDataFromSpinner; iv.putExtra("position", positionOfSelectedDataFromSpinner); ``` Create a New Method ``` spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapterView, View view, int i, long l) { positionOfSelectedDataFromSpinner= i; } @Override public void onNothingSelected(AdapterView adapterView) { } }); ``` And In Second Activity ``` int positionToShowToSpinner = iv.getIntExtra("position",0); spinner.setSelection(positionToShowToSpinner); ``` Upvotes: 0
2018/03/16
640
2,571
<issue_start>username_0: I've picked up on a project that's a few years old, and noted CURRENT\_TIMESTAMP is being sent with a lot of the php calls to update the datetime field in a lot of rows. This works perfectly on the live environment - however, on my local setup, it does not. Both the Live DB, and my local version from the WAMP64 download are running on MySQL5.7.19. A PHP script running a query that involves inserting CURRENT\_TIMESTAMP will return back with the following error; ``` Invalid default value for 'last_update' timestamp ``` Again though, on the live server, this works without issue. Both are using MySQLi to carry out these insert queries. Is there something I'm missing here? Some sort of server-side config setting that allows CURRENT\_TIME to be inserted into the timestamp field?<issue_comment>username_1: The specific column must be missing in the insert statement because the error message stated `Invalid default value`. Please take a look at: [Invalid default value for 'create\_date' timestamp field](https://stackoverflow.com/questions/9192027/invalid-default-value-for-create-date-timestamp-field) (and read the helpful comments here). ;-) Upvotes: 1 <issue_comment>username_2: The `CURRENT_TIMESTAMP` field automatically pick the current time of server.or will only accept the timestamp values. So `DATETIME` fields must be left either with a null default value, or no default value at all - default values must be a constant value, not the result of an expression. relevant docs: <http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html> You can work around this by setting a post-insert trigger on the table to fill in a "now" value on any new records. Upvotes: 2 <issue_comment>username_3: 1. If you are inserting the last\_update value manually from php code then make the mysql filed as var-char as you passing the date is not recognize by database as date and this error is occurring. 2. Or you can just set the default value as CURRENT\_TIMESTAMP and set attribute as on update insert CURRENT\_TIMESTAMP. [![enter image description here](https://i.stack.imgur.com/e5MXR.png)](https://i.stack.imgur.com/e5MXR.png) So that when ever any update on filed it will update the CURRENT\_TIMESTAMP automatically. Upvotes: 0 <issue_comment>username_4: Perhaps database lost the default value for the date. You can try either of the following: ``` ALTER TABLE mydb.mytable MODIFY myfield datetime DEFAULT CURRENT_TIMESTAMP; ``` Or ``` ALTER TABLE mydb.mytable MODIFY myfield datetime DEFAULT NOW(); ``` Upvotes: 2
2018/03/16
451
1,591
<issue_start>username_0: This call is being made from my service to retrieve a URL to download a document: ``` return this.http.get(this.buildUrl('issueDocument', 'get', pathParams), { responseType: 'blob', params: queryParams }); ``` The buildURL inside this.http.get is working properly I've tested it however, the return for this.http.get throws this error ``` ERROR TypeError: Cannot read property 'length' of undefined at HttpHeaders.applyUpdate (http.js:322) at eval (http.js:269) at Array.forEach () at HttpHeaders.init (http.js:269) at HttpHeaders.forEach (http.js:368) at Observable.eval [as \_subscribe] (http.js:2172) at Observable.\_trySubscribe (Observable.js:172) at Observable.subscribe (Observable.js:160) at CatchOperator.call (catchError.js:80) at Observable.subscribe (Observable.js:157) ``` Any ideas on what's going on? I can't fit together why this is happening... In the dev tools network tab it's not even showing a network call...<issue_comment>username_1: From the error message it appears you just need to not let `undefined` passed into your `.set(...)` of the headers. I do this: ``` getHeaders() { const headers = new HttpHeaders(); headers .set('Content-Type', 'application/json') .set('Authorization', localStorage.getItem('token') || ''); return headers; } ``` Upvotes: 1 <issue_comment>username_2: to fix this, check variable before setting into header ``` if (!headers.has("Content-Type")) { headers = headers.clone( { headers: headers.set("Content-Type", "application/json") }); } ``` Upvotes: 0
2018/03/16
695
2,323
<issue_start>username_0: In cassandra DB I am planning to store an array-of-object. What is the best way to do that. object mapping to Data mapping with model class in java. ``` Class Test{ @Column(name = "id") int id, @Column(name = "name") String name, Address[] address class Address{ String add1, String city, String state } } ``` Should I put all(id, name, add1, city, state) in one table by adding columns to same keyspace with add1, city, state also? or add new table for address Or any other options.. I have tried to add `TYPE` But throwing error as: "Error from server: code=2200 `[Invalid query] message="A user type cannot contain non-frozen UDTs`" From the error and type syntax I have used keyword '`frozen`', but not luck. Altering table also gives similar Error something like : "`mismatched input 'frozen' expecting EOF`" Also, What if I have to save column of type `'String[ ]'` As it is not custom type like Address[]. it is of String or text.? Do we need to just add alter statement? if so how it looks like<issue_comment>username_1: you can create UDT type: ``` CREATE TYPE people ( name text, address ); ``` and now declare your field like this ``` people set> ``` I hope it's help you Upvotes: 2 <issue_comment>username_2: For your case, first, you need to create a UDT(user defined type) in Cassandra. ``` Create TYPE address( add1 text, city text, state text ); ``` Then create a table including this UDT. ``` Create table Test( id int, name text, address list>, primary key(id) ); ``` If you want to know more about UTD and the usages, visit following links: * [Using a user-defined type](https://docs.datastax.com/en/cql/3.1/cql/cql_using/cqlUseUDT.html) * [Collection type (List, Set, Map)](https://docs.datastax.com/en/cql/3.1/cql/cql_reference/collection_type_r.html) **EDIT**: > > Also, What if I have to save column of type 'String[ ]' As it is not custom type like Address[]. it is of String or text.? Do we need to just add alter statement? if so how it looks like > > > **Answer**: `Alter table test add stringarr list` Check this links to get more idea about cassandra data types: [CQL data types](https://docs.datastax.com/en/cql/3.1/cql/cql_reference/cql_data_types_c.html) Upvotes: 4 [selected_answer]
2018/03/16
332
1,292
<issue_start>username_0: I am new to React and I am doing some tutorials online. Now I have task like this: *If the Component in the following code is a Stateless Functional Component, what expression would you write to access the items prop inside the Component?* ``` ``` I have no idea what is correct answer and why :/ Would you be so kind to help me ?<issue_comment>username_1: If it's stateless `props.items`. If its a class `this.props.items` Stateless functional components typically look something like this. Passing just a single prop to a child would like this. ``` const ChildComponent = ({ someProp }) => ( Child Component {someProp} ========================== ) ``` Passing all of the parents props to a child would like like this. ``` const ChildComponent = (props) => ( Child Component {props.someProp} ================================ ) ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can access all your props by using props.itemName. Ex: By simply typing props.items Upvotes: 0 <issue_comment>username_3: Your functional component will look something like below, ``` const IngredientList = props => { // here you get all the props passed to IngredientList const items = props.items.map(item => item); return items } ``` Upvotes: 0
2018/03/16
391
1,223
<issue_start>username_0: Is it possible to use telnet in a interactive mode with curl? When I connect with window's telnet command it does behave as a telnet client and I can interact with it.<issue_comment>username_1: An unusual way to phrase that question but, yes. Yes indeed. My personal favorites are (in no particular order): ### [wuzz](https://github.com/asciimoo/wuzz) — [![wuzz screenshot](https://i.stack.imgur.com/NB5Bs.png)](https://i.stack.imgur.com/NB5Bs.png) ### [http-prompt](https://github.com/eliangcs/http-prompt) (based on HTTPie) — [![http-prompt screenshot](https://i.stack.imgur.com/JyENj.png)](https://i.stack.imgur.com/JyENj.png) ### [httplab](https://github.com/gchaincl/httplab) (an interactive web *server*, not a client) — [![httplab screenshot](https://i.stack.imgur.com/6Nl99.png)](https://i.stack.imgur.com/6Nl99.png) Upvotes: 0 <issue_comment>username_2: The following does what you're asking: ``` $ curl -vLI telnet://www.google.com:80/ <<< "GET /" ``` Additionally you can drop off the here string `<<< "GET /"` and type whatever HTTP commands you want to send to the server as if you were a browser. Typically it's `GET / HTTP/1.1` or something along those lines. Upvotes: 2
2018/03/16
331
1,078
<issue_start>username_0: ``` <!--This is in in the body section.--!> ### paragraphs /p> paragraph 1 paragraph 2 paragraph 3 paragraph 4 var x = document.querySelector("#div11 p:nth-child(2)"); document.write(x); ``` This html code returns null. However, it works fine when I remove the < h3> tags from the first paragraph. Can someone please explain why it behaves in this way?<issue_comment>username_1: It is invalid using block elements inside a tag, so changing it to e.g. a `span` and it works (and use the correct `id` for the `div`). Stack snippet ```js var x = document.querySelector("#par p:nth-child(2)"); console.log(x.outerHTML); ``` ```html paragraphs paragraph 1 paragraph 2 paragraph 3 paragraph 4 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Make use of `querySelectorAll` to get all matches: ```js var x = document.querySelectorAll("div p:nth-child(2)"); console.log(x); ``` ```html <!--This is in in the body section.--!> ### paragraphs /p> paragraph 1 paragraph 2 paragraph 3 paragraph 4 ``` Upvotes: 0
2018/03/16
415
1,410
<issue_start>username_0: I am trying to select a random row from a column in my database. I need the query to search/make sure that the random row selected is not equal to any of the values stored in two other columns. Example: **DATABASE NAME: database\_name** **TABLE1 contains one column: male\_id** **TABLE2 contains two columns: number\_list1 and number\_list2** I need a query that will find a random number in the male\_id column THAT IS NOT FOUND IN number\_list1 or number\_list2. Is there anyway to do this? Here was my best shot at it (causes an error): ``` SELECT male_id FROM TABLE1 WHERE male_id IS NOT (SELECT number_list1 FROM TABLE2) AND (SELECT number_list2 FROM TABLE2) ORDER BY RAND() ```<issue_comment>username_1: It is invalid using block elements inside a tag, so changing it to e.g. a `span` and it works (and use the correct `id` for the `div`). Stack snippet ```js var x = document.querySelector("#par p:nth-child(2)"); console.log(x.outerHTML); ``` ```html paragraphs paragraph 1 paragraph 2 paragraph 3 paragraph 4 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Make use of `querySelectorAll` to get all matches: ```js var x = document.querySelectorAll("div p:nth-child(2)"); console.log(x); ``` ```html <!--This is in in the body section.--!> ### paragraphs /p> paragraph 1 paragraph 2 paragraph 3 paragraph 4 ``` Upvotes: 0
2018/03/16
503
1,465
<issue_start>username_0: Is it safe to directly compare ISO Date Strings like this: `"2018-03-16T18:00:00.000z" > "2018-04-16T18:00:00.000z" // false` It seems as long as leading zeros are used (proper ISO formatting) this comparison is safe and there is no need to convert the values to Date Objects. Am I overlooking something?<issue_comment>username_1: To answer your question comparing dates is tricky. I like to convert to something that is a little more concrete. Maybe not the most efficient answer, but it works for comparing dates. ``` var d = new Date(); var d1 = new Date(); console.log(d); console.log(d1); console.log(d.getTime()); console.log(d1.getTime()); console.log(d.getTime() === d1.getTime()); // true ``` Converting both to a number for a more valid comparison. Pulling the property off of the object itself. <http://jsbin.com/siwokibovi/edit?js,console> Upvotes: 0 <issue_comment>username_2: With the given format of a [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time, ``` 2018-03-16T18:00:00.000Z ^ ``` you could use a direct string comparison, because the given time zone is a > > ### Coordinated Universal Time (UTC) > > > If the time is in UTC, add a Z directly after the time without a space. Z is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z". > > > Upvotes: 4 [selected_answer]
2018/03/16
363
1,420
<issue_start>username_0: I have a word template that prompts the user for some text when opens a new document. I'm using the Fill-In field to do that and works fine. My question is: How can I reference the Fill-In field to assign the user text to Title of the document ? I'm using this code, but it's not working: ``` With Dialogs(wdDialogFileSummaryInfo) .Title = Fillin .Execute End With ``` Main goal here is: whatever the user writes on the prompt field when the document opens first time, will be the default filename of the word document when saving. There is a better way to achieve this ? Thanks.<issue_comment>username_1: All you need is: ``` ActiveDocument.Fields.Update ``` In a Document\_New macro in the 'ThisDocument' code module of the document's template. Upvotes: -1 <issue_comment>username_2: This field code combination will assign what the user types into the Fill-in field to the Title property that provides the default file name for a new document: ``` { TITLE { Fillin "Enter the document title" } } ``` It should display automatically when a new document is created from the template. As it stands, this will also display on the document surface. If you want it to be "hidden" you can nest the above in a SET field: ``` { Set bkmTitle { TITLE { Fillin "Enter the document title" } } } ``` A Set field creates a bookmark, but the content is hidden for the user. Upvotes: 0
2018/03/16
1,274
4,519
<issue_start>username_0: I am new to python 3 and I'm working on sentiment analysis of tweets. My code begins with a for loop that takes in 50 tweets, which i clean and pre-process. After this (still inside the for loop) i want to save each tweet in a text file(every tweet on a new line) Here's how the code goes: ``` for loop: .. print statments .. if loop: filename=open("withnouns.txt","a") sys.stdout = filename print(new_words)#tokenised tweet that i want to save in txt file print("\n") sys.stdout.close()#i close it because i dont want to save print statements OUTSIDE if loop to be saved in txt file .. .. print statements ``` After running this its showing error: I/O operation on closed file on line 71 (the first print statement after if loop) My question is, is there any way I can temporarily close and then open `sys.stdout` and have it active only inside the if loop?<issue_comment>username_1: I'm not sure if this is exactly what you want to do but you can change this ``` filename=open("withnouns.txt","a") sys.stdout = filename print(new_words) print("\n") sys.stdout.close() ``` to ``` filename=open("withnouns.txt","a") filename.write(new_words + "\n") filename.write("\n\n") filename.close() ``` alternatively, you can get the original value of `sys.stdout` from `sys.__stdout__`, so your code becomes ``` filename=open("withnouns.txt","a") sys.stdout = filename print(new_words) print("\n") filename.close() sys.stdout = sys.__stdout__ ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: You do not need to assign to `sys.stdout` *at all*. Just tell `print()` to write to the file instead, using the `file` argument: ``` print(new_words, file=filename) print("\n", file=filename) ``` There is no need to assign anything to `sys.stdout` now, because now `print()` writes directly to your file instead. You also want to use the file object as a context manager, so it is closed or you: ``` with open("withnouns.txt","a") as filename: print(new_words, file=filename) print("\n", file=filename) ``` You never needed to close the `sys.stdout` reference anyway, you wanted to close `filename` instead, and restore `sys.stdout` to it's former state. If you did want need to replace `sys.stdout`, you have a few options, from most correct to least: * Use [`contextlib.redirect_stdout()`](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout): ``` import contextlib with contextlib.redirect_stdout(some_fileobject): # do things that write to stdout ``` At the end of the block `stdout` is fixed up for you. * Manually store `sys.stdout` first: ``` old_stdout = sys.stdout sys.stdout = new_object try: # do things that write to stdout finally: sys.stdout = old_stdout ``` * Use the [`sys.__stdout__` copy](https://docs.python.org/3/library/sys.html#sys.__stdout__); this is set on start-up: ``` sys.stdout = new_object try: # do things that write to stdout finally: sys.stdout = sys.__stdout__ ``` You need to take into account that `sys.stdout` may have been replaced by something else before your code runs, and restoring it back to `sys.__stdout__` might be the wrong thing to do. Upvotes: 1 <issue_comment>username_3: You're confusing two different kinds of writing to file. `sys.stdout` pipes your output to the console/terminal. This can be written to file but it's very roundabout. Writing to file is different. In python you should look at the [`csv` module](https://docs.python.org/3/library/csv.html) if you're writing lists of values of all the same length (and maybe even if you're not, it's very easy to use). Open your file outside the loop. In the loop, write to file line by line. Close the file outside the loop. This is automatically done for you if you use the following "with" syntax: ``` import csv with open('file.csv') as f: writer = csv.writer(f, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) for loop: # tokenize tweet writer.writerow(tweet) ``` Alternatively, loop through and save tokenized-tweets to a list-of-lists. Then, outside and after the loop, write the entire thing to a file: ``` import csv tweets = [] for loop: # tokenize tweet tweets.append(tweet) with open('file.csv') as f: writer = csv.writer(f, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerows(tweets) ``` Upvotes: 0
2018/03/16
821
3,102
<issue_start>username_0: Reading over stack overflow and the internet i can't find a solution for a problem that seems simple to solve, but... i can't get it. The problem is pretty simple, `${match.path}/notas`} component={Dashboard} />` doesnt' render the `Dashboard` component... why? No idea.` Here is the general code: The index, where the routes begin: ``` const rootNode = document.getElementById('root') ReactDOM.render( , rootNode ) ``` The App component, main layout: ``` class App extends Component { componentWillMount() { const data = { loggedIn: false } sessionStorage.setItem('auth', JSON.stringify(data)) } render() { return ( {APP\_TITLE} ) } } ``` And the Home component: ``` const Home = ({match}) => { return } ``` Is that simple, nothing special... the idea is `Dashboard` will display some json content based on the `match.path`, but when i navigate to the established path, the app doesn't display anything, just a void , no idea why... A fast note: the first render of `Home` renders perfectly the Sidebar and the `Dashboard` related to the first route. Here is the navigation to get to the component: ``` const Sidebar = () => { return * Total * Videos * Notas } ``` **Edit** By petiton, the Dashboard component: ``` import React, { Component } from 'react' import { connect } from 'react-redux' class Dashboard extends Component { render() { return ( {this.props.match.path} ) } } const mapStateToProps = state => ({ dashboard: state.dashboard }) export default connect(mapStateToProps)(Dashboard) ``` yep, is that simple for now... Update ------ I've been experimenting around, my first thought was "update blocker" but any of the posible fixes in the documentation didn't work, wrapping the `Dashboard` component into a `withRouter` function like: `const WrappedDash = withRouter(Dashboard)` and passing it into a route, trying to render the child component with `render={() => }` nor passing explicitly the `location` object to Dashboard in the render method. Every case is the same, NavLink take me to the dictated route, and it renders nothing (a void section element). The weird case is, even if I make a plain route like `/videos` instead `${match}/videos`, the router keep rendering nothing. I thought that can be a problem with authenticated routes but it doesnt't make any sense for me.<issue_comment>username_1: In app ``` } /> } /> ``` In home ``` } /> } /> } /> ``` Need to use the render prop. Upvotes: 1 <issue_comment>username_2: Well, I fixed the problem, it was in the `exact` declaration of the Home route, I was expecting exactly the home route to render the content. Yes, is a very stupid detail but it matters a lot: ``` ``` The above code will not render anything else that the component of `/home`, and the code below (the inclusive route), will render everything: ``` ``` It was that simple, I'm sorry for the question but little details like this are difficult to see if it is your first time with new tools. Upvotes: 1 [selected_answer]
2018/03/16
723
2,493
<issue_start>username_0: Say I have an input that is stored in a `char c`, and in a conditional I need to check whether it is either of two different characters, for example `'n'` and `'N'`. It's obvious that I can make a conditional with a logical `OR` operator: ``` if(c == 'n' || c == 'N') ... ``` However, if there are significantly more than just two conditions, than that will require significantly more logical operators to be used, and it will become tedious to write, look at, and edit. Is there a way to condense this process? To make it look like something along the lines of this: ``` if(c == '[N][n]') ... ``` Does anything of the sort exist?<issue_comment>username_1: You can make a string of your matching characters and see if the character in question exists in the string: ``` char c; std::string good_chars = "nNyYq"; if(good_chars.find(c) != std::string::npos) { std::cout << "it's good!"; } ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You can use `to_upper` `or to_lower` APIs if your scanning is not case sensitive this way: ``` char c = 'n'; if( static_cast('N') == std::toupper(static\_cast(c)) ) // do something ``` Or: ``` char c = 'n'; if( static_cast('n') == std::tolower(static\_cast(c)) ) // Do something ``` Upvotes: 1 <issue_comment>username_3: A low-tech solution would be to use a `switch` statement instead. Reading and editing may turn out to be much easier with `case` labels if you have a lot of matching characters. ``` bool matches(char c) { switch (c) { case 'n': case 'N': case 'a': case 'b': case 'c': return true; } return false; } ``` A more advanced solution would be to store the characters in a container. `std::set` would be an option: ``` bool matches(char c) { // note: might want to use static storage for `chars` std::set const chars = { 'n', 'N', 'a', 'b', 'c', }; return chars.find(c) != end(chars); } ``` `std::string` allows for a more condensed form, which may be good or bad as far as readability and maintainability is concerned: ``` bool matches(char c) { // note: might want to use static storage for `chars` std::string const chars = "nNabc"; return chars.find(c) != std::string::npos; } ``` Note that different containers have different algorithmic complexity characteristics, which may be relevant if a function like `match` should actually turn out to be a performance bottleneck. Upvotes: 3
2018/03/16
430
1,420
<issue_start>username_0: I am trying to get my footer to be stickied to the bottom when the page's content doesn't reach the end of the screen. I am building an Angular 5 application. I added the , and tags to my `app.component.html`. I tried adding the required css from Materialize everywhere. In the global css file, the app.component css file, even in the Materialize css. I just don't know what I'm doing wrong. Here is my `app.component.html`: ``` ``` The `app-footer` starts with this: ``` ``` I'd like to know where to put the css required for my footer to go to the bottom of the page.<issue_comment>username_1: A fast answer is to put the html that is inside your FooterComponent in the index.html. Surround your tag with the tag, like this example: ``` ``` (remember to erase your html inside your FooterComponent) Upvotes: 1 <issue_comment>username_2: In your AppComponent.html: ``` ``` and change your style.css: ``` body > app-root { display: flex; min-height: 100vh; flex-direction: column; } main { flex: 1 0 auto; } ``` Upvotes: 0 <issue_comment>username_3: ### <NAME>'s answer worked for me! ***However*** It should be noted that the chunk: ``` body > app-root { display: flex; min-height: 100vh; flex-direction: column; } main { flex: 1 0 auto; } ``` had to be placed in the sitewide `styles.css` file for it to work. Upvotes: 0
2018/03/16
1,357
3,646
<issue_start>username_0: I am still a beginner, sorry if it's a silly question, I will try to keep it short and specific. So, I wanted to create a zooming out effect in an image grid using CSS grid display and transform scale properties. The result I got was off from the desired result, I'll post images of both after the code. Here's the code I have used: ```css .meals-gallery { background-color: #000; display: grid; grid-template-columns: repeat(4, 25%); grid-template-rows: repeat(2, 1fr); overflow: hidden; padding: 0; } .meals-gallery img { opacity: 0.7; transform: scale(1.15); transition: 0.5s; width: 100%; } .meals-gallery img:hover { opacity: 1; transform: scale(1.03); } ``` ```html ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ``` The images overlap while being at 70% opacity, so they look ugly, even though I have added overflow property to be hidden.. Here's the desired effect: ![Desired image effect](https://i.stack.imgur.com/jZTk0.jpg) And here's what I have achieved: ![The effect I get](https://i.stack.imgur.com/cMdii.jpg) Thank you in advance.<issue_comment>username_1: I think we'll need to wrap the `img` elements in a container, like a `div`, and use `overflow: hidden;` on the `div`. Then we can `transform: scale` the `img` elements on `div:hover`. I think this is the effect you're going for: ```css .meals-gallery { background-color: #000; display: grid; grid-template-columns: repeat(4, 25%); grid-template-rows: repeat(2, 1fr); overflow: hidden; padding: 0; } .meals-gallery > div { overflow: hidden; position: relative; } .meals-gallery img { opacity: 0.7; transform: scale(2); transform-origin: 50% 50%; transition: all 0.5s ease-in-out; display: block; width: 100%; } .meals-gallery div:hover img { opacity: 1; transform: scale(1.1); } ``` ```html ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: From this [blog](https://gridbyexample.com/examples/example1/) > > `grid-gap` property to create a gap between my columns and rows of 10px. > This property is a shorthand for `grid-column-gap` and `grid-row-gap` so > you can set these values individually. > > > ```css .meals-gallery { background-color: #000; display: grid; grid-template-columns: repeat(4, 35%); grid-template-rows: repeat(2, 1fr); } .meals-gallery img { display: grid; grid-template-columns: 100px 100px 100px; grid-gap: 10px; width: 100%; background-color: #fff; color: #444; } .meals-gallery img:hover { opacity: 1; transform: scale(1.03); } ``` ```html ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ![](http://placeholder.pics/svg/600x500) ``` Upvotes: 1
2018/03/16
627
2,370
<issue_start>username_0: I'm finding I'm able to set the shadow image on the navigation bar, but I only want to set it when I'm scrolling and not able to find how to do this. any help appreciated!!<issue_comment>username_1: ``` func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset.y if offset <= 0 { // scroll view is at the top, disable shadow } else { // scroll view has positive offset, enable shadow } print(offset) // if you aren't familiar with how it works } ``` You can access this delegate method from either a `UIScrollView` or a `UITableView` as the latter is a subclass of the former. Upvotes: 1 <issue_comment>username_2: You can use this code with [scrollViewDidScroll(\_:)](https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619392-scrollviewdidscroll): ``` import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = "Hello" return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func scrollViewDidScroll(_ scrollView: UIScrollView) { guard let navBar = navigationController?.navigationBar else { return } if scrollView.contentOffset.y > navBar.frame.height { addShadow(navBar) } else { deleteShadow(navBar) } } func addShadow(_ view: UIView) { view.layer.shadowColor = UIColor.gray.cgColor view.layer.shadowOffset = CGSize(width: 0.0, height: 6.0) view.layer.masksToBounds = false view.layer.shadowRadius = 10.0 view.layer.shadowOpacity = 0.5 } func deleteShadow(_ view: UIView) { view.layer.shadowOffset = CGSize(width: 0, height: 0.0) view.layer.shadowRadius = 0 view.layer.shadowOpacity = 0 } } ``` Upvotes: 0
2018/03/16
1,225
5,020
<issue_start>username_0: I'm using FluentAssertions to compare two objects using `Should().BeEquivalentTo()` where one object is an EF dynamic proxy. However, it appears that the unification of `ShouldBeEquivalentTo` and `ShouldAllBeEquivalentTo` ([#593](https://github.com/fluentassertions/fluentassertions/pull/593)) in 5.0.0 has broken the functionality when using `RespectingRuntimeTypes`. The property members of derived types of the declared types are no longer being compared unless I add `ComparingByMembers` explicitly for every type in my object graph. Is there any way around this using other settings?<issue_comment>username_1: I've written the following extension method in an attempt to resolve the problem, but it seems cumbersome just to fix an issue with derived types at run-time on dynamic proxies: ``` public static class FluentAssertionsExtensions { /// /// Extends the functionality of .ComparingByMembers by recursing into the entire object graph /// of the T or passed object and marks all property reference types as types that should be compared by its members even though it may override the /// System.Object.Equals(System.Object) method. T should be used in conjunction with RespectingDeclaredTypes. The passed object should be used in /// conjunction with RespectingRuntimeTypes. /// public static EquivalencyAssertionOptions ComparingByMembersRecursive(this EquivalencyAssertionOptions options, object obj = null) { var handledTypes = new HashSet(); var items = new Stack<(object obj, Type type)>(new[] { (obj, obj?.GetType() ?? typeof(T)) }); while (items.Any()) { (object obj, Type type) item = items.Pop(); Type type = item.obj?.GetType() ?? item.type; if (!handledTypes.Contains(type)) { handledTypes.Add(type); foreach (PropertyInfo pi in type.GetProperties()) { object nextObject = item.obj != null ? pi.GetValue(item.obj) : null; Type nextType = nextObject?.GetType() ?? pi.PropertyType; // Skip string as it is essentially an array of chars, and needn't be processed. if (nextType != typeof(string)) { if (nextType.GetInterface(nameof(IEnumerable)) != null) { nextType = nextType.HasElementType ? nextType.GetElementType() : nextType.GetGenericArguments().First(); if (nextObject != null) { // Look at all objects in a collection in case any derive from the collection element type. foreach (object enumObj in (IEnumerable)nextObject) { items.Push((enumObj, nextType)); } continue; } } items.Push((nextObject, nextType)); } } if (type.IsClass && type != typeof(string)) { // ReSharper disable once PossibleNullReferenceException options = (EquivalencyAssertionOptions)options .GetType() .GetMethod(nameof(EquivalencyAssertionOptions.ComparingByMembers)) .MakeGenericMethod(type).Invoke(options, null); } } } return options; } } ``` This should be called like this: ``` foo.Should().BeEquivalentTo(bar, o => o .RespectingRuntimeTypes() .ComparingByMembersRecursive(foo) .ExcludingMissingMembers()); ``` Upvotes: 2 <issue_comment>username_2: I Recently faced to the same problem by using `Microsoft.EntityFrameworkCore.Proxies`. In my case, I had to compare persistent properties and ignore comparing the rest even navigation properties. The solution is implementing the intercafe `FluentAssertions.Equivalency.IMemberSelectionRule` to excluding unnecessary properties. ``` public class PersistentPropertiesSelectionRule : IMemberSelectionRule where TEntity : class { public PersistentPropertiesSelectionRule(DbContext dbContext) => this.dbContext = dbContext; public bool IncludesMembers => false; public IEnumerable SelectMembers( IEnumerable selectedMembers, IMemberInfo context, IEquivalencyAssertionOptions config) { var dbPropertyNames = dbContext.Model .FindEntityType(typeof(TEntity)) .GetProperties() .Select(p => p.Name) .ToArray(); return selectedMembers.Where(x => dbPropertyNames.Contains(x.Name)); } public override string ToString() => "Include only persistent properties"; readonly DbContext dbContext; } ``` Then writing an extension method can help for convenient usage and also improve readability. The extension method can be something like the following piece of code. ``` public static class FluentAssertionExtensions { public static EquivalencyAssertionOptions IncludingPersistentProperties(this EquivalencyAssertionOptions options, DbContext dbContext) where TEntity : class { return options.Using(new PersistentPropertiesSelectionRule(dbContext)); } } ``` At the end you can call the extension method in you test like the below piece of code. ``` // Assert something using (var context = DbContextFactory.Create()) { var myEntitySet = context.MyEntities.ToArray(); myEntitySet.Should().BeEquivalentTo(expectedEntities, options => options .IncludingPersistentProperties(context) .Excluding(r => r.MyPrimaryKey)); } ``` This implementaion solved my problem and the code looks neat and tidy. Upvotes: 1
2018/03/16
1,187
4,914
<issue_start>username_0: I've installed css-loader and style-loader. Then I configured webpack.dev and webpack.prod. I suppose there's a problem with webpack because component's syntax isn't complicated. The component ignores styles. Why? package.json ``` "dependencies": { "css-loader": "^0.28.11", "prop-types": "^15.6.1", "react": "^16.2.0", "react-dom": "^16.2.0", "react-router-dom": "^4.2.2", "react-scripts": "1.1.1", "style-loader": "^0.20.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject"`enter code here`: "react-scripts eject" } ``` webpack.config.dev.js ``` test: /\.css$/, use: [ require.resolve('style-loader'), { loader: require.resolve('css-loader'), options: { importLoaders: 1, modules: true, localIdentName: '[name]__[local]__[hash:base64:5]' }, }, ``` webpack.config.prod.js ``` test: /\.css$/, loader: ExtractTextPlugin.extract( Object.assign( { fallback: { loader: require.resolve('style-loader'), options: { hmr: false, }, }, use: [ { loader: require.resolve('css-loader'), options: { importLoaders: 1, modules: true, localIdentName: '[name]__[local]__[hash:base64:5]', minimize: true, sourceMap: shouldUseSourceMap, }, }, ``` component ``` import React, { Component } from 'react'; import styles from './addTask.css'; export default class AddTask extends Component { render() { return ( this should be a big font ); } } ``` css for the component ``` .big { font-size: 111px; } ```<issue_comment>username_1: Can you try the following syntax for your webpack config file? <https://webpack.js.org/concepts/loaders/#configuration> <https://github.com/webpack-contrib/css-loader> ``` module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { importLoaders: 1, modules: true, localIdentName: '[name]__[local]__[hash:base64:5]' } } ] } ] } ``` Upvotes: 0 <issue_comment>username_2: I had same issue. Was using a git to track the files. Before running `npm run eject` to edit in the webpack.config file I have added and commit the react package into the repo. Then I run `npm run eject` and added above mentioned changes. and Again I restart the npm, it worked for me. Upvotes: 1 <issue_comment>username_3: Try to paste it below the " test: /.css$/, ". It helped me. ``` use: [ require.resolve('style-loader'), { loader: require.resolve('css-loader'), options: { importLoaders: 1, modules:true, localIdentName:'[name]__[local]__[hash:base64:5]' }, }, { loader: require.resolve('postcss-loader'), options: { // Necessary for external CSS imports to work // https://github.com/facebookincubator/create-react-app/issues/2677 ident: 'postcss', plugins: () => [ require('postcss-flexbugs-fixes'), autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ], flexbox: 'no-2009', }), ], }, }, ], ``` Upvotes: 0 <issue_comment>username_4: rename ``` addTask.css ``` to ``` addTask.module.css ``` and change the import to ``` import styles from './addTask.module.css' ``` Upvotes: 3 <issue_comment>username_5: In order for react to understand your css file is a css-module, you need to add the suffix `.module` to the file name while using a react-script version newer than `2.0.0`. Simply rename `addTask.css` to `addTask.module.css` and change the import to: ``` import styles from './addTask.module.css' ``` Upvotes: 2
2018/03/16
243
857
<issue_start>username_0: When i am trying to run my own flutter app in android studio it gives error like this **This is my app screenshot:** ![](https://i.stack.imgur.com/u5KWrl.png) **This is my logcat:** ![](https://i.stack.imgur.com/gfOQ8l.png)<issue_comment>username_1: The problem is that `Colors.black` is a single color, but `primarySwatch` expects a palette of multiple colors. If you look at the documentation for [Colors](https://docs.flutter.io/flutter/material/Colors-class.html), the different built in palettes are shown. For example, Colors.blue is a blue palette, and can be passed to `primarySwatch`. ``` new MaterialApp(theme: new ThemeData(primarySwatch: Colors.blue)) ``` Upvotes: 1 <issue_comment>username_2: see your space in single quotation, you should write like this : var first = ['answer':'black','white',...]; Upvotes: 0
2018/03/16
342
1,187
<issue_start>username_0: The problem with the code, below, is that it removes **characters** from the string rather than the **words**. ``` php $str = "In a minute, remove all of the corks from these bottles in the cellar"; $useless_words = array("the", "of", "or", "in", "a"); $newstr = str_replace($useless_words, "", $str); //OUTPUT OF ABOVE: "In mute, remove ll cks from se bottles cellr" ? ``` I need the output to be: **minute, remove all corks from these bottles cellar** I'm assuming I can't use `str_replace()`. What can I do to achieve this? .<issue_comment>username_1: The problem is that `Colors.black` is a single color, but `primarySwatch` expects a palette of multiple colors. If you look at the documentation for [Colors](https://docs.flutter.io/flutter/material/Colors-class.html), the different built in palettes are shown. For example, Colors.blue is a blue palette, and can be passed to `primarySwatch`. ``` new MaterialApp(theme: new ThemeData(primarySwatch: Colors.blue)) ``` Upvotes: 1 <issue_comment>username_2: see your space in single quotation, you should write like this : var first = ['answer':'black','white',...]; Upvotes: 0
2018/03/16
1,351
2,502
<issue_start>username_0: I have a data frame like this: ``` df = read.table(text="chr pos X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 Chr11 24398311 Chr21 Chr21 Chr21 Chr21 Chr21 Chr21 Chr21 Chr11 Chr11 Chr17 Chr21 788729 Chr21 Chr21 Chr21 Chr21 Chr21 Chr11 Chr21 Chr11 Chr11 Chr17 Chr21 1780922 Chr21 Chr21 Chr21 Chr17 Chr21 Chr11 Chr21 Chr11 Chr11 Chr17 Chr21 2935462 Chr21 Chr21 Chr21 Chr11 Chr21 Chr17 Chr21 Chr11 Chr11 Chr17 Chr21 3072338 Chr21 Chr21 Chr21 Chr21 Chr21 Chr11 Chr11 Chr11 Chr11 Chr17 Chr21 3130954 Chr21 Chr21 Chr17 Chr21 Chr21 Chr17 Chr21 Chr11 Chr11 Chr17 Chr21 3238190 Chr21 Chr21 Chr21 Chr17 Chr17 Chr11 Chr21 Chr11 Chr11 Chr17", header=T, stringsAsFactors=F) ``` I would like to pull out the first two values appeared from left to right for each row but they are not "Chr21" . The expected result: ``` chr pos L1 L2 Chr11 24398311 Chr11 Chr11 Chr21 788729 Chr11 Chr11 Chr21 1780922 Chr17 Chr11 Chr21 2935462 Chr11 Chr17 Chr21 3072338 Chr11 Chr11 Chr21 3130954 Chr17 Chr17 Chr21 3238190 Chr17 Chr17 ``` Thank you for helps.<issue_comment>username_1: With the `data.table`-package: ``` library(data.table) melt(setDT(df), id = 1:2)[value != 'Chr21', value[1:2], by = .(chr, pos) ][, dcast(.SD, chr + pos ~ rowid(chr, pos, prefix = 'L'))] ``` which gives: > > > ``` > chr pos L1 L2 > 1: Chr11 24398311 Chr11 Chr11 > 2: Chr21 788729 Chr11 Chr11 > 3: Chr21 1780922 Chr17 Chr11 > 4: Chr21 2935462 Chr11 Chr17 > 5: Chr21 3072338 Chr11 Chr11 > 6: Chr21 3130954 Chr17 Chr17 > 7: Chr21 3238190 Chr17 Chr17 > > ``` > > --- The same logic applied with `tidyverse`-packages: ``` library(dplyr) library(tidyr) df %>% gather(k, v, X1:X10) %>% filter(v != 'Chr21') %>% group_by(chr, pos) %>% slice(1:2) %>% mutate(k2 = paste0('L',row_number())) %>% select(-k) %>% spread(k2, v) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: In `base-R` one solution can be achieved using `apply` row-wise and then `cbind` with 1st two columns: ``` cbind(df[,1:2],t(apply(df[,3:ncol(df)], 1, function(x)x[x!="Chr21"][1:2]))) # chr pos 1 2 # 1 Chr11 24398311 Chr11 Chr11 # 2 Chr21 788729 Chr11 Chr11 # 3 Chr21 1780922 Chr17 Chr11 # 4 Chr21 2935462 Chr11 Chr17 # 5 Chr21 3072338 Chr11 Chr11 # 6 Chr21 3130954 Chr17 Chr17 # 7 Chr21 3238190 Chr17 Chr17 ``` Upvotes: 2
2018/03/16
1,725
6,138
<issue_start>username_0: I have a class `Foo` defined in a header `foo.hpp`. ``` class Foo{ ... some methods and properties ... }; ``` Furthermore, I need a function `bar()` which shall have the following properties: * The function `bar()` shall be defined in the file `foo.cpp` and its symbols shall not be exported, I want to use internal linkage because `bar()` is only used in `foo.cpp`. * The function `bar()` shall have access to the private elements of the function `Foo`. * The function `bar()` cannot be a member function because I want to pass its address to another function which uses it as a callback. **Is the above possible in C++?** I tried the following: Since the linkage shall be internal, I need to use the `static` keyword for `bar()` ([see for example here](http://www.goldsborough.me/c/c++/linker/2016/03/30/19-34-25-internal_and_external_linkage_in_c++/)). Furthermore, `bar()` needs to be declared as a `friend` of `Foo` in `foo.hpp` because it shall have access to its private members. Following [this explaination](https://stackoverflow.com/questions/19845478/is-it-possible-to-declare-a-friend-function-as-static), I need to declare `bar()` *prior* to `Foo` as static. So I adapted this in `foo.hpp` ``` static void bar(); class Foo{ ... some methods and properties ... friend void bar(); }; ``` Then `foo.cpp` would contain the code ``` static void bar(){ ... definition of bar() } ``` However, this has the following disadvantages: 1. In other compilation units that do not involve `foo.cpp` I get a warning saying something like `declared ‘static’ but never defined`. 2. The declaration of `bar()` is visible to any code that is including `foo.hpp`. I don't want that, as one could use this to access private members of `Foo` by redefining `bar()` in other compilation units. So this does not work. How would you solve this problem? NOTE: Of course `bar()` actually has some parameters that are used to access a specific instance of `Foo`. I omitted them here.<issue_comment>username_1: Just make `bar` a static member function of the class. It makes it a global function whose name is scoped to the class (meaning you can use it as a regular function pointer). You can even make it private so only members of your class can call it. Upvotes: 2 <issue_comment>username_2: This should be what you are looking for: **Foo.h** ``` class Foo { private: int f; public: Foo() : f( 5 ) {} int fOf() const { return f; } void callModify(); private: static friend void modifyFoo(Foo& F); // your bar }; ``` **Foo.cpp** ``` #include "Foo.h" // your static bar() -- must be defined first static void modifyFoo( Foo& F ) { F.f *= 2; } void Foo::callModify() { // caller to your static bar modifyFoo( *this ); // using it in your class } ``` **main.cpp** ``` #include #include "Foo.h" int main() { Foo foo; std::cout << foo.fOf() << std::endl; foo.callModify(); std::cout << foo.fOf() << std::endl; std::cout << "\nPress any key and enter to quit."; std::cin.get(); return 0; } ``` If you try to call modifyFoo() out side of `Foo.cpp` it is not declared nor defined because it is a `private static friend` of `Foo`. If you want it visible to the rest of the world then you can make it `public` in the class. If you are working with inheritance and polymorphism then you can make it `protected` for all sub classes while keeping it hidden from outside objects. --- **Edit** - According to the nature that the OP wants I had to make a work around as such: It involves the use an internal public struct that contains a static method. The class then has a caller method that will call the modifier, but it will also return the internal struct. This struct is a friend of its parent class. ``` class Foo { public: struct Modifier { friend class Foo; static void modify( class Foo& f ); }; private: Modifier modifier; int f; public: Foo : f(5) {} int fOf() const { return f; } Foo::Modifier caller() { modifier.modify( *this ); return this->modifier; } private: static friend struct FooModifier; static friend void Modifier::modifier( Foo& f ); }; #include "Foo.h"; void Foo::Modifier::modify( class Foo& f ) { F.f *= 4; } #include #include "Foo.h" int main() { Foo foo; std::cout << foo.fOf() << std::endl; Foo::Modifier m = foo.caller(); std::cout << foo.fOf() << std::endl; m.modifiy( foo ); std::cout << foo.fOf() << std::endl; // you can now pass the struct instance of `m` to your // library which conatiners the modifier function. return 0; } ``` *Output* ``` 5 20 80 ``` With this kind of setup you can create an instance of `Foo::Modifier` since it is public in the `Foo`'s class. Its internal method is static and takes a reference to a specific object of `Foo` and it is a friend to `Foo`. This way you can now pass the `Foo::Modifier`'s object `m` as a `struct` to your library or you can pass the function address with `m.modify( "some relative object of Foo" );` What you are asking for with your strict requirements is not an easy task to achieve. Upvotes: 1 <issue_comment>username_3: What I want does not seem to be possible. It seems that the only options are the following: 1. Do not declare the function `bar()` in `foo.hpp` as a friend, only declare and define it as static in `foo.cpp` and use dirty tricks with pointers and casts to change private elements of an instance of `Foo`. I don't like this one. 2. Drop the requirement that `bar()` should not be visible for code that is including `foo.hpp` and use username_1's answer. 3. Drop the requirement that `bar()` can access private members of an instance of `Foo` and use an anonymous namespace in `foo.cpp` where we derive a subclass `subFoo` of `Foo` (do not add new members) and define `bar()` as its friend function in the anonymous namespace and do not declare it in the header `foo.hpp`. It can then access at least protected members of `Foo` if we cast an instance of `Foo` to `subFoo` in `bar()`. I will use the third option. Upvotes: 0
2018/03/16
2,880
9,969
<issue_start>username_0: I am a beginner ASP.net coder. I understand that the controller is calling a List and the Model is calling a generic model and that this can be easily fixed be setting the model in the view to `@model IEnumerable` But I want to be able to call the model in the view so I can call it in my view. Below I posted my code. Controller: ``` public ActionResult Index(string group, string prin, string status, string osr, string groupnew, string stratvar, string fltstring, Strategy selg, FormCollection form) { if (Session["UserId"] != null) { Strategy strat = new Strategy(); int id = Int32.Parse(Session["UserId"].ToString()); // Get the user id from the session String em = db.UserAccounts.Find(id).Email.ToString(); // Use the id to get the associated email address EmailList emailListItem = db.EmailLists.First(x => x.Email == em); // Use the email address to get the associated emaillist object which holds the group string perm = emailListItem.Perm; if (perm == null) { perm = "0"; } ViewData["perm"] = perm; // if external if (!emailListItem.IntExt) { // Create a list to hold the Todos which we will end up showing List list = new List(); // this is a foreach loop, it goes through all the Todos returned from db.Todoes.ToList() foreach (Strategy s in db.Strategies.ToList()) { // makes sure that the group of a todo isn't null (empty) if (!String.IsNullOrEmpty(s.Group)) { // checks if the group of the user is equal to the group of the post. if so it adds the todo to the list. if (emailListItem.Group.Equals(s.Group)) { list.Add(s); } } } return View(list); } else { // This is the query building code. string p = emailListItem.Perm; string gr = emailListItem.Group; StringBuilder sb = new StringBuilder(); sb.Append("SELECT \* FROM dbo.Strategy WHERE "); //change table name for whatever you need returned foreach (char c in p.ToCharArray()) { if (group == null) { sb.Append("Perm LIKE '%"); sb.Append(c); sb.Append("%' OR "); } } sb.Length = sb.Length - 4; if (selg == null) { List list = db.Strategies.SqlQuery(sb.ToString()).ToList(); //change table name return View(list); } else { var groups = from g in db.Strategies select g; var prins = from pr in db.Strategies select pr; var osrs = from o in db.Strategies select o; var statuss = from s in db.Strategies select s; ViewBag.Groupcmb = (from g in db.Strategies.Include(p) where g.Group != null select g.Group).Distinct(); ViewBag.Principalcmb = (from pr in db.Strategies.Include(p) where pr.Principal != null select pr.Principal).Distinct(); ViewBag.OSRcmb = (from o in db.Strategies.Include(p) where o.OSR != null select o.OSR).Distinct(); ViewBag.Statuscmb = (from s in db.Strategies.Include(p) where s.Status != null select s.Status).Distinct(); //ViewData["OSR"] = new SelectList(ViewBag.OSRcmb); ViewBag.osrsel = osr; //if all filters are null if (group == null && stratvar == null && prin == null && osr == null && status == null) { return View(db.Strategies.ToList()); } //returns same search filter for group if edit if (stratvar != null && group == null) { group = stratvar; groups = groups.Where(g => g.Group.Contains(group)); // return View(group.ToList()); }; if (prin != null && group != null && osr != null && status != null) { ViewBag.osrsel = osr; prins = prins.Where(gpr => gpr.Principal.Contains(prin) && gpr.Group.Contains(group) && gpr.OSR.Contains(osr) && gpr.Status.Contains(status)); stratvar = null; return View(prins.ToList()); } return View(strat); } } } else { return RedirectToAction("Login", "Account"); } } ``` View: ``` @model WebApplication2.Models.Strategy Index ----- @Html.ActionLink("Create New", "Create") @if ((ViewData["perm"]).ToString() != "0") { using (Html.BeginForm()) { | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Group | @Html.DropDownList("group", new SelectList(ViewBag.Groupcmb), "--Select--") | Status | @Html.DropDownList("status", new SelectList(ViewBag.Statuscmb), "--Select--") | Principal | @Html.DropDownList("prin", new SelectList(ViewBag.Principalcmb), "--Select--") | OSR | @Html.DropDownListFor(m => m.OSR, new SelectList(ViewBag.OSRcmb), "--Select--") | | } } else if ((ViewData["perm"]).ToString() == "0") { @using (Html.BeginForm()) { } } | @Html.DisplayNameFor(model => model.Customer) | @Html.DisplayNameFor(model => model.Product) | @Html.DisplayNameFor(model => model.Status) | @Html.DisplayNameFor(model => model.NextAction) | @Html.DisplayNameFor(model => model.Updated) | @Html.DisplayNameFor(model => model.FollowUpDate) | @Html.DisplayNameFor(model => model.OSR) | @Html.DisplayNameFor(model => model.Principal) | @Html.DisplayNameFor(model => model.Value) | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | @\*@foreach (var item in Model) {\*@ | @Html.DisplayFor(model => model.Customer) | @Html.DisplayFor(model => model.Product) | @Html.DisplayFor(model => model.Status) | @Html.DisplayFor(model => model.NextAction) | @Html.DisplayFor(model => model.Updated) | @Html.DisplayFor(model => model.FollowUpDate) | @Html.DisplayFor(model => model.OSR) | @Html.DisplayFor(model => model.Principal) | @Html.DisplayFor(model => model.Value) | @Html.ActionLink("Edit", "Edit", new { id = Model.StrategyId, group = Model.Group }) | @Html.ActionLink("Details", "Details", new { id = Model.StrategyId }) @\*|\*@ | ```<issue_comment>username_1: Just make `bar` a static member function of the class. It makes it a global function whose name is scoped to the class (meaning you can use it as a regular function pointer). You can even make it private so only members of your class can call it. Upvotes: 2 <issue_comment>username_2: This should be what you are looking for: **Foo.h** ``` class Foo { private: int f; public: Foo() : f( 5 ) {} int fOf() const { return f; } void callModify(); private: static friend void modifyFoo(Foo& F); // your bar }; ``` **Foo.cpp** ``` #include "Foo.h" // your static bar() -- must be defined first static void modifyFoo( Foo& F ) { F.f *= 2; } void Foo::callModify() { // caller to your static bar modifyFoo( *this ); // using it in your class } ``` **main.cpp** ``` #include #include "Foo.h" int main() { Foo foo; std::cout << foo.fOf() << std::endl; foo.callModify(); std::cout << foo.fOf() << std::endl; std::cout << "\nPress any key and enter to quit."; std::cin.get(); return 0; } ``` If you try to call modifyFoo() out side of `Foo.cpp` it is not declared nor defined because it is a `private static friend` of `Foo`. If you want it visible to the rest of the world then you can make it `public` in the class. If you are working with inheritance and polymorphism then you can make it `protected` for all sub classes while keeping it hidden from outside objects. --- **Edit** - According to the nature that the OP wants I had to make a work around as such: It involves the use an internal public struct that contains a static method. The class then has a caller method that will call the modifier, but it will also return the internal struct. This struct is a friend of its parent class. ``` class Foo { public: struct Modifier { friend class Foo; static void modify( class Foo& f ); }; private: Modifier modifier; int f; public: Foo : f(5) {} int fOf() const { return f; } Foo::Modifier caller() { modifier.modify( *this ); return this->modifier; } private: static friend struct FooModifier; static friend void Modifier::modifier( Foo& f ); }; #include "Foo.h"; void Foo::Modifier::modify( class Foo& f ) { F.f *= 4; } #include #include "Foo.h" int main() { Foo foo; std::cout << foo.fOf() << std::endl; Foo::Modifier m = foo.caller(); std::cout << foo.fOf() << std::endl; m.modifiy( foo ); std::cout << foo.fOf() << std::endl; // you can now pass the struct instance of `m` to your // library which conatiners the modifier function. return 0; } ``` *Output* ``` 5 20 80 ``` With this kind of setup you can create an instance of `Foo::Modifier` since it is public in the `Foo`'s class. Its internal method is static and takes a reference to a specific object of `Foo` and it is a friend to `Foo`. This way you can now pass the `Foo::Modifier`'s object `m` as a `struct` to your library or you can pass the function address with `m.modify( "some relative object of Foo" );` What you are asking for with your strict requirements is not an easy task to achieve. Upvotes: 1 <issue_comment>username_3: What I want does not seem to be possible. It seems that the only options are the following: 1. Do not declare the function `bar()` in `foo.hpp` as a friend, only declare and define it as static in `foo.cpp` and use dirty tricks with pointers and casts to change private elements of an instance of `Foo`. I don't like this one. 2. Drop the requirement that `bar()` should not be visible for code that is including `foo.hpp` and use username_1's answer. 3. Drop the requirement that `bar()` can access private members of an instance of `Foo` and use an anonymous namespace in `foo.cpp` where we derive a subclass `subFoo` of `Foo` (do not add new members) and define `bar()` as its friend function in the anonymous namespace and do not declare it in the header `foo.hpp`. It can then access at least protected members of `Foo` if we cast an instance of `Foo` to `subFoo` in `bar()`. I will use the third option. Upvotes: 0
2018/03/16
813
2,825
<issue_start>username_0: I have a boolean in my function that decide what function to call. Both of the function that are beying called giving back an Array. Now in my eyes `Hex[] areaHexes` does exists but the compiler does not compile because it thinks its not set ( does not exists ). How do I call one of both function properly based on what value `bool semiRandom` has? ``` void ElevateArea(int q, int r, int range, bool semiRandom = false, float centerHeight = 1f) { Hex centerHex = GetHexAt(q, r); if (semiRandom) { Hex[] areaHexes = GetSemiRandomHexesWithinRangeOf(centerHex, range); } else { Hex[] areaHexes = GetHexesWithinRangeOf(centerHex, range); } foreach (Hex h in areaHexes) { //if (h.Elevation < 0) // h.Elevation = 0; h.Elevation += 0.5f * Mathf.Lerp(1f, 0.25f, Hex.Distance(centerHex, h ) / range); } } ```<issue_comment>username_1: Declare your array before your condition, like so: ``` Hex[] areaHexes; if (semiRandom) { areaHexes = GetSemiRandomHexesWithinRangeOf(centerHex, range); } else { areaHexes = GetHexesWithinRangeOf(centerHex, range); } ``` Upvotes: 2 <issue_comment>username_2: The reason it's not working is that you are currently declaring two local variables called `areaHexes`, each of which has a scope which is just the block they're declared in - so neither of them is in scope when you try to use them. Brandon's answer (declaring the variable outside the `if` statement and then assigning to it from different places) will work fine - `areaHexes` is now in scope when you use it later. However, you can do it more simply with a conditional ?: operator: ``` Hex[] areaHexes = semiRandom ? GetSemiRandomHexesWithinRangeOf(centerHex, range) : GetHexesWithinRangeOf(centerHex, range); ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: Your `areaHexes` is being declared locally within your `if-else` blocks, it's not visible outside of the scope of those blocks. You have two different local `areaHexes` variables: ``` if (semiRandom) { // This definition of areaHexes is visible only within these { } // and is not the same as the one in the else block below Hex[] areaHexes = GetSemiRandomHexesWithinRangeOf(centerHex, range); } else { // This definition of areaHexes is visible only within these { } // and is not the same one as the one above Hex[] areaHexes = GetHexesWithinRangeOf(centerHex, range); } ``` Declare it outside: ``` Hex[] areaHexes; if (semiRandom) { areaHexes = GetSemiRandomHexesWithinRangeOf(centerHex, range); } else { areaHexes = GetHexesWithinRangeOf(centerHex, range); } ``` Or, use the tertiary `?:` operator Jon showed. You should look up *variable scope rules* for C#. Upvotes: 3
2018/03/16
431
1,542
<issue_start>username_0: I have an anchor tag, that when clicked, I want an input to get focus and the page to scroll to the form. Neither are happening and I have no idea why because it's so simple. Here is the anchor tag: ``` [RSVP Now](#RSVPForm "RSVP Now!") ``` Here is the JavaScript: ``` const firstname = document.getElementById("firstname"); const rsvpcta = document.querySelector("a[href*='#RSVPForm']"); rsvpcta.addEventListener("click", () => {firstname.focus();}) ``` And it works in Safari, but in no other browser. I have no idea why it's not working anywhere else. My test url is: <https://meganandadam2018.com><issue_comment>username_1: Add an onclick event to anchor tag ``` RSVP Now ``` On clicking the link the focusfunc() function will be called.And add the focus() method as below: ``` function focusfunc(){ document.getElementById("firstname").focus(); } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I realized what the problem was. I don't have to scroll to the element (through an href on the `a` tag) AND focus the element. Those two actions combined will cancel each other out, and that's what was happening. So I just got rid of the `href` and only had the firstname box focus on click and it all works perfectly now! So here's what the markup looks like: ``` RSVP Now ``` And here's the JS: ``` const rsvpcta = document.getElementById("rsvpcta"), firstname = document.getElementById("firstname"); rsvpcta.addEventListener("click", () => {firstname.focus();}) ``` Upvotes: 0
2018/03/16
1,444
3,711
<issue_start>username_0: I am looking for a function in pandas that aligns data wrt to a different columns. For example, I have four columns, two times and two are identifiers. ``` id time id time a , 1:10, a , 1:11 a , 1:12 , a , 1:13 b , 1:13 c , 1:15 c , 1:14 d , 1:15 ``` I would like to match the rows with id `c` to each other and get the following: ``` id time id time a , 1:10, a , 1:11 a , 1:12, a , 1:13 b , 1:13, NaN, NaN c, 1:14, c , 1:15 d , 1:15, NaN, NaN ``` I have my data in a dataframe with respective labels. I have tried loops to find matches and reindexing, but run into errors. I can potentially have thousands of entries, with numerous missing points. ``` A = pd.DataFrame({'Error Time':array1[:,0],'Err ID':array1[:,1],'Alert Type':array1[:,2]}) B = pd.DataFrame({'Recover Time':array2[:,0], 'Rec ID':array2[:,1]}) data_array = pd.concat([A,B], axis=1) #Joins the two arrays together pd.to_datetime(data_array['Error Time'],format='%H:%M:%S.%f').dt.time pd.to_datetime(data_array['Recover Time'],format='%H:%M:%S.%f').dt.time #data_array = data_array.sort_values(by=['Error Time']) col_size = len(data_array['Error Time']) for i in range(col_size): if data_array.iloc[i,1] == data_array.iloc[i,3]: indexA.append(i) else: for j in range(col_size): if data_array.iloc[i,1] == data_array.iloc[j,3]: if indexA.count(j) > 0: j = j + 1 else: indexA.append(j) break for k in range(col_size): if indexA.count(k)== 0: indexA.append(k) data_array = data_array.reindex(['Error Time', 'Error ID', 'Alert Type],index=[indexA]) ```<issue_comment>username_1: As @Wen said, [`pandas.Merge`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html) is the way I would approach this. For your problem it would look something like this ``` df1 = pd.DataFrame([ ['a', '1:10'], ['a', '1:12'], ['b', '1:13'], ['c', '1:14'], ['d', '1:15'], ], columns=['id', 'time']) df2 = pd.DataFrame([ ['a', '1:11'], ['a', '1:13'], ['c', '1:14'], ], columns=['id', 'time']) df3 = df1.merge(df2, on='id', how='left') ``` df3 after merge will look like this ``` id time_x time_y 0 a 1:10 1:11 1 a 1:10 1:13 2 a 1:12 1:11 3 a 1:12 1:13 4 b 1:13 NaN 5 c 1:14 1:14 6 d 1:15 NaN ``` `pandas.merge` works like SQL joins and for your example you would choose `how='left'` which is equivalent to a left-outer SQL join. We'll need to drop the rows that get duplicated to achieve your desired output. You can do this with [`pandas.drop_duplicates`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html). The `reset_index` will just start the index count from zero again, it is optional. `df4 = df3.drop_duplicates(subset=['id', 'time_x']).reset_index(drop=True)` This will yield ``` id time_x time_y 0 a 1:10 1:11 1 a 1:12 1:11 2 b 1:13 NaN 3 c 1:14 1:14 4 d 1:15 NaN ``` Upvotes: 0 <issue_comment>username_2: ``` df1 = pd.DataFrame({'ID':['a','a','b','c','d'],'Time':['1:10','1:12','1:13','1:14','1:15']}) df2 = pd.DataFrame({'ID':['a','a','c'],'Time':['1:11','1:13','1:15']}) A = df1.assign(C=df1.groupby('ID').cumcount()) B = df2.assign(C=df2.groupby('ID').cumcount()) A.merge(B, on=['ID', 'C'], how='outer').drop('C', 1) ``` Out: ``` ID Time_x Time_y 0 a 1:10 1:11 1 a 1:12 1:13 2 b 1:13 NaN 3 c 1:14 1:15 4 d 1:15 NaN ``` Upvotes: 2 [selected_answer]
2018/03/16
897
2,353
<issue_start>username_0: Is there an easy way in Dask to push a pure-python module to the workers? I have many workers in a cluster and I want to distribute a local module that I have on my client. I understand that for large packages like NumPy or Python I should distribute things in a more robust fashion, but I have a small module that changes frequently that shouldn't be too much work to move around.<issue_comment>username_1: As @Wen said, [`pandas.Merge`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html) is the way I would approach this. For your problem it would look something like this ``` df1 = pd.DataFrame([ ['a', '1:10'], ['a', '1:12'], ['b', '1:13'], ['c', '1:14'], ['d', '1:15'], ], columns=['id', 'time']) df2 = pd.DataFrame([ ['a', '1:11'], ['a', '1:13'], ['c', '1:14'], ], columns=['id', 'time']) df3 = df1.merge(df2, on='id', how='left') ``` df3 after merge will look like this ``` id time_x time_y 0 a 1:10 1:11 1 a 1:10 1:13 2 a 1:12 1:11 3 a 1:12 1:13 4 b 1:13 NaN 5 c 1:14 1:14 6 d 1:15 NaN ``` `pandas.merge` works like SQL joins and for your example you would choose `how='left'` which is equivalent to a left-outer SQL join. We'll need to drop the rows that get duplicated to achieve your desired output. You can do this with [`pandas.drop_duplicates`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html). The `reset_index` will just start the index count from zero again, it is optional. `df4 = df3.drop_duplicates(subset=['id', 'time_x']).reset_index(drop=True)` This will yield ``` id time_x time_y 0 a 1:10 1:11 1 a 1:12 1:11 2 b 1:13 NaN 3 c 1:14 1:14 4 d 1:15 NaN ``` Upvotes: 0 <issue_comment>username_2: ``` df1 = pd.DataFrame({'ID':['a','a','b','c','d'],'Time':['1:10','1:12','1:13','1:14','1:15']}) df2 = pd.DataFrame({'ID':['a','a','c'],'Time':['1:11','1:13','1:15']}) A = df1.assign(C=df1.groupby('ID').cumcount()) B = df2.assign(C=df2.groupby('ID').cumcount()) A.merge(B, on=['ID', 'C'], how='outer').drop('C', 1) ``` Out: ``` ID Time_x Time_y 0 a 1:10 1:11 1 a 1:12 1:13 2 b 1:13 NaN 3 c 1:14 1:15 4 d 1:15 NaN ``` Upvotes: 2 [selected_answer]
2018/03/16
524
1,596
<issue_start>username_0: I have this code: ```js var utc = moment.tz(1521221491000, "UTC"); var local = utc.clone().tz(moment.tz.guess()); console.log(moment([2018, 03, 15]).fromNow()); console.log('moment() piece by piece: ' + moment().get('year') + ' ' + moment().get('month') + ' ' + moment().get('date') + '. Data inside of momment: ' + moment().format()); console.log(local.format("YYYY-MM-DD HH:MM:SS")); ``` ```html ``` In the line 3 > > console.log(moment([2018, 03, 15]).fromNow()); > > > Suppose to say '1 day ago', at the moment to write this question is 16 of March 2018... And for some reason the response is > > in a month... > > > Any idea why this error, the error is in the month var.<issue_comment>username_1: Like answered by Gnagy in this thread (<https://stackoverflow.com/a/20094956/8733102>), According to the [documentation](http://momentjs.com/docs/#/get-set/month/), months are zero indexed. So January is 0 and December is 11. Upvotes: -1 <issue_comment>username_2: Moment uses the same (annoying) date system as the JavaScript Date object, where January = 0, February = 1, etc. So 3 means April, which is a month from now. Upvotes: 1 <issue_comment>username_3: As indicated in moment's [documentation](https://momentjs.com/docs/#/parsing/array/), when parsing an array as the argument, moment mirrors the native javascript Date object's 0-based indexing for months. So 3 is, confusingly, April. I personally find it's much easier to have moment parse pre-formatted string or objects, though your mileage may vary. Upvotes: 2 [selected_answer]
2018/03/16
548
1,947
<issue_start>username_0: I had created a text file with the SSRS file backup Microsoft says to backup. I was using a batch file to locate all the files in the directory structure. Using the following commands ``` for /F %G in (C:\file.txt) dp dir /s /b %G >> c:\filepath.txt ``` It write the correct path out to the file but when I try to do a copy to another location I make the same path to a directory structure of my choice. ``` for /F %G in (C:\filepath.txt) do md "C:\Users\Location\Desktop\SSRS Migration Backup\FileBack%~pG" ``` After making the directory I would copy the file with this command. ``` for /F %G in (C:\filepath.txt) do copy "%G" "C:\Users\Location\Desktop\SSRS Migration Backup\FileBack%~pG" ``` The file path for C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer\" Will in the `%G` parameter pass as "\" Only I have tried forcing the parameter to `%~fG` it will only show "\Programs" I even have tried `@echo` the `%G` parameter and it only displays on screen "\" why will the path to the file not pass correct?<issue_comment>username_1: Like answered by Gnagy in this thread (<https://stackoverflow.com/a/20094956/8733102>), According to the [documentation](http://momentjs.com/docs/#/get-set/month/), months are zero indexed. So January is 0 and December is 11. Upvotes: -1 <issue_comment>username_2: Moment uses the same (annoying) date system as the JavaScript Date object, where January = 0, February = 1, etc. So 3 means April, which is a month from now. Upvotes: 1 <issue_comment>username_3: As indicated in moment's [documentation](https://momentjs.com/docs/#/parsing/array/), when parsing an array as the argument, moment mirrors the native javascript Date object's 0-based indexing for months. So 3 is, confusingly, April. I personally find it's much easier to have moment parse pre-formatted string or objects, though your mileage may vary. Upvotes: 2 [selected_answer]
2018/03/16
2,786
6,548
<issue_start>username_0: I have a list of multiple data frames. Example data: ``` df1 <- data.frame(Name=c("A", "B", "C"), E1=c(0, NA, 1), E2=c(1, 0, 1)) df2 <- data.frame(Name=c("A", "C", "F"), E1=c(1, 0, 1), E2=c(0, 0, 0)) ls <- list(df1, df2) ``` For each data frame, I'd like to create a new row at the bottom containing the sum of each column. So for df1 is would look like this: ``` Name E1 E2 "A" 0 1 "B" NA 0 "C" 1 1 Sum 1 2 ``` This is what I tried: ``` ls <- lapply(ls, function(x) { x[nrow(x)+1, -1] <- colSums(x[,-1], na.rm=TRUE) }) ``` I received the following error message: ``` Error in colSums(x[,-1], na.rm = TRUE) : 'x' must be numeric ``` All of my columns except "Names" contain just 1's, 0's, and NA's, so I thought that maybe they're being read as factors instead of numeric. My first attempt to coerce to numeric (which looked like the function below but without "unlist") resulted in an error (object type list cannot be coerced to type 'double') so I tried the following based on the answer in [this other post:](https://stackoverflow.com/questions/12384071/how-to-coerce-a-list-object-to-type-double) ``` ls <- lapply(ls, function(x) { x[,-1] <- as.numeric(unlist(x[,-1])) }) ``` But that just gives me a list of numeric strings, not a list of data frames like I want. Any advice on either fixing my original `colSums` function or successfully converting my data to numeric would be greatly appreciated!<issue_comment>username_1: You are very close! Your current function is only returning the last row, because functions by default return whatever object is on the last line. So you need something like the following. `as.character` is because the strings were inputted as factor, which wouldn't let you put `"Sum"` into the frame the right way. In general though, unless this is for some kind of output storing summary stats as a row inside the table is not a very tidy practice, because it can become confusing having some rows contain data and others not. ```r df1 <- data.frame(Name=c("A", "B", "C"), E1=c(0, NA, 1), E2=c(1, 0, 1)) df2 <- data.frame(Name=c("A", "C", "F"), E1=c(1, 0, 1), E2=c(0, 0, 0)) ls <- list(df1, df2) lapply(ls, function(x) { x[nrow(x)+1, -1] <- colSums(x[,-1], na.rm=TRUE) x[, 1] <- as.character(x[, 1]) x[nrow(x), 1] <- "Sum" return(x) }) #> [[1]] #> Name E1 E2 #> 1 A 0 1 #> 2 B NA 0 #> 3 C 1 1 #> 4 Sum 1 2 #> #> [[2]] #> Name E1 E2 #> 1 A 1 0 #> 2 C 0 0 #> 3 F 1 0 #> 4 Sum 2 0 ``` Created on 2018-03-16 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). Upvotes: 4 [selected_answer]<issue_comment>username_2: Another option could be by using `rbind` and `Map` as: ``` Map(rbind, ls, lapply(ls, function(x)sapply(x, function(x)if(class(x) == "character"){ "Sum:" }else{ sum(x, na.rm = TRUE)}))) # [[1]] # Name E1 E2 # 1 A 0 1 # 2 B 0 # 3 C 1 1 # 4 Sum: 1 2 # # [[2]] # Name E1 E2 # 1 A 1 0 # 2 C 0 0 # 3 F 1 0 # 4 Sum: 2 0 ``` **Data** Note: The `Name` column has been changed to 'character` for above solution. ``` df1 <- data.frame(Name=c("A", "B", "C"), E1=c(0, NA, 1), E2=c(1, 0, 1), stringsAsFactors = FALSE) df2 <- data.frame(Name=c("A", "C", "F"), E1=c(1, 0, 1), E2=c(0, 0, 0), stringsAsFactors = FALSE) ls <- list(df1, df2) ``` Upvotes: 0 <issue_comment>username_3: ``` lapply(ls,function(i) data.frame(rbind(apply(i,2,as.vector),c("Sum",colSums(i[,-1],na.rm = TRUE) )))) ``` Upvotes: 0 <issue_comment>username_4: You could use `rbind`: ``` df1 <- data.frame(Name=c("A", "B", "C"), E1=c(0, NA, 1), E2=c(1, 0, 1), stringsAsFactors = FALSE) df2 <- data.frame(Name=c("A", "C", "F"), E1=c(1, 0, 1), E2=c(0, 0, 0), stringsAsFactors = FALSE) ls <- list(df1, df2) ls <- lapply(ls, function(x) { x <- rbind(x, c( "Sum", sum(x[, "E1"], na.rm = TRUE), sum(x[, "E2"], na.rm = TRUE))) }) ls ``` Which yields ``` [[1]] Name E1 E2 1 A 0 1 2 B 0 3 C 1 1 4 Sum 1 2 [[2]] Name E1 E2 1 A 1 0 2 C 0 0 3 F 1 0 4 Sum 2 0 ``` Upvotes: 0 <issue_comment>username_5: For the sake of completeness, here is also a `data.table` solution. `data.table` is much more tolerant when adding character values to a factor column. No explicit type conversion is required. In addition, I want to suggest an alternative to "list of data.frames". ``` library(data.table) lapply(ls, function(x) rbind(setDT(x), x[, c(.(Name = "sum"), lapply(.SD, sum, na.rm = TRUE)), .SDcols = c("E1", "E2")] )) ``` > > > ``` > Name E1 E2 > 1: A 0 1 > 2: B NA 0 > 3: C 1 1 > 4: sum 1 2 > > [[2]] > Name E1 E2 > 1: A 1 0 > 2: C 0 0 > 3: F 1 0 > 4: sum 2 0 > > ``` > > The `Name` columns are still factors but with an additional factor level as can been seen by applying `str()` to the result: > > > ``` > List of 2 > $ :Classes ‘data.table’ and 'data.frame': 4 obs. of 3 variables: > ..$ Name: Factor w/ 4 levels "A","B","C","sum": 1 2 3 4 > ..$ E1 : num [1:4] 0 NA 1 1 > ..$ E2 : num [1:4] 1 0 1 2 > ..- attr(*, ".internal.selfref")= > $ :Classes ‘data.table’ and 'data.frame': 4 obs. of 3 variables: > ..$ Name: Factor w/ 4 levels "A","C","F","sum": 1 2 3 4 > ..$ E1 : num [1:4] 1 0 1 2 > ..$ E2 : num [1:4] 0 0 0 0 > ..- attr(\*, ".internal.selfref")= > > ``` > > ### Alternative to list of data.frames If the data.frames in the list all have the same structure, i.e., the same number, type and name of columns, then I prefer to store the data in one object: ``` library(data.table) DT <- rbindlist(ls, idcol = "df.id") DT ``` > > > ``` > df.id Name E1 E2 > 1: 1 A 0 1 > 2: 1 B NA 0 > 3: 1 C 1 1 > 4: 2 A 1 0 > 5: 2 C 0 0 > 6: 2 F 1 0 > > ``` > > The origin of each row is identified by the number in `df.id`. Now, we can use grouping instead of looping through the elements of the list, e.g., ``` DT[, lapply(.SD, sum, na.rm = TRUE), .SDcols = c("E1", "E2"), by = df.id] ``` > > > ``` > df.id E1 E2 > 1: 1 1 2 > 2: 2 2 0 > > ``` > > Or, if the `sum` rows are to be interspersed within the original data: ``` rbind( DT, DT[, c(.(Name = "sum"), lapply(.SD, sum, na.rm = TRUE)), .SDcols = c("E1", "E2"), by = df.id] )[order(df.id)] ``` > > > ``` > df.id Name E1 E2 > 1: 1 A 0 1 > 2: 1 B NA 0 > 3: 1 C 1 1 > 4: 1 sum 1 2 > 5: 2 A 1 0 > 6: 2 C 0 0 > 7: 2 F 1 0 > 8: 2 sum 2 0 > > ``` > > Upvotes: 1
2018/03/16
481
1,658
<issue_start>username_0: I am trying to define my own hashing function for `std::unordered_map` and I want to hash a field within a struct which is supposed to be the key. The code below is a simplified version of what I have: ``` struct TestStruct { char a[64]; char b[64]; } struct my_eq { bool operator()(const TestStruct& test_1, const TestStruct& test_2) const { return !strcmp(test_1.a, test_2.a) && !strcmp(test_1.b, test_2.b); } }; struct my_hash { unsigned long operator()(const TestStruct& test) const { return std::hash(std::string\_view(test.a)); } }; std::unordered\_map map; ``` The error I get is: ``` no matching function for call to ‘std::hash >::hash(std::string\_view&) ``` According to the [cppreference on `std::hash`](http://en.cppreference.com/w/cpp/utility/hash) the hash function should support `std::string_view`. I feel like I'm missing something simple but I cannot figure it out.<issue_comment>username_1: `std::hash` is a class template, **not** a function template. you need an instance to call it: ``` return std::hash()(std::string\_view(test.a)); ``` Upvotes: 2 <issue_comment>username_2: You're using `std::hash` wrong. `std::hash` is a class which provides a `operator()` that hashes the object. You are trying to pass the object to its constructor which doesn't work since it only has a default consdtructor. Your `operator()` also needs to be marked `const`. We put that all together and we get: ``` struct my_hash { unsigned long operator()(const TestStruct& test) const { return std::hash()(std::string\_view(test.a)); } }; ``` Upvotes: 4 [selected_answer]
2018/03/16
484
1,666
<issue_start>username_0: I am trying to create an accordion (either pure CSS or javascript/jquery). I have a list of links inside a span but need the accordion to work onclick of the first element inside this span and expand its following siblings like below: ``` [Header](#) [Service 1](#) [Service 2](#) ``` Here is a jsfiddle example of my setup. <https://jsfiddle.net/wb590xs3/7/> Edit: I cannot change this HTML structure as this is a slider and need these hrefs to be on the same level.<issue_comment>username_1: With using Jquery, You can do accordion with this documentation [jQuery Accordion.](https://jqueryui.com/accordion/) Example ```js $( function() { $( "#accordion" ).accordion(); } ); ``` ```html jQuery UI Accordion - Default functionality ### Section 1 Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. ### Section 2 Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor velit, faucibus interdum tellus libero ac justo. Vivamus non quam. ``` Upvotes: 0 <issue_comment>username_2: Did you try seeing Bootstrap collapse plugin? Just check [this](https://getbootstrap.com/docs/4.0/components/collapse/) Upvotes: 1 <issue_comment>username_3: You can try this pure CSS way: ``` .pager > a {display: block;} .pager div {display: none;} .pager div:target {display: block;} [Header](#showServices) [Service 1](#) [Service 2](#) ``` Hope it helps. Upvotes: 0
2018/03/16
728
2,552
<issue_start>username_0: I am having trouble installing paramiko on one system. This same command worked earlier, but then something changed and I had reinstall Python, and now paramiko will not install. I am using Windows 7 with Python 3.6.4. Pip returns the following error: ``` C:\Users\me>pip --trusted-host pypi.python.org install paramiko Collecting paramiko Could not fetch URL https://pypi.python.org/simple/paramiko/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - skipping Could not find a version that satisfies the requirement paramiko (from versions: ) No matching distribution found for paramiko ``` How can I fix this?<issue_comment>username_1: According to Paramiko [installation](http://www.paramiko.org/installing.html) documentation : Versions supported : * Python 2.7 * Python 3.4+ Looks like you are using incompatible version of Python ``` C:\Users\User>python -V Python 3.6.4 ``` Installation ``` pip3 install paramiko ``` or ``` pip install paramiko ``` **SSL: CERTIFICATE\_VERIFY\_FAILED** can be caused by pip [issue](https://github.com/pypa/pip/issues/4205) or [python issue on Mac](https://bugs.python.org/issue29065) Please upgrade pip to latest version for the same. ``` pip install --upgrade pip ``` After this issue should be resolved Or try installing incremental ``` pip install incremental ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Using following commands helped me. please try this 1. For upgrading pip `python -m pip install --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org --upgrade pip` 2. For installing new packages, eg numpy, pandas etc. `python -m pip install PACKAGE NAME --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org` ![Installing numpy package](https://i.stack.imgur.com/JNXyM.png) ![Upgrade pip](https://i.stack.imgur.com/PD9y6.png) Upvotes: 5 <issue_comment>username_3: Additionally If you get stuck after collecting the package but at the installation you get this following error: > > Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\Program Files (x86)\Python37-32\Lib\site-packages\numpy' > check the permissions. > > > Following alternation to the command worked just fine for me: ``` python -m pip install --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org --user numpy ``` Upvotes: 0
2018/03/16
558
1,985
<issue_start>username_0: This is my checkout.php page. I cant see after this form submitting charge will happen on stripe. ``` ``` This is my process.php. But my problem is how to get any confirmation from stripe. If the charge is success or not. ``` session_start(); // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys require_once('stripe-php/init.php');// add the php library for stripe \Stripe\Stripe::setApiKey("<KEY>"); // Token is created using Checkout or Elements! // Get the payment token ID submitted by the form: $token = $_POST['stripeToken']; $amount=$_SESSION['amount']; // Charge the user's card: $charge = \Stripe\Charge::create(array( "amount" => $amount, "currency" => "usd", "description" => "Example charge", "metadata" => array("order_id" => 6735), "source" => $token, )); ```<issue_comment>username_1: If the charge is successful, the Charge object will be populated with something that has a Charge ID. If it's not successful, that API Method `\Stripe\Charge::create()` will raise an exception (probably a Card Error exception). You can learn more about those here: <https://stripe.com/docs/api#error_handling> Hope that helps get you started! Upvotes: 1 <issue_comment>username_2: > > The best way to get the 100% confirmation result is to use the [Stripe Webhooks](https://stripe.com/docs/webhooks#when-to-use-webhooks) > > > **Stripe will send a payload to your endpoint about any event what you registered** Stripe will send you an [Event](https://stripe.com/docs/api#events) object which will contain specific event's response with details. In your case you need to catch the [charge.succeeded](https://stripe.com/docs/api/curl#event_types-charge.succeeded) event which will hold the [charge object](https://stripe.com/docs/api/curl#charge_object) where you can get detail info about it! Upvotes: 0
2018/03/16
1,910
7,659
<issue_start>username_0: I'm curious about how to effectively generate emails in a multilingual application. For the sake of getting all answers aligned: let's say you have a typical commercial newsletter with lots of images, markup, and of course many textual paragraphs. Assume that all text does NOT come from a database but should be hard-coded. Moreover, some words in these paragraphs can be bolded, emphasized,... The newsletter will be sent in the subscriber's preferred locale. How can I build a system to handle this? * Would you reference each paragraph with `trans()` and define all translations in Laravel's *lang* folder? How about the individual words markup part then? Incorporating HTML tags in language files feels somehow wrong to me. * Or would you create separate language folders for emails (e.g. views/emails/en) and make Laravel fetch the right one? But then lots of duplicate mail layout definition will probably exist... * Or perhaps something completely else?<issue_comment>username_1: I would go with the first option with some modification, by using a **markdown parser** in emails, so you won't be incorporating HTML inside language files, you will be sending parsed markdown strings to the blade template: * Each time a template change needed, you wouldn't have to update each template for each language. * Localization codes are already implemented in Laravel & Blade template engine. * For a daily campaign e-mail, you would only create one template (maybe one more for languages like RTL ones) and *n x m* translation strings where *n* stands for each string the template contains and *m* for each language. * You will be able to use string modifiers like singularity/plurality, replacing, and extend the system with your own helpers. For example, a simple html email could be built like this (using Laravel 5.6): **Translation Files Structure** ``` /resources /lang /en /dailydigest.php /de /dailydigest.php ``` **Mailable** DailyDigest.php ``` php namespace App\Mail; use App\User; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Mail\Markdown; use Illuminate\Queue\SerializesModels; class DailyDigest extends Mailable { use Queueable; protected $user; public function __construct($user) { $this-user= $user; } public function build() { return $this ->from("<EMAIL>") ->view('emails.dailydigest', [ 'user' => $this->user, 'messageSection1' => Markdown::parse(Lang::get("dailydigest.message1",[],$this->user->locale)), 'messageImage1' => 'http://example.com/images/test.png', 'messageSection2' => Markdown::parse(Lang::get("dailydigest.message2",[],$this->user->locale)), // if it's a language specific image 'messageImage2' => Lang::get("dailydigest.image2",[],$this->user->locale), ]); } } ``` **Template** /resources/views/emails/dailydigest.blade.php A standard blade template containing HTML and blade directives, created for daily digest email. **Controller** SendDailyDigest.php ``` php namespace App\Http\Controllers; use App\User; use App\Mail\DailyDigest; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use App\Http\Controllers\Controller; class DailyDigestController extends Controller { /** * Send the dailydigest to all members. * * @param Request $request * @return Response */ public function send(Request $request) { $users = App\User::all(); // build the email message with the users locale and add to queue foreach($users as $user){ Mail::to($user-email) ->send(new DailyDigest($user)) ->queue("digest"); } } } ``` And there's a publication that I recently found: <https://laravel-news.com/laravel-campaign-monitor> Upvotes: 1 <issue_comment>username_2: For newsletters with static content: 1. Avoid translation files 2. Use template composition for reusable structural elements Laravel's localization system works well for strings in an application, but, for the text-heavy content in an email, these definitions will be cumbersome to maintain, especially for content that contains inline markup or that changes regularly. Templates with many `trans()` calls also render more slowly, especially when batching thousands of emails. If somebody else writes the content, it's much easier to add a few Blade directives where needed than to extract every chunk of text into a localization entry. Remember, we'll need to repeat this work for *every* newsletter. Instead, just write the content directly into the template, and use a naming hierarchy for messages translated to different languages. Extract structural and display elements into reusable components to minimize the amount of markup mixed in with the content. Our template file hierarchy might look like this: ```php resources/views/newsletters/ ├── components/ │   └── article_summary.blade.php ├── en/ │   └── 2018-01-01.blade.php ├── es/ │   └── 2018-01-01.blade.php ├── fr/ │   └── 2018-01-01.blade.php └── newsletter.blade.php ``` The *newsletter.blade.php* master template contains basic elements displayed in every newsletter, like a header, logo, and footer. It will `@include()` the appropriate newsletter body based on the user's locale and the date of publication: ```php {{-- ... common header markup ... --}} @include("newsletters.$locale.$date") {{-- ... common footer markup ... --}} ``` Each template in the localization folders contains the text for the message in that language, with a bit of inline HTML or markdown for formatting as needed. Here's an example: ```php # Newsletter Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc finibus sapien nec sapien dictum, vitae dictum dolor mattis. Nunc bibendum id augue... @component('newsletters.components.article_summary', [ 'title' => 'Article Title 1', 'fullArticleUrl' => 'http://...', ]) Ut aliquet lobortis leo, cursus volutpat mi convallis ut. Vivamus id orci ut quam rhoncus eleifend. Nulla condimentum... @endcomponent @component('newsletters.components.article_summary', [ 'title' => 'Article Title 2', 'fullArticleUrl' => 'http://...', ]) Donec non finibus tellus, efficitur tincidunt leo. Nam nibh augue, consectetur tincidunt dui et, fermentum dictum eros... @endcomponent ``` As we can see, there's very little to distract from the content of the message. The `article_summary` component hides the markup from the message body: ```php [{{ $title }} ------------]({{ $fullArticleUrl }}) {{ $slot }} ``` By using components, we're free to change the layout in each newsletter, and we avoid rewriting markup that we use often. Laravel includes [some useful built-in components](https://laravel.com/docs/mail#writing-markdown-messages) for markdown messages. To send the message, we just pass in the locale and the newsletter date that our master template will resolve from the available languages: ```php public function build() { return $this->->markdown('newsletters.newsletter')->with([ 'locale' => $this->user->locale, 'date' => '2018-01-01', ]); } ``` As a final note, we don't need to skip using `trans()` entirely. It may make sense in some cases, such as in shared components. For the majority of the content, we gain readability and maintainability by writing it directly in the template. Upvotes: 4 [selected_answer]
2018/03/16
2,041
7,983
<issue_start>username_0: To preface, I'm completely new to NodeJs and MySQL. I have a website running on Node with express like this ``` var express = require('express'); var app = express(); var path = require("path"); var mysql = require("mysql"); app.use(express.static('Script')); var con = mysql.createConnection({ host: "localhost", user: "root", password: "<PASSWORD>", database: "blocks" }); con.connect(function(err){ if(err) throw err; console.log("connected!"); con.query("SELECT * FROM blockchain", function(err, result, fields){ if(err) throw err; console.log(result); }); }); app.get('/', function (req, res) { res.sendFile(path.join(__dirname + '/index.html')); }); app.listen(8080); ``` It's connected to the server successfully, and can print out the server values on my command prompt. Is there a way to send this data to my website such that I can use the values for client side scripting? For example, I want a create a new element in my `index.html` file to represent every entry in the database, and thus alter my websites displayed information. So if the database was empty, my website would look empty. If the database had three entries, my website would have 3 elements that corresponded to the inputs of the three entries.<issue_comment>username_1: I would go with the first option with some modification, by using a **markdown parser** in emails, so you won't be incorporating HTML inside language files, you will be sending parsed markdown strings to the blade template: * Each time a template change needed, you wouldn't have to update each template for each language. * Localization codes are already implemented in Laravel & Blade template engine. * For a daily campaign e-mail, you would only create one template (maybe one more for languages like RTL ones) and *n x m* translation strings where *n* stands for each string the template contains and *m* for each language. * You will be able to use string modifiers like singularity/plurality, replacing, and extend the system with your own helpers. For example, a simple html email could be built like this (using Laravel 5.6): **Translation Files Structure** ``` /resources /lang /en /dailydigest.php /de /dailydigest.php ``` **Mailable** DailyDigest.php ``` php namespace App\Mail; use App\User; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Mail\Markdown; use Illuminate\Queue\SerializesModels; class DailyDigest extends Mailable { use Queueable; protected $user; public function __construct($user) { $this-user= $user; } public function build() { return $this ->from("<EMAIL>") ->view('emails.dailydigest', [ 'user' => $this->user, 'messageSection1' => Markdown::parse(Lang::get("dailydigest.message1",[],$this->user->locale)), 'messageImage1' => 'http://example.com/images/test.png', 'messageSection2' => Markdown::parse(Lang::get("dailydigest.message2",[],$this->user->locale)), // if it's a language specific image 'messageImage2' => Lang::get("dailydigest.image2",[],$this->user->locale), ]); } } ``` **Template** /resources/views/emails/dailydigest.blade.php A standard blade template containing HTML and blade directives, created for daily digest email. **Controller** SendDailyDigest.php ``` php namespace App\Http\Controllers; use App\User; use App\Mail\DailyDigest; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use App\Http\Controllers\Controller; class DailyDigestController extends Controller { /** * Send the dailydigest to all members. * * @param Request $request * @return Response */ public function send(Request $request) { $users = App\User::all(); // build the email message with the users locale and add to queue foreach($users as $user){ Mail::to($user-email) ->send(new DailyDigest($user)) ->queue("digest"); } } } ``` And there's a publication that I recently found: <https://laravel-news.com/laravel-campaign-monitor> Upvotes: 1 <issue_comment>username_2: For newsletters with static content: 1. Avoid translation files 2. Use template composition for reusable structural elements Laravel's localization system works well for strings in an application, but, for the text-heavy content in an email, these definitions will be cumbersome to maintain, especially for content that contains inline markup or that changes regularly. Templates with many `trans()` calls also render more slowly, especially when batching thousands of emails. If somebody else writes the content, it's much easier to add a few Blade directives where needed than to extract every chunk of text into a localization entry. Remember, we'll need to repeat this work for *every* newsletter. Instead, just write the content directly into the template, and use a naming hierarchy for messages translated to different languages. Extract structural and display elements into reusable components to minimize the amount of markup mixed in with the content. Our template file hierarchy might look like this: ```php resources/views/newsletters/ ├── components/ │   └── article_summary.blade.php ├── en/ │   └── 2018-01-01.blade.php ├── es/ │   └── 2018-01-01.blade.php ├── fr/ │   └── 2018-01-01.blade.php └── newsletter.blade.php ``` The *newsletter.blade.php* master template contains basic elements displayed in every newsletter, like a header, logo, and footer. It will `@include()` the appropriate newsletter body based on the user's locale and the date of publication: ```php {{-- ... common header markup ... --}} @include("newsletters.$locale.$date") {{-- ... common footer markup ... --}} ``` Each template in the localization folders contains the text for the message in that language, with a bit of inline HTML or markdown for formatting as needed. Here's an example: ```php # Newsletter Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc finibus sapien nec sapien dictum, vitae dictum dolor mattis. Nunc bibendum id augue... @component('newsletters.components.article_summary', [ 'title' => 'Article Title 1', 'fullArticleUrl' => 'http://...', ]) Ut aliquet lobortis leo, cursus volutpat mi convallis ut. Vivamus id orci ut quam rhoncus eleifend. Nulla condimentum... @endcomponent @component('newsletters.components.article_summary', [ 'title' => 'Article Title 2', 'fullArticleUrl' => 'http://...', ]) Donec non finibus tellus, efficitur tincidunt leo. Nam nibh augue, consectetur tincidunt dui et, fermentum dictum eros... @endcomponent ``` As we can see, there's very little to distract from the content of the message. The `article_summary` component hides the markup from the message body: ```php [{{ $title }} ------------]({{ $fullArticleUrl }}) {{ $slot }} ``` By using components, we're free to change the layout in each newsletter, and we avoid rewriting markup that we use often. Laravel includes [some useful built-in components](https://laravel.com/docs/mail#writing-markdown-messages) for markdown messages. To send the message, we just pass in the locale and the newsletter date that our master template will resolve from the available languages: ```php public function build() { return $this->->markdown('newsletters.newsletter')->with([ 'locale' => $this->user->locale, 'date' => '2018-01-01', ]); } ``` As a final note, we don't need to skip using `trans()` entirely. It may make sense in some cases, such as in shared components. For the majority of the content, we gain readability and maintainability by writing it directly in the template. Upvotes: 4 [selected_answer]
2018/03/16
894
3,446
<issue_start>username_0: How can I get Jersey to inject classes without creating and registering factories on a one-for-one basis? I have the following config: ```java public class MyConfig extends ResourceConfig { public MyConfig() { register(new AbstractBinder() { @Override protected void configure() { bindFactory(FooFactory.class).to(Foo.class); bindFactory(BazFactory.class).to(Baz.class); } }); } } ``` hk2 will now successfully inject Foo and Baz: ```java // this works; Foo is created by the registered FooFactory and injected @GET @Path("test") @Produces("application/json") public Response getTest(@Context Foo foo) { // code } ``` But that's not my goal. My goal is to inject objects that wrap these classes. There are many and they each consume different combinations of Foo and Baz. Some examples: ```java public class FooExtender implements WrapperInterface { public FooExtender(Foo foo) { // code } } public class FooBazExtender implements WrapperInterface { public FooBazExtender(Foo foo, Baz baz) { // code } } public class TestExtender implements WrapperInterface { public TestExtender(Foo foo) { // code } // code } ``` And so on. The following does not work: ```java // this does not work @GET @Path("test") @Produces("application/json") public Response getTest(@Context TestExtender test) { // code } ``` I could create a factory for each and register it in my application config class, using the `bindFactory` syntax like I did with Foo and Baz. But that is not a good approach due to the number of objects in question. I have read much of the hk2 documentation, and tried a variety of approaches. I just don't know enough of how hk2 actually works to come up with the answer, and it seems like a common enough problem that there should be a straightforward solution.<issue_comment>username_1: Factories are really only needed for more complex initializations. If you don't need this, all you need to do is bind the service ``` @Override protected void configure() { // bind service and advertise it as itself in a per lookup scope bindAsContract(TestExtender.class); // or bind service as a singleton bindAsContract(TestExtender.class).in(Singleton.class); // or bind the service and advertise as an interface bind(TestExtender.class).to(ITestExtender.class); // or bind the service and advertise as interface in a scope bind(TestExtender.class).to(ITestExtender.class).in(RequestScoped.class); } ``` You also need to add `@Inject` on the constructors so HK2 knows to inject the `Foo` and `Baz` ``` @Inject public TestExtender(Foo foo, Baz baz) {} ``` Upvotes: 2 <issue_comment>username_2: I wound up using [FastClasspathScanner](https://github.com/lukehutch/fast-classpath-scanner) to grab classes from the package(s) I was interested in. Then I called the appropriate bind methods (`bindAsContract` or `bind`) in batches, as mentioned in [username_1's answer](https://stackoverflow.com/a/49331036/9500925) (after also adding the appropriate `@Inject` annotations). That seemed to be the most expedient method available to emulate autoscanning and avoid having to manually register each class. It feels like a hack and I'd be surprised if hk2 doesn't have a better method baked in. Upvotes: 1 [selected_answer]
2018/03/16
738
2,123
<issue_start>username_0: I'm trying to make a transition to some 'a' tags. And which is that when it is mouse hovered, the underline is slowly grow from the left to the right on its text string. I figured that I should make it with pseudo of the a tag, I succeed to make a similar transition, but it has a problem that make me stuck. ```css .test a { font-size: 5vw; text-decoration: none; color: #000; } .test a::after { content: ''; display: block; height: 0.1em; left: 0; background-color: #000; transition: 0.5s ease-in-out; width: 0; } .test a:hover::after { width: 100%; } ``` ```html [text for the test](#) ``` I make the transition to change width of a::after from 0 to 100% but width 100% is rendered by the size of .test, not to the size of 'a'. So the length of underline doesn't fits to the text. It fits to the screen size. I cannot understand that why a::after doesn't follow the size of its parent, a. And want to know how can I make a::after to follow the size of 'a'.<issue_comment>username_1: You can either add: ``` .test { display: inline-block; } ``` or ``` .test a { display: inline-block; } ``` So that the size of the box matches the content. ```css .test { display: inline-block; } .test a { font-size: 5vw; text-decoration: none; color: #000; } .test a::after { content: ''; display: block; height: 0.1em; left: 0; background-color: #000; transition: 0.5s ease-in-out; width: 0; } .test a:hover::after { width: 100%; } ``` ```html [text for the test](#) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is another idea without the use of pseudo element and without the issue of size: ```css .test a { font-size: 5vw; text-decoration: none; color: #000; padding-bottom:0.1em; background-image:linear-gradient(#000,#000); background-size:0% 0.1em; background-position:0 100%; background-repeat:no-repeat; transition: 0.5s ease-in-out; } .test a:hover { background-size:100% 0.1em; } ``` ```html [text for the test](#) ``` Upvotes: 1
2018/03/16
523
1,929
<issue_start>username_0: I want to create a list of objects based of 2 lists from different types. I have a code snippet right now that works, but I would like to see if it can be converted into LINQ to make it smaller and more efficient. ``` List regions = new List { new Region { Name = "America" }, new Region { Name = "Europe" }, new Region { Name = "Asia" } }; List concepts = new List { new Concept { Name = "Population" }, new Concept { Name = "Location" }, new Concept { Name = "Temperature" }, new Concept { Name = "President" } }; List result = new List(); foreach (var region in regions) { foreach (var concept in concepts) { result.Add(new { region = region.Name, concept = concept.Name }); } } ```<issue_comment>username_1: With linq query: ``` var results = from region in regions from concept in concepts select new { region = region.Name, concept = concept.Name }; ``` Upvotes: 0 <issue_comment>username_2: You can perform the equivalent of a cross join in LINQ like this: ``` var regionConcepts = regions.SelectMany(x => concepts.Select(y => new { Region = x.Name, Concept = y.Name })); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Something like this: ``` var result = regions.SelectMany(r => concepts, (r, c) => new Tuple(r, c)); ``` Upvotes: 0 <issue_comment>username_4: This is the equivalent of what your code currently does using LINQ. ``` List resultSet = regions.SelectMany(region => concepts.Select(concept => new { Region = region.Name, Concept = concept.Name }) ) .Cast() .ToList(); ``` Another variant: ``` List resultSet = (from region in regions from concept in concepts select new { region = region.Name, concept = concept.Name }).Cast() .ToList(); ``` Upvotes: 0
2018/03/16
439
1,446
<issue_start>username_0: I'd like to create a new zip file using python. I'd like to zip files from different directories and put it in one zip file with custom folder structure. My source will come from ``` /mydir/sample1.txt /mydir/data/sample1_data.txt ``` The desired zip structure looks like this ``` sample1.txt /Data/sample1_data.txt ``` Please let me know if you have a solution.<issue_comment>username_1: As @sciroccorics suggested everything is in the [documentation](https://docs.python.org/3/library/zipfile.html). A short example would be something like: ``` from zipfile import ZipFile with ZipFile('out.zip', 'w') as z: z.write('/mydir/sample1.txt', 'sample1.txt') z.write('/mydir/data/sample1_data.txt', '/Data/sample1_data.txt') ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Python has a built in zip library ``` mydir = 'mydir' myzipfile = 'fancy.zip' from zipfile import ZipFile import os with ZipFile(myzipfile, 'w') as zipout: for dirpath, dirnames, filenames in os.walk(mydir): for filename in filenames: with open(os.path.join(dirpath[len(mydir)+1:], filename), 'r') as fin: with zipout.open(os.path.join(dirpath, filename), 'w') as fout: fout.write(fin.read()) ``` This will take all the files from mydir and copy them into fancy.zip It will also recurse into subdirectories of mydir and copy those files as well. Upvotes: -1
2018/03/16
484
1,597
<issue_start>username_0: I have pandas data frame like this.. ``` user pwd _message_ 0 _robin_ | usi | _I like coffee_ 1 _priya_ | ind | _I like green tea_ 2 gate | ldn | _I like to play_ 3 _Reh_ | ksm | _I respect others_ ``` I have value "ksm", and I want to change the value of next column of it and in the same row. it means I want to change "I respect others" to "I love myself". I have searched about it but I could not find straight forward way to do this task. Is there is any straight forward way to do this.<issue_comment>username_1: As @sciroccorics suggested everything is in the [documentation](https://docs.python.org/3/library/zipfile.html). A short example would be something like: ``` from zipfile import ZipFile with ZipFile('out.zip', 'w') as z: z.write('/mydir/sample1.txt', 'sample1.txt') z.write('/mydir/data/sample1_data.txt', '/Data/sample1_data.txt') ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Python has a built in zip library ``` mydir = 'mydir' myzipfile = 'fancy.zip' from zipfile import ZipFile import os with ZipFile(myzipfile, 'w') as zipout: for dirpath, dirnames, filenames in os.walk(mydir): for filename in filenames: with open(os.path.join(dirpath[len(mydir)+1:], filename), 'r') as fin: with zipout.open(os.path.join(dirpath, filename), 'w') as fout: fout.write(fin.read()) ``` This will take all the files from mydir and copy them into fancy.zip It will also recurse into subdirectories of mydir and copy those files as well. Upvotes: -1
2018/03/16
677
2,545
<issue_start>username_0: I want to generate multiple airflow dags using one script. The dag names should be "test\_parameter". Below is my script: ``` from datetime import datetime # Importing Airflow modules from airflow.models import DAG from airflow.operators import DummyOperator # Specifying the default arguments for the DAG default_args = { 'owner': 'Test', 'start_date': datetime.now() } parameter_list = ["abc", "pqr", "xyz"] for parameter in parameter_list: dag = DAG("test_"+parameter, default_args=default_args, schedule_interval=None) dag.doc_md = "This is a test dag" # Creating Start Dummy Operator start = DummyOperator( task_id="start", dag=dag) # Creating End Dummy Operator end = DummyOperator( task_id="end", dag=dag) # Design workflow of tasks in the dag end.set_upstream(start) ``` So in this case, it should create 3 dags: "test\_abc", "test\_pqr" and "test\_xyz". But on running the script, it creates only one dag "test\_xyz". Any insights on how to solve this issue. Thanks in advance :)<issue_comment>username_1: I guess the problem is that the dag objects 'start' and 'end' get overwrote by the forloop hence only the last value is retained. It is weird that although you cant create dag dynamically, but you can create tasks dynamically through a loop. maybe that helps. ``` for i in range(3): t1 = BashOperator( task_id='Success_test'+str(i), bash_command='cd home', dag=dag) slack_notification.set_upstream(t1) ``` Upvotes: 2 <issue_comment>username_2: You can register the dynamically created dags in the global namespace. For example: ``` globals()[parameter] = dag ``` Upvotes: 1 <issue_comment>username_3: Yes, it's possible, you can save your config for each DAG namely inside a storage. For example you can save your configuration within a persistent storage (DB) and then fetch the configuration and save the result inside a cache. This was done mainly because we want to prevent the dag script fetching the configuration from DB each time the DAG script refreshed. So instead, we use a cache and save its expire time. You can refer to this [article](https://airflow.incubator.apache.org/faq.html#how-can-i-create-dags-dynamically) on how to create a dynamic DAG ``` for i in range(10): dag_id = 'foo_{}'.format(i) globals()[dag_id] = DAG(dag_id) ``` In turn you also want to create a dynamic sub-DAG and dynamic tasks as well. Hope it helps :-) Upvotes: 3
2018/03/16
974
3,914
<issue_start>username_0: I have written an angular 4.3.0 typescript library. While building my library I saw below error in \*.d.ts file. > > ERROR in [at-loader] ..\myLibrary\lib-commonjs\my-guard.service.d.ts:13:5 > TS2416: Property 'canActivate' in type 'MyGuard' is not assignable to the same property in base type 'CanActivate'. > Type '(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | Promise | Observ...' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | Observable | Pr...'. > Type 'boolean | Promise | Observable' is not assignable to type 'boolean | Observable | Promise'. > Type 'Observable' is not assignable to type 'boolean | Observable | Promise'. > Type 'Observable' is not assignable to type 'Promise'. > Property '[Symbol.toStringTag]' is missing in type 'Observable'. > > > This is how my guard looks like ``` @Injectable() export class MyGuard implements CanActivate { canActivate( next: ActivatedRouteSnapshot ,state: RouterStateSnapshot): Observable | Promise | boolean { return true; } } ``` The error goes away after I removed the return type (Observable | Promise | boolean ) from canActivate. I want to understand why I need to remove it to make it work. ``` canActivate( next: ActivatedRouteSnapshot ,state: RouterStateSnapshot) { } ``` Error<issue_comment>username_1: @user911 - I recently started learning angular and fortunately came up with the same issue. The reason for the error would probably be that your IDE accidentally imported Promise from 'q' `import {Promise} from 'q'`; remove this and you can even declare the return type of the `canActivate` method which is `Observable< boolean>` | `Promise< boolean>` | `boolean`. The import is the only reason for which your app works fine when you remove the return type of the `canActivate` method. Try this for better understanding: 1. Make sure you define the return type of the `canActivate` method and while defining the type let IDE automatically import the Promise from q or import it manually. 2. As we expect there will be error and now remove `Promise< boolean>` from the return type and the error should go away unless you are returning a promise with your `canActivate` method. Upvotes: 1 <issue_comment>username_2: The error you are facing is because you copied the code that is for a different version of Angular than what you are using. The error went away when you removed the return value because you made the function compatible with the version you have on your machine. You can check the function signature at your current version by navigating to `CanActivate` on your machine. If you are using Visual Studio Code, you can press Ctrl and click on it to navigate to its file. Upvotes: 4 <issue_comment>username_3: For me, I put in the return type `Observable< Boolean> | Promise< Boolean> | Boolean` isntead of `Observable< boolean> | Promise< boolean> | boolean`. When I replace it works. Upvotes: -1 <issue_comment>username_4: Change this `(: Observable | Promise | boolean )` to `:any` would definitely work for you Upvotes: -1 <issue_comment>username_5: What fixed it for me, was an **import** mismatch issue. I created an interface and implemented it in a class. In the class I imported the correct module, but I didn't do the same in the interface declaration. That caused the compiler to yell at me, and took me some time to realize it was because of the imports, the typescript compiler doesn't mention it. Upvotes: 0 <issue_comment>username_6: To match the parent function signature, I had to specify the types `Observable` for the Observable. Then the error went away. ``` canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { return new Observable((obs) => { this.myService.token.subscribe(ntoken => { ... obs.next(true); }); }); ``` Upvotes: 0
2018/03/16
846
2,932
<issue_start>username_0: On my Ionic app the ngx-translate is giving me this message on console: > > **.... assets/i18n/.json 404 (Not Found)** > > > With another details on HttpErrorResponse So my app on BROWSER keeps giving this error, and when I build to use on phone it just trigger an alert message with this error and closes the app **My Setup:** Android. "cordova-plugin-crosswalk-webview": "^2.4.0" **<- LITE** "@ngx-translate/core": "^9.1.1", "@ngx-translate/http-loader": "^2.0.1", Ionic 3 Here's my ***app.module.ts*** ``` import { HttpClientModule, HttpClient } from '@angular/common/http'; import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, '../assets/i18n/', '.json'); } imports: [ BrowserModule, IonicModule.forRoot(MyApp), HttpClientModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }) ``` I saw other users having issues with the ``` export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, '../assets/i18n/', '.json'); ``` Changing it to just Http instead of HttpClient, but was no use for me. Typescript tells me the `http` has to be HttpClient type. This is my **app.component.ts** ``` import { TranslateService } from '@ngx-translate/core'; . . . constructor( private translateService: TranslateService, public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen ) { this.initializeApp(); } initializeApp() { this.platform.ready().then(() => { this.statusBar.styleDefault(); this.splashScreen.hide(); // this.setAppTranslation(); this.translateService.addLangs(["en", "pt"]); this.translateService.setDefaultLang('en'); this.translateService.use('en'); }); } ``` I've follow this tutorial to apply the function to my app: <https://www.gajotres.net/ionic-2-internationalize-and-localize-your-app-with-angular-2/> Can anyone help me at least understand? My assets/i18n folder has 2 files: *en.json pt.json*<issue_comment>username_1: I've had that problem before, try these two things: Change your loader to this (as @Mohsen said): ``` return new TranslateHttpLoader(http, './assets/i18n/', '.json'); ``` And your useFactory to this: ``` useFactory: (HttpLoaderFactory) ``` IMPORTANT: Make sure your assets folder is at this level: / src / assets / Upvotes: 3 [selected_answer]<issue_comment>username_2: SEARCH ``` key: "loadUrl", value: function(t, e) { var n = this; ``` THEN ADD, if (t !== undefined) t = t.replace("../../../app-assets/", "../../../control/app-assets/"); Upvotes: 0
2018/03/16
617
2,042
<issue_start>username_0: Say I have a class with a method that takes a function as an argument. Is there any way to make this function change inclass variables? ``` def f(): # something here to change MyClass.var class MyClass: def __init__(): self.var = 1 def method(self, func): #does something func() obj = MyClass() obj.method(f) print(obj.var) ```<issue_comment>username_1: Simply pass the internal reference of your class - `self` - into the function: ``` >>> class Class: def __init__(self): self.var = 1 def method(self, func): func(self) >>> def func(inst): inst.var = 0 >>> cls = Class() >>> cls.var 1 >>> cls.method(func) >>> cls.var 0 >>> ``` On a related side note, I'd argue that it'd be cleaner and clearer to actually make your function a method of your class: ``` >>> from types import MethodType >>> >>> def func(self): self.var = 0 >>> class Class: def __init__(self): self.var = 1 >>> cls = Class() >>> cls.var 1 >>> cls.func = MethodType(func, cls) >>> cls.func() >>> cls.var 0 >>> ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: This should work: ``` def f(obj): obj.var = 2 class MyClass: def __init__(self): self.var = 1 def method(self, func): # does something func(self) obj = MyClass() obj.method(f) print(obj.var) # --> 2 ``` Upvotes: 0 <issue_comment>username_3: Since the function `f` is defined outside the scope of the class, it can not access the class variable. However you can pass the class variable as an argument to f, and in that case it will be able to do any operation on it. ``` def f(x): return x**2 # just for the demonstration. Will square the existing value\\ # of the class variable class MyClass: def __init__(self): self.var = 2 def method(self, func): #does something self.var = func(self.var) obj = MyClass() obj.method(f) print(obj.var) >>> 4 ``` Upvotes: 0
2018/03/16
458
1,535
<issue_start>username_0: I'm trying to count all values in a column `Value` that are over 5. However, some results in that column appear like '>10' (it has the greater than symbol `>` in the field) I'd like to still count that as > 5. To do that, I did the following: ``` (COUNT(CASE WHEN t.VALUE LIKE '*>*' and Replace(t.VALUE, '>', ' ') > 5) Then 1 Else NULL End ) ``` But, for whatever reason, it's not replacing.<issue_comment>username_1: Well, how about converting to a number? ``` select sum(case when try_convert(int, replace(t.value, '>', '')) > 5 then 1 else 0 end) as values_over_5 ``` Your data model is suspicious, because you are doing numeric comparisons on a column that contains numbers. Upvotes: 2 <issue_comment>username_2: A couple of things. The asterisk isn't a valid wildcard character in SQL Server, so we'll change that. Also, if you want the string to become a number, you'll want to replace the greater-than with an empty string, not a space. It doesn't affect the outcome, but it's the right thing to do. This isn't as elegant as Gordon's one-liner, but it produced the expected results. ``` DECLARE @t TABLE (VALUE VARCHAR(5)); INSERT @t (VALUE) VALUES ('1'),('10'),('>10'); SELECT COUNT(*) AS Over5 FROM ( SELECT CASE WHEN t.VALUE LIKE '%>%' THEN Replace(t.VALUE, '>', '') ELSE t.VALUE END AS NewVal FROM @t as t ) AS d WHERE NewVal > 5; +-------+ | Over5 | +-------+ | 2 | +-------+ ``` Upvotes: 2 [selected_answer]
2018/03/16
968
3,540
<issue_start>username_0: I was recently coming up with some rather funky singleton work and discovered that I can access a protected static member from any unique inherited type using the same base of inheritance where generics are used. An example of what I'm talking about is as follows: ``` public abstract class Class { protected static int number = 5; public void Print() { Console.WriteLine(number); } } public class ClassA : Class { } public class ClassB : Class { public ClassB() { number = 1; } } public class ClassC : Class { public ClassC() { number = ClassA.number;//I don't want to be able to see "number" } } ``` Since generics are in use here, each unique inheriting type gets its own "number" (which is what I want). But I don't like that I can access "number" from other types inheriting the same base type when generics are used. Is there a way to fix this? And also why does this happen (I understand why it happens with inheritance without generics, but it doesn't seem right that it happens with generics)?<issue_comment>username_1: You can use the [private](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private) modifier to make the static member invisible to descendents. Use protected only if you want the descendants to be able to access it. It makes no difference generic vs. non. ``` public abstract class Class { private static int number = 5; //Private now public void Print() { Console.WriteLine(number); //Works } } public class ClassA : Class { //No number } public class ClassB : Class { public ClassB() { number = 1; //Will not compile } } public class ClassC : Class { public ClassC() { number = ClassA.number;//Will not compile } } ``` If you want the static variable to be accessible only to some descendants and not others, define the variable in the first class in the inheritance chain that needs access: ``` public abstract class Class { } public class ClassA : Class { static private int number = 7; } public class ClassB : Class { static private int number = 7; public ClassB() { ClassA.number = 5; //Does not compile ClassB.number = 6; } } public class ClassC : Class { static private int number = 7; public ClassC() { Console.WriteLine(ClassA.number); //Does not compile Console.WriteLine(ClassB.number); //Does not compile Console.WriteLine(ClassC.number); //Compiles } } ``` You cannot define something in an ancestor class and remove it from a descendant. Upvotes: -1 <issue_comment>username_2: > > I don't like that I can access "number" from other classes inheriting the same base class when generics are used. Is there a way to fix this? > > > The only true fix is to declare separate `private static` variables for each class. This will keep you from being able see the number variable in one class type from any other class type. ``` public abstract class Class { private static int number = 5; public void Print() { Console.WriteLine(number); } } public class ClassA : Class { } public class ClassB : Class { private static int number; public ClassB() { number = 1; } } public class ClassC : Class { private static int number; public ClassC() { number = 123; // Cannot see ClassA.number because it is private to `Class` } } ``` The side effect is being caused by declaring the variable `protected static` and using it with inheritance. It is unclear why you would attempt to do that when the behavior you are after is that of a `private static` field. Upvotes: 1
2018/03/16
537
1,753
<issue_start>username_0: So far I have this which replaces the text in the input box if it has the object name in it, with the object value: ``` var obj = { '1': 'fish', 'q': 'apple', 'z': 'banana', }; $("#inputBoxID").on("keyup", function() { if(obj.hasOwnProperty($("#inputBoxID").val())) $(this).val(obj[$("#inputBoxID").val()]); }); ``` I would like to modify this so that on any occurrence of a object name it would replace the object name with the value, here's an example of what I'm trying to do: User enters `hello q` I want that to be replaced with: `hello apple` How would I go about doing this?<issue_comment>username_1: You might wanna replace each word separately by splitting the string into an array of words and then replacing it: ``` $("#inputBoxID").val((_, v) => v.split(" ").map(word => obj[word] || word).join(" ")) ``` Upvotes: 0 <issue_comment>username_2: You can split by space, map and then join! ```js var obj = { '1': 'fish', 'q': 'apple', 'e': 'banana'}; $("#inputBoxID").on("keyup", function() { var str = $("#inputBoxID").val().split(' ').map(function(word) { return obj[word] || word; }).join(' '); $(this).val(str); }); ``` ```html ``` Upvotes: 2 <issue_comment>username_3: you can simply replace any occurrence of key with it's value, like below(I know it's little heavy as for each key press we are iterating through object). ```js var obj = { '1': 'fish', 'q': 'apple', 'z': 'banana', }; $("#inputBoxID").on("keyup", function() { var str = $("#inputBoxID").val(); for(var x in obj){ if(obj.hasOwnProperty(x)){ str=str.replace(x,obj[x]); } } $(this).val(str); }); ``` ```html ``` Upvotes: 2 [selected_answer]
2018/03/16
262
1,055
<issue_start>username_0: Basically what the title states. I'm aware of what detached HEAD state is and how you get to one and how to checkout of it. But I was curious if there was a direct use case to have a detached HEAD. Possibly better question: What is a real life dev scenario where you would want to checkout to a specific commit SHA, but not check it out into a branch.<issue_comment>username_1: When you're trying to find where in history a bug was introduced. Or When you're trying to reproduce the behavior of a previous build, to diagnose an issue reported by a client/customer whose working version is not a branch tip in your repo. Upvotes: 2 <issue_comment>username_2: Bisecting, or any other kind of "time travel" debugging will put you in this state. It's useful because you can find out what your app looked like at a certain point in time (commit). Upvotes: 4 [selected_answer]<issue_comment>username_3: [Submodules](https://git-scm.com/docs/git-submodule#git-submodule-checkout) are almost always in detached HEAD state. Upvotes: 0
2018/03/16
414
1,473
<issue_start>username_0: I am going through a Maven tutorial and it mentions that you can lookup information about a dependency on ibiblio.org: > > Let's add another dependency to our project. Let's say we've added > some logging to the code and need to add log4j as a dependency. First, > we need to know what the groupId, artifactId, and version are for > log4j. We can browse ibiblio and look for it, or use Google to help by > searching for "site:www.ibiblio.org maven2 log4j". The search shows a > directory called /maven2/log4j/log4j (or > /pub/packages/maven2/log4j/log4j). In that directory is a file called > maven-metadata.xml. Here's what the maven-metadata.xml for log4j looks > like... > > > Does ibiblio have some sort of special role in Maven? Or is it just a mirror?<issue_comment>username_1: When you're trying to find where in history a bug was introduced. Or When you're trying to reproduce the behavior of a previous build, to diagnose an issue reported by a client/customer whose working version is not a branch tip in your repo. Upvotes: 2 <issue_comment>username_2: Bisecting, or any other kind of "time travel" debugging will put you in this state. It's useful because you can find out what your app looked like at a certain point in time (commit). Upvotes: 4 [selected_answer]<issue_comment>username_3: [Submodules](https://git-scm.com/docs/git-submodule#git-submodule-checkout) are almost always in detached HEAD state. Upvotes: 0
2018/03/16
674
2,292
<issue_start>username_0: Here is my code for the program. ``` #include int main() { int number; printf("Enter an integer: "); scanf("%d", &number); printf("You entered: %d", number); return 0; } ``` If I enter an integer: `12345678912345678` Result is Showing: `1578423886` Why is this happening ?<issue_comment>username_1: That happens because data types on any programming language have limits, so you cannot simply put any number into an integer data type. Probably for your test the limit is 2.147.483.647 for integer data type, if you want to receive a bigger number you will have to switch to long or maybe unsigned long, it all depends of your needs, and when it comes to handle really really big numbers probably you will need to read it as string and then parse it to a special structure or class than can handle that really big number. Upvotes: 0 <issue_comment>username_2: The problem is that on the system you're running on, `int` is not large enough to store integers as large as you're trying to enter (the limit is architecture-specific, and can be checked via `INT_MAX`). If you define your variable as a `long long` instead, it will be able to hold larger values (`long long` is 64 bits on most common architectures), and so: ``` #include int main() { long long number; printf("Enter an integer: "); scanf("%lld", &number); printf("You entered: %lld", number); return 0; } ``` outputs: ``` Enter an integer: 12345678912345678 You entered: 12345678912345678 ``` Upvotes: 1 <issue_comment>username_3: This is happening because On a system if the value won't fit in an `int`, then the result of the conversion is implementation-defined. (Or, starting in C99, it can raise an implementation-defined signal, but I don't know of any compilers that actually do that.) What *typically* happens is that the **high-order bits are discarded**, but you shouldn't depend on that. (The rules are different for unsigned types; the result of converting a signed or unsigned integer to an unsigned type is well defined.) Because of this discarding you get result like mention in comment `12345678912345678 is a 54-bit number. In hex it's 0x2bdc545e14d64e. Interestingly enough 1578423886 is 0x5e14d64e`(lower bits are same and higher are discarded) Upvotes: 0
2018/03/16
765
2,834
<issue_start>username_0: I am trying to remove item from a node in for each loop on my cloud function. But it always looking only first item. I want to loop all items. Here is my codes: ``` snapshot.forEach(function(child) { console.log('all items'); return thisAppDb.ref('userRemindMatches/'+child.key+'/'+compId).once('value').then(snapshot => { if (snapshot.exists()) { snapshot.ref.remove(); console.log('match removed from this user : '+child.key); } return thisAppDb.ref('user : '+child.key+' matches removed'); }); }); ``` As you see here, in snapshot.foreach, I am calling another ref. Node then I want to remove item from that node. It is working only once. How can I loop this for each items? (In my opinion, it occurs because of return in loop)<issue_comment>username_1: That happens because data types on any programming language have limits, so you cannot simply put any number into an integer data type. Probably for your test the limit is 2.147.483.647 for integer data type, if you want to receive a bigger number you will have to switch to long or maybe unsigned long, it all depends of your needs, and when it comes to handle really really big numbers probably you will need to read it as string and then parse it to a special structure or class than can handle that really big number. Upvotes: 0 <issue_comment>username_2: The problem is that on the system you're running on, `int` is not large enough to store integers as large as you're trying to enter (the limit is architecture-specific, and can be checked via `INT_MAX`). If you define your variable as a `long long` instead, it will be able to hold larger values (`long long` is 64 bits on most common architectures), and so: ``` #include int main() { long long number; printf("Enter an integer: "); scanf("%lld", &number); printf("You entered: %lld", number); return 0; } ``` outputs: ``` Enter an integer: 12345678912345678 You entered: 12345678912345678 ``` Upvotes: 1 <issue_comment>username_3: This is happening because On a system if the value won't fit in an `int`, then the result of the conversion is implementation-defined. (Or, starting in C99, it can raise an implementation-defined signal, but I don't know of any compilers that actually do that.) What *typically* happens is that the **high-order bits are discarded**, but you shouldn't depend on that. (The rules are different for unsigned types; the result of converting a signed or unsigned integer to an unsigned type is well defined.) Because of this discarding you get result like mention in comment `12345678912345678 is a 54-bit number. In hex it's 0x2bdc545e14d64e. Interestingly enough 1578423886 is 0x5e14d64e`(lower bits are same and higher are discarded) Upvotes: 0
2018/03/16
295
1,000
<issue_start>username_0: I need to create a graph in HTML page with Flask. I've used this tutorial: <http://blog.ruanbekker.com/blog/2017/12/14/graphing-pretty-charts-with-python-flask-and-chartjs/> My app has to run in offline mode eventually, so instead of using: ``` ``` in my HTML file, i've copied the code in `Chart.min.js` to my computer and replaced the code line with: ``` ``` There is no path error. The path `/static/Chart.min.js` exists. In the first case (online mode) the graph works perfectly, on the second case (offline) the graph isn't displayed. What's the problem? Thanks!<issue_comment>username_1: Write the src tag for calling the js file as ``` ``` Upvotes: 1 <issue_comment>username_2: I had the same problem before, So do this on your script tag change "Chart.min.js" to "chart.min.js". The issue there was capital letter on Chart.js although the file i have was named Chart.js but when i change it to small letter it work. Sorry for the poor english Upvotes: 0
2018/03/16
192
746
<issue_start>username_0: I'm doing cross browser javascript and the line of javascript below works fine in IE11 but doesn't work in Chrome. ``` selectedItem._element.childNodes[0].getElementsByTagName('input').item().checked; ``` The error message I get is: TypeError: Failed to execute 'item' on 'HTMLCollection': 1 argument required, but only 0<issue_comment>username_1: Write the src tag for calling the js file as ``` ``` Upvotes: 1 <issue_comment>username_2: I had the same problem before, So do this on your script tag change "Chart.min.js" to "chart.min.js". The issue there was capital letter on Chart.js although the file i have was named Chart.js but when i change it to small letter it work. Sorry for the poor english Upvotes: 0
2018/03/16
778
2,932
<issue_start>username_0: I am trying to create an API App in **Azure App Service** with PowerShell. The cmdlet I am calling always create a Web App by default. If it is possible, I would like to know how I can specify the type/kind to be `Api App` instead of `Web App`? ``` New-AzureRmWebApp -Name $name -Location $location -AppServicePlan $plan -ResourceGroupName $resourceGroup ``` From my reading there is not much different between both except the icon, is it worth it to set the type to "Api App" if it's what my app is all about? I am using version 5.4.0 of AzureRM PowerShell module. ``` > Get-Module "AzureRM" ModuleType Version Name ---------- ------- ---- Script 5.4.0 AzureRM ```<issue_comment>username_1: There is not a parameter in `New-AzureRmWebApp` supported to explicitly indicate whether API App or Web App. The resource provider is still `Microsoft.Web`. And there is no parameter which indicates the type in ARM template. These two types technically still work in the same way. The difference would be the purpose, icon, OS running choice and debugging capability (refer here [What is the difference between an API App and a Web App?](https://stackoverflow.com/questions/31387073/what-is-the-difference-between-an-api-app-and-a-web-app)). You may want to classify between the two types by tagging it, which would help manage in case your resource groups have many web resources. [![enter image description here](https://i.stack.imgur.com/3jyOo.png)](https://i.stack.imgur.com/3jyOo.png) You can create API App via Azure Portal, or Visual Studio. Also, look at Azure API Management for more flexibility of API wrapping instead of Azure App Service. Upvotes: 0 <issue_comment>username_2: Just call `New-AzureRmResource` instead and pass in `-Kind 'api'`: ``` # CREATE "just-an-api" API App $ResourceLocation = "West US" $ResourceName = "just-an-api" $ResourceGroupName = "demo" $PropertiesObject = @{ # serverFarmId points to the App Service Plan resource id serverFarmId = "/subscriptions/SUBSCRIPTION-GUID/resourceGroups/demo/providers/Microsoft.Web/serverfarms/plan1" } New-AzureRmResource -Location $ResourceLocation ` -PropertyObject $PropertiesObject ` -ResourceGroupName $ResourceGroupName ` -ResourceType Microsoft.Web/sites ` -ResourceName "just-an-api/$ResourceName" ` -Kind 'api' ` -ApiVersion 2016-08-01 -Force ``` ..which produces an API App, a `Microsoft.Web/sites` resource **type** of the `api` kind: [![Portal screenshot](https://i.stack.imgur.com/ncgC8.png)](https://i.stack.imgur.com/ncgC8.png) > > *Hold on.. How did you come up with this stuff?* > > > Visit <https://resources.azure.com> and navigate to an existing API App, build the PowerShell syntax by combining the PowerShell tab with the desired values from the JSON resource definition. Upvotes: 4 [selected_answer]
2018/03/16
780
2,169
<issue_start>username_0: I'm using POST Method and I want the PHP script to return the data in JSON format //data 1: ``` ``` //data 2: ``` ``` **i want result be like :** ``` {id:1,name:"aa",stuff:"cc"},{id:2,name:"dd",stuff:"ff"} ``` I understand that if we use json\_encode($\_POST,true) i will have : ``` {"id":["1","2"],"name":["aa","dd"],"stuff":["cc","ff"]} ``` i can do that with js using get method **not** post ``` id[]=1&name[]=aa&stuff=cc&id[]=2&name[]=dd&stuff[]=ff ``` Check my solution <https://jsfiddle.net/cqvny3th/> Or what if we generate url from the post method using **http\_build\_query**, result is : ``` id[]=1&id[]=2&name[]=aa&name[]=dd&stuff=cc&stuff[]=ff ``` But my solution works only with : ``` id[]=1&name[]=aa&stuff=cc&id[]=2&name[]=dd&stuff[]=ff ``` Regards<issue_comment>username_1: Rename your inputs, if you can. ``` ``` That will group the data properly. Use `array_values` before `json_encode` so you'll get an array of objects rather than an object. ``` echo json_encode(array_values($_GET)); ``` Upvotes: 2 <issue_comment>username_2: Definitely less elegant than @username_1's solution, but in case you want/need to keep your `name` attributes as they are, this will work: ``` //prep $repeated_post_vars = ['id', 'name', 'stuff']; $arr = []; //find which column has the most values, just in case they're not all equal $num_items = max(array_map(function($col) { return !empty($_POST[$col]) ? count($_POST[$col]) : 0; }, $repeated_post_vars)); //iterate over value sets for ($g=0; $g<$num_items; $g++) { foreach($repeated_post_vars as $col) $tmp[$col] = !empty($_POST[$col][$g]) ? $_POST[$col][$g] : null; $arr[] = $tmp; } ``` So if `$_POST` on submit looks like: ``` [ 'id' => [1, 2], 'name' => ['foo', 'bar'], 'stuff' => [3] ]; ``` The code produces: ``` [{"id":1,"name":"foo","stuff":3},{"id":2,"name":"bar","stuff":null}] ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: Could you do something like this? ``` $list = array(); for ($i=0; $i $values) $item->{$key} = $values[$i]; $list[] = $item; } print json\_encode( $list ); ``` Upvotes: 0
2018/03/16
553
1,695
<issue_start>username_0: I always have same problem when installing node-sass sudo npm install -g node-sass *gyp ERR! stack Error: EACCES: permission denied, mkdir '/Users/max/Sites/xxxxxxx/node\_modules/node-sass/build'* I have update my node and npm version but the same nothing to do, it seems something with permission.... any idea?<issue_comment>username_1: Rename your inputs, if you can. ``` ``` That will group the data properly. Use `array_values` before `json_encode` so you'll get an array of objects rather than an object. ``` echo json_encode(array_values($_GET)); ``` Upvotes: 2 <issue_comment>username_2: Definitely less elegant than @username_1's solution, but in case you want/need to keep your `name` attributes as they are, this will work: ``` //prep $repeated_post_vars = ['id', 'name', 'stuff']; $arr = []; //find which column has the most values, just in case they're not all equal $num_items = max(array_map(function($col) { return !empty($_POST[$col]) ? count($_POST[$col]) : 0; }, $repeated_post_vars)); //iterate over value sets for ($g=0; $g<$num_items; $g++) { foreach($repeated_post_vars as $col) $tmp[$col] = !empty($_POST[$col][$g]) ? $_POST[$col][$g] : null; $arr[] = $tmp; } ``` So if `$_POST` on submit looks like: ``` [ 'id' => [1, 2], 'name' => ['foo', 'bar'], 'stuff' => [3] ]; ``` The code produces: ``` [{"id":1,"name":"foo","stuff":3},{"id":2,"name":"bar","stuff":null}] ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: Could you do something like this? ``` $list = array(); for ($i=0; $i $values) $item->{$key} = $values[$i]; $list[] = $item; } print json\_encode( $list ); ``` Upvotes: 0
2018/03/16
344
1,202
<issue_start>username_0: I know it may sound very small issue but need to resolve, following is my SQL query ``` SELECT CASE WHEN A.ReleaseDate = '1900-01-01' THEN '' WHEN A.ReleaseDate IS NULL THEN '' ELSE ReleaseDate END AS ReleaseDate FROM XYZ ``` I can see `Releasedate` is `1900-01-01` in my table but still case is using `ELSE` condition. I can't find out the reason.<issue_comment>username_1: A `case` expression returns a single type. I think yours will return a date. Hence you get a date and a blank string turns into some very old date. If you want it to return a blank string, then you want a string back. So use explicit conversion: ``` SELECT (CASE WHEN A.ReleaseDate = '1900-01-01' THEN '' WHEN A.ReleaseDate is null THEN '' ELSE CONVERT(VARCHAR(10), ReleaseDate, 121) END) as ReleaseDate FROM XYZ; ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can cast your ReleaseDate as Varchar ``` SELECT (CASE WHEN ReleaseDate = '1900-01-01' THEN '' WHEN ReleaseDate is null THEN '' ELSE cast(ReleaseDate as varchar) END) as ReleaseDate FROM XYZ; ``` Upvotes: 2
2018/03/16
454
1,802
<issue_start>username_0: So i am currently developing a web app that will use laravel api for future mobile use and laravel passport. My passport is set up to where i used postman to login, register, and delete an account, the usual functions. The laravel API also works independently as can make the requests from my routes. Using Passport, i log in, and it returns a token, in which if i am correct, is the token that will be used for the API. Now upon creating the api, which will be accepting the forms/parameter to the main function for my app, **How do i use the token i received from Passport with the API?** In the request to the API do i need to ask for the user's token and if so how to check that its a token that can be used from my application. It's this middle part of connecting them i cannot understand, as I can make the passport work by itself, and the laravel api by itself that im just sending the posts/get from postman and getting my json responses that ill use later for my js frontend.<issue_comment>username_1: A `case` expression returns a single type. I think yours will return a date. Hence you get a date and a blank string turns into some very old date. If you want it to return a blank string, then you want a string back. So use explicit conversion: ``` SELECT (CASE WHEN A.ReleaseDate = '1900-01-01' THEN '' WHEN A.ReleaseDate is null THEN '' ELSE CONVERT(VARCHAR(10), ReleaseDate, 121) END) as ReleaseDate FROM XYZ; ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can cast your ReleaseDate as Varchar ``` SELECT (CASE WHEN ReleaseDate = '1900-01-01' THEN '' WHEN ReleaseDate is null THEN '' ELSE cast(ReleaseDate as varchar) END) as ReleaseDate FROM XYZ; ``` Upvotes: 2
2018/03/16
291
921
<issue_start>username_0: I'm running a python script, where I have to convert a string column from a pandas `df` to `int`, using the `astype(int)` method. However, I get this following error: ``` "Python int too large to convert to C long" ``` My strings are all numbers in string format, up to 15 characters. Is there a way to convert this column to int type without this popping this error?<issue_comment>username_1: You need to use `.astype('int64')` ``` import pandas as pd df = pd.DataFrame({'test': ['999999999999999','111111111111111']}) df['int'] = df['test'].astype('int64') ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: Check whether you are assigning a Large Integer values to variable. 1) Instead of applying multiplication, using power For example: ```py x = [10**i for i in range(1,1000)] instead of [10*i for i in range(1,1000)] ,which will cross the variable limit ``` Upvotes: -1
2018/03/16
810
3,150
<issue_start>username_0: I have an old site that used to use `Identity` to get a new invoice number. In SQL Server 2005, this worked fine, but since moving to SQL Server 2014, I get gaps (approx 1000 after a reboot). Yes I know (now) you shouldn't use `Identity` for this. So I thought the solution would be using a `Sequence`. I did this ``` CREATE SEQUENCE SeqInvoice AS INTEGER START WITH 2971 INCREMENT BY 1 MINVALUE 1 MAXVALUE 999999999 NO CYCLE; ``` And to get next number do this. ``` SELECT NEXT VALUE FOR SeqInvoice; ``` worked fine ..... until I noticed a gap - it jumped from 3028 to 3067 I thought `Sequence` was supposed to not have gaps. Can `Sequence` have gaps? If so do I need to have table with last number used and use transactions to ensure no duplicates?<issue_comment>username_1: Think about the logic of the situation for a minute. In the case that you came up with - two users creating invoices at the same time - how do you handle it if one user gets the "next" invoice number, then they change their mind and cancel it. Or the system crashes. Or they lose their connection. These are just some of the reasons that there isn't a built in "no gaps" type of ID. SQL Server needs to be able to have ACID transactions and that can't be done with autoincrementing numbers that never have gaps. The best solution that I can come up with is to have your system generate an invoice number as soon as someone starts to create an invoice. That's *immediately* saved to the database. If anything happens to that invoice (the user cancels it, the system crashes, etc.) then the invoice is canceled out in the system by giving it a canceled status code or something along those lines. That way it will still exist and you can point to it for the auditors and say, "Here's why that invoice number doesn't have a real invoice attached - the user created it, but then canceled it." (for example) To generate the invoice number you could use a single table with a single column and single row for `next_invoice_number`. When your system wants to generate a new invoice number it locks that table, saves a blank invoice in the Invoices table with the next number, increments the `next_invoice_number` in the table, then releases the lock on the table. If you have a lot of users creating invoices then this could cause problems with users having to wait for the locks on the table to be released, but it's about the best that you can do, IMO. Upvotes: 2 <issue_comment>username_2: A `SEQUENCE` in SQL Server caches a default of 50 sequential values in memory, so when a reboot or power outage etc. occurs, yes, there can be gaps of up to 50 numbers. **BUT:** the `CREATE SEQUENCE` (<https://learn.microsoft.com/en-us/sql/t-sql/statements/create-sequence-transact-sql>) does allow you to **specify** how many cached sequential numbers you want - with the `CACHE n` directive. You can also use `NO CACHE` to have absolutely no caching - then, you should pretty much avoid gaps altogether - **BUT** at the price that dishing out the sequential numbers with `NEXT VALUE FOR ...` becomes a bit slower. Take your pick! Upvotes: 1
2018/03/16
1,448
4,995
<issue_start>username_0: I have set up a custom single template for a specific category using the following: ``` // custom single template for specific category function wpse_custom_category_single_template( $single_template ) { // global $post; // get all categories of current post $categories = get_the_category( $post->ID ); $top_categories = array(); // get top level categories foreach( $categories as $cat ) { if ( $cat->parent != 0 ) { $top_categories[] = $cat->parent; } else { $top_categories[] = $cat->term_id; } } // check if specific category exists in array if ( in_array( '7', $top_categories ) ) { if ( file_exists( get_template_directory() . '/single-custom.php' ) ) return get_template_directory() . '/single-custom.php'; } return $single_template; } add_filter( 'single_template', 'wpse_custom_category_single_template' ); ``` Within single-custom.php, I am using: ``` php echo get_the_date('F jS, Y', $post-ID); ?> ``` but it is pulling in the date from very first post in all of this category (ie. showing the same date on each single post). Within all other posts not using the custom single template, the date appears fine. Can anyone suggest where I am making the error. EDIT to show single-custom.php ``` php /** * The template for displaying all single posts and attachments * * @package FoundationPress * @since FoundationPress 1.0.0 */ get_header(); ? php if ( function_exists('yoast_breadcrumb') ) { yoast_breadcrumb(' <p id="breadcrumbs"',' '); } ?> Customers & Resources ===================== Case Studies ------------ php $args = array( 'prev\_text' = ' Previous Study', 'next\_text' => 'Next Study ', 'screen\_reader\_text' => 'News navigation', 'excluded\_terms' => '6', 'taxonomy' => 'category' ); the\_post\_navigation($args); ?> php while ( have\_posts() ) : the\_post(); ? > ### php wp\_title(); ? php get\_the\_date('F jS, Y', $post-ID); ?> php the\_content(); ? php edit\_post\_link( \_\_( '(Edit)', 'foundationpress' ), '<span class="edit-link"', '' ); ?> php wp\_link\_pages( array( 'before' = '' . \_\_( 'Pages:', 'foundationpress' ), 'after' => ' ', ) ); ?> php $tag = get\_the\_tags(); if ( $tag ) { ?php the\_tags(); ? php } ? php $args = array( 'prev\_text' = ' Previous Study', 'next\_text' => 'Next Study ', 'screen\_reader\_text' => 'Case Study navigation' ); the\_post\_navigation($args); ?> php endwhile;? php echo do_shortcode("[consultant]"); ? php get_footer(); </code ```<issue_comment>username_1: Without seeing the code from `single-custom.php` it is hard to say for certain but it sounds like your `$post` variable does not contain the item that you are wanting the date for. Be sure that you are reassigning the global `$post` variable on each loop iteration. Something like this will do it placed inside your loop. ``` $your_query_object->the_post(); echo get_the_date('F jS, Y', $post->ID) ``` Upvotes: 0 <issue_comment>username_2: I believe you could just remove the `$post->ID` from `get_the_date()`: ``` echo get_the_date( 'F jS, Y' ); ``` If that doesn't work, you could try using the function `get_the_ID()` instead of `$post->ID`: ``` echo get_the_date( 'F jS, Y', get_the_ID() ); ``` Side note: It also appears you have an extra in your code, is that intentional? If not, I've cleaned it up a little bit to make it a bit easier to parse through: ``` php /** * The template for displaying all single posts and attachments * * @package FoundationPress * @since FoundationPress 1.0.0 */ get_header(); if( function_exists( 'yoast_breadcrumb' ) ) yoast_breadcrumb( '<p id="breadcrumbs"', '' ); ?> Customers & Resources ===================== Case Studies ------------ php $args = array( 'prev\_text' = ' Previous Study', 'next\_text' => 'Next Study ', 'screen\_reader\_text' => 'News navigation', 'excluded\_terms' => '6', 'taxonomy' => 'category' ); the\_post\_navigation( $args ); ?> php while ( have\_posts() ) : the\_post(); ? > ### php wp\_title(); ? php get\_the\_date( 'F jS, Y' ); ? php the\_content(); ? php edit\_post\_link( \_\_( '(Edit)', 'foundationpress' ), '<span class="edit-link"', '' ); ?> php wp\_link\_pages( array( 'before' = '' . \_\_( 'Pages:', 'foundationpress' ), 'after' => ' ', ) ); if( get\_the\_tags() ) the\_tags( '', ', ', ' ' ); ?> php $args = array( 'prev\_text' = ' Previous Study', 'next\_text' => 'Next Study ', 'screen\_reader\_text' => 'Case Study navigation' ); the\_post\_navigation( $args ); ?> php endwhile;? php echo do_shortcode("[consultant]"); get_footer(); ? ``` Upvotes: 2
2018/03/16
507
1,693
<issue_start>username_0: I want to make a JavaScript array contains the user's id of class `.user-status` to send to PHP by using ajax. This is my HTML: ``` ``` This is my JavaScript: ``` $('.user-status').each(function() { $(this).attr('data-userid'); }); var users = ["", "", "", ""]; jQuery.ajax({ url: ajaxURL, data: { action : 'user_status', usersid: users }, dataType: 'JSON', type: 'POST', success: function (response) { } }); ``` Until here I can't continue I can't make the array of the user's id to can send it.<issue_comment>username_1: Push the user id into the array. ``` $('.user-status').each(function() { users.push($(this).attr('data-userid')); }); ``` Upvotes: 0 <issue_comment>username_2: You can do it like this: ``` var users = []; jQuery('.user-status').each(function() { users.push($(this).attr('data-userid'); }); ``` I start with an empty array, or otherwise you'd end up with an array with 8 items, four of them empty strings. Upvotes: 2 [selected_answer]<issue_comment>username_3: You can also use jquery's data property such as ``` var users = []; $('.user-status').each(function() { users.push($(this).data('userid')); }); ``` Upvotes: 1 <issue_comment>username_4: You can use the function `map` along with the function `$.toArray()` ``` var users = $('.user-status').toArray().map(function(elem) { return $(elem).data('userid'); }); ``` Upvotes: 0 <issue_comment>username_5: Using `Array.from` you can avoid creating an empty array and push. ```js console.log(Array.from($('.user-status'), function(element) { return $(element).data("userid") })) ``` ```html ``` Upvotes: 0
2018/03/16
1,005
3,130
<issue_start>username_0: I have 2 squares in a and I want that when I click one, it become black and the other don't. My current code is working but I gave them the same function and `id`, so when I click the first, it work well, but when I click the second, it's the first one that changes. I know whats wrong, but I don't know how to correct it without having to create a function for each `id`. Let's say I want 100 squares, I won't write one function to each one, so what can I do? ```js function myFunc() { var element = document.getElementById("cc"); element.classList.toggle("th"); } ``` ```css table, th, td { border: solid black 1px; width: 100px; height: 100px; } .th { background-color: black; } ``` ```html | | | | --- | --- | ```<issue_comment>username_1: Your function is storing the first square in a variable with the `cc` identifier. Instead, you should pass a reference of the element clicked and store that element in the variable. That way, the element clicked will be toggled. ``` function myFunc(ref) { var element = document.getElementById(ref.id).innerHTML; element.classList.toggle("th"); } ``` Notice that must also add `this` to the call of the function. Upvotes: 0 <issue_comment>username_2: First of all, and more important: `id` must be unique, thats why it is called id (identifier). Said that, I will show you two options to solve your question: **1. The better option**: Don't add any inline (direct in HTML) `onclick` listener. Add a common class to all `|`, then in Javascript add a single listener to each element that has the class, and use `this` inside the function, since `this` scope will be the clicked element. Example: ```js let allTh = document.querySelectorAll(".clickableTh").forEach(x => x.onclick = myFunc) function myFunc() { this.classList.toggle("th"); } ``` ```css table, th, td { border:solid black 1px; width:100px; height:100px; } .th { background-color:black; } ``` ```html | | | | | | | | --- | --- | --- | --- | --- | --- | ``` **2. Keeping your current structure**: As said in the comments, you pass `this` as parameter (`onclick="myFunc(this)"`), then inside `myFunc` you don't need to find the element, you'll already have it in as parameter. Click below to see the snippet code of example ```js function myFunc(elem) { elem.classList.toggle("th"); } ``` ```css table, th, td { border:solid black 1px; width:100px; height:100px; } .th { background-color:black; } ``` ```html | | | | | | | | --- | --- | --- | --- | --- | --- | ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: For less markup you can bind the click event on all `th` ```js var th = document.getElementsByTagName("th"); for (var i = 0; i < th.length; i++) { th[i].addEventListener("click", function() { this.classList.toggle("th"); }); } ``` ```css th, td { border: solid black 1px; width: 100px; height: 100px; } .th { background-color: black; } ``` ```html | | | | | | --- | --- | --- | --- | ``` Upvotes: 1
2018/03/16
511
1,833
<issue_start>username_0: The code below was copied directly from the current perlsyn page on perldoc.perl.org. [I've added an initialization and declarations as needed to make it run (and it works as expected), but the point is the 'when' keyword] Perl 5.24 complains about 'when' being experimental. Fair enough, but I don't want to see this every time I use the keyword. no warnings qw(experimental::when) does not work - "Unknown warning category ..." I also tried "switch" as the category Is there another way to suppress this warning (other than disabling warnings in general)? ``` use v5.14; for ($var) { $abc = 1 when /^abc/; $def = 1 when /^def/; $xyz = 1 when /^xyz/; default { $nothing = 1 } } ```<issue_comment>username_1: `given` and `when` are part of the `smartmatch` experiment, so these warnings can be disabled using: ``` no warnings qw( experimental::smartmatch ); ``` Upvotes: 2 <issue_comment>username_2: You can enable this construct without warnings via ``` use experimental 'switch'; ``` or merely disable the "experimental" warning category via ``` no warnings 'experimental::smartmatch'; ``` (see the [full list of available warning categories in `perldoc warnings`](https://metacpan.org/pod/warnings#Category-Hierarchy)). But please note that smartmatch, `given`, and `when` constructs are considered to be fundamentally broken, and are being removed/redesigned. Just silencing the warning will break your code when you run that code on other perl versions. Instead, please prefer out to spell this code out explicitly: ``` for ($var) { if (/^abc/) { $abc = 1 } elsif (/^def/) { $def = 1 } elsif (/^xyz/) { $xyz = 1 } else { $nothing = 1 } } ``` Yes, it's more ugly, but it will also work for all values of `$var` and for all Perl5 versions. Upvotes: 3
2018/03/16
1,498
5,545
<issue_start>username_0: I am implementing a client for communicate with some server by the cryptological way. The client sends get request with public RSA key to the server. Documentation "how to communicate with server" has the sample with java code. The following code generates the public key: ``` KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair keypair = keyGen.genKeyPair(); byte[] pubKeyBytes = keypair.getPublic().getEncoded(); ``` I need to implement my client in C#. I found the way how to do the same in C#: ``` var rsa = new RSACryptoServiceProvider(2048); var parameters = _rsa.ExportParameters(includePrivateParameters: false); ``` The client uses parameters and solution from [How to adapt public/private RSA keys of C# for using them as in Java?](https://stackoverflow.com/questions/49282558/how-to-adapt-public-private-rsa-keys-of-c-sharp-for-using-them-as-in-java) That's ok. The client can generate the key which can pass verification on the server. As result, I have the encrypted response and trying to decrypt it. ``` responseContent = rsa.Decrypt(responseContent) ``` But this code throws following exception: > > **System.Security.Cryptography.CryptographicException:** 'The data to be > decrypted exceeds the maximum for this modulus of 256 bytes.' > > > *responseContent* is byte array with length 250996. And as I see there is impossible to decrypt response content by way above. From the documentation, I know that [![enter image description here](https://i.stack.imgur.com/4VPBz.png)](https://i.stack.imgur.com/4VPBz.png) Also, I have an example how to decrypt response in java: ``` JWEObject jweObject = JWEObject.parse(encryptedPayload); RSAPrivateKey rsaPrivatteKey = (RSAPrivateKey)KeyFactory .getInstance("RSA") .generatePrivate(new PKCS8EncodedKeySpec(keybytes)); RSADecrypter RSADecrypter rsaDecrypter= new RSADecrypter(rsaPrivateKey); JWEObject jweObject.decrypt(rsaDecrypter); String decryptedResponse = jweObject.getPayload().toString(); ``` I thought that rsa.Decrypt is analog of code above. But as I sow - not. After some research, I found that my response is JWE source. Based on <https://www.rfc-editor.org/rfc/rfc7516> I split my response to parts which was separated by '.' and decode each of them from base64url. As result I have: * Header (which is JSON: {"enc":"A256CBC-HS512", "alg":"RSA1\_5"}) * Encryption key (size 256 bytes) * Initialization Vector (size 16 bytes) * Cipertext (size 1844688 bytes) * Authentication Tag (size 32 bytes) I think the main content is in *Cipertext* and I need to decrypt it. But I don't know how because of the *Cipertext* size is more than 256 bytes and I can't use rsa.Decrypt. How to decrypt source when size of it is more than RSA key?<issue_comment>username_1: I found this library [js-jose](https://github.com/square/js-jose) that can do exactly what I need. I added it as NuGet package, written following code: ``` JWT.Decode(responseContent, // content as String read from Response rsa, // RSACryptoServiceProvider JweAlgorithm.RSA1_5, JweEncryption.A256CBC_HS512); ``` and has decrypted content as result. Upvotes: 2 [selected_answer]<issue_comment>username_2: I have just finished an experimental console app using **.NET6** to get familiar with the concepts of JWT, JWS and JWE. Maybe this could help someone... I wanted to get it working without the use of any third party packages. These are all using statements: ``` using Microsoft.IdentityModel.Tokens; using System.Security.Claims; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; ``` You will need a **TokenValidationParameters** object that configures the validation. For this, you need to have: * a public key to verify the signature * a private key to decrypt the header & payload Both of these are stored locally for demo purposes. ``` // Get public key to verify the signature string publicKeySign = File.ReadAllText(@"C:\Docs\publicKeySign.pem"); var rsaPublicKey = RSA.Create(); rsaPublicKey.ImportFromPem(publicKeySign); // Get private key to decrypt string privateKeyEncrypt = File.ReadAllText(@"C:\Docs\privateKeyEncrypt.key"); rsaPrivateKey = RSA.Create(); rsaPrivateKey.ImportFromPem(privateKeyEncrypt); // Pass those keys into the TokenValidationParameters object var validationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = true, ValidIssuer = "http://mysite.example.com", ValidAudience = "http://myaudience.example.com", IssuerSigningKey = new RsaSecurityKey(rsaPublicKey), TokenDecryptionKey = new RsaSecurityKey(rsaPrivateKey) }; // Pass in the token (as a string) and your tokenValidationParameters JwtSecurityTokenHandler jwtSecurityTokenHandler = new(); TokenValidationResult result = await jwtSecurityTokenHandler.ValidateTokenAsync(token, tokenValidationParameters); ``` The result is a **TokenValidationResult**, [MS Docs here](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.tokenvalidationresult?view=azure-dotnet). It has the following properties: 1. Claims, which is a Dictionary 2. ClaimsIdentity, which in turn has a property: * Claims, which is an IEnumerable This way, you can inspect the claims sent along with the JWE. Hope this helps, have a good one! Upvotes: 2
2018/03/16
831
2,849
<issue_start>username_0: We are using Facebook Graph API v2.9 to run "feed balancing" application: [Like What You Hate](https://likewhatyoubleep.com) The app runs React served from a NodeJs server. The app was running fine a few months ago (Dec. 2017) when we made some updates but we recently discovered that the app had stopped working. Upon investigation I found that when I hit the following endpoints: ``` /me/picture?height=80&width=80 /me/picture /{a-defined-user-id}/picture ``` graph api is returning the following error in the response: ``` { "error": { "code": 1, "error_subcode": 1357046, "message": "Received Invalid JSON reply.", "type": "http" } } ``` Other endpoints, such as: ``` /me /me/likes /me/likes?limit=1000 ``` return a JSON object as expected. I've used the [Graph API Explorer](https://developers.facebook.com/tools/explorer/) to hit the `/me/picture` endpoint and I get what seems to be a valid JSON response. So it seems to be something with the SDK code. We are using the [Javascript SDK](https://developers.facebook.com/docs/javascript) and mounting it in our app thusly: ``` window.fbAsyncInit = function() { window.FB.init({ appId : fbAppId, xfbml : true, version : 'v2.9', cookie : true }); window.FB.AppEvents.logPageView(); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = '//connect.facebook.net/da_DK/sdk.js'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); ``` One thing to note is that we are getting the Danish SDK (`da_DK`) servers, but I have also tried the US version (`en_US`) and saw the same issue. ### Edit: Just found that there is a recent [Bug Report](https://developers.facebook.com/bugs/794347400765683/) open for this issue.<issue_comment>username_1: We ended up just using the current user id from the response of `/me` and putting the endpoint directly into the source of the image component in React: ``` export default class Avatar extends React.Component { static propTypes = { userId }; render () { const { userID } = this.props; return ![]({{) } } ``` Upvotes: 2 <issue_comment>username_2: There is a workaround until facebook solves this bug. You can use ``` /me/?fields=picture ``` This will work with Pages picture as well ``` {page-id}/?fields=picture ``` but sadly doesn't seem to work with userId Upvotes: 2 <issue_comment>username_3: Was just able to resolve this issue by modifying the endpoint URL, per the latest on the bug report. change: `/{USER_ID}/picture` to: `/{USER_ID}/picture?redirect=false` Upvotes: 6 [selected_answer]
2018/03/16
814
2,286
<issue_start>username_0: I am new to Pandas and Python. I will write my question over an example. I have a data such as ``` df = pd.DataFrame([[1, 2], [1, 3], [4, 6], [5,6], [7,8], [9,10], [11,12], [13,14]], columns=['A', 'B']) df A B 0 1 2 1 1 3 2 4 6 3 5 6 4 7 8 5 9 10 6 11 12 7 13 14 ``` I am taking 3 samples from both column. ``` x = df['A'].sample(n=3) x = x.reset_index(drop=True) x 0 7 1 9 2 11 y = df['B'].sample(n=3) y = y.reset_index(drop=True) y 0 6 1 12 2 2 ``` I would like to do this taking sample(n=3) 10 times. I tried `[y] * 10`, it produces columns 10 times out of 6,12,2. I want to do this 10 times from main data.Then I would like to make a new data out of this new columns generated from A and B. I thought maybe I should write for loop but I am not so familiar with them. Thanks for the helps.<issue_comment>username_1: Seems like you need ``` df.apply(lambda x : x.sample(3)).apply(lambda x : sorted(x,key=pd.isnull)).dropna().reset_index(drop=True) Out[353]: A B 0 7.0 2.0 1 11.0 6.0 2 13.0 12.0 ``` Sorry for the misleading , I overlook the 10 times ``` l=[] count = 1 while (count < 11): l.append(df.apply(lambda x : x.sample(3)).apply(lambda x : sorted(x,key=pd.isnull)).dropna().reset_index(drop=True)) count = count + 1 pd.concat(l) ``` Upvotes: 0 <issue_comment>username_2: As WeNYoBen showed, it is good practice to split the task into 1. generating the sample replicates, 2. concatinating the data frames. My suggestion: Write a [generator](https://stackoverflow.com/a/231855/2136626) function that is used to create a generator (instead of a list) of your sample replicates. Then you can concatenate the items (in this case, data frames) that the generator yields. ```python # a generator function def sample_rep(dframe, n=None, replicates=None): for i in range(replicates): yield dframe.sample(n) d = pd.concat(sample_rep(df, n=3, replicates=10), keys=range(1, 11), names=["replicate"]) ``` The generator uses up less memory because it produces everything on the fly. The `pd.concat()` function triggers `sample_rep()` on your dataframe which generates the list of data frames to concatenate. Upvotes: 1
2018/03/16
400
1,405
<issue_start>username_0: i'm filtering my view queryset base on the request query\_params but I don't like how i do it, is there any way to do this most pythonic? ``` def get_queryset(self): qs = Publication.objects if self.request.query_params.get('user'): user = self.request.query_params.get('user') if user.isdigit(): qs = qs.filter(owner__pk=user) limit = self.request.query_params.get('limit') if limit and limit.isdigit(): return qs.all()[:int(limit)] return qs.all() ```<issue_comment>username_1: `.get` takes a second `default` argument so you don't have to check if parameter exists or not. If request data does not contain `user`, it will be `''`. So, this might be better: ``` def get_queryset(self): qs = Publication.objects user = self.request.query_params.get('user', '') limit = self.request.query_params.get('limit', '') if user.isdigit(): qs = qs.filter(owner__pk=user) if limit.isdigit(): return qs.all()[:int(limit)] return qs.all() ``` Upvotes: 1 <issue_comment>username_2: ``` def get_queryset(self): qs = Publication.objects.all() user = self.request.query_params.get('user', None) limit = self.request.query_params.get('limit', None) if user: qs = qs.filter(owner__pk=user) if limit: return qs[:int(limit)] return qs ``` Upvotes: 0
2018/03/16
1,375
4,544
<issue_start>username_0: * *Problem*: I want to show an `v-html` into the *modal* interface, and the content comes from an URL (ajax)... The snipped code is running, but it is bad, not professional: try to run. You click *GO*, take a message saying to *CLOSE* and click *GO* again... I need to "[promisify](https://stackoverflow.com/q/30008114/287948) my code" with Vue's best practices. **Question**: how to do this interface better, all with Vuetify? I need one-click (*GO*) interface, and with mininal waiting time for user. (need also to load other URLs, so using AJAX many times as other buttons, etc.) I am supposing that Vuetify have good approaches to AJAX-load (as [these](https://vuejsdevelopers.com/2017/08/28/vue-js-ajax-recipes/)), so I need to use the best one! for this situation. PS: I not see how to implement the Vue-AJAX strategies in a single HTML page (not a big Node.js system). A simplified ugly-interface example ----------------------------------- It is running, but is mixing non-VueJS code and have all the explained problems, to be fixed by the answer. ```js var URL = 'https://codepen.io/chriscoyier/pen/difoC.html'; var loadFromUrl_cache = '... PLEASE WAYTE 10 seconds ...'+ ' close and back here.'; function loadFromUrl(URL,tmpStore) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE) { if (xmlhttp.status == 200) { loadFromUrl_cache = xmlhttp.responseText; } else { alert('ERROR, something else other than status 200:'+ xmlhttp.status); } } }; xmlhttp.open("GET", URL, true); // async xmlhttp.send(); } // to get rid of "missing v-app" error message var app = document.createElement('div'); app.setAttribute('data-app', true); document.body.appendChild(app); let mainVue = new Vue({ el: '#main' }); new Vue({ el: '#appDlg', data() { return { dialog: false, ct_header: 'the header1 here', ct_body: 'the body1 here' } }, mounted() { mainVue.$on('go-modal', this.handleMain); }, methods: { handleMain(data) { this.ct_header = data.title; loadFromUrl(URL,'tmp-store'); this.ct_body = loadFromUrl_cache; this.dialog = true; } } }); ``` ```css .myDialog { padding: 10px; height: 100%; background-color: white; } .myDialog .btn { margin: 20px 0 0 -4px; } ``` ```html Go Close #### {{ ct\_header }} Close ``` --- PS: thanks to the [code at this answer](https://stackoverflow.com/a/49309307/287948). If you prefer you can use [codepen/NYRGyv](https://codepen.io/ppKrauss/pen/NYRGyv).<issue_comment>username_1: > > I am supposing that Vuetify have good approaches to AJAX-load (as these), so I need to use the best one! for this situation. > > > You can try [axios](https://github.com/axios/axios) then you can change for example `ct_body` html like so: ``` handleMain(data) { var URL = "your HTML url here"; axios.get(URL) .then(response => { this.ct_body = response.data; }) } ``` Currently your problem is that you are trying to change html before you even fetch the data. You should set it after you retrieve it with ajax call. Note that fetching HTML from url is not instant (tho it should be relatively fast), so depends on your case where you want to put loading indicator. Thus it's up to you where you want to set `this.dialog = true` - inside `.then()` will make it open only when you retrieve html data. [Codepen](https://codepen.io/anon/pen/xWRmQG) Upvotes: 3 [selected_answer]<issue_comment>username_2: Pure Javascript (ECMAScript 2015) --------------------------------- We can use `fetch()` and its embedded [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then)! See [developer.mozilla.org/Fetch\_API/Using\_Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). ``` handleMain(data) { var self = this; self.ct_header = data.title; fetch(URL) .then(function(res) { return res.text(); }) .then(function(data) { self.ct_body = data; self.dialog = true; }); } ``` ... Is equivalent to Axios, but, as **it seems exactly the same**, the solution **is better** because avoid to lost of CPU-time, internet-bandwidth and memory (13kb) loading *Axios*. See <https://codepen.io/ppKrauss/pen/oqYOrY> Upvotes: 1
2018/03/16
695
2,499
<issue_start>username_0: SQL queries are not one of my strong suits, and I have run into a problem that I was able to solve but am hoping to improve and make more efficient. I am using Laravel's Query Builder in these examples but don't mind using a raw request if I have to. Currently I am making two queries as follows and merging them after. ``` $acc_id = 10; $locat_id= 3; //First get all sites with account id $allSites = collect(DB::table('sites')->where('acc_id', $acc_id)->get()): //Next get only sites with account id and connections with current location id $connectedSites = collect( DB::table('sites') ->select('sites.id','name','active','url') ->join('connections as conn','sites.id','=','conn.site_id') ->where('acc_id',$acc_id) ->where('conn.locat_id',$locat_id) ->get() ); //Merge the collections and drop first row with duplicate site_id $sites = $allSites->merge($connectedSites)->keyBy('id'); return $sites; ``` So this gives me the desired results. E.g. all the sites that are associated with the account id, and also the connection data for sites associated with both the account and location ids. **However, I would like to learn how to do this in one query if possible.**<issue_comment>username_1: This can be done with one query, but I use eloquent instead of the query builder. Check out the with() method, it allows you to eager load the relationship. ``` $sites = Sites::with('connections')->where('acc_id', $acc_id)->get(); ``` Now you can access the connections data from the model instance without needing to do anymore queries. ``` foreach($sites as $site){ $site->connection->stuff; // No query generated } ``` if you need to separate the two that's easy as well. ``` $connectedSites = $sites->where('connection.locat_id', $locat_id) // No query generated from the above, but now $connectedSites has all of // the connected sites ``` When you get into laravel's collections, you find out that a LOT of queries can be replaced by using them. <https://laravel.com/docs/5.6/collections#available-methods> Upvotes: 0 <issue_comment>username_2: Try a LEFT JOIN: ``` $sites = DB::table('sites') ->select('sites.*','name','active','url') ->leftJoin('connections as conn', function($query) use($locat_id) { $query->on('sites.id', '=', 'conn.site_id') ->where('conn.locat_id', $locat_id); }) ->where('acc_id',$acc_id) ->get(); ``` Upvotes: 3 [selected_answer]
2018/03/16
1,266
3,906
<issue_start>username_0: I have a `Vec` of nontrivial types with a size I am certain of. I need to convert this into fixed size array. Ideally I would like to do this 1. without copying the data over - I would like to consume the `Vec` 2. without preinitializing the array with zero data because that would be a waste of CPU cycles Question written as code: ``` struct Point { x: i32, y: i32, } fn main() { let points = vec![ Point { x: 1, y: 2 }, Point { x: 3, y: 4 }, Point { x: 5, y: 6 }, ]; // I would like this to be an array of points let array: [Point; 3] = ???; } ``` This seems like a trivial issue, however I have not been able to find satisfactory solution in `Vec` docs, slicing sections of Rust Books or by Googling. Only thing that I found is to first initialize the array with zero data and later copy all elements over from `Vec`, however this does not satisfy my requirements.<issue_comment>username_1: Doing this correctly is exceedingly difficult. The problem lies in properly handling a panic when there's a partially uninitialized array. If the type inside the array implements `Drop`, then it would access uninitialized memory, causing undefined behavior. The easiest, safest way is to use [arrayvec](https://crates.io/crates/arrayvec): ``` extern crate arrayvec; use arrayvec::ArrayVec; #[derive(Debug)] struct Point { x: i32, y: i32, } fn main() { let points = vec![ Point { x: 1, y: 2 }, Point { x: 3, y: 4 }, Point { x: 5, y: 6 }, ]; let array: ArrayVec<_> = points.into_iter().collect(); let array: [Point; 3] = array.into_inner().unwrap(); println!("{:?}", array); } ``` Beware this only works for [specific sizes of arrays](https://docs.rs/arrayvec/0.4.7/arrayvec/trait.Array.html) because Rust does not yet have generic integers. [`into_inner`](https://docs.rs/arrayvec/0.4.7/arrayvec/struct.ArrayVec.html#method.into_inner) also has a performance warning you should pay attention to. See also: * [What is the proper way to initialize a fixed length array?](https://stackoverflow.com/q/31360993/155423) (especially [this answer](https://stackoverflow.com/a/41592218/155423)) * [Convert vectors to arrays and back](https://stackoverflow.com/q/29784502/155423), which inadvertently wrote code that worked without copies, but does not explicitly claim it was on purpose * [How to get a slice as an array in Rust?](https://stackoverflow.com/q/25428920/155423) * [Is there a good way to convert a Vec to an array?](https://stackoverflow.com/q/29570607/155423) * [Slice to fixed-size array](https://stackoverflow.com/q/37668886/155423) Upvotes: 4 [selected_answer]<issue_comment>username_2: Just for fun, here are examples that shows that safe Rust gives us ways of doing it for small specific sizes, for example like this: ``` /// Return the array inside Some(_), or None if there were too few elements pub fn take_array3(v: &mut Vec) -> Option<[T; 3]> { let mut iter = v.drain(..); if let (Some(x), Some(y), Some(z)) = (iter.next(), iter.next(), iter.next()) { return Some([x, y, z]); } None } /// Convert a Vec of length 3 to an array. /// /// Panics if the Vec is not of the exact required length pub fn into\_array3(mut v: Vec) -> [T; 3] { assert\_eq!(v.len(), 3); let z = v.remove(2); let y = v.remove(1); let x = v.remove(0); [x, y, z] } ``` The basic ways of having a `Vec` give you back ownership of its elements are `remove`, `pop`, `drain`, `into_iter`, etc. Upvotes: 1 <issue_comment>username_3: There is also `try_into`? ```rust use std::convert::TryInto; #[derive(Debug)] struct Point { x: i32, y: i32, } fn main() { let v: Vec = vec![Point { x: 1, y: 1 }, Point { x: 2, y: 2 }]; let a: &[Point; 2] = v[..].try\_into().unwrap(); println!("{:?}", a); } ``` It borrows immutably so the Vec is not consumed. Upvotes: 2
2018/03/16
997
3,415
<issue_start>username_0: I'm trying to generate `kotlin` code from a swagger json file, and I can't figure out the command-line parameters that should be used. I've tried Swagger codegen `v2.3.1` and `v2.2.3` and both fail for `kotlin`, `kotlin-client`, and `kotlin-server` with the same error. What's the correct switch to generate Kotlin? Update from Helen's question: I installed swagger codegen with: ``` git clone <EMAIL>:swagger-api/swagger-codegen.git ./swagger-codegen cd swagger-codegen git checkout tags/v2.2.3 ``` I also tested with Swagger codegen's `bin/kotlin-client-petstore.sh` and `kotlin` was not recognized for that script. (I've also tried the [Swagger Codegen plugin for IntelliJ](https://github.com/jimschubert/intellij-swagger-codegen/ "Swagger Codegen plugin for IntelliJ") because it does list `kotlin` as an output target, but it does not correctly process the swagger json.) Here's the command-line pattern I'm using, which works for `typescript-node`: ``` java -jar ./swagger-codegen/modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -i sample.json -l typescript-node -o typescript_node_sdk ``` However, it fails for `kotlin`, `kotlin-client`, `kotlin-server`: ```none $ java -jar ./swagger-codegen/modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -i sample.json -l kotlin -o kotlin_sdk Exception in thread "main" java.lang.RuntimeException: Can't load config class with name kotlin Available: android aspnet5 async-scala csharp dart flash python-flask go java jaxrs jaxrs-cxf jaxrs-resteasy inflector javascript javascript-closure-angular jmeter nodejs-server objc perl php python qt5cpp ruby scala scalatra silex-PHP sinatra slim spring-mvc dynamic-html html swagger swagger-yaml swift tizen typescript-angular typescript-node akka-scala CsharpDotNet2 clojure haskell-servant at io.swagger.codegen.CodegenConfigLoader.forName(CodegenConfigLoader.java:31) at io.swagger.codegen.config.CodegenConfigurator.toClientOptInput(CodegenConfigurator.java:346) at io.swagger.codegen.cmd.Generate.run(Generate.java:221) at io.swagger.codegen.SwaggerCodegen.main(SwaggerCodegen.java:36) Caused by: java.lang.ClassNotFoundException: kotlin at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) at io.swagger.codegen.CodegenConfigLoader.forName(CodegenConfigLoader.java:29) ... 3 more ```<issue_comment>username_1: Thanks to Helen's question, I looked at [Swagger Codegen Building](https://github.com/swagger-api/swagger-codegen#building "Swagger Codegen Building") and ``` mvn clean package ``` made `kotlin` appear as a recognized switch. Upvotes: 4 [selected_answer]<issue_comment>username_2: You can also use [openapi generator](https://github.com/OpenAPITools/openapi-generator) to generate the code in kotlin using: ``` openapi-generator generate -i petstore.yml -g kotlin --config api-config.json ``` openapi generator is a fork of the swagger codegen and offers the same kind of functionalities. Find the kotlin generators specs in [the documentation](https://github.com/OpenAPITools/openapi-generator/blob/master/docs/generators/kotlin.md). Upvotes: 1