date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/22
414
1,167
<issue_start>username_0: I want ABCD on the left and DATE should be in the center. How to achieve this? ```css .flex-items { display: flex; justify-content: flex-start; padding-left: 17px; } .abcd1 {} .date1 { /*this item should be in the center.*/ } ``` ```html ABCD DATE ```<issue_comment>username_1: Try this code ```css .flex-items { display: flex; justify-content: flex-start; padding-left: 17px; } .abcd1 { } .date1 { margin-left: auto; margin-right: auto; } ``` ```html ABCD DATE ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: See below. Hope this helps. ```css .flex-items { display: flex; padding-left: 17px; text-align: center; } .date1 { flex: 1; } ``` ```html ABCD DATE ``` Upvotes: 0 <issue_comment>username_3: Text-align: center works when there is a width provided. This also works: ```css .flex-items { display: flex; justify-content: flex-start; padding-left: 17px; } .abcd1 { } .date1 { /*this item should be in the center.*/ text-align: center; width: 100%; } ``` ```html ABCD DATE ``` Upvotes: 0
2018/03/22
495
1,772
<issue_start>username_0: > > I'm not using sqlite3 gem > > I'm using mysql2 gem > > > I'm retrieving data from MySQL database given that it meets the condition of a certain `event type` and `severity`. However, it returns only one row instead of an array of results. It really puzzles me. Shouldnt .map return an array? ``` result = connect.query("SELECT * FROM data WHERE event_type = 'ALARM_OPENED' AND severity = '2'") equipments = result.map do |record| [ record['sourcetime'].strftime('%H:%M:%S'), record['equipment_id'], record['description'] ] end p equipments ```<issue_comment>username_1: You must need to change your sql statement : ``` result = connect.query("SELECT * FROM data WHERE event_type = 'ALARM_OPENED' AND severity = '2'", :as => :array) ``` Upvotes: 0 <issue_comment>username_2: I had misread your question...I think what you are looking for is in [here](https://stackoverflow.com/questions/41919299/return-values-of-execute-and-query-methods-of-sqlite3-gem). **UPDATE** You can use each instead, like this: ``` #!/usr/bin/env ruby require 'mysql2' connect= Mysql2::Client.new(:host => '', :username => '', :password => '', :database => '') equipments = [] result = connect.query("SELECT * FROM data WHERE event_type = 'ALARM_OPENED' AND severity = '2'", :symbolize_keys => true).each do |row| equipments << [ row[:sourcetime].strftime('%H:%M:%S'), row[:equipment_id], row[:description] ] end puts "#equipments {equipments}" ``` EDITED: I forgot to add .each at the end of the query. So it was returning the initialized empty array instead. Upvotes: 2 [selected_answer]
2018/03/22
1,001
3,554
<issue_start>username_0: I ama noob in to flutter and is now experimenting with flutter. I was trying to implement a splashscreen. My requirements: * The flash screen should appear 3 seconds at the time of app launch. * It should disappear after 3 seconds. * It should show a progress bar at the time of displaying and complete within 3 seconds.<issue_comment>username_1: Try this You can Use [**`Future.delayed()`**](https://www.dartdocs.org/documentation/flutter/0.0.33-dev/dart-async/Future/Future.delayed.html) Constructor ``` Future.delayed(Duration duration, [ dynamic computation() ]) ``` > > Creates a future that runs its computation after a delay. > > > The computation will be executed after the given duration has passed, and the future is completed with the result of the computation, > > > If the duration is 0 or less, it completes no sooner than in the next event-loop iteration, after all microtasks have run. > > > **SAMPLE CODE** ``` new Future.delayed(const Duration(seconds: 3), () { // You action here }); ``` **SAMPLE CODE** ``` import 'dart:async'; import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: SplashScreen(), )); // runApp(HomePage()); } class SplashScreen extends StatefulWidget { @override _SplashScreenState createState() => new _SplashScreenState(); } class _SplashScreenState extends State { startTime() async { var \_duration = new Duration(seconds: 2); return new Timer(\_duration, navigationPage); } void navigationPage() { Navigator.of(context).pushReplacementNamed('/Registration'); } @override void initState() { super.initState(); startTime(); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: FlutterLogo( size: 100.0, ), ), ); } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` return new SplashScreen( seconds: 4, navigateAfterSeconds: new HomeScreen(), title: new Text( 'WELCOME TO <NAME>', style: new TextStyle( fontWeight: FontWeight.bold, fontSize: 20.0, fontFamily: 'Chunkfive'), ), image: Image.asset("images/splashlogo.png"), backgroundColor: Colors.lightBlueAccent, styleTextUnderTheLoader: new TextStyle(fontFamily: 'Chunkfive'), photoSize: 100.0, loaderColor: Colors.black, ); ``` Upvotes: 2 <issue_comment>username_3: Check the complete code here ``` import 'package:flutter/material.dart'; import 'package:splashscreen/splashscreen.dart'; void main() { runApp(MaterialApp( debugShowCheckedModeBanner: false, home: MyApp(), )); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State { @override Widget build(BuildContext context) { return SplashScreen( seconds: 14, navigateAfterSeconds: new AfterSplash(), image: new Image.asset('assets/logo.png'), backgroundColor: Colors.white, photoSize: 100.0, ); } } class AfterSplash extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Welcome In SplashScreen Package"), automaticallyImplyLeading: false), body: Center( child: Text( "Done!", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 30.0), ), ), ); } } ``` Don't forget to add the dependency ``` dependencies: flutter: sdk: flutter splashscreen: ``` Upvotes: 0
2018/03/22
1,144
4,194
<issue_start>username_0: I need to return form the text template key value which will be like comment and command like following ``` #Description for npm install npm install #Description for test npm test #Description for test2 run test2 ``` For that I've created a function like the following: ``` // example with switch func (d Dependency) TypeCommand() Command { switch d.Type { case "runner": cmd1 := Command{"#Description for npm install", "npm install"} cmd2 := Command{"#Description for test", "npm test"} cmd3 := Command{"#Description for test2", "run test2"} case "runner2": return "test 2" } return "command_baz" } ``` The template is: ``` const tmpl = ` {{- range .File.Dependency}} {{.TypeCommand}} {{end}}` type Command struct { Info string Command string } ``` When I change the template to the following, I get an error: ``` const tmpl = ` {{- range .File.Dependency}} {{ TypeCommand .}} {{ range .Command}} {{ .Info }} {{ .Command }} {{end}} {{end}} ' ``` `executing "tmpl3.txt" at <.Command>: can't evaluate field Command in type *Dependency` I use [this](https://play.golang.org/p/VAmh_WvBX54) as reference.<issue_comment>username_1: The error message you're getting is because you're just throwing away the return value of `TypeCommand` instead of passing it on to where you try to access its struct fields. We could fix that, but that's probably not what you wanted to do anyways, since your `TypeCommand` function looks like it should probably be returning multiple commands instead of a single one. So let's re-write that first: ``` func (d Dependency) TypeCommand() []Command { switch d.Type { case "runner": return []Command{ Command{"#Description for npm install", "npm install"}, Command{"#Description for test", "npm test"}, Command{"#Description for test2", "run test2"}, } case "runner2": return []Command{Command{"#test 2", "foo"}} } return []Command{Command{"#command_baz", "baz"}} } ``` Now that we're returning multiple commands, we can just range over them in the template and they'll be automatically bound. I tweaked your template a little bit to the following: ``` const tmpl = ` {{- range .File.Dependency}} {{- range .TypeCommand }} {{ .Info}} {{ .Command}} {{- end}}{{end}}` ``` When I ran this in the Go Playground, this got me the following output, which seemed to be what you were going for: ``` #Description for npm install npm install #Description for test npm test #Description for test2 run test2 #test 2 foo ``` Upvotes: 2 <issue_comment>username_2: ``` package main import ( "os" "text/template" ) type File struct { TypeVersion string `yaml:"_type-version"` Dependency []Dependency } type Dependency struct { Name string Type string CWD string } type Command struct { Info string Command string } func (d Dependency) TypeCommand() []Command { switch d.Type { case "runner": return []Command{ {"#Description for npm install", "npm install"}, {"#Description for test", "npm test"}, {"#Description for test2", "run test2"}, } case "runner2": return []Command{{"#test 2", "foo"}} } return []Command{{"#command_baz", "baz"}} } type Install map[string]string const tmpl = ` {{- range .File.Dependency}} {{- range .TypeCommand }} {{ .Info}} {{ .Command}} {{- end}}{{end}}` type API map[string]string func main() { f := new(File) f.Dependency = []Dependency{{ Name: "ui", Type: "runner", CWD: "/ui", }, { Name: "ui2", Type: "runner2", CWD: "/ui2", }} t, err := template.New("t").Parse(tmpl) if err != nil { panic(err) } var data struct { File *File API API } data.File = f if err := t.Execute(os.Stdout, data); err != nil { panic(err) } } ``` This Should Work Properly. The main problem was with the return type of the method of Dependency Upvotes: -1
2018/03/22
1,080
4,172
<issue_start>username_0: I have taken the full snapshot from a node. I have copied the snapshot directory and placed in the `/var/lib/cassandra/data/Keyspace/Tables/` directory in the restoration node. I have tried both restarting the service and also tried using `nodetool refresh` command for restoring the data in new node. It worked like a charm. I am unable to list the number of records for tables with high number of records. I am facing **`Connection timed out`** error for tables with higher records. So I am unable to validate that the total data from the table has been successfully restored. Also I tried check the size occupied by the keyspace using `nodetool cfstats -H` and `nodetool tablestats -H` and "Space used" parameter seems to be exactly matching. I use below command for listing the total count of the specific tables. ``` select count(*) from milestone LIMIT 100000; ``` **My Question:** What if few of the records went missing during restoration? What if the count from the backup and restored data has mismatched and I have no way of knowing it. Could you please suggest the way to validate that the restoration is successful? How will I ensure the total number of records have successfully copied?<issue_comment>username_1: The error message you're getting is because you're just throwing away the return value of `TypeCommand` instead of passing it on to where you try to access its struct fields. We could fix that, but that's probably not what you wanted to do anyways, since your `TypeCommand` function looks like it should probably be returning multiple commands instead of a single one. So let's re-write that first: ``` func (d Dependency) TypeCommand() []Command { switch d.Type { case "runner": return []Command{ Command{"#Description for npm install", "npm install"}, Command{"#Description for test", "npm test"}, Command{"#Description for test2", "run test2"}, } case "runner2": return []Command{Command{"#test 2", "foo"}} } return []Command{Command{"#command_baz", "baz"}} } ``` Now that we're returning multiple commands, we can just range over them in the template and they'll be automatically bound. I tweaked your template a little bit to the following: ``` const tmpl = ` {{- range .File.Dependency}} {{- range .TypeCommand }} {{ .Info}} {{ .Command}} {{- end}}{{end}}` ``` When I ran this in the Go Playground, this got me the following output, which seemed to be what you were going for: ``` #Description for npm install npm install #Description for test npm test #Description for test2 run test2 #test 2 foo ``` Upvotes: 2 <issue_comment>username_2: ``` package main import ( "os" "text/template" ) type File struct { TypeVersion string `yaml:"_type-version"` Dependency []Dependency } type Dependency struct { Name string Type string CWD string } type Command struct { Info string Command string } func (d Dependency) TypeCommand() []Command { switch d.Type { case "runner": return []Command{ {"#Description for npm install", "npm install"}, {"#Description for test", "npm test"}, {"#Description for test2", "run test2"}, } case "runner2": return []Command{{"#test 2", "foo"}} } return []Command{{"#command_baz", "baz"}} } type Install map[string]string const tmpl = ` {{- range .File.Dependency}} {{- range .TypeCommand }} {{ .Info}} {{ .Command}} {{- end}}{{end}}` type API map[string]string func main() { f := new(File) f.Dependency = []Dependency{{ Name: "ui", Type: "runner", CWD: "/ui", }, { Name: "ui2", Type: "runner2", CWD: "/ui2", }} t, err := template.New("t").Parse(tmpl) if err != nil { panic(err) } var data struct { File *File API API } data.File = f if err := t.Execute(os.Stdout, data); err != nil { panic(err) } } ``` This Should Work Properly. The main problem was with the return type of the method of Dependency Upvotes: -1
2018/03/22
1,007
3,865
<issue_start>username_0: I am using mat-auto complete component from material.angular.io. The default behavior is user can input any value as well as it gives options to choose from. Also you can add your input to chosen values. You can check example here. <https://stackblitz.com/angular/ngmvgralayd?file=app%2Fautocomplete-simple-> example.html here is the code I am using for generating auto complete input field. ``` {{ option }} ``` But I want the form field to take only values from the given option and want to prevent from entering any values by users apart from given option. How to achieve this? It is like select input with auto complete feature.<issue_comment>username_1: As already suggested in comment by @trichetriche this is a use case for select. You can use material version of select, like this ``` {{ food.viewValue }} ``` If you need filter above the select, than I suggest to you PrimeNg Dropdown <https://www.primefaces.org/primeng/#/dropdown> Upvotes: 0 <issue_comment>username_2: > > You can do something like this > > > **Markup:** ``` {{ option.name }} ``` **Component:** ``` selectedOption; changeMyControl(): void { if (isUndefined(this.selectedOption) { // also check selected item and entered text are not same this.myForm.get('myControl').setErrors({'incorrect': true}); } } onSelectedOption(isSelected: boolean, id: number): void { if (isSelected) { setTimeout(() => { const option = this.options.filter(bt => bt.id === id); if (option.length > 0) { this.selectedOption= option[0]; // patch formcontrol value here } }, 200); } } ``` Upvotes: 3 <issue_comment>username_3: The [Material demo for chips autocomplete](https://stackblitz.com/angular/gjjmadpndjoa?file=app%2Fchips-autocomplete-example.ts) shows bindings on both the `input` and to the `mat-autocomplete`: ``` ``` If you only want to allow options from the autocomplete, just omit the `add` function from the input. Upvotes: 1 <issue_comment>username_4: I think there is a UI/UX question here - in what way do we prevent the user from typing something that is not in the list of options, but still allow them to filter by a string? I see a couple of potential options. First one is to just display an error "Invalid entry" when the option isn't in the list adjacent to the input. The second option would be to actually prevent the entry of characters that no longer match any options. So if there is a single option "foo" and a user types "for", only "fo" would be accepted, and the 'r' gets thrown out. The [PrimeNg](https://www.primefaces.org/primeng/#/dropdown) solution is not quite the same as a text field that allows a user to start typing on focus. The user needs to first click to open a search, and there appears to be no keyboard accessibility. I don't really see why they haven't implemented it such that display and the search are the same, except they've got logos displayed. Upvotes: 1 <issue_comment>username_5: Found this solution on [github](https://github.com/angular/components/issues/3334) it may provide a simple alternative to those who end up here. Create a custom validator: ``` private requireMatch(control: FormControl): ValidationErrors | null { const selection: any = control.value; if (this.options && this.options.indexOf(selection) < 0) { return { requireMatch: true }; } return null; } ``` Attach it to your control (we need to bind it to this so that our validator can access our options in our component's scope) ``` myControl = new FormControl(undefined, [Validators.required, this.requireMatch.bind(this)]); ``` Optionally show error: ``` Value need match available options ``` Example here -----------> <https://stackblitz.com/edit/angular-hph5yz> Upvotes: 4
2018/03/22
991
3,704
<issue_start>username_0: Is it possible to load UI (Static content) of an embedded jar? Example I have a fat jar `main.jar` which runs(UI as well) on `localhost:8080` . Within `main.jar` I have another jar `b.jar` embedded. `b.jar's` static content is an Angular JS application, which I want to load while launching `main.jar`. Like there can be a button in nav bar of `main.jar` UI which would navigate to `b.jar` UI. Is it possible to do it? I don't want to have static files of `b.jar` in main project.<issue_comment>username_1: As already suggested in comment by @trichetriche this is a use case for select. You can use material version of select, like this ``` {{ food.viewValue }} ``` If you need filter above the select, than I suggest to you PrimeNg Dropdown <https://www.primefaces.org/primeng/#/dropdown> Upvotes: 0 <issue_comment>username_2: > > You can do something like this > > > **Markup:** ``` {{ option.name }} ``` **Component:** ``` selectedOption; changeMyControl(): void { if (isUndefined(this.selectedOption) { // also check selected item and entered text are not same this.myForm.get('myControl').setErrors({'incorrect': true}); } } onSelectedOption(isSelected: boolean, id: number): void { if (isSelected) { setTimeout(() => { const option = this.options.filter(bt => bt.id === id); if (option.length > 0) { this.selectedOption= option[0]; // patch formcontrol value here } }, 200); } } ``` Upvotes: 3 <issue_comment>username_3: The [Material demo for chips autocomplete](https://stackblitz.com/angular/gjjmadpndjoa?file=app%2Fchips-autocomplete-example.ts) shows bindings on both the `input` and to the `mat-autocomplete`: ``` ``` If you only want to allow options from the autocomplete, just omit the `add` function from the input. Upvotes: 1 <issue_comment>username_4: I think there is a UI/UX question here - in what way do we prevent the user from typing something that is not in the list of options, but still allow them to filter by a string? I see a couple of potential options. First one is to just display an error "Invalid entry" when the option isn't in the list adjacent to the input. The second option would be to actually prevent the entry of characters that no longer match any options. So if there is a single option "foo" and a user types "for", only "fo" would be accepted, and the 'r' gets thrown out. The [PrimeNg](https://www.primefaces.org/primeng/#/dropdown) solution is not quite the same as a text field that allows a user to start typing on focus. The user needs to first click to open a search, and there appears to be no keyboard accessibility. I don't really see why they haven't implemented it such that display and the search are the same, except they've got logos displayed. Upvotes: 1 <issue_comment>username_5: Found this solution on [github](https://github.com/angular/components/issues/3334) it may provide a simple alternative to those who end up here. Create a custom validator: ``` private requireMatch(control: FormControl): ValidationErrors | null { const selection: any = control.value; if (this.options && this.options.indexOf(selection) < 0) { return { requireMatch: true }; } return null; } ``` Attach it to your control (we need to bind it to this so that our validator can access our options in our component's scope) ``` myControl = new FormControl(undefined, [Validators.required, this.requireMatch.bind(this)]); ``` Optionally show error: ``` Value need match available options ``` Example here -----------> <https://stackblitz.com/edit/angular-hph5yz> Upvotes: 4
2018/03/22
614
1,939
<issue_start>username_0: For tuples we can use the star unpacking to throw everything we don't need into a `_` or similar, e.g. like so ``` some_tuple = ("obj1", "obj2", "obj3", "obj4") obj1, *_ = some_tuple print(obj1) ``` So now I don't need to worry about the number of elements. I only want the N first. If I made a string out of these, I could similarly do ``` some_text = "{} + {} + {} + {}".format(*some_tuple) ``` But now I realize that if I only wanted to write some expression ``` some_text = "{} + {}".format(*some_tuple) ``` I would have to go in and manually sort out the tuple to match the number of brackets. In this toy example this is of course not a problem, but if you want to output the results of some calculations with many variables on top of a graph, it quickly gets very cumbersome to unpack a tuple of lots of numbers. What I'm looking for is, I don't know... a "silent" bracket for string formatting? E.g. ``` some_text = "{} {*silent*} {*silent*} + {}".format(*some_tuple_with_4_elements) ```<issue_comment>username_1: Would this be okay with you: ``` some_tuple = ("obj1", "obj2", "obj3", "obj4") indices = (0,3) some_text = "{} + {}".format(*(x for i, x in enumerate(some_tuple) if i in indices)) ``` Upvotes: 2 <issue_comment>username_2: Similar to other answers/comments: ``` some_text = "{} + {}".format(some_tuple[0], some_tuple[3]) ``` Upvotes: 0 <issue_comment>username_3: Borrowing the inputs from [zipa](https://stackoverflow.com/a/49425861/6260170), you could use `operator.itemgetter()`: ``` >>> from operator import itemgetter >>> some_tuple = ("obj1", "obj2", "obj3", "obj4") >>> indices = (0,3) >>> "{} + {}".format(*itemgetter(*indices)(some_tuple)) 'obj1 + obj4' ``` Upvotes: 1 <issue_comment>username_4: What i understand from your question. This is solution. ``` for t in some_tuple: print("{} ".format(t)) ``` This will display all the objects in tuple. Upvotes: 0
2018/03/22
775
2,337
<issue_start>username_0: Having this input: ``` myArray = [ {name: "name1", id: 1, parameters: ["first", "second"]}, {name: "name2", id: 2, parameters: ["first"]}, {name: "name3", id: 3, parameters: ["first", "second"]}, ]; ``` I want to put it on a table to look similar to this: [![enter image description here](https://i.stack.imgur.com/y3EjV.png)](https://i.stack.imgur.com/y3EjV.png) I tried to do it, the first two columns are correct but the last one doesn't appear: ``` | {{$ctrl.name[$index]}} | {{$ctrl.id[$index]}} | {{$ctrl.parameters[$index][$secondIndex]}} | ``` The error message is > > Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use > 'track by' expression to specify unique keys. > > > So probably two ng-repeats aren't the solution but it don't know how to do this. Any ideas?<issue_comment>username_1: The solution suggested by [<NAME>](https://stackoverflow.com/users/8495123/aleksey-solovey) solved the problem: ``` | {{$ctrl.name[$index]}} | {{$ctrl.id[$index]}} | {{$ctrl.parameters[$parent.$index][$index]}} | ``` Upvotes: 0 <issue_comment>username_2: Well, you should use `ng-repeat` on `myArray` and then show whatever you want. And to show the `parameters` in the desired format you can use `row.parameters.toString().replace(',', ' ')` Please check the working snipppet Thanks ```js var app = angular.module('myApp', []); app.controller('ctrl', function($scope){ $scope.myArray = [ {name: "name1", id: 1, parameters: ["first", "second"]}, {name: "name2", id: 2, parameters: ["first"]}, {name: "name3", id: 3, parameters: ["first", "second"]}, ]; }) ``` ```css table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } ``` ```html | Name | Id | Parameters | | --- | --- | --- | | {{row.name}} | {{row.id}} | {{ row.parameters.join(' ') }} | ``` Upvotes: 1 <issue_comment>username_3: This should also work: ``` | {{item.name}} | {{item.id}} | {{subItem}} | ``` Upvotes: 1 <issue_comment>username_4: Use this ``` | {{ rows.name }} | {{ rows.id }} | {{ data+ " " }} | ``` Upvotes: 0
2018/03/22
541
1,765
<issue_start>username_0: I have metrics sas table like below ``` work.met_table Metrics_Id Metrics_desc 1 Count_Column 2 Sum_Column 3 Eliminate_column ``` I wanna do something like doing while loop in T-sql ``` select count(*) :cnt_tbl from work.met_table %let init_cnt = 1 while (&init_cnt = &cnt_tbl) begin select Metrics_desc into :met_nm from work.met_table where metrics_id = 1 Insert into some_sas_table Select * from another table where Metrics_desc =&met_nm /* Here I wanna loop all values in metrics table one by one */ end %put &init_cnt = ∫_cnt+1; ``` How this can be done in proc sql? Thanks in advance<issue_comment>username_1: If you want to dynamically generate code then use the SAS macro language. But for your example there is no need to dynamically generate code. ``` proc sql ; insert into some_sas_table select * from another_table where Metrics_desc in (select Metrics_desc from work.met_table) ; quit; ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can also do an explicit pass through. Send your native t-sql code to run on the database Server through SAS rather than bringing the data to the SAS application server to query it. The example below is explained in details [here](https://www.mwsug.org/proceedings/2014/SA/MWSUG-2014-SA03.pdf). ``` PROC SQL; CONNECT TO ODBC(DATASRC=SQLdb USER=&SYSUSERID) ; /* Explicit PASSTHRU with SELECT */ SELECT * FROM CONNECTION TO ODBC ( SELECT b.idnum o.[SSdatecol] AS mydate FROM dbo.big_SS_table1 b LEFT JOIN dbo.other_SStable o ON b.idnum = o.memberid WHERE o.otherdatecol >= '2014-10-06' --This is a T-SQL comment that works inside SQL Server ) ; ; DISCONNECT FROM ODBC ; QUIT; ``` Upvotes: 0
2018/03/22
421
1,493
<issue_start>username_0: I have an IAM SSL certificate attached to an ELB. It is about to expire in a day or two. I know I can create a new certificate and upload it to use this but this will affect my clients who are already using my application.They would be requiring to install the new certificate which they aren't ready to do. Is there any way where i can renew this IAM certificate without replacing it.<issue_comment>username_1: If you want to dynamically generate code then use the SAS macro language. But for your example there is no need to dynamically generate code. ``` proc sql ; insert into some_sas_table select * from another_table where Metrics_desc in (select Metrics_desc from work.met_table) ; quit; ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can also do an explicit pass through. Send your native t-sql code to run on the database Server through SAS rather than bringing the data to the SAS application server to query it. The example below is explained in details [here](https://www.mwsug.org/proceedings/2014/SA/MWSUG-2014-SA03.pdf). ``` PROC SQL; CONNECT TO ODBC(DATASRC=SQLdb USER=&SYSUSERID) ; /* Explicit PASSTHRU with SELECT */ SELECT * FROM CONNECTION TO ODBC ( SELECT b.idnum o.[SSdatecol] AS mydate FROM dbo.big_SS_table1 b LEFT JOIN dbo.other_SStable o ON b.idnum = o.memberid WHERE o.otherdatecol >= '2014-10-06' --This is a T-SQL comment that works inside SQL Server ) ; ; DISCONNECT FROM ODBC ; QUIT; ``` Upvotes: 0
2018/03/22
597
1,808
<issue_start>username_0: I have a question as i write on title. I'll explain it with examples. There is a txt file which is looks like, > > This offense was closed with reason: Non-Issue. Notes: There is no > suspicious situation. u0t9231 21 Mar 2018 10:38:46 > > > This offense was closed with reason: Non-Issue. Notes: Expected > traffic. u0t9231 21 Mar 2018 14:20:11 > > > I want to read that txt file and I want to write to another file that will contain just part of "Notes: There is no suspicious situation." **So input**, *This offense was closed with reason: Non-Issue. Notes: There is no suspicious situation. u0t9231 21 Mar 2018 10:38:46"* **Output**, ``` Notes: There is no suspicious situation ```<issue_comment>username_1: If you want to dynamically generate code then use the SAS macro language. But for your example there is no need to dynamically generate code. ``` proc sql ; insert into some_sas_table select * from another_table where Metrics_desc in (select Metrics_desc from work.met_table) ; quit; ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can also do an explicit pass through. Send your native t-sql code to run on the database Server through SAS rather than bringing the data to the SAS application server to query it. The example below is explained in details [here](https://www.mwsug.org/proceedings/2014/SA/MWSUG-2014-SA03.pdf). ``` PROC SQL; CONNECT TO ODBC(DATASRC=SQLdb USER=&SYSUSERID) ; /* Explicit PASSTHRU with SELECT */ SELECT * FROM CONNECTION TO ODBC ( SELECT b.idnum o.[SSdatecol] AS mydate FROM dbo.big_SS_table1 b LEFT JOIN dbo.other_SStable o ON b.idnum = o.memberid WHERE o.otherdatecol >= '2014-10-06' --This is a T-SQL comment that works inside SQL Server ) ; ; DISCONNECT FROM ODBC ; QUIT; ``` Upvotes: 0
2018/03/22
528
1,872
<issue_start>username_0: I cannot understand why **in the arrow functions** we do not need to wrap the literal of arrow function in the `({})` braces, instead of in this example the literal just wrapped in the single `()` braces. Why? I had surfed the internet to find an answer on it, but it failed. And also why we put the arguments in double braces `({})`, instead of just `()`? ``` const FilterLink = ({ filter, children }) => ( {children} ) ```<issue_comment>username_1: Using `({})` is to [`destructure`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) the arguments and `=> ()` is an implicit return equivalent to `=> { return ()}` and `(` only serves to disambiguate between the start of an object and the opening braces of a function body and would generally be used when you have a multiline return value. You could simply avoid using `(` and have the `NavLink` in the same line as the arrow `=>` ``` const FilterLink = ({ filter, children }) => ( // <-- implicit return {children} ) ``` is equivalent to ``` const FilterLink = ({ filter, children }) => { return ( {children} ) } ``` Check this answer for [more details on the usage of destructuring in `({ filter, children })`](https://stackoverflow.com/questions/44734548/children-prop-in-react-component/44734573#44734573) Upvotes: 7 [selected_answer]<issue_comment>username_2: `const add = ( a, b ) => ( a + b )` Is equivalent to `const add = ( a, b ) => { return a+b; }` When you use the `()` after your `=>` it just automatically returns the values inside. **Edit:** you can also omit the `()` after `=>` entirely when its just a single line of return code, (thanks to [Tom Fenesh](https://stackoverflow.com/users/2088135/tom-fenech)) as `()` is only needed with return code spanning across multiple lines. Upvotes: 5
2018/03/22
872
3,242
<issue_start>username_0: How can I generate records for elasticsearch? I would like to generate at least 1 million records to test the memory size. ``` const now = new Date() const startOfDay = new Date(now.getFullYear(), now.getMonth(), Math.random(now.getDate())) const timestamp = startOfDay / 1000 const randomRecords = Array(10000000).fill(timestamp) randomRecords.forEach((record, i) => { clientTest.index({ index: 'test', type: 'test', id: '1', body: { [record]: `${record}${i}`, }, }).then(function (resp) { logger.silly('Pushing of data completed', resp) return resp }, function (err) { console.trace(err.message) }) }) ```<issue_comment>username_1: For each record in your array, you set the `id=1`. This means, that for every iteration you overwrite the record with id=1, ending up saving one record. So, you have two solutions: * use a counter that gets increased for every iteration, instead of the number 1, OR * use the [bulk API](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html), which also improves the performance of index operation. **Note** that you should also use an auto-increment (or at least unique) id for each record. Please let me know, if you have further issues. Upvotes: 1 <issue_comment>username_2: Use should use the iterator `i` to increment the `id` field. If you use the same id in elasticsearch when indexing it will simply overwrite the field each time. Change: `id: '1',` `id: i,` This should work, but I would recommend using `bulk api` for this. So instead of indexing on each iteration. Therefore, make a bulk index collection before hand in and then bulk index it in one request. [Bulk API](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html) Upvotes: 0 <issue_comment>username_3: Actually, it works for me also. ``` export const pushTest = (message, type) => new Promise(async resolve => { try { let client = createClient() await client.index({ index: type.toLowerCase(), type, body: message, }, (error, response) => { logger.silly('Pushing of data completed', response) resolve(response) }) } catch (e) { logger.error(e) } }) for (let index = 0; index < 100; index++) { let messageTest = { 'timestamp': {seconds: timestamp, nanos: 467737400}, type: randomItem(alarmTypes), location: `Room_${Math.floor(Math.random() * 100)}`, zone: `Zone_${Math.floor(Math.random() * 100)}`, personName: '<NAME>', personRoom: `Room_${Math.floor(Math.random() * 100)}`, pageSize: 10, cancelTimestamp: {seconds: timestamp, nanos: 467737400}, cancelPerson: 'person name', cancelLocation: `Room_${Math.floor(Math.random() * 100)}`, responseTime: {seconds: Math.floor(Math.random() * 1000000), nanos: 321549100}, } pushTest(messageTest, 'Call') } ``` Upvotes: 0
2018/03/22
492
1,962
<issue_start>username_0: I have a custom php file (myform.php) inside my theme folder that contains custom form with behavior defined in javascript. I've created a new page in wp dashboard, and I've assigned MyForm as page template. There is a lot of custom logic regarding that form. This form calculates something based on your specificiation, and it is supposed to go to stripe and charge your credit card. At first, I've created a model in javascript and used it to fill that form with data. Now I want to do two things: 1. Fill form data using ajax 2. On form submit using ajax I want to get into my PHP function and do some calculation and validation, going to payment gateway API etc. Which is the best way to achieve that, and how to do it? Should I place my methods in functions.php, or wp-ajax.php(NOTE: user is not going to be logged in) or myform.php ? Please state your opinion, pros and cons, and provide me with example method that returns "Test" string. I'm having problems with stepping into method with postman.<issue_comment>username_1: Is this a problem to achieve a ajax post to your php? Because if you want to post to another file and return information without reloading the page this is the best way to achieve it. I think you should put your function in the file which will be used to receive the ajax post. So you can calcute your information and return information if needed. I hope this is the solution you were looking for. Upvotes: 0 <issue_comment>username_2: 1st advice: Don't touch `wp-ajax.php`, you should only edit files in your theme (folder). `funtions.php` vs. `myform.php`: I'd put the template (html) into `myform.php` and the methods in some other file. It could be `functions.php`, but I'd use another file and include that later (e.g. in your `functions.php`). This way you won't end up with a crowded `functions.php` in the end. Your .js code should be in seperate files too - just my opinion ;-) Upvotes: 1
2018/03/22
838
2,424
<issue_start>username_0: here is [demo fiddel](http://jsfiddle.net/jkwvus8u/5/), need line chart start from first column left border to last column right border like image below [![enter image description here](https://i.stack.imgur.com/LmF1O.png)](https://i.stack.imgur.com/LmF1O.png) in demo fiddel it is start for center of bars. here is my code of series or you can see in fiddel : ``` series: [{ name: 'Rainfall', type: 'column', yAxis: 1, data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], tooltip: { valueSuffix: ' mm' } }, { name: 'Temperature', type: 'line', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6], tooltip: { valueSuffix: '°C' }, step: 'center', rangeSelector: { selected: 0 } }] ```<issue_comment>username_1: You need to add some javascript after the highcharts script code. The script is as following: ``` var rectangles = document.querySelectorAll(".highcharts-series-group > g > rect"); var last = parseInt(rectangles[rectangles.length-1].getAttribute("x")) + parseInt(rectangles[0].getAttribute("x")); var increment = (last)/11; // 11 is the no of gaps in the bar graph var x=0; for(i=0;i<rectangles.length;i++) { rectangles[i].setAttribute("x",x); x= x+increment; } ``` here is the jsfiddle <http://jsfiddle.net/jkwvus8u/15/> This is probably what you want.But add this code after the highcharts code since it will work on the high chart generated content Upvotes: 0 <issue_comment>username_2: I achieved the desired result in two steps: 1. I added a point before the first point and after the last point. Then I set `min` and `max` properties of `xAxis`. This causes that additional points are not visible but lines to them are. 2. Create and apply a clip path to line series. The dimensions of `clipRect` are based on the x positions of the first and the last column: ``` var columnSeries = this.series[0], lineSeries = this.series[1], firstPoint = columnSeries.points[0], lastPoint = columnSeries.points[columnSeries.points.length - 1], clipRect = this.renderer.clipRect(firstPoint.shapeArgs.x, 0, lastPoint.plotX, 9999); lineSeries.graph.clip(clipRect); ``` **Live demo:** <http://jsfiddle.net/BlackLabel/x2r34huc/> **API reference:** <https://api.highcharts.com/class-reference/Highcharts.SVGElement#clip> Upvotes: 1
2018/03/22
1,631
6,450
<issue_start>username_0: I am trying to setup replication of encrypted objects to an S3 bucket in a different region. When doing this, I will need to specify one or more KMS keys to be used to decrypt the *source* object. I am using the following Terraform script: ``` replication_configuration { role = "${aws_iam_role.replication.arn}" rules { id = "${var.service}" prefix = "${var.replication_bucket_prefix}" status = "Enabled" destination { bucket = "${aws_s3_bucket.replication_bucket.arn}" storage_class = "STANDARD" replica_kms_key_id = "xxxxx" } source_selection_criteria { sse_kms_encrypted_objects { enabled = true } } } } ``` This script work (it applies), but when checking in the AWS console, no KMS keys are selected for the source object. Looking at the configuration, I can't see anywhere to specify these keys. The `replica_kms_key_id` is to specify the KMS key to use for encrypting the objects in the *destination* bucket.<issue_comment>username_1: I ran into the same problem when trying to implement a KMS encrypted cross region, cross account replication with terraform. At some point I noticed that the source KMS key is missing in the configuration (like you did) and added it via the S3 web interface. After doing so, AWS created another policy (without mentioning it anywhere; I found it a day later while doing something else) called something like `crr-$SOURCE_BUCKET_NAME-to-$TARGET_BUCKET_NAME` and attached it to the replication role. After inspecting that rule, I realised that this is the missing piece to the puzzle. This is the important part of the policy: ``` { "Action": [ "kms:Decrypt" ], "Effect": "Allow", "Condition": { "StringLike": { "kms:ViaService": "s3.${var.source_bucket_region}.amazonaws.com", "kms:EncryptionContext:aws:s3:arn": [ "arn:aws:s3:::${var.source_bucket_name}/*" ] } }, "Resource": [ "${var.source_kms_key_arn}" ] }, ``` `${var.source_kms_key_arn}` is your source KMS key arn. PS: This issue drove me crazy! (╯°□°)╯︵ ┻━┻ Upvotes: 3 <issue_comment>username_2: When you setup replication in the console it creates a new policy and attaches it to your replication role. If you create this policy with Terraform it will reflect in the console and replication will work. The code below assumes you are creating all of the buckets and keys in terraform and the resource names are `aws_s3_bucket.source` and `aws_s3_bucket.replica` and the key resources are `aws_kms_key.source` and `aws_kms_key.replica`. This should definitely be described in the s3 bucket resource documentation on the Terraform site because it won't work without it, but it's not. ``` resource "aws_iam_policy" "replication" { name = "tf-iam-role-policy-replication-12345" policy = < ``` More details can be found in [issue #6046](https://github.com/terraform-providers/terraform-provider-aws/issues/6046#issuecomment-427960842) on the terraform-provider-aws repo Upvotes: 2 <issue_comment>username_3: Ran into same problem. I started with the policy documents in earlier comments from [Matt](https://stackoverflow.com/a/59496246/10919660) and [username_1](https://stackoverflow.com/a/52780498/10919660), but only got it working with this: ``` { "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:ListBucket", "s3:GetReplicationConfiguration", "s3:GetObjectVersionForReplication", "s3:GetObjectVersion", "s3:GetObjectVersionAcl", "s3:GetObjectVersionTagging", "s3:GetObjectRetention", "s3:GetObjectLegalHold" ], "Effect": "Allow", "Resource": [ "${aws_s3_bucket.source.arn}", "${aws_s3_bucket.source.arn}/*" ] }, { "Action": [ "s3:ReplicateObject", "s3:ReplicateDelete", "s3:ReplicateTags", "s3:GetObjectVersionTagging" ], "Effect": "Allow", "Condition": { "StringLikeIfExists": { "s3:x-amz-server-side-encryption": [ "aws:kms", "AES256" ], "s3:x-amz-server-side-encryption-aws-kms-key-id": [ "${aws_kms_key.replica.arn}" ] } }, "Resource": [ "${aws_s3_bucket.replica.arn}/*" ] }, { "Action": [ "kms:Decrypt" ], "Effect": "Allow", "Condition": { "StringLike": { "kms:ViaService": "s3.${aws_s3_bucket.source.region}.amazonaws.com", "kms:EncryptionContext:aws:s3:arn": [ "${aws_s3_bucket.source.arn}/*" ] } }, "Resource": [ "${aws_kms_key.source.arn}" ] }, { "Action": [ "kms:Encrypt" ], "Effect": "Allow", "Condition": { "StringLike": { "kms:ViaService": "s3.${aws_s3_bucket.replica.region}.amazonaws.com", "kms:EncryptionContext:aws:s3:arn": [ "${aws_s3_bucket.replica.arn}/*" ] } }, "Resource": [ "${aws_kms_key.replica.arn}" ] } ] } ``` Note the changes, maybe from V3 of CRR policy (AWS creates s3crr\_kms\_v3\_\* when selected from console): ``` "Condition": { "StringLikeIfExists": { "s3:x-amz-server-side-encryption": [ "aws:kms", "AES256" ], "s3:x-amz-server-side-encryption-aws-kms-key-id": [ "${aws_kms_key.replica.arn}" ] } } ``` Terraform documentation on S3 CRR with KMS is still very limited. Upvotes: 1
2018/03/22
831
1,878
<issue_start>username_0: I have four point like ``` P1A (10,9) P1B (10,10) P2A (11,10) P2B (11,9) ``` This shows the `LineA(from P1A ~ P2A)` and `LineB(from P1B ~ P2B)` Now,I would like to get the angle of two lines. In this case, angle must be 90 degree. How can I get the angle by programming?? I am glad If I could get the idea on php or javascript I think formula must be like this with vector a,b. `cosΘ = a1 x b1 + a2 x b2 / MathSqrt(a1 x a1 + a2 x a2) x MathSqrt(b1 x b1 + b2 x b2)` However how can I adopt P1A,P1B,P2A,P2B into this formula??<issue_comment>username_1: in javascript you could use [Math.atan2()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2) > > The Math.atan2() method returns a numeric value between -π and π > representing the angle theta of an (x, y) point. > > > ``` let P1A = { x: 10, y: 9 }; let P1B = { x: 11, y: 10 }; // angle in radians let angleRadians = Math.atan2(P1B.y - P1A.y, P1B.x - P1A.x); // angle in degrees let angleDeg = Math.atan2(P1B.y - P1A.y, P1B.x - P1A.x) * 180 / Math.PI; ``` Upvotes: 2 <issue_comment>username_2: You have two vectors, each defined by two points. Let's call `A` your line from `P1A` to `P2A`: ``` A = P2A - P1A = [11, 10] - [10, 9] = [1, 1] ``` Similarly you need a vector `B` between `P1B` and `P2B`: ``` B = P2B - P1B = [11, 9] - [10, 10] = [1, -1] ``` To find the angle between the vectors you need either: ``` A x B = |A| * |B| * sin(theta) ``` or ``` A . B = |A| * |B| * cos(theta) ``` Using the first method shown above: ``` theta = asin((A x B) / (|A| * |B|)) ``` where `A x B = A.x * B.y - A.y * B.x` so in your case `A x B = (1 * -1) - (1 * 1) = -2` Your vectors both have length `sqrt(2)` so: ``` theta = asin(-2 / (sqrt(2) * sqrt(2)) = asin(-1) = -π / 2 radians = -90 degrees ``` Upvotes: 1
2018/03/22
660
2,233
<issue_start>username_0: I am working on Spark SQL using Scala. I have a requirement where I need first convert the o/p of each query to double and then divide them.This is what I tried. Query1 - ``` scala> var noofentry = sqlContext.sql("select count(*) from bankdata") noofentry: org.apache.spark.sql.DataFrame = [count(1): bigint] ``` Query2 ``` var noofsubscribed = sqlContext.sql("select count(*) from bankdata where y='yes'") noofsubscribed: org.apache.spark.sql.DataFrame = [count(1): bigint] ``` Now, I need to convert the output of each query to double and divide them. ``` scala > var result = noofsubscribed.head().getDouble(0) / noofentry.head().getDouble(0) ``` On doing this I've ended up with the following error. ``` java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double at scala.runtime.BoxesRunTime.unboxToDouble(BoxesRunTime.java:114) at org.apache.spark.sql.Row$class.getDouble(Row.scala:248) at org.apache.spark.sql.catalyst.expressions.GenericRow.getDouble(rows.scala:165)... 50 elided ```<issue_comment>username_1: You are getting a `ClassCastException` because the value in your Row is a `Long`, but you are calling `getDouble(0)` which expects a Double, as shown in the exception message: > > java.lang.Long cannot be cast to java.lang.Double > > > You need to call `getLong(0)` first, then apply `toDouble` to convert the Long to Double. For example: ``` noofsubscribed.head().getLong(0).toDouble ``` Upvotes: 1 <issue_comment>username_2: As much as I agree with @username_1's answer, I'd like to attack this question in another way maybe considering best practice. Doing the following is just meaningless : ``` scala> var noofentry = sqlContext.sql("select count(*) from bankdata") ``` You ought doing the following instead : ``` scala> val noofentry = sqlContext.sql("select * from bankdata").count ``` Same thing for the other query : ``` scala> val noofsubscribed = sqlContext.sql("select * from bankdata where y='yes'").count ``` now you'll just need to convert one of them : ``` scala > val result = noofsubscribed.toDouble / noofentry ``` So this is actually a code review and an answer at the same time. Upvotes: 3 [selected_answer]
2018/03/22
549
1,812
<issue_start>username_0: I'm new to stored procedure when I query without stored procedure it's working fine, but when I run the stored procedure it shows error. > > **ERROR 1690 (22003): BIGINT UNSIGNED value is out of range** > > > ``` DELIMITER ;; DROP PROCEDURE IF EXISTS sp_price; Create Procedure sp_price( IN user_date INT, OUT exp INT, BEGIN select case when (cast((((start_date) + (31536000 * a))-t2.start_time) as unsigned) )>0 then sum(t2.price) else 0 end into exp from product t1 join customer t2 on t1.p_id=t2.c_id where t2.created >= user_date; END ;; ```<issue_comment>username_1: You are getting a `ClassCastException` because the value in your Row is a `Long`, but you are calling `getDouble(0)` which expects a Double, as shown in the exception message: > > java.lang.Long cannot be cast to java.lang.Double > > > You need to call `getLong(0)` first, then apply `toDouble` to convert the Long to Double. For example: ``` noofsubscribed.head().getLong(0).toDouble ``` Upvotes: 1 <issue_comment>username_2: As much as I agree with @username_1's answer, I'd like to attack this question in another way maybe considering best practice. Doing the following is just meaningless : ``` scala> var noofentry = sqlContext.sql("select count(*) from bankdata") ``` You ought doing the following instead : ``` scala> val noofentry = sqlContext.sql("select * from bankdata").count ``` Same thing for the other query : ``` scala> val noofsubscribed = sqlContext.sql("select * from bankdata where y='yes'").count ``` now you'll just need to convert one of them : ``` scala > val result = noofsubscribed.toDouble / noofentry ``` So this is actually a code review and an answer at the same time. Upvotes: 3 [selected_answer]
2018/03/22
752
2,758
<issue_start>username_0: I've read some qestions about errors in redux but still not quite understand it. For example in my app I have `activeUser` reducer where I store `null` or `object` with logged user. It listens to `actions` and changes its state if needed. Simple. But how `errors` reducers should work and look? I did my errors reducers this way: I have single `error/index.js` file where I store all errors reducers: ``` import * as actionTypes from '../../constants' export const wrongUsername = (state = false, action) => { switch (action.type) { case actionTypes.WRONG_USERNAME: return state = true case actionTypes.RESET_ERRORS: return state = false default: return state } } export const wrongPassword = (state = false, action) => { switch (action.type) { case actionTypes.WRONG_PASSWORD: return state = true case actionTypes.RESET_ERRORS: return state = false default: return state } } export const usernameIsTaken = (state = false, action) => { switch (action.type) { case actionTypes.USERNAME_IS_TAKEN: return state = true case actionTypes.RESET_ERRORS: return state = false default: return state } } ``` And this is my `reducers/index.js` file wher I combine all my `reducers`: ``` const reducers = combineReducers({ activeUser, viewableUser, isLoading, isFriend, userMessages, users, wasRequestSend, wrongUsername, wrongPassword, usernameIsTaken }) ``` is this normal or not? Should I change structure of my `errors` reducers?<issue_comment>username_1: You are getting a `ClassCastException` because the value in your Row is a `Long`, but you are calling `getDouble(0)` which expects a Double, as shown in the exception message: > > java.lang.Long cannot be cast to java.lang.Double > > > You need to call `getLong(0)` first, then apply `toDouble` to convert the Long to Double. For example: ``` noofsubscribed.head().getLong(0).toDouble ``` Upvotes: 1 <issue_comment>username_2: As much as I agree with @username_1's answer, I'd like to attack this question in another way maybe considering best practice. Doing the following is just meaningless : ``` scala> var noofentry = sqlContext.sql("select count(*) from bankdata") ``` You ought doing the following instead : ``` scala> val noofentry = sqlContext.sql("select * from bankdata").count ``` Same thing for the other query : ``` scala> val noofsubscribed = sqlContext.sql("select * from bankdata where y='yes'").count ``` now you'll just need to convert one of them : ``` scala > val result = noofsubscribed.toDouble / noofentry ``` So this is actually a code review and an answer at the same time. Upvotes: 3 [selected_answer]
2018/03/22
857
3,563
<issue_start>username_0: I want to import some tables from a postgres database into Elastic search and also hold the tables in sync with the data in elastic search. I have looked at a course on udemy, and also talked with a colleague who has a lot of experience with this issue to see what the best way to do it is. I am surprised to hear from both of them, it seems like the best way to do it, is to write code in python, java or some other language that handles this import and sync it which brings me to my question. Is this actually the best way to handle this situation? It seems like there would be a library, plugin, or something that would handle the situation of importing data into elastic search and holding it in sync with an external database. What is the best way to handle this situation?<issue_comment>username_1: As anything in life,best is subjective. Your colleague likes to write and maintain code to keep this in sync. There's nothing wrong with that. I would say the best way would be to use some data pipeline. There's plethora of choices, really overwheleming, you can explore the various solutions which support Postgres and ElasticSearch. Here are options I'm familiar with. Note that these are tools/platform for your solution, not the solution itself. YOU have to configure, customize and enhance them to fit your definition of **in sync** * [LogStash](https://www.elastic.co/products/logstash) * [Apachi Nifi](https://nifi.apache.org/) * [Kafka Connect](https://www.confluent.io/product/connectors/) Upvotes: 1 <issue_comment>username_2: It depends on your use case. A common practice is to handle this on the application layer. Basically what you do is to replicate the actions of one db to the other. So for example if you save one entry in postgres you do the same in elasticsearch. If you do this however you'll have to have a queuing system in place. Either the queue is integrated on your application layer, e.g. if the save in elasticsearch fails then you can replay the operation. Moreover on your queuing system you'll implement a throttling mechanism in order to not overwhelm elasticsearch. Another approach would be to send events to another app (e.g. logstash etc), so the throttling and persistence will be handled by that system and not your application. Another approach would be this <https://www.elastic.co/blog/logstash-jdbc-input-plugin>. You use another system that "polls" your database and sends the changes to elasticsearch. In this case logstash is ideal since it's part of the ELK stack and it has a great integration. Check this too <https://www.elastic.co/guide/en/logstash/current/plugins-inputs-jdbc.html> Another approach is to use the [NOTIFY](https://www.postgresql.org/docs/9.0/static/sql-notify.html) mechanism of postgres to send events to some queue that will handle saving the changes in elasticsearch. Upvotes: 4 [selected_answer]<issue_comment>username_3: There is a more recent tool called "abc", developped by appbase.io It's performance is uncomparable with logstash: - abc is based on go - logstash is jruby Anybody who's ever used logstash knows that it takes at least 20 seconds just to start. The same basic table import task from postgresql to elasticsearch takes ~1 min on logstash, and 5 seconds with abc **Pros**: * Performance * Performance * Simplicity (no conf) **Cons**: * More adapted for one-shot imports, the daemon mode is limited * Less middlewares (logstash filters) as you are required to write a transform.js file that manually changes events Upvotes: 2
2018/03/22
1,189
4,218
<issue_start>username_0: I am using async and await for achieving this. Following is my code and it is working as expected. ``` function publish() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve("SUCCESS"); }, 3000); }); } var res; async function sendRequest() { console.log("START\n"); res = await publish(); console.log("RESULT: ",res) console.log("END\n"); } sendRequest(); ``` Following is the output: ``` START SUCCESS END ``` But what I am trying to achieve is given below: ``` function publish() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve("SUCCESS"); }, 3000); }); } var res; async function sendRequest() { console.log("START\n"); res = await publish(); console.log("RESULT: ",res) console.log("END\n"); return res; } /** * EXPECTED BEHAVIOUR * Assume this function is an action of a controller class * It will call sendRequest() and waits for its response. * Once received, it will return that response to the client who called the action. */ function controller () { return sendRequest(); } /** * ACTUAL BEHAVIOUR: It will out put following * START * FINAL RESPONSE Promise { } \* RESULT: SUCCESS \* SEND \*/ var endResult = controller (); console.log("FINAL RESPONSE",endResult); ``` So my question is why this `FINAL RESPONSE Promise { }` is printed before `RESULT: SUCCESS`. * If this is the behaviour of `async` `await`, how can I achieve my expected behaviour. I don't want to use `then()` in my controller. * Is it possible using while loop? May be I am wrong. It would be great if any one can guide me.<issue_comment>username_1: You have to handle the last `async` function as a `Promise`, like: ``` function controller () { return sendRequest() } controller().then(endResult => console.log("FINAL RESPONSE",endResult)) ``` Upvotes: 0 <issue_comment>username_2: You can add a wrapper function ```js // Code goes here (async function(){ function publish() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve("SUCCESS"); }, 3000); }); } var res; async function sendRequest() { console.log("START\n"); res = await publish(); console.log("RESULT: ",res) console.log("END\n"); return res; } /** * EXPECTED BEHAVIOUR * Assume this function is an action of a controller class * It will call sendRequest() and waits for its response. * Once received, it will return that response to the client who called the action. */ function controller () { return sendRequest(); } /** * ACTUAL BEHAVIOUR: It will out put following * START * FINAL RESPONSE Promise { } \* RESULT: SUCCESS \* SEND \*/ var endResult = await controller (); console.log("FINAL RESPONSE",endResult); }()) ``` Upvotes: 0 <issue_comment>username_3: `async..await` is syntactic sugar for promises that provides syncronous-like flow of control. `async` function is just a function that always returns a promise. Each `async` function can be rewritten as regular function that uses `Promise` explicitly and returns a promise. > > I don't want to use then() in my controller. > > > Then `controller` can optionally be `async`, and the function where it is called should be `async`: ``` let endResult = await controller(); ``` Otherwise control flow results in [this infamous problem](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). > > Is it possible using while loop? > > > `while` and other loop statements support `async..await`. As long as the loop is performed inside `async` function, it is: ``` while (condition) { let endResult = await controller(); // ... } ``` It's preferable to use `async..await` for this purpose, because desugared version is less appealing and harder to comprehend: ``` let resultsPromise = Promise.resolve(); while (condition) { resultsPromise = resultsPromise .then(() => controller()) .then(endResult => { // ... }); } resultsPromise.then(() => { /* loop has finished */ }) ``` Upvotes: 2 [selected_answer]
2018/03/22
863
3,278
<issue_start>username_0: I was wandering, is there a property, to which I can attach a listener, that represents the action of "When the list view starts to show the ScrollBar"? The thing is, that I have an output to the ListView, and at some point the ListView's scrollBar triggers. I want to capture that event and scroll to the bottom so the next addition to the ListView object will automatically scroll to the bottom. I do understand that I may use the listener for the item change, but I want to preserve the behavior when I decide to scroll up and it will not scroll back to the last position as soon as an item gets added.<issue_comment>username_1: Maybe this can help you: ``` private boolean scroll = true; private ListView listView = new ListView<>(); Constructor(){ outputListView.addEventFilter(ScrollEvent.ANY, (e) ->{ //get every scroll event if(e.getTextDeltaY() > 0){ //set Scroll event to false when the user scrolls up scroll = false; } }); } public void addToListView(String s){ listView.getItems().add(s); if(scroll) listView.scrollTo(listView.getItems().size() -1 ); } ``` In this case the listView scrolls down when the scroll bar will shown but when the user scrolls up the listView doesn't scroll down anymore until the user scroll at the bottom of Listview (this is a standart listview behavior) Upvotes: 1 <issue_comment>username_2: Try this: ``` for (Node node : listView.lookupAll(".scroll-bar")) { if (node instanceof ScrollBar) { ScrollBar scrollBar = (ScrollBar) node; scrollBar.visibleProperty().addListener((observable, oldValue, newValue) -> { System.out.println(String.format("%s ScrollBar Visible Property Changed From: %s To: %s", scrollBar.getOrientation(), oldValue, newValue)); }); } } ``` **Output:** > > VERTICAL ScrollBar Visible Property Changed From: false To: true > > > **Note:** This code should be added after you set the items in your `ListView` to avoid `NullPointerException` Upvotes: 3 [selected_answer]<issue_comment>username_3: Personally, I'm not crazy about the CSS lookup approach, because it feels too much like a hack to me (I don't like relying on hard-coded property lookups). What I like to do instead is just search through the physical layout tree for a scrollbar with the proper orientation: ``` public static Optional getScrollbar(Node n, Orientation o) { LinkedList queue = new LinkedList<>(); queue.add(n); while(! queue.isEmpty()) { n = queue.removeFirst(); if (n instanceof ScrollBar) { ScrollBar sb = (ScrollBar)n; if (sb.getOrientation() == o) { return Optional.of(sb); } } if (n instanceof Parent) { queue.addAll(((Parent) n).getChildrenUnmodifiable()); } } return Optional.empty(); } ``` For example, if I am anchoring a floating button to the upper-right of my list view, when the layout bounds property of my list view changes, I'll do: ``` Optional sb = getScrollbar(listView, Orientation.VERTICAL); if (sb.isPresent() && sb.get().isVisible()) { StackPane.setMargin(hoverButton, new Insets(1, sb.get().getWidth(), 0, 0)); } else { StackPane.setMargin(hoverButton, new Insets(1, 1, 0, 0)); } ``` And that'll scoot my button over so it doesn't hover over the scrollbar. Upvotes: -1
2018/03/22
752
2,641
<issue_start>username_0: I have a data frame with a column that contains long text, and I would like to split it every 30 words, creating the necessary new rows with exactly the same contents in the other columns. The character solution does not work as I need it to work, and that is why I am posting this different question. ``` df1<-data_frame(V1=c(1, 2, 3), V2=c('Red', 'Blue', 'Red'), text=c('Folly words widow one downs few age every seven. If miss part by fact he park just shew. Discovered had get considered projection who favourable. Necessary up knowledge it tolerably. Unwilling departure education is be dashwoods or an. Use off agreeable law unwilling sir deficient curiosity instantly. Easy mind life fact with see has bore ten. Parish any chatty can elinor direct for former. Up as meant widow equal an share least', 'Bringing unlocked me an striking ye perceive. Mr by wound hours oh happy. Me in resolution pianoforte continuing we. Most my no spot felt by no. He he in forfeited furniture sweetness he arranging. Me tedious so to behaved written account ferrars moments. Too objection for elsewhere her preferred allowance her. Marianne shutters mr steepest to me. Up mr ignorant produced distance although is sociable blessing. Ham whom call all lain like.', 'Did shy say mention enabled through elderly improve. As at so believe account evening behaved hearted is. House is tiled we aware. It ye greatest removing concerns an overcame appetite. Manner result square father boy behind its his. Their above spoke match ye mr right oh as first. Be my depending to believing perfectly concealed household. Point could to built no hours smile sense.Breakfast agreeable incommode departure it an. By ignorant at on wondered relation. Enough at tastes really so cousin am of. Extensive therefore supported by extremity of contented. Is pursuit compact demesne invited elderly be. View him she roof tell her case has sigh. Moreover is possible he admitted sociable concerns. By in cold no less been sent hard hill.' )) ``` I have tried the following: ``` df <- df1%>% mutate(text = strsplit(as.character(text), "\\W+{30}")) %>% unnest(text) ``` But it just doesn't work.<issue_comment>username_1: Here is one option with `separate_rows` and then `paste` it together ``` df1 %>% separate_rows(text) %>% group_by(V1) %>% group_by(V2, grp = ((row_number()-1) %/%30) + 1, add = TRUE) %>% summarise(text = paste(text, collapse= ' ')) %>% ungroup %>% select(-grp) ``` Upvotes: 1 <issue_comment>username_2: Try this, it worked for me. ``` str_match_all(text, "(?:\\w+\\W*){30}") ``` Upvotes: 0
2018/03/22
1,797
5,364
<issue_start>username_0: I want to align three items in a flexbox like this. The context is that these are unknown-length (but wrappable) labels for an unknown-width (unwrappable) slider/row of buttons in a survey. `[L] [R] [variable width]` How do I align the top two items to the width of the lower/*middle* item without fixing the width of the container to the (in reality unknown width of the *middle* item)? I considered putting *left* and *right* into another flexbox and using a column layout for the top container. I don't like that way, because I'd have to break with the true content order (left-middle-right), but I couldn't even make it work this way. ```css div { border: 1px dotted; } .container { display: flex; flex-wrap: wrap; width: 300px; /* I want to get rid of this */ } .left { order: 1; flex: 1 0; } .right { order: 2; flex: 1 0; text-align: right; } .middle { order: 3; flex: 2 0 auto; } ``` ```html left Some unknown-width unwrappable thing here. right label may wrap if it's wider than 50% ```<issue_comment>username_1: I don't think `flex` can be configured like that. The effect you are looking for can be achieved using `position:absolute` on the left/right elements: ```css .container { position: relative; padding-top: 1em; display: inline-block; } .left, .right { position: absolute; top: 0; } .left { left: 0; } .right { right: 0; } .middle {} ``` ```html left So in my real example, there is some unknown-width unwrappable thing here. right ``` Upvotes: 1 <issue_comment>username_2: Here is an idea of solution without adding extra markup: ```css .container { display: inline-flex; flex-wrap: wrap; max-width: 100%; border: 1px solid; margin: 20px; } .left { order: 1; min-width: 0; width: 0.5px; white-space: nowrap; } .right { order: 2; min-width: 0; width: 0.5px; margin-left: auto; display: flex; justify-content: flex-end; white-space: nowrap; } .middle { order: 3; flex-basis: 100% } ``` ```html some left content So in my real example, there is some unknown-width unwrappable thing here. there is some unknown-width unwrappable thing here. some right content some left content So in my real example, there is some unknown-width unwrappable thing here. right left So in my real example, there is. right left So in my right ``` But if you are ok to slightly adjust the HTML you can try something like this: ```css .container { display: inline-flex; flex-direction: column; max-width: 100%; border: 1px solid; margin: 20px; } .sub { display: flex; justify-content: space-between; } ``` ```html some left content some right content So in my real example, there is some unknown-width unwrappable thing here. there is some unknown-width unwrappable thing here. some left content some right content So in my real example, there is some unk left right So in my real example, ``` Upvotes: 2 <issue_comment>username_3: You could change the `flex` from `auto` to `100%`, and add `text-align: center` to `.middle`, like so: ```css .container { display: flex; flex-wrap: wrap; } .left { order: 1; flex: 1 0; } .right { order: 2; flex: 1 0; text-align: right; } .middle { order: 3; flex: 2 0 100%; /* change this to 100% instead of auto */ text-align: center; /* To center the text */ } ``` ```html left So in my real example, there is some unknown-width unwrappable thing here. right ``` Upvotes: 0 <issue_comment>username_4: The only pure CSS possibility to align items as you want is CSS Grid. ```css div { border: 1px dotted; } .container { display: inline-grid; grid-template-columns: min-content min-content; } .right { grid-column: 2; grid-row: 1; } .middle { grid-column: 1 / span 2; white-space: nowrap; } ``` ```html left Some unknown-width unwrappable thing here. right label may wrap if it's wider than 50% ``` Also if you need IE10+ support it's easy to achieve: ```css div { border: 1px dotted; } .container { display: -ms-inline-grid; display: inline-grid; -ms-grid-columns: min-content min-content; grid-template-columns: min-content min-content; } .right { -ms-grid-column: 2; grid-column: 2; grid-row: 1; } .middle { -ms-grid-row: 2; -ms-grid-column-span: 2; grid-column: 1 / span 2; white-space: nowrap; } ``` ```html left Some unknown-width unwrappable thing here. right label may wrap if it's wider than 50% ``` Upvotes: 2 [selected_answer]<issue_comment>username_5: Use `flex-basis: number%` it works very well and supported by IE 10+, and you can choose your breaking point in media query selectors if you want. check my code: ```css div { border: 1px dotted; } .container { display: flex; flex-flow: row wrap; justify-content: space-between; } .left { flex-basis: 49.55%; /* change this to whatever you want */ } .right { flex-basis: 49.55%; /* change this to whatever you want */ } .middle { order: 3; flex-basis: 100%; } ``` ```html left Some unknown-width unwrappable thing here. right label may wrap if it's wider than 50% ``` Upvotes: -1
2018/03/22
743
1,828
<issue_start>username_0: Sample: ``` df1 = pd.DataFrame({'a':list('ab'), 'b':[[1,2],[4,5]]}) print (df1) a b 0 a [1, 2] 1 b [4, 5] df2 = pd.DataFrame({'c':list('cd'), 'b':[[1,7],[4,5]]}) print (df2) b c 0 [1, 7] c 1 [4, 5] d ``` I try merge by column `b` with `list`s: ``` df = pd.merge(df1, df2, on='b') ``` > > TypeError: type object argument after \* must be a sequence, not map > > > I find solution with convert columns to tuples: ``` df1['b'] = df1['b'].apply(tuple) df2['b'] = df2['b'].apply(tuple) df = pd.merge(df1, df2, on='b') print (df) a b c 0 b (4, 5) d ``` But why `merge` with `list`s columns failed?<issue_comment>username_1: I'm not sure about it, but it seems that using a dict instead of a list such as: ``` df1 = pd.DataFrame({'a':list('ab'), 'b':[{1:2},{4:5}]}) df2 = pd.DataFrame({'c':list('cd'), 'b':[{1:7},{4:5}]}) ``` or set: ``` df1 = pd.DataFrame({'a':list('ab'), 'b':[{1,2},{4,5}]}) df2 = pd.DataFrame({'c':list('cd'), 'b':[{1,7},{4,5}]}) ``` you will get the same error. So I believe that merge with `list` columns failed because they are **mutable** while `tuble` are not Upvotes: 2 <issue_comment>username_2: When I try your example in python3.6 ``` df1 = pd.DataFrame({'a':list('ab'), 'b':[[1,2],[4,5]]}) print (df1) df2 = pd.DataFrame({'c':list('cd'), 'b':[[1,7],[4,5]]}) print (df2) df = pd.merge(df1, df2, on='b') ``` I get the (final) error ``` TypeError: unhashable type: 'list' ``` Because for merging, the column to merge on needs to be hashable. The same error is given, if you try to hash one of your values ``` hash([1,7]) ``` Converting the values to tuple makes them hashable ``` print(hash((1,7))) 1303117175 ``` That's why mergeing column with lists is not possible. No hash. Upvotes: 2 [selected_answer]
2018/03/22
633
1,891
<issue_start>username_0: I have two objects : channel and tag a with many-to-many relation. A channel can have multiple tags, and a tag can have multiple channels. So I have three tables: -channel table -tag table -junction table On the channel page, there will be the list of the tags linked to it. I also want that if a user clicks on a tag, it increases a counter linked to it. But I'm not sure how to do that. Can I add a third column on the junction table for the number of clicks ? Or can I have duplicates in the junction table (i.e each time a user clicks on tag "kids" of channel "omega", it would add a line to the junction table linking id of "kids" and id "omega") Or is there another/better way to do this ?<issue_comment>username_1: I'm not sure about it, but it seems that using a dict instead of a list such as: ``` df1 = pd.DataFrame({'a':list('ab'), 'b':[{1:2},{4:5}]}) df2 = pd.DataFrame({'c':list('cd'), 'b':[{1:7},{4:5}]}) ``` or set: ``` df1 = pd.DataFrame({'a':list('ab'), 'b':[{1,2},{4,5}]}) df2 = pd.DataFrame({'c':list('cd'), 'b':[{1,7},{4,5}]}) ``` you will get the same error. So I believe that merge with `list` columns failed because they are **mutable** while `tuble` are not Upvotes: 2 <issue_comment>username_2: When I try your example in python3.6 ``` df1 = pd.DataFrame({'a':list('ab'), 'b':[[1,2],[4,5]]}) print (df1) df2 = pd.DataFrame({'c':list('cd'), 'b':[[1,7],[4,5]]}) print (df2) df = pd.merge(df1, df2, on='b') ``` I get the (final) error ``` TypeError: unhashable type: 'list' ``` Because for merging, the column to merge on needs to be hashable. The same error is given, if you try to hash one of your values ``` hash([1,7]) ``` Converting the values to tuple makes them hashable ``` print(hash((1,7))) 1303117175 ``` That's why mergeing column with lists is not possible. No hash. Upvotes: 2 [selected_answer]
2018/03/22
1,305
4,371
<issue_start>username_0: Let's say ``` a = {1:2, 3:4, 5:6} ``` Is there a builtin function (maybe something like `a.get2(7,5))` that will return `a[7]`, or `a[5]` if `a[7]` doesn't exist? Such function can be defined easily as `a.get(val, a.get(def_key))` but would prefer a builtin solution if exists.<issue_comment>username_1: Setting a constant fallback value is possible. One method is to use `collections.defaultdict`. Note this requires creating a new dictionary. This, of course, we can assign to the same variable. ``` from collections import defaultdict a = {1:2, 3:4, 5:6} a = defaultdict(lambda: a[5], a) ``` This sets the default value to a constant `6`, which will be returned when a key is not found. You will have to reset your default value each time `a[5]` is updated, if required. Upvotes: 1 <issue_comment>username_2: you can subclass `dict`: ``` class MyDict(dict): def get2(self,*keys): for k in keys: if k in self: return self.get(k) return None # if not found a = {1:2, 3:4, 5:6} b = MyDict(a) print(b.get2(2,10,5)) ``` The positional arguments allow to extend the behaviour to n keys. The general case cannot use `get` to know if the key is in the dict, as some values *could* be `None` hence the `in` test. avoid double dict test with a *sentinel object* ``` class MyDict(dict): __notfound = object() def get2(self,*keys): for k in keys: x = self.get(k,self.__notfound ) if x is not self.__notfound : return x return None # if not found ``` Upvotes: 2 <issue_comment>username_3: You could define a subclass of dict to access the dictionary entries with a virtual default value that will apply to any non-existing key but will not actually create any key when referencing them (as opposed to the setdefault() function) ``` class dictWithDefault(dict): def __init__(self,aDict={},defaultValue=None): super().__init__(aDict) def aFunction():pass self._default = defaultValue if type(defaultValue) == type(aFunction) else lambda : defaultValue def __getitem__(self,key): return super().__getitem__(key) if key in self else self._default() d = {1:2, 3:4, 5:6} d = dictWithDefault(d,99) d[1] # >>> 2 d[7] # >>> 99 this is the default value, but key 7 still doesn't exist d[7] = 97 d[7] # >>> 97 once assigned the key has its own value d._default = 100 # you can change the virtual default at any time d[9] # >>> 100 d[8] += 5 # this can be useful when key/values are used to count things # (using a default value of zero) akin to a Bag structure d[8] # >>> 105 d # >>> {1: 2, 3: 4, 5: 6, 7: 97, 8: 105} ``` You could also create the dictionary with a default value directly: ``` d = dictWithDefault({1:2, 3:4, 5:6},99) ``` To have a default key instead of a default value, you can use the same technique and just change the implementation of the **getitem** method. Or, you can simply use d = dictWithDefault(d) without a default value and use the **or** operator to get to the alternative key(s): ``` d = dictWithDefault(d) value = d[7] or d[5] ``` **[EDIT]** Changed code to support objects as default values. You have to be careful with this when using objects (e.g. lists) as values for the dictionary. On the first implicit assignment to a new key, it would merely be assigned a reference to the \_default object. This means that all these keys would end up referencing the same object. For example: d = dictWithDefault(defaultValue=[]) will not work as expected. ``` d = dictWithDefault(defaultValue=[]) d["A"].append(1) d["B"].append(2) # will end up with { "A":[1,2], "A":[1,2] } # because both keys (A and B) reference the same list instance. ``` To work around this, I changed the function so it could accept a lambda: in cases where an object is used as a default. This allows the default value to create a new instance when it is used for a new key. ``` d = dictWithDefault(defaultValue=lambda:[]) d["A"].append(1) d["B"].append(2) # now works properly giving: { "A":[1], "B":[2] } ``` You can still use the class without a lambda for simple types (strings, integers, ...) but you have to make sure to use a lambda: with an instance creation method when the dictionary stores objects as values. Upvotes: 1
2018/03/22
717
2,646
<issue_start>username_0: I have an ASP.net MVC application hosted on pivotal cloud foundry. As a space developer, I have access to Apps Manager tile, and the cf CLI. Is it possible to attach a remote debugger to my application running in the windows container? I have found that it is possible for a linux stack on cloud foundry, but so far no luck getting any such resources for .NET. No dev guides on pivotal have this usecase. Are all .net applications debugged by checking the logs (acknowledge that .net apps are not pushed to pcf that often)? Any help is appreciated thanks.<issue_comment>username_1: It is possible, for testing purpose you can add a code for generating text file in your that code where you want have debugging. Create file there and append all code results line by line in that file. It will be created on your hosting server where you have website. Then you can open and verify results in that file. Upvotes: 0 <issue_comment>username_2: **2023 Update!** This should now be possible, and in fact fairly easy, via the extension [Tanzu Toolkit for Visual Studio](https://github.com/vmware-tanzu/tanzu-toolkit-for-visual-studio). There are several demo videos on that page, this feature is in [this video](https://github.com/vmware-tanzu/tanzu-toolkit-for-visual-studio#remote-debugging-net-apps-running-on-tanzu-application-service) --- **Original Answer** There isn't any official documentation yet, but the piece that was missing was SSH support, which is now included with PASW2016. The Garden Windows team has been able to debug applications on Windows Server 2016 with these steps: * Publish project with `Debug any-cpu` * Download the version of Remote tools that matches your Visual Studio version: <https://learn.microsoft.com/en-us/visualstudio/debugger/remote-debugging> * Copy the contents of the folder you get from that installer (C:\Program Files\Microsoft Visual Studio 15.0\Remote Tools\DiagnosticsHub for my 2017 install) into your app's publish directory * `cf push` the publish folder with included debugger tools * `cf ssh app -L 4022:localhost:4022` * Start the msvsmon.exe from the app dir with the following arguments: `.\msvsmon /noauth /anyuser /port 4022 /silent /nosecuritywarn` * in VS go to Debug>Attach to process + Select Remote (no authentication) + Qualifier: `localhost:4022` + Make sure attach to is set to `Managed (v4.6, v4.5...)` + select `hwc.exe` + Set a debug point and make requests to your app This info is from <https://www.pivotaltracker.com/n/projects/1156164/stories/152283658> I have not had a chance to personally test it out yet Upvotes: 3 [selected_answer]
2018/03/22
327
1,244
<issue_start>username_0: I'm trying to design an overlay screen in `Nativescript`. I need a half-transparent screen with full transparency that shows what the user needs to do. Is there any default plugin available or layouts?<issue_comment>username_1: ``` ``` Upvotes: 0 <issue_comment>username_2: ``` ``` By default everything in GridLayout is placed in the first row in the first column unless you define otherwise. If you define two views in the same column and row, the lowest view will be stacked in front of the previous one. You can of course use any layouts inside and use things such as colSpan or rowSpan. ``` ``` Upvotes: 2 <issue_comment>username_3: You can use this to display overlay. Fill the content with your loading and set opacity if needed. In case you need to hide ActionBar, just set height to "0" using ContextBinding and Observables. ``` ``` Upvotes: 0 <issue_comment>username_4: You can use this nativescript example template for use overlay screen. <https://play.nativescript.org/?template=play-js&id=7wQ8EL&v=5> This template is already have a half screen overlay with full transparent. [![enter image description here](https://i.stack.imgur.com/Xa7Pq.gif)](https://i.stack.imgur.com/Xa7Pq.gif) Upvotes: 2
2018/03/22
562
1,985
<issue_start>username_0: This is a function in python3 that prints 1 through 10. There are a few things I don't understand about this, since I'm a programming noob. This function will subtract 1 from a given number as long as that number is above 1. So if number = 10 it will subtract 1 from 10 to give 9 and then 1 from 9 to give 8 and so on... until it reaches 1, which will be printed to the screen. I don't understand is why the function subsequently prints 2, 3, 4, 5, 6, 7, 8, 9 and 10. Since these numbers are above one, shouldn't they enter the if-statement and then not be printed? According to my understanding of the code, only numbers that are equal to or below 1 will be printed. In other words: "Why is the output of this function, not "1" alone?" ``` def print_numbers(number): if number > 1: print_numbers(number-1) print(number) print_numbers(10) ``` You can try out the code in python to see that the output is 1 through 10?<issue_comment>username_1: ``` ``` Upvotes: 0 <issue_comment>username_2: ``` ``` By default everything in GridLayout is placed in the first row in the first column unless you define otherwise. If you define two views in the same column and row, the lowest view will be stacked in front of the previous one. You can of course use any layouts inside and use things such as colSpan or rowSpan. ``` ``` Upvotes: 2 <issue_comment>username_3: You can use this to display overlay. Fill the content with your loading and set opacity if needed. In case you need to hide ActionBar, just set height to "0" using ContextBinding and Observables. ``` ``` Upvotes: 0 <issue_comment>username_4: You can use this nativescript example template for use overlay screen. <https://play.nativescript.org/?template=play-js&id=7wQ8EL&v=5> This template is already have a half screen overlay with full transparent. [![enter image description here](https://i.stack.imgur.com/Xa7Pq.gif)](https://i.stack.imgur.com/Xa7Pq.gif) Upvotes: 2
2018/03/22
327
1,216
<issue_start>username_0: I have the following column in SQLAlchemy: ``` name = Column(String(32), nullable=False) ``` I want that if no value is passed onto an insertion, it should enter a default value of either completely blank or if not possible, then default as NULL. Should I define the column as : ``` name = Column(String(32), nullable=False, default=NULL) ``` Because in python `NULL` object is actually `None` Any suggestions?<issue_comment>username_1: If you want an empty string as default, you can: ``` name = Column(String(32), nullable=False, default='') ``` However, if you just do: ``` name = Column(String(32), nullable=True) ``` then the default value of the column will be a NULL. Note that a NULL value indicates “unknown value”, and typically should not be confused with an empty string. If your application needs the concept of “unknown value”, then make your column nullable. If not, make it non-nullable and default to empty strings. Upvotes: 5 <issue_comment>username_2: If you want exactly `default NULL` in your SQL, you may define the column as follow: ``` name = Column(String(32), server_default=sqlalchemy.sql.elements.TextClause('NULL')) ``` Upvotes: 0
2018/03/22
1,027
2,624
<issue_start>username_0: I have to tranform url's entered in plain text into html hrefs and I want to find multiple urls. This: `Hi here is a link for you: http://www.google.com. Hope it works.` Will become: `Hi here is a link for you: <http://www.google.com>. Hope it works.` Found this code: ``` public String transformURLIntoLinks(String text){ String urlValidationRegex = "(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?"; Pattern p = Pattern.compile(urlValidationRegex); Matcher m = p.matcher(text); StringBuffer sb = new StringBuffer(); while(m.find()){ String found =m.group(0); m.appendReplacement(sb, "<"+found+">"); } m.appendTail(sb); return sb.toString(); } ``` Posted here <https://stackoverflow.com/a/17704902> And it works perfectly. For all urls properly prefixed with `http`. But I also want to find url's starting with just `www`. Can anyone that knows his regex help me out?<issue_comment>username_1: Make the `(https?|ftp)://` part optional. This is done by adding a question mark `?`. So it will be `((https?|ftp)://)?` Use this RegEx: ```regex \b((https?|ftp):\/\/)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[A-Za-z]{2,6}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)*(?:\/|\b) ``` Escape Java escape character (\): ```regex \\b((https?|ftp):\\/\\/)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[A-Za-z]{2,6}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)*(?:\\/|\\b) ``` Examples -------- ### Example 1 (with protocol, in sentence) [![Example 1](https://i.stack.imgur.com/4EN3n.png)](https://i.stack.imgur.com/4EN3n.png) ### Example 2 (without protocol, in sentence) [![Example 2](https://i.stack.imgur.com/ycJRr.png)](https://i.stack.imgur.com/ycJRr.png) Upvotes: 2 [selected_answer]<issue_comment>username_2: Make the www optinnal by surrounding. You case try this: ``` final String urlValidationRegex = "(https?|ftp)://(www\\d?)?(|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?" ``` Upvotes: 0 <issue_comment>username_3: You could try the following pattern. > > ((https?|ftp)://)?(www\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(:|.)([a-zA-Z0-9.]+|(\d+)?)([/?:].\*)? > > > The updated code will be ``` public String transformURLIntoLinks(String text){ String urlValidationRegex = "((https?|ftp)://)?(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?"; Pattern p = Pattern.compile(urlValidationRegex); Matcher m = p.matcher(text); StringBuffer sb = new StringBuffer(); while(m.find()){ String found =m.group(0); m.appendReplacement(sb, "<"+found+">"); } m.appendTail(sb); return sb.toString(); } ``` Upvotes: 0
2018/03/22
1,030
2,492
<issue_start>username_0: Consider the analysis of the 1st sentence from Wikipedia page of <NAME>: <http://localhost:8983/solr/#/trans/analysis?analysis.fieldvalue=Albert%20Einstein%20(14%20March%201879%20%E2%80%93%2018%20April%201955)%20was%20a%20German-born%20theoretical%20physicist%5B5%5D%20who%20developed%20the%20theory%20of%20relativity,%20one%20of%20the%20two%20pillars%20of%20modern%20physics%20(alongside%20quantum%20mechanics)&analysis.fieldtype=text_en&verbose_output=0> and its output: [![enter image description here](https://i.stack.imgur.com/ixEFQ.png)](https://i.stack.imgur.com/ixEFQ.png) Question: Is there any way to get this in some semi-strictured way from solr? Ultimately, I am interesting in referencing the character sequences from the original text to the exact tokens of the last line..<issue_comment>username_1: Make the `(https?|ftp)://` part optional. This is done by adding a question mark `?`. So it will be `((https?|ftp)://)?` Use this RegEx: ```regex \b((https?|ftp):\/\/)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[A-Za-z]{2,6}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)*(?:\/|\b) ``` Escape Java escape character (\): ```regex \\b((https?|ftp):\\/\\/)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[A-Za-z]{2,6}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)*(?:\\/|\\b) ``` Examples -------- ### Example 1 (with protocol, in sentence) [![Example 1](https://i.stack.imgur.com/4EN3n.png)](https://i.stack.imgur.com/4EN3n.png) ### Example 2 (without protocol, in sentence) [![Example 2](https://i.stack.imgur.com/ycJRr.png)](https://i.stack.imgur.com/ycJRr.png) Upvotes: 2 [selected_answer]<issue_comment>username_2: Make the www optinnal by surrounding. You case try this: ``` final String urlValidationRegex = "(https?|ftp)://(www\\d?)?(|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?" ``` Upvotes: 0 <issue_comment>username_3: You could try the following pattern. > > ((https?|ftp)://)?(www\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(:|.)([a-zA-Z0-9.]+|(\d+)?)([/?:].\*)? > > > The updated code will be ``` public String transformURLIntoLinks(String text){ String urlValidationRegex = "((https?|ftp)://)?(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?"; Pattern p = Pattern.compile(urlValidationRegex); Matcher m = p.matcher(text); StringBuffer sb = new StringBuffer(); while(m.find()){ String found =m.group(0); m.appendReplacement(sb, "<"+found+">"); } m.appendTail(sb); return sb.toString(); } ``` Upvotes: 0
2018/03/22
1,014
2,885
<issue_start>username_0: I'm testing a function that will make 2 calls to a mongo database, each one with different arguments. The function is called 'saveAchProgress' and will make 2 'updateOne' requests to db. I'm using a mock cause I need to spy the function AND block the db calls at he same time (not connected to db during unit tests). I would like to check the arguments but only for the second db call I can easily manage to check calls 1 and 2 are properly made: ``` it('should update if value >= achNumber', async function (): Promise { mock.expects('updateOne').twice().returns('foo'); await achievementsServiceFunctions.saveAchProgress(1, 1); mock.verify(); }); ``` However, when I check the arguments, I get an error with the arguments of the first call. ``` it('should update game with right arguments: collection', async function (): Promise { mock.expects('updateOne').withArgs('game', sinon.match.any, sinon.match.any).returns('foo'); await achievementsServiceFunctions.saveAchProgress(1, 1); mock.verify(); }); ``` I know sinon mock have their own way of check stuff but I couldn't find anything fitting my needs in sinon documentation. Is there a solution?<issue_comment>username_1: Make the `(https?|ftp)://` part optional. This is done by adding a question mark `?`. So it will be `((https?|ftp)://)?` Use this RegEx: ```regex \b((https?|ftp):\/\/)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[A-Za-z]{2,6}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)*(?:\/|\b) ``` Escape Java escape character (\): ```regex \\b((https?|ftp):\\/\\/)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[A-Za-z]{2,6}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)*(?:\\/|\\b) ``` Examples -------- ### Example 1 (with protocol, in sentence) [![Example 1](https://i.stack.imgur.com/4EN3n.png)](https://i.stack.imgur.com/4EN3n.png) ### Example 2 (without protocol, in sentence) [![Example 2](https://i.stack.imgur.com/ycJRr.png)](https://i.stack.imgur.com/ycJRr.png) Upvotes: 2 [selected_answer]<issue_comment>username_2: Make the www optinnal by surrounding. You case try this: ``` final String urlValidationRegex = "(https?|ftp)://(www\\d?)?(|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?" ``` Upvotes: 0 <issue_comment>username_3: You could try the following pattern. > > ((https?|ftp)://)?(www\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(:|.)([a-zA-Z0-9.]+|(\d+)?)([/?:].\*)? > > > The updated code will be ``` public String transformURLIntoLinks(String text){ String urlValidationRegex = "((https?|ftp)://)?(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?"; Pattern p = Pattern.compile(urlValidationRegex); Matcher m = p.matcher(text); StringBuffer sb = new StringBuffer(); while(m.find()){ String found =m.group(0); m.appendReplacement(sb, "<"+found+">"); } m.appendTail(sb); return sb.toString(); } ``` Upvotes: 0
2018/03/22
1,364
4,739
<issue_start>username_0: I am trying to write a string in my pdf file creating using apache pdfbox. I have used ISO-8859-1 as encoding with UTF-8. but still, it is printing question mark. Tried a lot and looked for solutions on the internet(StackOverflow). Could someone please help. Thanks in advance ``` public class TestClass { public static void main(String[] args) throws IOException{ PDDocument doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream cos= new PDPageContentStream(doc, page); cos.beginText(); String text = "Deposited Cash of ₹10,00,000/- or more in a Saving Bank Account"; cos.newLineAtOffset(25, 700); byte[] ptext = text.getBytes("ISO-8859-1"); String value = new String(ptext, "UTF-8"); } cos.setFont(PDType1Font.TIMES_ROMAN, 12); cos.showText(value); cos.endText(); cos.close(); doc.save("C:\\Users\\xyz\\Desktop\\Sample.pdf"); doc.close(); } } ``` In pdf, it is writing question mark instead of rupee symbol.<issue_comment>username_1: You use the font `PDType1Font.TIMES_ROMAN`. This is a standard 14 font, i.e. a font every PDF-1.x viewer must have available but merely for a limited character set which the Rupee symbol does not belong to (cf. Annex D of the PDF specification ISO 32000-1). PDFBox in particular uses **WinAnsiEncoding** for standard 14 fonts which the Rupee symbol very definitively is not among. Thus, use a local font for which you know that it includes the Rupee symbol (e.g. ARIALUNI for test purposes) with an encoding which allows representing the Rupee symbol (e.g. Identity-H). And don't do ``` byte[] ptext = text.getBytes("ISO-8859-1"); String value = new String(ptext, "UTF-8"); ``` This encodes text as bytes according to one encoding and decodes those bytes according to a different encoding. Such code usually only damages the text, often beyond repair. (There are seldom occasions in which such code might sense, in particular if the original string already was damaged, decoded using a wrong encoding. But it does not in your case.) --- As the OP asked, this is the code that worked for me: ``` PDDocument doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream cos= new PDPageContentStream(doc, page); cos.beginText(); String text = "Deposited Cash of ₹10,00,000/- or more in a Saving Bank Account"; cos.newLineAtOffset(25, 700); cos.setFont(PDType0Font.load(doc, new File("c:/windows/fonts/arial.ttf")), 12); cos.showText(text); cos.endText(); cos.close(); doc.save("IndianRupee.pdf"); doc.close(); ``` *([ShowSpecialGlyph](https://github.com/username_1-public/testarea-pdfbox2/blob/master/src/test/java/username_1/testarea/pdfbox2/content/ShowSpecialGlyph.java#L34) test `testIndianRupeeForVandanaSharma`)* The result: [![Screenshot](https://i.stack.imgur.com/9O33n.png)](https://i.stack.imgur.com/9O33n.png) As @Tilman already stressed, one needs to have a new enough font file to make this work: The Indian Rupee Sign ₹ (U+20B9) was introduced to Unicode in version 6.0.0 (October 2010) and it might have taken font developers some time to implement that glyph. E.g. I use ArialMT (arial.ttf) version 6.90 with "(c) 2015 The Monotype Corporation." And of course, if your font file is not located in "c:/windows/fonts/", use the path it has on your system. Upvotes: 3 [selected_answer]<issue_comment>username_2: Solution to the above question: Purpose:trying to write IndianRupeeSymbol(₹) in PDF using Apache PDFBox library. Error:there was some problem in writing this symbol in PDF (refer the question for exact details.) Approach:I was looking for font which support reading/writing unicode character in PDF file.I downloaded many .ttf files for various fonts from internet , i was placing it somewhere in my system, using that .ttf file to read/write (encode/decode) the unicode character so that i can write the same in my pdf file. Mistake:any font style you want to use to read/write character, the font file for that particular font must be installed in the system.However, i was simply downloading the file and was trying to read it in my code. Solution:As provided by @Tilman and @username_1, there are some default font files installed in our system (C:\Windows\Fonts....)(I am using windowsOS). You can use these pre-installed files to fulfill your purpose. Please check the version of the font file installed in your system once. Version should be latest to support latest features. In case, you find the fonts installed are not the latest one, you can download the respective font file and install in your system. Upvotes: 0
2018/03/22
1,579
4,787
<issue_start>username_0: I have a PHP array with an unknown amount of values, technically it can go on forever. But I would like to have a sum of values after 7 values. Example: sum of: $array[0], $array [7] and so forth. Starting with 0 and 7th, 14th, etc. This issue has been a headache for me, I am a beginning php programmer. ``` $day1 = $array[0] + $array[7]; $day2 = $array[1] + $array[8]; $day3 = $array[2] + $array[9]; $day4 = $array[3] + $array[10]; $day5 = $array[4] + $array[11]; $day6 = $array[5] + $array[12]; $day7 = $array[6] + $array[13]; ``` but then what if I have more values ``` $day1 = $array[0] + $array[7] + $array[13]; $day2 = $array[1] + $array[8] + $array[15]; $day3 = $array[2] + $array[9] + $array[16]; ... ``` At this point it is no longer an issue of getting something done but rather a logical quest. How to get the sum of elements after every 7 values?<issue_comment>username_1: This way is not very elegant but i think the logic is here : ``` php $array = [1, 2, 3, 4, 5, 6 , 7, 8, 9, 1, 2,3,4,5,6,7]; $day1=$day2=$day3=$day4=$day5=$day6=$day7=0; foreach ($array as $key = $value) { switch ($key % 7){ case 0: $day1 = $day1 + $value; break; case 1: $day2 = $day2 + $value; break; case 2: $day3 = $day3 + $value; break; case 3: $day4 = $day4 + $value; break; case 4: $day5 = $day5 + $value; break; case 5: $day6 = $day6 + $value; break; case 6: $day7 = $day7 + $value; break; } } ``` Upvotes: 1 <issue_comment>username_2: If you want to have the sum of each seven following values: ``` //break the array into an array of arrays with 7 items each $chunks = array_chunk($array, 7); //map the items $sums = array_map(function ($chunk) { //reduce the sum return array_reduce($chunk, function ($sum, $val){ return $sum + $val; }, 0); }, $chunks); ``` **update** due to the comment of @username_3, the above can be replaced by: ``` $sums = array_map(function ($chunk) { return array_sum($chunk); }, $chunks); ``` Please not that this does not deal with the case, that the last item in chunks may have less than seven items. If you want to have the sum of the first and seventh, second eighth, third and ninth, etc: ``` $sums = []; for ($i = 0; $i < 7; $i++) { $sum = 0; for ($n = $i; $n < count($array); $n += 7) { $sum += $array[$n]; } $sums[] = $sum; } ``` note that this also does not deal with the case that `count($array) % 7` might not be zero. Upvotes: 0 <issue_comment>username_3: ### A PHP 5.6+ solution: ``` // Split the array into chunks of 7 items; the last chunk could be smaller $chunks = array_chunk($array, 7); // Iteratively apply a function to corresponding elements of each array $result = array_map( // The mapping function receives 7 arguments, one from each chunk function(...$values) { // Pack the arguments into a single array return array_sum($values); // Return the sum of arguments }, // Unpack $chunks into individual arguments (7 arrays) ...$chunks ); ``` Read more about the [arguments packing and unpacking](http://php.net/manual/en/migration56.new-features.php#migration56.new-features.splat) using what other languages call *"the **splat** operator"* (`...`). It was introduced in PHP 5.6. ### A PHP 5.3+ solution ``` // Split the array into chunks of 7 items; the last chunk could be smaller $chunks = array_chunk($array, 7); // Prepare the arguments list for array_map() into $chunks // Put the mapping function in front of the arrays array_unshift($chunks, function() { // Return the sum of function arguments return array_sum(func_get_args()); }); // Call array_map() with the arguments stored in $chunks $result = call_user_func_array('array_map', $chunks); ``` Read more about [`func_get_args()`](http://php.net/manual/en/function.func-get-args.php), [`call_user_func_array()`](http://php.net/manual/en/function.call-user-func-array.php) and [anonymous functions](http://php.net/manual/en/functions.anonymous.php). Anonymous functions were introduced in PHP 5.3 ### A solution that works with any PHP version ``` // Initialize the 7 sums with 0 $result = array_fill(0, 7, 0); // Iterate over the array, add each item to the correct sum foreach ($array as $key => $value) { // $key % 7 distributes each value to the next index // starting over on each multiple of 7 $result[$key % 7] += $value; } ``` ### Final word Use the first or the second solution to impress your friends or a recruiter. Use the last solution in production code; it is more clear and, for small input arrays (less than 100 items), it is faster than the other two. For larger arrays, the 5.6+ solution is faster, especially on PHP 7. Upvotes: 3 [selected_answer]
2018/03/22
423
1,348
<issue_start>username_0: What is the difference between in php function * A parameter passage by **variable** * A parameter pass by **reference**?<issue_comment>username_1: The best way to understand it is from an example: ``` function foo($a) { $a = 123; echo "Value in function: " . $a; } function bar(&$a) { $a = 123; echo "Value in function: " . $a; } $var = 555; foo($var); echo "After foo: " . $var; bar($var); echo "After bar: " . $var; ``` Basically you will change the value pointed by the reference, changing it also out of the function scope, while in a normal by-value when the function is finished the changes made to the variable will be lost. Here is an official PHP manual [link](https://secure.php.net/manual/en/functions.arguments.php), with more examples. Upvotes: 1 <issue_comment>username_2: **A parameter passage by value** - value of a variable is passed. ``` $b = 1; function a($c) { $c = 2; // modifying this doesn't change the value of $b, since only the value was passed to $c. } a($b); echo $b; // still outputs 1 ``` **A parameter pass by reference?** - a pointer to a variable is passed. ``` $b = 1; function a($c) { $c = 2; // modifying this also changes the value of $b, since variable $c points to it } a($b); echo $b; // outputs 2 now after calling a(); ``` Upvotes: -1 [selected_answer]
2018/03/22
405
1,295
<issue_start>username_0: I am getting the following error while creating the angular4 new App. **Error:** ``` Error: Path "/app/app.module.ts" does not exist. Path "/app/app.module.ts" does not exist. ``` I have node version `9.4` and `angular-cli version 1.7.1` and when I type like below. ``` subrajyoti@subrajyoti-H81M-S:/var/www/html/angular4-learning$ ng new myapp ``` I have also the write permission o this folder but still getting the above error. Here I need to resolve this error so that I can create new App.<issue_comment>username_1: I just attempted to recreate this issue without any luck. Steps: ``` npm uninstall -g @angular/cli npm cache clean npm install -g @angular/cli ng new foo This worked successfully for me. ``` macOs node: 8.9.0 npm: 5.6.0 @angular/cli: 1.6.3 Upvotes: 0 <issue_comment>username_2: I was also getting the same error, First I thought the issue is in npm but when I ran "npm audit" it shown me 0 vulnerabilities. Then I came to know that issue might be in angluar cli. So I have removed the angular cli, cleared the npm cache and install fresh angular cli. It works! **Steps that I followed:** 1. `npm uninstall -g @angular/cli` 2. `npm install --cache /tmp/empty-cache` 3. `npm install -g @angular/cli` 4. `ng new NewProject` Upvotes: 1
2018/03/22
377
1,214
<issue_start>username_0: ``` import boto3 s3 = boto3.resource('s3') for bucket in s3.buckets.all(): print(bucket.name) ``` but this code does not work, how to import my AWS credentials so that this will return correct output? > > **error :** botocore.exceptions.EndpointConnectionError: Could not connect > to the endpoint URL: "<https://s3.aws-east-2.amazonaws.com/>" > > > ***expected output :*** list of buckets in my aws account.<issue_comment>username_1: I just attempted to recreate this issue without any luck. Steps: ``` npm uninstall -g @angular/cli npm cache clean npm install -g @angular/cli ng new foo This worked successfully for me. ``` macOs node: 8.9.0 npm: 5.6.0 @angular/cli: 1.6.3 Upvotes: 0 <issue_comment>username_2: I was also getting the same error, First I thought the issue is in npm but when I ran "npm audit" it shown me 0 vulnerabilities. Then I came to know that issue might be in angluar cli. So I have removed the angular cli, cleared the npm cache and install fresh angular cli. It works! **Steps that I followed:** 1. `npm uninstall -g @angular/cli` 2. `npm install --cache /tmp/empty-cache` 3. `npm install -g @angular/cli` 4. `ng new NewProject` Upvotes: 1
2018/03/22
890
3,458
<issue_start>username_0: I use a third party library for which i need to change a constant. I would like to customize the library without overwriting the file. The pas file is a library file, not an inheritable class. Currently i can achieve my goal by editing the file ``` unit libraryconstants; interface uses System.Types; const constant1 = 'foo'; constant2 = 32; constant3: Integer = 12; constant4: TSize = (cx: 32; cy: 32); ``` Somehow I need to change `constant4` like this: ``` constant4: TSize = (cx: 16; cy: 8); ``` I can edit libraryconstants.pas and save it, but as i update the library (because a new version is released) i will lose this change. Of course I can remind me to apply this change each time i update the library, but I'd like to avoid this if possible. Since the constant is not a published property i do not know how to achieve the desired result. I'd like to interfere with the library code as less as possible. I am looking for a Delphi language "trick" i do not know. Thanks.<issue_comment>username_1: In project settings (`CTRL`+`SHIFT`+`F11`): ``` Delphi compiler \ Compiling \ Syntax options ``` Change value of "**Assignable typed constants**" to True. Then you can modify typed constants as regular variables: ``` constant4.cx := 16; constant4.cy := 8; ``` Upvotes: -1 <issue_comment>username_2: Make a new UNIT: ``` unit libraryconstantspatch; interface implementation uses System.Types, libraryconstants; initialization asm mov eax,offset libraryconstants.constant4 mov [eax+offset TSize.cx],16 mov [eax+offset TSize.cy],8 end finalization end. ``` then list this unit in the USES statement AFTER the libraryconstants unit in your application. Upvotes: 1 <issue_comment>username_3: I was erroneously under the impression that typed constants are stored in read only memory, as they would be in other languages. That's not the case. So you can change the value of this typed constant quite easily by accessing it via a pointer. ``` PSize(@constant4).cx := 16; PSize(@constant4).cy := 8; ``` Add this code to the initialization section of one of your units. You'll need to make sure that it runs early enough to effect the change before any code that depends on the constant is executed. I think my misapprehension comes about through the knowledge that string literals are stored in read only memory. So I assumed that the same would be true for typed constants. I suspect that when the assignable typed constants "feature" was added, the compiler switch simply made the compiler reject writes to typed constants, rather than also moving them to read only memory. Note that what I say about read only memory is true on the desktop compilers. I am not sure whether or not it is true on the mobile compilers. It may well be the case that this code fails with a runtime memory protection error on the mobile compilers. In which case you would need temporarily to alter the memory protection before writing to it. Upvotes: 3 [selected_answer]<issue_comment>username_4: My suggestion: do not change the constant, change the method. Examine what method (procedure or function) using the constant, then "overload" the method using new constant. If it is in a class, just inherit the class, and modify only the method, using new name, like procedure 'aMethod\_size2'. Name size2 is giving sign about it. This is usual practice as I know. Upvotes: 0
2018/03/22
723
2,608
<issue_start>username_0: I've been using FlatList a lot of times, and never had such experience.I'm having one view with an image on top on of a page and my list is below.When I try to scroll, list bounces to the top. Can not find a good solution for this. Here is my list: ``` index} /> renderDetailsItem({ item, index }) { return (); } ``` Here is my CardDetailsComment component: ``` const CardDetailsComment = (props) => { return ( { props.username } { props.comment } {moment.utc(props.time, 'YYYY-MM-DD HH:mm:ss').local().fromNow()} ); }; const styles = StyleSheet.create({ avatarStyle: { height: 40, width: 40, borderRadius: 20, }, containerStyle: { position: 'relative', top: 415, left: 10, bottom: 5, }, holderStyle: { display: 'flex', flexDirection: 'column', position: 'relative', left: 50, top: -40, }, userStyle: { paddingBottom: 5, }, timeStyle: { paddingBottom: 10, } }); ```<issue_comment>username_1: You need to use the [ScrollView](https://facebook.github.io/react-native/docs/scrollview.html) Upvotes: -1 <issue_comment>username_2: If I'm not wrong, I'm 80% sure that it happened to me and I fix it adding style to FlatList with flex: 1. Try it to see what happen! Upvotes: 2 <issue_comment>username_3: I am not very clear as to what you want to achieve. Your description says you want one image on top of the page and then the list. However on analysing your code i find that you are passing a component to the renderItem in your flatList which will load a list of components ( i.e the length of your data will the time that component will appear on screen ) The component has an image ( i.e number of images will again be the length of your data ) and below this image you are using properties of top, bottom, left to style your text. If you want a single image on top of the page and then the entire list should load, then simply use the `Image` tag in a `View` and then load the `FlatList` below the image. ( This will lead the image to be always on top and the data inside the `FlatList` will be scrollable ) Does this answer your question or have i completely missed your point? Upvotes: 0 <issue_comment>username_4: In my case, I have added `scrollEnabled={false}` by mistake. I removed that and fixed it. if somebody may have the same mistake. that's why I put it as a reply. Upvotes: 2 <issue_comment>username_5: In the cardDetailsComment function, make sure you are setting the height of the parent view (containerStyle) to a number (ex: height: 300). Upvotes: 1
2018/03/22
451
1,795
<issue_start>username_0: In my ionic 3 application, i want to add dynamic content in splash screen so that i can show current version of my application in the splash screen, what should i do?<issue_comment>username_1: You need to use the [ScrollView](https://facebook.github.io/react-native/docs/scrollview.html) Upvotes: -1 <issue_comment>username_2: If I'm not wrong, I'm 80% sure that it happened to me and I fix it adding style to FlatList with flex: 1. Try it to see what happen! Upvotes: 2 <issue_comment>username_3: I am not very clear as to what you want to achieve. Your description says you want one image on top of the page and then the list. However on analysing your code i find that you are passing a component to the renderItem in your flatList which will load a list of components ( i.e the length of your data will the time that component will appear on screen ) The component has an image ( i.e number of images will again be the length of your data ) and below this image you are using properties of top, bottom, left to style your text. If you want a single image on top of the page and then the entire list should load, then simply use the `Image` tag in a `View` and then load the `FlatList` below the image. ( This will lead the image to be always on top and the data inside the `FlatList` will be scrollable ) Does this answer your question or have i completely missed your point? Upvotes: 0 <issue_comment>username_4: In my case, I have added `scrollEnabled={false}` by mistake. I removed that and fixed it. if somebody may have the same mistake. that's why I put it as a reply. Upvotes: 2 <issue_comment>username_5: In the cardDetailsComment function, make sure you are setting the height of the parent view (containerStyle) to a number (ex: height: 300). Upvotes: 1
2018/03/22
475
1,685
<issue_start>username_0: I know this question has been asked a lot already, but although I've been searching for days now I didn't find a suitable answer. We are running Coldfusion 9 Standard with JDK 1.7. I'm trying to perform a request with cfhttp, following code: ``` ``` I get the following when dumping out the result: [![1]](https://i.stack.imgur.com/CqDs9.png) I already imported all certificates in the certificate chain to the right keystore. The CA is Let's Encrypt. Funny thing is, we have another site from which we are asking a webservice, also with certificate from Let's Encrypt and it is working. Accessed from the same Coldfusion server. I also tried following code in onApplicationStart in Application.cfc, but didn't work: ``` ```<issue_comment>username_1: I simply had to add `port="443"` to the `cfhttp` tag, which made the following code works just fine: ``` ``` I'm crying because I didn't try that earlier. Strange thing is that with the other request I don't have to specify the port and it works fine. I also removed the setting below from the JVM Settings. It didn't have any effect on my problem. ``` -Dhttps.protocols=TLSv1.1,TLSv1.2 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Hope, this is related to JRE. Your coldfusion server working with TLS 1.0 i think. So, you need to update the coldfusion server JRE. For adding this, follow below steps, 1. Upgrade to Java 8. 2. Login to ColdFusion Administrator > Java JVM 3. Change the path of the JVM to the new installed path (defaults to: C:\Program Files\Java\jre1.8.0\_102 in windows. ) 4. Restart ColdFusion Server - Service. 5. Re-Test.. it should work now.. Upvotes: 0
2018/03/22
2,782
6,337
<issue_start>username_0: I produced a dynamic pivot with the following query which work but the column (monthyear) are in alphabetical order but I want them in chronological order The monthyear column is derived using a function in SQL Server 2014 ``` CREATE TABLE ##MyTable (Num VARCHAR(10), StartDate DATE, [Types] VARCHAR(10)) INSERT INTO ##MyTable VALUES ('AA1','2016-01-01', 'Type1'),('AA2','2017-01-04', 'Type1'),('AA3','2016-01-04', 'Type1'),('AA4','2017-01-01', 'Type2'), ('AA5','2017-01-10', 'Type3'),('AA6','2016-01-02', 'Type1'),('AA7','2017-01-05', 'Type1'),('AA8','2016-01-12', 'Type1'), ('AA9','2016-01-06', 'Type1'),('AA10','2016-01-10', 'Type3'),('AA11','2017-01-11', 'Type1'),('AA12','2016-01-09', 'Type2'), ('AA13','2016-08-06', 'Type3'),('AA14','2017-01-02', 'Type1'),('AA15','2016-01-05', 'Type1'),('AA16','2017-01-07', 'Type1'), ('AA17','2016-01-04', 'Type1'),('AA18','2017-01-03', 'Type3'),('AA19','2017-01-01', 'Type1'),('AA20','2016-01-10', 'Type2'), ('AA21','2018-01-02', 'Type3'),('AA22','2017-01-10', 'Type1'),('AA23','2017-01-11', 'Type1'),('AA24','2017-01-12', 'Type1'), ('AA25','2017-01-09', 'Type1'),('AA26','2017-01-03', 'Type3'),('AA27','2016-01-07', 'Type1'),('AA28','2017-01-03', 'Type3'), ('AA29','2016-01-09', 'Type3'),('AA30','2017-10-12', 'Type1'),('AA31','2016-01-08', 'Type1'),('AA32','2017-01-10', 'Type1'), ('AA33','2016-01-04', 'Type1'),('AA34','2016-01-03', 'Type1'),('AA35','2018-01-01', 'Type3'),('AA36','2016-01-12', 'Type3'), ('AA37','2017-01-12', 'Type1'),('AA38','2016-01-05', 'Type1'),('AA39','2017-01-01', 'Type1'),('AA40','2017-01-12', 'Type3'), ('AA41','2017-01-07', 'Type1'),('AA42','2017-01-04', 'Type3'),('AA43','2018-01-03', 'Type1'),('AA44','2016-01-08', 'Type1'), ('AA45','2016-09-10', 'Type1'),('AA46','2016-01-11', 'Type3'),('AA47','2017-01-10', 'Type1'),('AA48','2017-01-08', 'Type1'), ('AA49','2017-01-08', 'Type1'),('AA50','2016-01-06', 'Type3'),('AA51','2016-02-08', 'Type3'),('AA52','2017-01-02', 'Type3'), ('AA53','2018-01-01', 'Type3'),('AA54','2016-01-05', 'Type3'),('AA55','2018-01-02', 'Type1'),('AA56','2018-01-01', 'Type1'), ('AA57','2017-01-10', 'Type1'),('AA58','2017-01-11', 'Type3'),('AA59','2018-01-03', 'Type3'),('AA60','2017-01-05', 'Type1'), ('AA61','2016-01-10', 'Type3'),('AA62','2017-01-08', 'Type3'),('AA63','2016-01-06', 'Type2'),('AA64','2017-01-05', 'Type3'), ('AA65','2018-01-01', 'Type3'),('AA66','2017-02-03', 'Type1'),('AA67','2016-01-12', 'Type1'),('AA68','2016-01-11', 'Type3'), ('AA69','2016-01-09', 'Type3'),('AA70','2017-01-12', 'Type2'),('AA71','2016-01-08', 'Type3'),('AA72','2016-01-10', 'Type1'), ('AA73','2017-01-05', 'Type3'),('AA74','2016-01-02', 'Type3'),('AA75','2016-01-12', 'Type3'),('AA76','2016-01-02', 'Type1'), ('AA77','2017-02-08', 'Type1'),('AA78','2016-01-12', 'Type3'),('AA79','2017-01-04', 'Type1'),('AA80','2018-01-01', 'Type2'), ('AA81','2016-01-08', 'Type3'),('AA82','2017-01-11', 'Type1'),('AA83','2017-01-05', 'Type1'); -- -- PIVOT SELECT Num, [Types], StartDate, FORMAT(StartDate,'MMM-yy')AS MonthYear INTO ##MyTable2 FROM ##MyTable ------------------------------------------------------------------------------- DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX); SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(MonthYear) FROM ##MyTable2 c FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = ' SELECT * FROM ( SELECT Num, [Types], MonthYear FROM ##MyTable2) AS PV PIVOT ( COUNT(Num) FOR [MonthYear] IN (' + @cols + ') ) AS PV1' EXECUTE (@query); DROP TABLE ##MyTable; DROP TABLE ##MyTable2; ``` Current output ``` Types Aug-16 Feb-16 Feb-17 Jan-16 Jan-17 Jan-18 Oct-17 Sep-16 Type1 0 0 2 16 22 3 1 1 Type2 0 0 0 3 2 1 0 0 Type3 1 1 0 14 11 5 0 0 ``` Desired output ``` Types Jan-16 Feb-16 Aug-16 Sep-16 Jan-17 Feb-17 Oct-17 Jan-18 Type1 16 0 0 1 22 2 1 3 Type2 3 0 0 0 2 0 0 1 Type3 14 1 1 0 11 0 0 5 ``` Is there a way this can be achieved in sql ?<issue_comment>username_1: You can change the `@cols` query to: ``` SET @cols = STUFF((SELECT ',' + MAX(QUOTENAME(MonthYear)) FROM ##MyTable2 c GROUP BY MONTH(StartDate), YEAR(StartDate) -- use group by instead of distinct ORDER BY YEAR(StartDate), MONTH(StartDate) -- use `order by` here FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') ``` This produces: ``` [Jan-16],[Feb-16],[Aug-16],[Sep-16],[Jan-17],[Feb-17],[Oct-17],[Jan-18] ``` [**Demo here**](http://rextester.com/WGJ31101) **Edit:** (thanks to @EzequielLópezPetrucci) You should also use `'Types, ' + @cols` instead of `*` in order to *explicitly* specify the column order. `*` doesn't guarantee that the ordinal position of each column returned by the `SELECT` will be the same as the position defined on table creation. Upvotes: 3 <issue_comment>username_2: I'd use the following approach to sort the months in ascending order [**Demo**](http://rextester.com/PMLU77595) ``` SELECT Num, [Types], StartDate, FORMAT(StartDate,'MMM-yy')AS MonthYear, CONVERT(INT,REPLACE(CONVERT(VARCHAR(7),StartDate),'-','')) MonthYearSort INTO ##MyTable2 FROM ##MyTable DECLARE @cols AS NVARCHAR(MAX)='', @query AS NVARCHAR(MAX); WITH T AS ( SELECT TOP 100 PERCENT QUOTENAME(MonthYear) MonthYear , MonthYearSort FROM ##MyTable2 GROUP BY QUOTENAME(MonthYear) , MonthYearSort ORDER BY MonthYearSort ) SELECT @cols += ','+ MonthYear FROM T ORDER BY MonthYearSort SET @cols = STUFF(@Cols ,1,1,'') set @query = ' SELECT [Types], '+@cols+' FROM ( SELECT Num, [Types], MonthYear FROM ##MyTable2) AS PV PIVOT ( COUNT(Num) FOR [MonthYear] IN (' + @cols + ') ) AS PV1 EXECUTE (@query); ``` Upvotes: 2 [selected_answer]
2018/03/22
331
1,237
<issue_start>username_0: I currently have this: ``` Press Here For Instructions ``` Followed by: ``` function ins() { document.write("(write instructions)") document.getElementById("demo").innerHTML = ins; } ``` My issue is it goes to a new page when the function runs, how do i keep it on the same page?<issue_comment>username_1: You should read what document.write does, e.g. here: <https://developer.mozilla.org/en-US/docs/Web/API/Document/write> You are trying to change a already closed document, which will instead open a new one. Upvotes: -1 <issue_comment>username_2: //remove document.write dont use it //it is used for debugging purpose instead use console.log which doesnt affect your dom you can view the result in browser itself using F12 key ``` function ins() { document.getElementById("demo").innerHTML = ins; } ``` Upvotes: 0 <issue_comment>username_3: Assuming the element with id `demo` is a `div` and you want to set its content to `Press Here For Instructions` when the button is clicked; this should work for you: ```js function ins() { document.getElementById("demo").innerHTML = "(write instructions)"; } ``` ```html JS Bin Press Here For Instructions ``` Upvotes: 3 [selected_answer]
2018/03/22
1,212
3,606
<issue_start>username_0: I have a "Response" content : [![enter image description here](https://i.stack.imgur.com/PI9FH.png)](https://i.stack.imgur.com/PI9FH.png) But I can't console.log it. Update (15:00 22/03/2018, this is new version) : in actions.component.ts : ``` generatePOR(){ this._api.exportToERP(this.selection).subscribe((res) => { console.log('heelo I am second phase'); console.log(res); }, (error) => console.log(error), () => {}); } ``` in api.ts : ``` generatePOR (idList): any { const apiURL = `${this.API_URL}/purchaseorders/generatePOR`; return this._http.post(apiURL, idList, { headers: new HttpHeaders().set('Content-Type', 'application/json') }); } ``` here is is the console log : ``` ro {headers: Ge, status: 200, statusText: "OK", url: "http://localhost:8080/purchaseorders/generatePOR", ok: false, …}error: {error: SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse () at XMLHttp…, text: "PARTNER\_RELATION\_CUSTOMER\_GROUPCODE;PARTNER\_RELATI…95;2;NEW ORDER PUBLISHED;;;2017-10-289 08:00:00 ↵"}headers: Ge {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}message: "Http failure during parsing for http://localhost:8080/purchaseorders/generatePOR"name: "HttpErrorResponse"ok: falsestatus: 200statusText: "OK"url: "http://localhost:8080/purchaseorders/generatePOR"\_\_proto\_\_: eo ``` Update (16:31) : ``` generatePOR (idList): any { const apiURL = `${this.API_URL}/purchaseorders/generatePOR`; this.PORresult = this._http.post(apiURL, idList, { observe: 'response', headers: new HttpHeaders({'Content-Type': 'application/json'}), responseType: 'text' as 'text' }) .map((res, i) => { console.log('hi'); console.log(res); }); return this.PORresult; } ``` output : ``` hi ao {headers: Ge, status: 200, statusText: "OK", url: "http://localhost:8080/purchaseorders/generatePOR", ok: true, …}body: "PARTNER_RELATION_CUSTOMER_GROUPCODE;PARTNER_RELATION_CUSTOMER_PLANTCODE;PO_UpdateVersion;PARTNER_RELATION_SUPPLIER_NOLOCAL;PO_PoNumber;PO_PosNumber;PO_RequestNumber;PARTNER_RELATION_SUPPLIER_NO;PO_CollabPrice;PO_CollabPromQty;PO_Status;PO_SupAckNumber;PO_CollabComment;PO_CollabPromDate ↵PARTNER_RELATION_CUSTOMER_GROUPCODE;PARTNER_RELATION_CUSTOMER_PLANTCODE;1;PARTNER_RELATION_SUPPLIER_NOLOCAL;4500634818;00070;0001;PARTNER_RELATION_SUPPLIER_NO;464.95;2;NEW ORDER PUBLISHED;;;2017-10-289 08:00:00 ↵"headers: Ge {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}ok: truestatus: 200statusText: "OK"type: 4url: "http://localhost:8080/purchaseorders/generatePOR"__proto__: eo heelo I am second phase undefined ```<issue_comment>username_1: You should read what document.write does, e.g. here: <https://developer.mozilla.org/en-US/docs/Web/API/Document/write> You are trying to change a already closed document, which will instead open a new one. Upvotes: -1 <issue_comment>username_2: //remove document.write dont use it //it is used for debugging purpose instead use console.log which doesnt affect your dom you can view the result in browser itself using F12 key ``` function ins() { document.getElementById("demo").innerHTML = ins; } ``` Upvotes: 0 <issue_comment>username_3: Assuming the element with id `demo` is a `div` and you want to set its content to `Press Here For Instructions` when the button is clicked; this should work for you: ```js function ins() { document.getElementById("demo").innerHTML = "(write instructions)"; } ``` ```html JS Bin Press Here For Instructions ``` Upvotes: 3 [selected_answer]
2018/03/22
579
2,004
<issue_start>username_0: I've got an Azure Hybrid Application [On-Premise SQL DB & Azure WebApp].I've created an Azure Hybrid connection manager with endpoint w.r.to my On-premise DB in Windows10 machine. The Status of my hybrid connected shows **Not Connected** Any help on this would be of great help[![Hybrid Connection Status](https://i.stack.imgur.com/dvw74.png)](https://i.stack.imgur.com/dvw74.png) I remember Azure Hybrid connection is configured with Service Bus. I'm not sure but seen [here](https://stackoverflow.com/questions/46823422/azure-hybrid-connection-manager-does-not-work) that Listener should be enabled. Its first time, i'm experimenting, kindly suggest<issue_comment>username_1: > > I'm not sure but seen here that Listener should be enabled. > > > Yes, the Listener could be enabled. I add a hybrid connection and the status is also Not connected. You could follow my steps. 1.Download connection manager and install it. [![enter image description here](https://i.stack.imgur.com/hDHQT.jpg)](https://i.stack.imgur.com/hDHQT.jpg) 2.Enter Manually - enter your connection string in your hybrid connection properties - Add Then you can see the status is Connected on Hybrid Manager and Azure Portal. [![enter image description here](https://i.stack.imgur.com/tt5Ec.jpg)](https://i.stack.imgur.com/tt5Ec.jpg) [![enter image description here](https://i.stack.imgur.com/Vvb4a.jpg)](https://i.stack.imgur.com/Vvb4a.jpg) [![enter image description here](https://i.stack.imgur.com/Sw2gU.jpg)](https://i.stack.imgur.com/Sw2gU.jpg) For more details, you could refer to this [article](https://github.com/Huachao/azure-content/blob/master/includes/app-service-hybrid-connections-manager-install.md). Upvotes: 3 [selected_answer]<issue_comment>username_2: Just in case it might help someone else: I was getting the same problem until I tried to restart the Windows Service "Azure Hybrid Connection Manager Service" AND reopened Hybrid Connection Manager (v.0.7.7) Upvotes: 5
2018/03/22
711
2,279
<issue_start>username_0: I am trying to push a host file to my adb device. So, I did: ``` [~/Library/Android/sdk/tools]$ emulator -avd Nexus_5X_API_26_x86 -writable-system emulator: WARNING: System image is writable emulator: ### WARNING: /etc/localtime does not point to /usr . /share/zoneinfo/, can't determine zoneinfo timezone name emulator: ### WARNING: /etc/localtime does not point to /usr/share/zoneinfo/, can't determine zoneinfo timezone name ``` Now in a different console I do `adb push hosts /system/etc/hosts` But I get the follwing error: > > adb: error: failed to copy 'hosts' to '/system/etc/hosts': remote couldn't create file: Read-only file system > hosts: 0 files pushed. 0.1 MB/s (93 bytes in 0.001s) > > > Any suggestions?<issue_comment>username_1: Try this: ``` $emulator -avd Nexus_5X_API_26_x86 -writable-system $adb root $adb remount $adb push hosts /system/etc/hosts ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: For those coming here in 2020: In my case the steps in the answer didn't work as the version `30` API didn't support a writable system. I had to use the version `28` API version. Upvotes: 4 <issue_comment>username_3: Maybe its a missing directory! ------------------------------ Make sure you're pushing to a directory which exists. I made a mistake and added a `~` at the start when trying to push photos to the pictures folder on my emulator: it should be `adb push -s emulator-5554 harold /sdcard/Pictures`. I often navigate the system first, with `adb shell` For 2020, --------- **API level 30** has not changed anything, username_2s existing answer is just wrong, as I have always seen it work with API level 30 devices with & without Play Store (see the screenshot, named `Pixel_4_API_30`): > > username_2: the version 30 API didn't support a writable system. > > > [![Screenshot](https://i.stack.imgur.com/67h8R.png)](https://i.stack.imgur.com/67h8R.png) Upvotes: 0 <issue_comment>username_4: I found I needed the extra step of disabling verification. Have this working on emulators up to android 32 (current) ``` emulator -writable-system -- @emulator_name adb root adb shell avbctl disable-verification adb reboot adb remount adb push ./local.file /remote-location ``` Upvotes: 1
2018/03/22
667
2,167
<issue_start>username_0: I can't figure out why I get a foreign key mismatch with the sqlite below: ``` PRAGMA foreign_keys=ON; CREATE TABLE a ( id INT NOT NULL, PRIMARY KEY (id)); CREATE TABLE b ( a_id INT NOT NULL, id INT NOT NULL, PRIMARY KEY (a_id, id), FOREIGN KEY (a_id) REFERENCES a(id)); CREATE TABLE c ( b_id INT NOT NULL, id INT NOT NULL, PRIMARY KEY (b_id, id), FOREIGN KEY (b_id) REFERENCES b(id)); insert into a VALUES (1); insert into b VALUES (1, 2); insert into c VALUES (2, 3); ``` The last line causes: ``` Error: foreign key mismatch - "c" referencing "b" ``` What am I doing wrong?<issue_comment>username_1: Try this: ``` $emulator -avd Nexus_5X_API_26_x86 -writable-system $adb root $adb remount $adb push hosts /system/etc/hosts ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: For those coming here in 2020: In my case the steps in the answer didn't work as the version `30` API didn't support a writable system. I had to use the version `28` API version. Upvotes: 4 <issue_comment>username_3: Maybe its a missing directory! ------------------------------ Make sure you're pushing to a directory which exists. I made a mistake and added a `~` at the start when trying to push photos to the pictures folder on my emulator: it should be `adb push -s emulator-5554 harold /sdcard/Pictures`. I often navigate the system first, with `adb shell` For 2020, --------- **API level 30** has not changed anything, username_2s existing answer is just wrong, as I have always seen it work with API level 30 devices with & without Play Store (see the screenshot, named `Pixel_4_API_30`): > > username_2: the version 30 API didn't support a writable system. > > > [![Screenshot](https://i.stack.imgur.com/67h8R.png)](https://i.stack.imgur.com/67h8R.png) Upvotes: 0 <issue_comment>username_4: I found I needed the extra step of disabling verification. Have this working on emulators up to android 32 (current) ``` emulator -writable-system -- @emulator_name adb root adb shell avbctl disable-verification adb reboot adb remount adb push ./local.file /remote-location ``` Upvotes: 1
2018/03/22
1,220
3,614
<issue_start>username_0: I am working on drawing dxf files in Java. So far I am able to draw, `LINES`, `POLYLINES`, `TEXT`, `CIRCLE`, `ARC`, `LWPOLYLINES`. But I am having problems on drawing `INSERT` entities. I know this is mapped to block entities but when I draw them nothing get displayed. I understand you have to do some transformation on `INSERT` entities but I have no idea how to do that. I Googled a lot about this but no luck. So I hope you can give some direction how to process the `INSERT` entities. I also looked at some frameworks like ycad and dxf-code but that code is difficult to trace. What is the algortihm for translation `INSERT` to entities like `LINE` and `ARC` Thanks Johan<issue_comment>username_1: It is hard to provide you a definitive answer because we see no code. But the way `INSERT` features are managed is described on the AutoDesk website. Here is the information for [blocks in DXF files](https://www.autodesk.com/techpubs/autocad/acadr14/dxf/blocks_in_dxf_files_al_u05_c.htm). It also provides information about two important entries [`BLOCK`](https://www.autodesk.com/techpubs/autocad/acadr14/dxf/block_al_u05_c.htm) and [`ENDBLCK`](https://www.autodesk.com/techpubs/autocad/acadr14/dxf/endblk_al_u05_c.htm). Here is an example of a block that has a `LINE` and an `ARC` in it. The block will look like this: [![Block](https://i.stack.imgur.com/VCDX2.png)](https://i.stack.imgur.com/VCDX2.png) The block is called **SAMPLE**: ``` 0 BLOCK 8 0 2 SAMPLE 70 0 10 0.0 20 0.0 30 0.0 3 SAMPLE 1 0 ARC 5 263 8 0 10 0.0 20 22.4468613708478415 30 0.0 40 242.9028467109147016 50 354.6976825438280798 51 185.3023174561718918 0 LINE 5 264 8 0 10 -241.8634560136443099 20 0.0000000000001137 30 0.0 11 241.8634560136443099 21 -0.0000000000002274 31 0.0 0 ENDBLK 5 262 8 0 ``` Basically, you have an entry which defines the block entities. It will have an **origin** and all the values are relative to the origin for the elements. If you design it first then you will know what to do. Once you have the `BLOCK` defined you will be able to use it as an [`INSERT`](https://www.autodesk.com/techpubs/autocad/acadr14/dxf/insert_al_u05_c.htm). --- The `BLOCK` itself. The key is the origin. Most are defined with a coordinate of 0,0,0. Then the `ENTITIES` are drawn relative to this origin for a scale of 1:1. Imagine a rectangle that is 1 unit square for the scale factor of one. Then the coordinates would be: ``` -0.5, 0.5 0.5, 0.5 0.5, -0.5 -0.5, -0.5 ``` I hope this information helps you. Upvotes: 2 <issue_comment>username_2: The `BLOCK` entity (otherwise known as a Block Definition) is essentially the 'blueprints' for an `INSERT` (otherwise known as a Block Reference). Rather than duplicating all of the geometric information constituting the block for every block reference in a drawing, the block definition (`BLOCK` entity) is a 'template' for each block reference, meaning that only the position, rotation & scale of each block reference need be stored. The Block Definition resides within the Block Symbol Table and is comprised of a `BLOCK` header entity (defining the block name and origin (usually 0,0) among other properties), followed by all geometry forming the block definition, and finally a terminating `ENDBLK` entity. All geometry contained within the Block Definition is defined relative to the origin of the Block Definition; then, when a Block Reference (`INSERT`) is created, the Block Definition geometry is transformed relative to the insertion point of the Block Reference. Upvotes: 0
2018/03/22
398
1,468
<issue_start>username_0: I'm trying to add my package in doze whitelist. With `($ adb shell dumpsys deviceidle whitelist +PACKAGE)`, I can add my package in whitelist, and this command makes change in the **`file /data/system/deviceidle.xml.`** Now, I'm curious about who generate `deviceidle.xml.` Is there anyone who knows about `deviceidle.xml`?<issue_comment>username_1: I found a clue in framework module, **`IDeviceController.addPowerSaveWhitelistApp(String name)`** helps to add my package into ; also, /data/system/deviceidle.xml is updated. You can check with adb dumpsys `$ adb shell dumpsys deviceidle` `$ adb shell cat /data/system/deviceidle.xml` Upvotes: 2 <issue_comment>username_2: As far as I know, doze whitelisting is done by system creators. You can ask user for whitelisting via intent action: Settings.ACTION\_IGNORE\_BATTERY\_OPTIMIZATION\_SETTINGS. In the [DeviceIdleController soruce code](https://android.googlesource.com/platform/frameworks/base/+/master/services/core/java/com/android/server/DeviceIdleController.java) you can see that it reads deviceidle.xml in constructor. It might be that, if you know the file structure and have rooted device you can manually create and edit this file. ``` @VisibleForTesting DeviceIdleController(Context context, Injector injector) { super(context); mInjector = injector; mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml")); [...] } ``` Upvotes: 0
2018/03/22
505
1,936
<issue_start>username_0: How to do these check via powershell. I have some resources like 1. FunctionApp 2. FunctionAppService 3. EventHub Namespace 4. Storage Account 5. ServiceBus [![enter image description here](https://i.stack.imgur.com/vuE84.png)](https://i.stack.imgur.com/vuE84.png) I am able to verify the EventHub Namespace and Storage account via built-in cmdlets available. like **Get-AzureRmStorageAccountNameAvailability** and **Test-AzureRmEventHubName**, but I cannot achieve any custom logic that can check if the name of the entered resource is valid. Some users tend to provide name's to resources that are most commonly used, so I have partially avoided this by appending some unique characters to the resources, but it will be good to have cmdlets or such for other types of resources too. Thanks<issue_comment>username_1: I found a clue in framework module, **`IDeviceController.addPowerSaveWhitelistApp(String name)`** helps to add my package into ; also, /data/system/deviceidle.xml is updated. You can check with adb dumpsys `$ adb shell dumpsys deviceidle` `$ adb shell cat /data/system/deviceidle.xml` Upvotes: 2 <issue_comment>username_2: As far as I know, doze whitelisting is done by system creators. You can ask user for whitelisting via intent action: Settings.ACTION\_IGNORE\_BATTERY\_OPTIMIZATION\_SETTINGS. In the [DeviceIdleController soruce code](https://android.googlesource.com/platform/frameworks/base/+/master/services/core/java/com/android/server/DeviceIdleController.java) you can see that it reads deviceidle.xml in constructor. It might be that, if you know the file structure and have rooted device you can manually create and edit this file. ``` @VisibleForTesting DeviceIdleController(Context context, Injector injector) { super(context); mInjector = injector; mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml")); [...] } ``` Upvotes: 0
2018/03/22
688
1,833
<issue_start>username_0: I want to interleave `interElem` after every 2 list elements. ### Data: ``` listi <- c(rbind(letters[1:4], list(c(13,37)))) interElem <- c("inter","leavistan") ``` looks like: ``` > listi [[1]] [1] "a" [[2]] [1] 13 37 [[3]] [1] "b" [[4]] [1] 13 37 [[5]] [1] "c" [[6]] [1] 13 37 [[7]] [1] "d" [[8]] [1] 13 37 > ``` Desired result (list element numbers are not accurate) ====================================================== ``` > listi [[1]] [1] "a" [[2]] [1] 13 37 [[XXX]] [1] "inter" "leavistan" [[3]] [1] "b" [[4]] [1] 13 37 [[XXX]] [1] "inter" "leavistan" [[5]] [1] "c" [[6]] [1] 13 37 [[XXX]] [1] "inter" "leavistan" [[7]] [1] "d" [[8]] [1] 13 37 > ```<issue_comment>username_1: I found a clue in framework module, **`IDeviceController.addPowerSaveWhitelistApp(String name)`** helps to add my package into ; also, /data/system/deviceidle.xml is updated. You can check with adb dumpsys `$ adb shell dumpsys deviceidle` `$ adb shell cat /data/system/deviceidle.xml` Upvotes: 2 <issue_comment>username_2: As far as I know, doze whitelisting is done by system creators. You can ask user for whitelisting via intent action: Settings.ACTION\_IGNORE\_BATTERY\_OPTIMIZATION\_SETTINGS. In the [DeviceIdleController soruce code](https://android.googlesource.com/platform/frameworks/base/+/master/services/core/java/com/android/server/DeviceIdleController.java) you can see that it reads deviceidle.xml in constructor. It might be that, if you know the file structure and have rooted device you can manually create and edit this file. ``` @VisibleForTesting DeviceIdleController(Context context, Injector injector) { super(context); mInjector = injector; mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml")); [...] } ``` Upvotes: 0
2018/03/22
317
1,065
<issue_start>username_0: Using SQL in PostgreSQL I need to select all the rows from my table called "crop" when the first digit of the integer numbers in column "field\_id" is 7. ``` select * from crop where (left (field_id,1) = 7) ```<issue_comment>username_1: First, you know that the column is a number, so I would be inclined to explicitly convert it, no matter what you do: ``` where left(crop::text, 1) = '7' where crop::text like '7%' ``` The conversion to `text` is simply to be explicit about what is happening and it makes it easier for Postgres to parse the query. More importantly, if the value has a fixed number of digits, then I would suggest using a numeric range; something like this: ``` where crop >= 700000 and crop < 800000 ``` This makes it easier for Postgres to use an index on the column. Upvotes: 2 <issue_comment>username_2: Try with cast, like this: ``` select * from crop where cast(substring(cast(field_id as varchar(5)),1,1) as int) = 7 ``` where 5 in varchar(5) you should put number how long is your integer. Upvotes: 0
2018/03/22
1,441
3,872
<issue_start>username_0: I am trying to extract the json content in my javascript by running it but I am not getting the desired output My JSON is of the form ``` var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; ``` The loop which I am trying to extract content from JSON is ``` for(var index=0;index-![]({% static )',json[index].size\_x,json[index].size\_y,json[index].col,json[index].row); }; ``` What I want is ``` ![]({% static ) #for first elemet ``` I am sure I am missing some comma in it but not sure where exactly **Update 1** The `"{% static 'images/abc.jpg' %}"` This is exact comma structure I want in my ouput **Update 2** Here's a snippet console logging the arguments I'm creating: ```js var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; for (var index = 0; index < json.length; index++) { console.log('- -![]({% static ) ', json[index].size_x, json[index].size_y, json[index].col, json[index].row); }; ```<issue_comment>username_1: Your loop is returning this ``` - -![]({% static ) 2 2 1 1 - -![]({% static ) 2 2 4 1 - -![]({% static ) 2 2 6 1 - -![]({% static ) 1 1 1 3 - -![]({% static ) 1 1 4 3 - -![]({% static ) 1 1 6 3 ``` You might have extra comma here: "images/def.jpg," at index=1 Upvotes: 1 <issue_comment>username_2: if you replace gridster.add\_widget with console.log, the output looks fine: ``` ![]({% static ) ``` Try adding space before closing tag: ``` ..json[index].html+'" %}"> ^here ``` Upvotes: 0 <issue_comment>username_3: You have a problem with the use of quotes. Fix it be prefixing your inner `'` characters with a slash `\'` (this is called *escaping*): ``` gridster.add_widget('- -![]({% static \'images/'+json[index].html+'\'%}) ',json[index].size_x,json[index].size_y,json[index].col,json[index].row); ``` ```js var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; for (var index = 0; index < json.length; index++) { console.log('![]({% static \'images/' + json[index].html + '\' %})'); }; ``` Upvotes: 2 [selected_answer]
2018/03/22
824
2,315
<issue_start>username_0: I'm trying to re-write a python algorithm to Java for some needs. In python algorithm I have the following code : ``` row_ind, col_ind = linear_sum_assignment(cost) ``` `linear_sum_assignment` is a [scipy function](https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.optimize.linear_sum_assignment.html) Do you guys know an equivalent of that function in java ? I found [this one](https://github.com/KevinStern/software-and-algorithms/blob/master/src/main/java/blogspot/software_and_algorithms/stern_library/optimization/HungarianAlgorithm.java) but I didn't get the row indice and column indice in this one.<issue_comment>username_1: Your loop is returning this ``` - -![]({% static ) 2 2 1 1 - -![]({% static ) 2 2 4 1 - -![]({% static ) 2 2 6 1 - -![]({% static ) 1 1 1 3 - -![]({% static ) 1 1 4 3 - -![]({% static ) 1 1 6 3 ``` You might have extra comma here: "images/def.jpg," at index=1 Upvotes: 1 <issue_comment>username_2: if you replace gridster.add\_widget with console.log, the output looks fine: ``` ![]({% static ) ``` Try adding space before closing tag: ``` ..json[index].html+'" %}"> ^here ``` Upvotes: 0 <issue_comment>username_3: You have a problem with the use of quotes. Fix it be prefixing your inner `'` characters with a slash `\'` (this is called *escaping*): ``` gridster.add_widget('- -![]({% static \'images/'+json[index].html+'\'%}) ',json[index].size_x,json[index].size_y,json[index].col,json[index].row); ``` ```js var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; for (var index = 0; index < json.length; index++) { console.log('![]({% static \'images/' + json[index].html + '\' %})'); }; ``` Upvotes: 2 [selected_answer]
2018/03/22
1,362
4,299
<issue_start>username_0: I am trying to setup code coverage on our **ASP.NET Core 2.0** web application. I use **dotcover** (from JetBrains) to provide code coverage on all my other builds (by running dotcover from the command-line during the build process). When I run dotcover from our build server for our .NET Core 2.0 web app I see this. [![enter image description here](https://i.stack.imgur.com/vdRqu.png)](https://i.stack.imgur.com/vdRqu.png) It states that it has run successfully but then just hangs there and no code coverage files are created. ``` dotcover analyse /TargetExecutable:"C:\Program Files\dotnet\dotnet.exe" /TargetArguments:"test MyUnitTests.csproj" /Output:report.html /ReportType:HTML /LogFile=dotcover.log ``` If I try and add code coverage collection I see this. [![enter image description here](https://i.stack.imgur.com/3ASiu.png)](https://i.stack.imgur.com/3ASiu.png) ``` dotcover analyse /TargetExecutable:"C:\Program Files\dotnet\dotnet.exe" /TargetArguments:"test MyUnitTests.csproj --collect:coverage" /Output:report.html /ReportType:HTML /LogFile=dotcover.log ``` And finally if I run **dotnet test** on its own (without dotcover) it seems to have worked, but again no coverage output is created. [![enter image description here](https://i.stack.imgur.com/W8UBB.png)](https://i.stack.imgur.com/W8UBB.png) ``` dotnet test "MyUnitTests.csproj" -- collect:coverage ``` I'm unsure how to generate code coverage for a .NET Core 2.0 app, and not sure how / what data collectors are and how they should be used. Is dotcover the data collector in this example? Basically, I just want to generate code coverage for a .NET Core 2.0 application. **UPDATE:** As per the suggestion I have installed *coverlet* as an alternative to *dotcover*. I have got it working but am getting inconsistent behaviour. When I run my batch file from the server it's all fine. [![enter image description here](https://i.stack.imgur.com/HZuWh.png)](https://i.stack.imgur.com/HZuWh.png) But when run from TFS I get an error. [![enter image description here](https://i.stack.imgur.com/BbRSz.png)](https://i.stack.imgur.com/BbRSz.png) **System.IO.FileNotFoundException: No test is available in . Make sure test project has a nuget reference of package "Microsoft.NET.Test.Sdk" and framework version settings are appropriate and try again.** My project **does** have a reference to that assembly (it's installed by default by VS itself when you create a unit test project). Why is TFS complaining about that assembly when it's definitely there and can be run manually from the command-line without an error?<issue_comment>username_1: Your loop is returning this ``` - -![]({% static ) 2 2 1 1 - -![]({% static ) 2 2 4 1 - -![]({% static ) 2 2 6 1 - -![]({% static ) 1 1 1 3 - -![]({% static ) 1 1 4 3 - -![]({% static ) 1 1 6 3 ``` You might have extra comma here: "images/def.jpg," at index=1 Upvotes: 1 <issue_comment>username_2: if you replace gridster.add\_widget with console.log, the output looks fine: ``` ![]({% static ) ``` Try adding space before closing tag: ``` ..json[index].html+'" %}"> ^here ``` Upvotes: 0 <issue_comment>username_3: You have a problem with the use of quotes. Fix it be prefixing your inner `'` characters with a slash `\'` (this is called *escaping*): ``` gridster.add_widget('- -![]({% static \'images/'+json[index].html+'\'%}) ',json[index].size_x,json[index].size_y,json[index].col,json[index].row); ``` ```js var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; for (var index = 0; index < json.length; index++) { console.log('![]({% static \'images/' + json[index].html + '\' %})'); }; ``` Upvotes: 2 [selected_answer]
2018/03/22
1,166
4,216
<issue_start>username_0: I'm using inline formsets in Django, and for each item showing one "extra" form, for adding another object. The forms for existing objects have "Delete" checkboxes, for removing that object, which makes sense. But also the "extra" forms have these "Delete" checkboxes... which makes no sense because there's nothing there to delete. Inline forms in the Django admin don't show these "Delete" checkboxes for "extra" forms. How can I remove these checkboxes on the "extra" inline forms? The inline formsets part of my template is something like this ([simplified, full version on GitHub](https://github.com/philgyford/django-nested-inline-formsets-example/blob/master/publishing/books/templates/books/publisher_update.html#L54)): ``` {% for bookimage_form in form.forms %} {% for hidden_field in bookimage_form.hidden_fields %} {{ hidden_field.errors }} {% endfor %} {{ bookimage_form.as_table }} {% endfor %} ``` And here's the "Delete" checkbox that seems superfluous: [![example screenshot](https://i.stack.imgur.com/OA7EO.png)](https://i.stack.imgur.com/OA7EO.png)<issue_comment>username_1: You can use the [can\_delete](https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.can_delete) setting of the `InlineModelAdmin` class (`TabularInline` inherits from `InlineModelAdmin`): ``` class BookImageInline(admin.TabularInline): model = BookImage extra = 1 can_delete = False ``` Upvotes: 3 <issue_comment>username_2: here's a way to get there in the template when you're looping through forms: ``` {% if bookimage_form.instance.pk %} **{{ bookimage\_form.DELETE.label\_tag }}** {{ bookimage_form.DELETE}} {% else %} {% endif %} ``` you won't be able to use the `as_table()` method I don't think, though. You'll have to express every other field in the form. Here's another thing you could try out after you initialise the form, but before it goes into the context: ``` for f in form.forms: if not f.instance.pk: f.fields['DELETE'] = None ``` Not sure how that'll come out in the table, but you may be able to monkey with the idea. Upvotes: 1 <issue_comment>username_3: My suggest is to render the template in nested for loops and add this: ``` {% if forloop.parentloop.last and forloop.last%} not render form filds {% else %} render field {% endif %} ``` Upvotes: 0 <issue_comment>username_4: Update for Django 3.2+ ([link](https://docs.djangoproject.com/en/3.2/topics/forms/formsets/#can-delete-extra)), you can now pass in `can_delete_extra` as False to formset\_factory or it extended classes to remove checkbox from extra forms > > can\_delete\_extra New in Django 3.2. > > > BaseFormSet.can\_delete\_extra > > > Default: True > > > While setting can\_delete=True, specifying can\_delete\_extra=False will > remove the option to delete extra forms. > > > For anyone having Django version under 3.2 and do not wish to upgrade, please use the following method of overriding the BaseFormSet: ``` class CustomFormSetBase(BaseModelFormSet): def add_fields(self, form, index): super().add_fields(form, index) if 'DELETE' in form.fields and form.instance.pk: # check if have instance form.fields['DELETE'] = forms.BooleanField( label=_('Delete'), widget=forms.CheckboxInput( attrs={ 'class': 'form-check-input' } ), required=False ) else: form.fields.pop('DELETE', None) YourFormSet = modelformset_factory( formset=CustomFormSetBase, can_delete=True, extra=2 ) ``` *only took them 13 years to add this >.> <https://code.djangoproject.com/ticket/9061>* Upvotes: 2 <issue_comment>username_5: I found a way to remove the delete checkbox in the official django documentation [here](https://docs.djangoproject.com/en/3.2/topics/forms/formsets/) you just have to add 'can\_delete=false' as an argument to inlineformset\_factory in your views.py file ``` inlineformset_factory(can_delete=false) ``` Upvotes: 2
2018/03/22
1,195
4,151
<issue_start>username_0: ``` #include using namespace std; ``` I want the user to input two char sequences (such as adc and abd) and the program will tell them that the characters are equal as a whole or not.(the output now would be FALSE ) I am not sure what to do with declaring my char variables. ``` char x[100]{}; char y[100]{}; ``` This is my isEqual function to work out if the two char values are the same ``` void isEqual(char x , char y) { for ( int i = 0 ; x[i] != '\0';i++){ for ( int j = 0 ; y[j] != '\0'; j++){ if ( x[i]==y[j]){ cout<<"TRUE"; }else{ cout<<"FALSE"; } } } } ``` So the user inputs two char variables here and then I call the isEqual function to see if they are True or False. ``` int main() { cout<<"Enter first characters :"; cin>>x; cout<<"Enter second characters :"; cin>>y; isEqual(x,y); } ```<issue_comment>username_1: In your example, you have one mistake and one unclarity. 1. Mistake: You have defined x and y like this: ``` char x[100]{}; char y[100]{}; ``` After words you create a method, which has two parameters: ``` void isEqual(char x , char y) ``` If you notice, x and y are char arrays. Meanwhile the method isEqual has two parameters, which are just char and not char arrays. So whenever you want to use the first two elements in the method, it will be impossible, because of this incosistency. 2. In this example, I understand, that you want to compare actually two strings. Only comparing the strings to be more exact. As such there is a far easier and better way to compare groups of chars using strings: ``` #include #include using namespace std; int main() { string x, y; cin >> x >> y; if (x.compare(y) == 0) /\*They are equal\*/ { cout << "True"; } else { cout << "False"; } } ``` This is a simple example, which uses functions from libraries, already existing in c++. You can check this [page](http://www.cplusplus.com/reference/string/string/compare/) for more details on the compare function mentioned above. Supposing you are a begginer, the most important part, you should understand at the beggining, to be able to use it later on: * 0: They compare equal * smaller than 0: Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter. * greater than 0: Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer. Upvotes: 2 <issue_comment>username_2: Char is a single character like 'a', "abc" is not a char variable it is string varibale. Comparing char not differs form comparing any other type like integer numbers just use == operator: ``` char a = 'a'; char b = 'b'; bool isSame = a == b; ``` Is same will be false in this case. In C there is no variable type for string, so you should use array of chars, and you couldn't use == operator, there is a special function for it, it's called [strcmp](http://www.cplusplus.com/reference/cstring/strcmp/): ``` const char* string1 = "I am a string"; const char* string2 = "I am a string"; int isEqual = strcmp( string1, string2 ); ``` In this case isEqual will return 0, means that string is equal, don't get confused by this, see description for details of meaning values. In C++ there is special class for strings it's called [std::string](http://en.cppreference.com/w/cpp/string/basic_string), also there is a speciali defined [== operator](http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp) for this type, so you can use it as usual: ``` std::string string1 = "I am a string"; std::string string2 = "I am a string"; bool isEqual = string1 == string2; ``` Or you can use method [compare](http://en.cppreference.com/w/cpp/string/basic_string/compare) wich is same as strcmp: ``` std::string string1 = "I am a string"; std::string string2 = "I am a different string"; int res = string1.compare( string2 ); ``` In this case res will be equal to 1 Upvotes: 1
2018/03/22
616
2,294
<issue_start>username_0: I have a customer who likes to do some basic stuff in Domino Designer in a specific database. He only works with Forms, agents etc and never do any Xpages stuff. I have done all the xpages stuff in the Database. This morning when I opened designer I can see that almost all of the xpages design object has been signed by him. but he has not opened any of the xpages design objects. (only forms) and have not signed the application. When I look at the webpage I can see that the designn changes I did from a few days back have disapeared, so I seem to be looking at an older version of my webpage. If I go in to the application and Build the application with my id everything is back to normal. This scenario seem to repeat only a few times a week even though my customer do changes to the application every day. Image show the xpages time stamp this morning which seem to be about the same time my customer opened the application in designer. [![enter image description here](https://i.stack.imgur.com/tIpIr.jpg)](https://i.stack.imgur.com/tIpIr.jpg) Currently we are both using 9.0.1 FP10 but I have also seen this problem before FP10 ps. Not sure if it is related but my customer also have another version of Domino Designer (8.5.3 Swedish) which he use when signing agents as signing them with v9 cause them to not work. What can be the cause of this behaviour and how can I avoid it. thanks Thomas<issue_comment>username_1: Open Designer. From the top menu, select Project > Build Automatically and ensure it is disabled (not checked). [![DDE disable build automatically ](https://i.stack.imgur.com/5KnDf.png)](https://i.stack.imgur.com/5KnDf.png) For additional reading, refer to <NAME>'s wonderful article "Taming Domino Designer" <https://nathantfreeman.files.wordpress.com/2013/04/tamingdesigner.pdf> Upvotes: 3 <issue_comment>username_2: I am pretty sure that it's the 8.5.3 Designer that does the rebuild when opening the database in Designer. So this happens when the user just wants to sign some agents. This problematic behaviour has been fixed in 9.0.1 (or perhaps in a fix pack release of 9.0.1). See this IBM technote about the problem: <http://www-01.ibm.com/support/docview.wss?uid=swg1LO80591> Upvotes: 2 [selected_answer]
2018/03/22
376
1,573
<issue_start>username_0: The code below runs however when I go to run the application in an android emulator the application will open then close immediately .I am an android programming beginner thankyou the code in question is below ``` login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String emailString =email.getText().toString(); String pwd =password.getText().toString(); if(!emailString.equals("")&& !pwd.equals("")){ mAuth.signInWithEmailAndPassword(emailString,pwd) .addOnCompleteListener(MainActivity.this, new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if(!task.isSuccessful()){ Toast.makeText(MainActivity.this,"Unrecognised Credentials",Toast.LENGTH\_LONG).show(); } else { Toast.makeText (MainActivity.this,"recognised Credentials",Toast.LENGTH\_LONG).show(); } } }); } @Override protected void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } @Override protected void onStop() { super.onStop(); if(mAuthListener != null){ mAuth.removeAuthStateListener(mAuthListener); } } } ```<issue_comment>username_1: Make sure your loginActivity or MainActivity, whatever. That is define in AndroidManifest file. and check onCreate method again, is there any syntax mistake. Upvotes: 0 <issue_comment>username_2: Initialize FirebaseAuth.and put .json file in app folder ``` mFirebaseAuth = FirebaseAuth.getInstance(); ``` Upvotes: 1
2018/03/22
291
988
<issue_start>username_0: I was trying to check the length of second field of a TSV file (hundreds of thousands of lines). However, it runs very very slowly. I guess it should be something wrong with "echo", but not sure how to do. Input file: ``` prob name 1.0 Claire 1.0 Mark ... ... 0.9 GFGKHJGJGHKGDFUFULFD ``` So I need to print out what went wrong in the name. I tested with a little example using "head -100" and it worked. But just can't cope with original file. This is what I ran: ``` for title in `cat filename | cut -f2`;do length=`echo -n $line | wc -m` if [ "$length" -gt 10 ];then echo $line fi done ```<issue_comment>username_1: Make sure your loginActivity or MainActivity, whatever. That is define in AndroidManifest file. and check onCreate method again, is there any syntax mistake. Upvotes: 0 <issue_comment>username_2: Initialize FirebaseAuth.and put .json file in app folder ``` mFirebaseAuth = FirebaseAuth.getInstance(); ``` Upvotes: 1
2018/03/22
1,164
4,874
<issue_start>username_0: I am trying to use PDF.js to view PDF documents. I find the display really low resolutions to the point of being blurry. Is there a fix? [![enter image description here](https://i.stack.imgur.com/3UVjA.jpg)](https://i.stack.imgur.com/3UVjA.jpg) ``` // URL of PDF document var url = "https://www.myFilePath/1Mpublic.pdf"; // Asynchronous download PDF PDFJS.getDocument(url) .then(function(pdf) { return pdf.getPage(1); }) .then(function(page) { // Set scale (zoom) level var scale = 1.2; // Get viewport (dimensions) var viewport = page.getViewport(scale); // Get canvas#the-canvas var canvas = document.getElementById('the-canvas'); // Fetch canvas' 2d context var context = canvas.getContext('2d'); // Set dimensions to Canvas canvas.height = viewport.height; canvas.width = viewport.width; // Prepare object needed by render method var renderContext = { canvasContext: context, viewport: viewport }; // Render PDF page page.render(renderContext); }); ```<issue_comment>username_1: There are two things you can do. I tested and somehow it worked, but you will get a bigger memory consumption. 1. Go to pdf.js and change the parameter `MAX_GROUP_SIZE` to like `8192` (double it for example). Be sure to have your browser cache disabled while testing. 2. You can force the `getViewport` to retrieve the image in better quality but like, I don't know how to say in English, compress it so a smaller size while showing: ```js // URL of PDF document var url = "https://www.myFilePath/1Mpublic.pdf"; // Asynchronous download PDF PDFJS.getDocument(url) .then(function(pdf) { return pdf.getPage(1); }) .then(function(page) { // Set scale (zoom) level var scale = 1.2; // Get viewport (dimensions) var viewport = page.getViewport(scale); // Get canvas#the-canvas var canvas = document.getElementById('the-canvas'); // Fetch canvas' 2d context var context = canvas.getContext('2d'); // Set dimensions to Canvas var resolution = 2 ; // for example canvas.height = resolution * viewport.height; //actual size canvas.width = resolution * viewport.width; canvas.style.height = viewport.height; //showing size will be smaller size canvas.style .width = viewport.width; // Prepare object needed by render method var renderContext = { canvasContext: context, viewport: viewport, transform: [resolution, 0, 0, resolution, 0, 0] // force it bigger size }; // Render PDF page page.render(renderContext); } ); ``` Hope it helps! Upvotes: 4 <issue_comment>username_2: This code will help you, my issue was pdf was not rendering in crisp quality according with the responsiveness. So I searched, and modified my code like this. Now it works for rendering crisp and clear pdf according to the div size you want to give. ```js var loadingTask = pdfjsLib.getDocument("your_pdfurl"); loadingTask.promise.then(function(pdf) { console.log('PDF loaded'); // Fetch the first page var pageNumber = 1; pdf.getPage(pageNumber).then(function(page) { console.log('Page loaded'); var container = document.getElementById("container") // Container of the body var wrapper = document.getElementById("wrapper"); // render your pdf inside a div called wrapper var canvas = document.getElementById('pdf'); var context = canvas.getContext('2d'); const pageWidthScale = container.clientWidth / page.view[2]; const pageHeightScale = container.clientHeight / page.view[3]; var scales = { 1: 3.2, 2: 4 }, defaultScale = 4, scale = scales[window.devicePixelRatio] || defaultScale; var viewport = page.getViewport({ scale: scale }); canvas.height = viewport.height; canvas.width = viewport.width; var displayWidth = Math.min(pageWidthScale, pageHeightScale);; canvas.style.width = `${(viewport.width * displayWidth) / scale}px`; canvas.style.height = `${(viewport.height * displayWidth) / scale}px`; // Render PDF page into canvas context var renderContext = { canvasContext: context, viewport: viewport }; var renderTask = page.render(renderContext); renderTask.promise.then(function() { console.log('Page rendered'); }); }); }, function(reason) { // PDF loading error console.error(reason); }); ``` Upvotes: 1
2018/03/22
477
1,762
<issue_start>username_0: I'm trying to show user group name instead of it's id . I have this serilizer class for user class and I used this `User = auth.get_user_model()` for user Model but it show NULL instead of theier name .. when i delete get\_groups function i will see related groups id why ? what is correct way to get all users group? ``` class UserSerializer(ModelSerializer): groups = SerializerMethodField() def get_groups(self, obj): return obj.groups.name class Meta: model = User fields = [ 'id', 'username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login', 'is_staff', 'is_superuser', 'is_active', 'groups' ] ```<issue_comment>username_1: try it ``` groups = serializers.SlugRelatedField(many=True, read_only=True, slug_field="name") ``` Upvotes: 2 <issue_comment>username_2: Try this, ``` class UserSerializer(ModelSerializer): def get_groups(self, obj): return obj.groups.values_list('name', flat=True) class Meta: model = User fields = [ 'id', 'username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login', 'is_staff', 'is_superuser', 'is_active', 'groups' ] ``` This would return all grups related to paricular user as `list` **Example:** ``` In [5]: user =User.objects.get(id=1) In [6]: user.groups.values_list('name',flat=True) Out[6]: ['grp_name_1', 'grp_name_2'] In [8]: user.groups.all() Out[8]: [, ] ``` Upvotes: 2 [selected_answer]
2018/03/22
559
1,713
<issue_start>username_0: I am trying to take latitude and longitude values from cllocation. Its coming full location data. Since I need only latitude and longitude data to send my back end. I have to send multiple latitude and longitude data to server. Even I tried with CLLocationCoordinate2D, but, its taking CLLocationCoordinate inside the data while sending to server. > > I want to take in single array both latitude and longitude, not in two > arrays. > > > Can anyone suggest me, how to take only latitude and longitude values > to append to array in swift? > > > Here is my code ``` var myLocations: [CLLocation] = [] func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { myLocations.append(locations[0] as CLLocation) } ``` > > > ``` > output is > > ``` > > ``` <+10.92088132,+77.56955708> +/- 1414.00m (speed -1.00 mps / course -1.00) @ 22/03/18, 1:17:30 PM India Standard Time [<+10.92088132,+77.56955708> +/- 1414.00m (speed -1.00 mps / course -1.00) @ 22/03/18, 1:17:30 PM India Standard Time] ```<issue_comment>username_1: You can try ``` let loc = myLocations.last let lat = currentLocation.coordinate.latitude let lon = currentLocation.coordinate.longitude ``` then declare arr like this ``` var myLocations: [String] = [] let last = locations[0] as CLLocation myLocations.append("\(last.coordinate.latitude),\(last.coordinate.longitude)") ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` var location = CLLocation() location = myLocations.last! as CLLocation let lat = location.coordinate.latitude let longit = location.coordinate.longitude ``` Upvotes: 1
2018/03/22
496
1,677
<issue_start>username_0: I am trying to execute the below code in pycharm. ``` def auth_login(func): def wrapper(*args, **kwargs): print("Authenticating......") func(*args, **kwargs) return wrapper() @auth_login def login(username, password): print("Successfully logged in:",username) login('setu', 'setu') ``` Looks pretty straight forward but I getting the below error: Output : ``` > Traceback (most recent call last): > Authenticating...... > File "C:/Users/611834094/PycharmProjects/PractiseProject/decorators/example3.py", > line 10, in > @auth\_login > File "C:/Users/611834094/PycharmProjects/PractiseProject/decorators/example3.py", > line 7, in auth\_login > return wrapper() > File "C:/Users/611834094/PycharmProjects/PractiseProject/decorators/example3.py", > line 5, in wrapper > func(\*args, \*\*kwargs) > TypeError: login() missing 2 required positional arguments: 'username' and 'password' > > Process finished with exit code 1 ```<issue_comment>username_1: You are returning the value of wrapper. Instead just return the function. ``` def auth_login(func): def wrapper(*args, **kwargs): print("Authenticating......") func(*args, **kwargs) return wrapper # Here was the issue. @auth_login def login(username, password): print("Successfully logged in:",username) login('setu', 'setu') ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Remove the brackets while returning wrapper function ``` def auth_login(func): def wrapper(*args, **kwargs): print("Authenticating......") func(*args, **kwargs) # Remove the brackets from wrapper return wrapper ``` Upvotes: 1
2018/03/22
1,324
4,823
<issue_start>username_0: Sorry for this such long pot but I need help here. I am new to Android World and follows the book "Android Development" by <NAME> (The Big Nerd Ranch). All goes well but now I got stuck. When I run my application, it crashes with this line of code ``` String text = Integer.toString(question); ``` According to book, it shows me the Question Text. I changed my code to this as well but it show me 0. ``` String text = Integer.toString(Integer.toString(question)); ``` Any solution for this. Thanks in Advance. Here is my complete code. QuizActivity.java ``` package com.example.subrose.geoquiz; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class QuizActivity extends AppCompatActivity { private Button mTrueButton; private Button mFalseButton; private Button mNextButton; private TextView mQuestionTextView; private Question[] mQuestionBank = new Question[]{ new Question(R.string.question_oceans,true), new Question(R.string.question_mideast, false), new Question(R.string.question_africa, false), new Question(R.string.question_americas, true), new Question(R.string.question_asia, true), }; private int mCurrentIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz); mQuestionTextView = (TextView)findViewById(R.id.question_text_view); int question = mQuestionBank[mCurrentIndex].getTextResId(); mQuestionTextView.setText(question); mTrueButton = (Button)findViewById(R.id.true_button); mTrueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show(); } }); mFalseButton = (Button)findViewById(R.id.false_button); mFalseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(QuizActivity.this, R.string.incorrect_toast, Toast.LENGTH_SHORT).show(); } }); } } ``` Question.java ``` public class Question { private int mTextResId; private boolean mAnswerTrue; public Question(int mTextResId, boolean mAnswerTrue) { mTextResId = mTextResId; mAnswerTrue = mAnswerTrue; } public int getTextResId() { return mTextResId; } public void setTextResId(int textResId) { mTextResId = textResId; } public boolean isAnswerTrue() { return mAnswerTrue; } public void setAnswerTrue(boolean answerTrue) { mAnswerTrue = answerTrue; } } ``` Strings.xml ``` GeoQuiz True False Next Correct! Incorrect! Settings The Pacific Ocean is larger than the Atlantic Ocean. The Suez Canal connects the Red Sea and the Indian Ocean. The source of the Nile River is in Egypt. The Amazon River is the longest river in the Americas. Lake Baikal is the world\'s oldest and deepest freshwater lake. ``` activity\_quiz.xml ``` xml version="1.0" encoding="utf-8"? ```<issue_comment>username_1: you can't set integer in settext so change code from `mQuestionTextView.setText(question);` to replace with ``` mQuestionTextView.setText(String.valueOf(question)); ``` Upvotes: 1 <issue_comment>username_2: Why don't you check using: ``` mQuestionTextView.setText(getString(mQuestionBank[mCurrentIndex].getTextResId())); ``` Anyway, I didn't see any error in your Code to set the text in your View. Upvotes: 0 <issue_comment>username_3: ``` int question = mQuestionBank[mCurrentIndex].getTextResId(); mQuestionTextView.setText(question); ``` to set integer in TextView you have below possibilities : replace it with: ``` mQuestionTextView.setText(String.format(Locale.US, "%d", question)); ``` or ``` mQuestionTextView.setText(question+""); ``` or ``` mQuestionTextView.setText(String.valueOf(question)); ``` Upvotes: 1 <issue_comment>username_4: The main problem in your constructor . Change it as below. ``` public Question(int mTextResId, boolean mAnswerTrue) { this.mTextResId = mTextResId; this.mAnswerTrue = mAnswerTrue; } ``` You should use `this` in data shadowing . Currently value is not assigned to instance variable cause you just used local ones. That's why they are returning the default value. Do it as above . Apart from that `setText()` has several variant if you are using a resource id the you can directly use `setText(int id)`. Read [setText varients](https://developer.android.com/reference/android/widget/TextView.html#setText(int)) . Upvotes: 2 [selected_answer]
2018/03/22
1,031
3,771
<issue_start>username_0: It has been already clarified what's the difference between `val` and `const val` [here](https://stackoverflow.com/questions/37595936/what-is-the-difference-between-const-and-val). But my question is, why we should use `const` keyword? There is no difference from the generated Java code perspective. This Kotlin code: ``` class Application private val testVal = "example" private const val testConst = "another example" ``` Generates: ``` public final class ApplicationKt { private static final String testVal = "example"; private static final String testConst = "another example"; } ```<issue_comment>username_1: In my opinion the main difference is that `val` means that no setter will be generated for the property (but a getter will be generated) and not that the value is constant, while a `const val` is a constant (like a Java's `private/public static final xxx`). Example: ``` class Foo { private val testVal: String get() = Random().nextInt().toString() } ``` Upvotes: 2 <issue_comment>username_2: It's not always the same generated code. If `testVal` and `testConst` were `public`, the generated code wouldn't be the same. `testVal` would be `private` with a `public` `get`, whereas `testConst` would be `public`, without any getter. So `const` avoids generating a getter. Upvotes: 2 <issue_comment>username_3: As directly mentioned in the documentation, `testConst` can be used in annotation parameters, but `testVal` can't. More generally speaking, `const` *guarantees* that you have a constant variable in the Java sense, and > > [Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1), reachability (§14.21), and definite assignment (§16.1.1).](https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.12.4) > > > Upvotes: 2 <issue_comment>username_4: There are also differences in using them. Example of constants(Kotlin): ``` class Constants { companion object { val EXAMPLE1 = "example1" // need companion and a getter const val EXAMPLE2 = "example2" // no getter, but companion is generated and useless @JvmField val EXAMPLE3 = "example3"; // public static final with no getters and companion } } ``` How to use(Java): ``` public class UseConstants { public void method(){ String ex1 = Constants.Companion.getEXAMPLE1(); String ex2 = Constants.EXAMPLE2; String ex3 = Constants.EXAMPLE3; } } ``` Upvotes: 0 <issue_comment>username_5: You don't see the difference between generated code because your variables are `private`. Otherwise the result would have the `getter` for `testVal`: ``` public final class ApplicationKt { @NotNull private static final String testVal = "example"; @NotNull public static final String testConst = "another example"; @NotNull public static final String getTestVal() { return testVal; } } ``` So in your particular case it is the same, except you can use `const` properties in `annotations`: ``` const val testVal: String = "This subsystem is deprecated" @Deprecated(testVal) fun foo() { ... } ``` Upvotes: 2 <issue_comment>username_6: "Consts" are compile time Constants whereas "val" is used to define constants at run time. This means, that "consts" can never be assigned to a function or any class constructor, but only to a String or primitive. Example: ``` const val NAME = "<NAME>" val PICon = getPI() fun getPI(): Double { return 3.14 } fun main(args: Array) { println("Name : $NAME") println("Value of PI : $PICon") } ``` Output: ``` Name : <NAME> Value of PI : 3.14 ``` Upvotes: 0
2018/03/22
1,167
4,133
<issue_start>username_0: I am uploading product programmatically in Magento2 I have same name product with different SKU but when I run script Magento 2 gives an error because of Url Key : `Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'reine-de-naples-jour-nuit-8998.html-1' for key 'URL_REWRITE_REQUEST_PATH_STORE_ID` my script is those we use to save a product programmatically ``` php use Magento\Framework\App\Bootstrap; include('app/bootstrap.php'); $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap-getObjectManager(); $objectManager1 = Magento\Framework\App\ObjectManager::getInstance(); $directoryList = $objectManager1->get('\Magento\Framework\App\Filesystem\DirectoryList'); $path = $directoryList->getPath('media'); //var_dump($path); die; $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $myarray = glob("Book2.csv"); usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);')); if(count($myarray)){ /*This will create an array of associative arrays with the first row column headers as the keys.*/ $csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1])); array_walk($csv_map, function(&$a) use ($csv_map) { $a = array_combine($csv_map[0], $a); }); array_shift($csv_map); # remove column header /*End*/ $message = ''; $count = 1; foreach($csv_map as $data){ //echo ' ``` ';print_r($data);exit; $product = $objectManager->create('Magento\Catalog\Model\Product'); $product->setName(trim($data['Name'])); $product->setTypeId('simple'); $product->setAttributeSetId(4); $product->setSku(trim($data['model_no'])); $product->setURL(trim($data['Name']).trim($data['model_no'])); $product->setWebsiteIds(array(1)); $product->setVisibility(4); $product->setCreatedAt(strtotime('now')); $product->setPrice(trim($data['price'])); //$_product->setShortDescription(trim($data['Short Description'])); // add text attribute //$_product->setDescription(trim($data['Long Description'])); // add text attribute $img_url = trim($data['img_big']); //$lastWord = substr($img_url, strrpos($img_url, '/') + 1); //copy($img_url, 'pub/media/product/'); $dir = $directoryList->getPath('media').'/big/'; $imgpath = $dir.$img_url; //echo $imgpath; die; /*$_product->addImageToMediaGallery($imgpath, array('image','thumbnail','small_image'), false, false); */ $product->addImageToMediaGallery($imgpath, array('image', 'small_image', 'thumbnail'), false, false); //$_product->setImage($imgpath); //$_product->setSmallImage($imgpath); //$_product->setThumbnail($imgpath); $product->setStockData(array( 'use_config_manage_stock' => 0, //'Use config settings' checkbox 'manage_stock' => 1, //manage stock 'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart 'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart 'is_in_stock' => 1, //Stock Availability 'qty' => 100 //qty ) ); $product->save(); } echo'success'; } ?> ``` ``` please suggest how to add Url key to script my script is working fine without the same name<issue_comment>username_1: Have you tried omitting that field, so Magento generates the **url\_key** itself? If you want **model\_no** to be in the url (due to SEO requirements, I suppose) you'd better add it to name, which could be even better for SEO ``` $product->setName(trim($data['Name']) . trim($data['model_no'])); ``` Feel free to join <https://magento.stackexchange.com/questions> & post more details about what you want Upvotes: 2 <issue_comment>username_2: You are using set on wrong attribute i.e `setUrl()` instead you should use `setUrlKey()` and because you are not setting different url keys so magento is trying to use name for generating url keys and as you have same names for multiple products so it ends up trying to save same keys for multiple products which is giving you this error. Upvotes: 0
2018/03/22
701
2,268
<issue_start>username_0: Is there a simple way to escape all occurrences of `\` in a string? I start with the following string: ```cpp #include #include std::string escapeSlashes(std::string str) { // I have no idea what to do here return str; } int main () { std::string str = "a\b\c\d"; std::cout << escapeSlashes(str) << "\n"; // Desired output: // a\\b\\c\\d return 0; } ``` Basically, I am looking for the inverse to [this](https://stackoverflow.com/q/5612182/4920424) question. The problem is that I cannot search for `\` in the string, because C++ already treats it as an escape sequence. **NOTE:** ~~I am not able to change the string str in the first place. It is parsed from a LaTeX file. Thus, [this](https://stackoverflow.com/a/12103512/4920424) answers to a similar question does not apply.~~ **Edit:** The parsing failed due to an unrelated problem, the question here is about string literals. **Edit:** There are nice solutions to find and replace known escape sequences, such as [this](https://stackoverflow.com/a/2417770/4920424) answer. Another option is to use `boost::regex("\p{cntrl}")`. However, I haven't found one that works for unknown (erroneous) escape sequences.<issue_comment>username_1: You can use raw string literal. See <http://en.cppreference.com/w/cpp/language/string_literal> ``` #include #include int main() { std::string str = R"(a\b\c\d)"; std::cout << str << "\n"; return 0; } ``` Output: ``` a\b\c\d ``` Upvotes: 3 <issue_comment>username_2: It is not possible to convert the string literal `a\b\c\d` to `a\\b\\c\\d`, i.e. escaping the backslashes. Why? Because the compiler converts `\c` and `\d` directly to `c` and `d`, respectively, giving you a warning about `Unknown escape sequence \c` and `Unknown escape sequence \d` (`\b` is fine as it is a valid escape sequence). This happens directly to the string literal before you have any chance to work with it. To see this, you can compile to assembler ``` gcc -S main.cpp ``` and you will find the following line somewhere in your assembler code: ``` .string "a\bcd" ``` Thus, your problem is either in your parsing function or you use string literals for experimenting and you should use raw strings `R"(a\b\c\d)"` instead. Upvotes: 1
2018/03/22
1,557
5,123
<issue_start>username_0: How to call a nested Rails route from Ember app if I don't need nested templates ? I have the following routes in Rails router: ``` # routes.rb resources :shops do resources :shop_languages end ``` So to get a list of shop languages the `shops/:shop_id/shop_languages` should be hit. Here is ShopsLanguagesController: ``` # controllers/shop_languages_controller.rb class ShopLanguagesController < ApplicationController before_action :find_shop def index json_response @shop.shop_languages, :ok, include: 'language' end private def find_shop @shop = Shop.find(params[:shop_id]) end end ``` In Ember app I have the routes defined as follows: ``` # router.js Router.map(function() { ... this.route('languages', { path: '/shops/:shop_id/shop_languages'}); }); ``` In Ember `application.hbs` template the languages link is defined as follows ``` # application.hbs {{#link-to 'languages' currentUser.user.shop.id class="nav-link"}} .. {{/link-to}} ``` In Ember `languages.js` route handler, I'm trying to load shop languages: ``` # routes/languages.js model(params) { return this.store.query('shop-language', { shop_id: params.shop_id }) } ``` Ember hits `/shop-languages` end-point instead of the nested one `shops/:shop_id/shop_languages`. Of course, I've defined the corresponding models on Ember side: ``` # models/shop-language.js import DS from 'ember-data'; export default DS.Model.extend({ shop: DS.belongsTo('shop'), language: DS.belongsTo('language'), modified_by: DS.attr('string') }); ``` What is wrong with that and how to get it work? Thank you<issue_comment>username_1: The short answer; requests made to the server do not match your route structure, but are based on your model and the adapter you're using e.g. REST vs JSON API based on that the URL called at your server may differ. So to get your `/shop/:id/` added as a prefix for your `shop-language` query you'll have to override the default behavior of your adapter. To get started generate an adapter for your model `ember g adapter shop-language` In your new adapter you'll probably have to override 2 functions 1) `query` (<https://github.com/emberjs/data/blob/master/addon/adapters/rest.js#L549>) 2) `urlForQuery` (<https://github.com/emberjs/data/blob/master/addon/-private/adapters/build-url-mixin.js#L188>) Also look at `buildURL` (<https://github.com/emberjs/data/blob/master/addon/-private/adapters/build-url-mixin.js#L55>) which handles all different scenarios. In 1) you probably want to remove the `shop_id` from the query params so you don't end up with an URL like `/shops/1/shop-languages?shop_id=1` In 2) you'll have to add `/shops/1` to your URL based on the passed query params Upvotes: 2 <issue_comment>username_2: Thanks to @username_1 here is a solution I came to to get it work. **On Ember side** Declare the languages route as follows: ``` #router.js Router.map(function() { this.route('languages', { path: 'shops/:shopId/languages'}); .. }); ``` Modify/create `languages.js` route handler as follows: ``` #routes/languages.js import Route from '@ember/routing/route'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; export default Route.extend(AuthenticatedRouteMixin, { model(params) { return this.store.query('shop-language', { shopId: params.shopId}); } }); ``` Create/modify `shop-language.js` adapter as follows: ``` #adapters/shop-language.js export default ApplicationAdapter.extend({ urlForQuery (query) { return this._buildShopUrl(query.shop_id) }, urlForCreateRecord(modelName, snapshot) { return this._buildShopUrl(snapshot.belongsTo('shop').id); }, urlForDeleteRecord(id, modelName, snapshot) { return this._buildShopUrl(snapshot.id, id); }, _buildShopUrl(shop_id, id) { if (id) { return `shops/${shop_id}/languages/${id}`; } return `shops/${shop_id}/languages`; } }); ``` Add a link to load shop languages to your template: ``` #templates/application.hbs ... {{#link-to 'languages' currentUser.user.shop.id class="nav-link"}} ... {{/link-to}} ``` Display shop languages in `languages.hbs` template: ``` #templates/languages.hbs {{#each model as |lang|}} * {{lang.tag}} {{/each}} ``` **On Rails API side** Declare a shop\_languages resource as nested route: ``` #routes.rb ... resources :shops do resources :shop_languages, path: '/languages' end ``` Load shop languages in `ShopLanguagesController`: ``` #controllers/shop_languages_controller.rb class ShopLanguagesController < ApplicationController before_action :find_shop def index json_response @shop.languages, :ok end private def find_shop @shop = Shop.find(params[:shop_id]) end end ``` I'll have one thing to do - remove `?shopId=613` from the URL and fix the params hash that contains a kind of double values: ``` Started GET "/shops/613/languages?shopId=613" for 127.0.0.1 at 2018-03-23 10:05:53 +0100 Processing by ShopLanguagesController#index as JSONAPI Parameters: {"shopId"=>"613", "shop_id"=>"613"} ``` Upvotes: 0
2018/03/22
1,986
7,237
<issue_start>username_0: I have used `ReactDOM.createPortal` inside the render method of a stateful component like so: ``` class MyComponent extends Component { ... render() { return ( {ReactDOM.createPortal(, 'dom-location')} ) } } ``` ... but can it also be used by a stateless (functional) component?<issue_comment>username_1: Yes, according to [docs](https://reactjs.org/docs/portals.html) the main requirements are: > > The first argument (child) is any renderable React child, such as an element, string, or fragment. The second argument (container) is a DOM element. > > > In case of stateless component you can pass element via props and render it via portal. Hope it will helps. Upvotes: 2 <issue_comment>username_2: ``` const X = ({ children }) => ReactDOM.createPortal(children, 'dom-location') ``` Upvotes: 1 <issue_comment>username_3: It can be done like this for a fixed component: ``` const MyComponent = () => ReactDOM.createPortal(, 'dom-location') ``` or, to make the function more flexible, by passing a `component` prop: ``` const MyComponent = ({ component }) => ReactDOM.createPortal(component, 'dom-location') ``` Upvotes: 5 [selected_answer]<issue_comment>username_4: > > **can it also be used by a stateless (functional) component > ?** > > > yes. ``` const Modal = (props) => { const modalRoot = document.getElementById('myEle'); return ReactDOM.createPortal(props.children, modalRoot,); } ``` Inside render : ``` render() { const modal = this.state.showModal ? ( ) : null; return ( ); } ``` Working [`codesandbox#demo`](https://codepen.io/riyajk/pen/MVmzMb?editors=0011) Upvotes: 3 <issue_comment>username_5: Will chime in with an option where you dont want to manually update your index.html and add extra markup, this snippet will dynamically create a div for you, then insert the children. ```js export const Portal = ({ children, className = 'root-portal', el = 'div' }) => { const [container] = React.useState(() => { // This will be executed only on the initial render // https://reactjs.org/docs/hooks-reference.html#lazy-initial-state return document.createElement(el); }); React.useEffect(() => { container.classList.add(className) document.body.appendChild(container) return () => { document.body.removeChild(container) } }, []) return ReactDOM.createPortal(children, container) } ``` Upvotes: 6 <issue_comment>username_6: Portal with SSR (NextJS) ------------------------ If you are trying to use any of the above with SSR (for example NextJS) you may run into difficulty. The following should get you what you need. This methods allows for passing in an id/selector to use for the portal which can be helpful in some cases, otherwise it creates a default using **`__ROOT_PORTAL__`**. If it can't find the selector then it will create and attach a div. **NOTE**: you could also statically add a div and specify a known id in `pages/_document.tsx` (or .jsx) if again using NextJS. Pass in that id and it will attempt to find and use it. ``` import { PropsWithChildren, useEffect, useState, useRef } from 'react'; import { createPortal } from 'react-dom'; export interface IPortal { selector?: string; } const Portal = (props: PropsWithChildren) => { props = { selector: '\_\_ROOT\_PORTAL\_\_', ...props }; const { selector, children } = props; const ref = useRef() const [mounted, setMounted] = useState(false); const selectorPrefixed = '#' + selector.replace(/^#/, ''); useEffect(() => { ref.current = document.querySelector(selectorPrefixed); if (!ref.current) { const div = document.createElement('div'); div.setAttribute('id', selector); document.body.appendChild(div); ref.current = div; } setMounted(true); }, [selector]); return mounted ? createPortal(children, ref.current) : null; }; export default Portal; ``` Usage ----- The below is a quickie example of using the portal. It does NOT take into account position etc. Just something simple to show you usage. Sky is limit from there :) ``` import React, { useState, CSSProperties } from 'react'; import Portal from './path/to/portal'; // Path to above const modalStyle: CSSProperties = { padding: '3rem', backgroundColor: '#eee', margin: '0 auto', width: 400 }; const Home = () => { const [visible, setVisible] = useState(false); return ( <> Hello World [setVisible(true)}>Show Modal](#) {visible ? Hello Modal! [setVisible(false)}>Close](#) : null} ); }; export default Home; ``` Upvotes: 2 <issue_comment>username_7: TSX version based on @username_5's answer (React 17, TS 4.1): ``` // portal.tsx import * as React from 'react' import * as ReactDOM from 'react-dom' interface IProps { className? : string el? : string children : React.ReactNode } /** * React portal based on https://stackoverflow.com/a/59154364 * @param children Child elements * @param className CSS classname * @param el HTML element to create. default: div */ const Portal : React.FC = ( { children, className, el = 'div' } : IProps ) => { const [container] = React.useState(document.createElement(el)) if ( className ) container.classList.add(className) React.useEffect(() => { document.body.appendChild(container) return () => { document.body.removeChild(container) } }, []) return ReactDOM.createPortal(children, container) } export default Portal ``` Upvotes: 3 <issue_comment>username_8: Sharing my solution: ``` // PortalWrapperModal.js import React, { useRef, useEffect } from 'react'; import ReactDOM from 'react-dom'; import $ from 'jquery'; const PortalWrapperModal = ({ children, onHide, backdrop = 'static', focus = true, keyboard = false, }) => { const portalRef = useRef(null); const handleClose = (e) => { if (e) e.preventDefault(); if (portalRef.current) $(portalRef.current).modal('hide'); }; useEffect(() => { if (portalRef.current) { $(portalRef.current).modal({ backdrop, focus, keyboard }); $(portalRef.current).modal('show'); $(portalRef.current).on('hidden.bs.modal', onHide); } }, [onHide, backdrop, focus, keyboard]); return ReactDOM.createPortal( <>{children(portalRef, handleClose)}, document.getElementById('modal-root') ); }; export { PortalWrapperModal }; ``` Upvotes: 0 <issue_comment>username_9: IMPORTANT useRef/useState to prevent bugs ========================================= It's important that you use useState or useRef to store the element you created via document.createElement because otherwise it gets recreated on every re-render ``` //This div with id of "overlay-portal" needs to be added to your index.html or for next.js _document.tsx const modalRoot = document.getElementById("overlay-portal")!; //we use useRef here to only initialize el once and not recreate it on every rerender, which would cause bugs const el = useRef(document.createElement("div")); useEffect(() => { modalRoot.appendChild(el.current); return () => { modalRoot.removeChild(el.current); }; }, []); return ReactDOM.createPortal( {renderImages()} , el.current ); ``` Upvotes: 2
2018/03/22
2,153
7,771
<issue_start>username_0: ``` // int c = 1; public System.Windows.Forms.Button AddNewButton() { System.Windows.Forms.Button btn = new System.Windows.Forms.Button(); this.Controls.Add(btn); btn.Top = 350; btn.Left = c * 80; btn.Text = "" + this.c.ToString(); btn.Name = "MButton" + this.c.ToString(); c = c + 1; return btn; } // AddNewButton(); AddNewButton(); . . . AddNewButton(); // Create the button through the for statement. ``` I dynamically generate buttons. When I click the generated button 1 Console.WriteLine("Click\_Button1"); When I click the generated button 2 Console.WriteLine("Click\_Button2"); . . . When I click the generated button 50 Console.WriteLine("Click\_Button50"); --- In this way I want to create a dynamic event. How can I generate a dynamic event?<issue_comment>username_1: Yes, according to [docs](https://reactjs.org/docs/portals.html) the main requirements are: > > The first argument (child) is any renderable React child, such as an element, string, or fragment. The second argument (container) is a DOM element. > > > In case of stateless component you can pass element via props and render it via portal. Hope it will helps. Upvotes: 2 <issue_comment>username_2: ``` const X = ({ children }) => ReactDOM.createPortal(children, 'dom-location') ``` Upvotes: 1 <issue_comment>username_3: It can be done like this for a fixed component: ``` const MyComponent = () => ReactDOM.createPortal(, 'dom-location') ``` or, to make the function more flexible, by passing a `component` prop: ``` const MyComponent = ({ component }) => ReactDOM.createPortal(component, 'dom-location') ``` Upvotes: 5 [selected_answer]<issue_comment>username_4: > > **can it also be used by a stateless (functional) component > ?** > > > yes. ``` const Modal = (props) => { const modalRoot = document.getElementById('myEle'); return ReactDOM.createPortal(props.children, modalRoot,); } ``` Inside render : ``` render() { const modal = this.state.showModal ? ( ) : null; return ( ); } ``` Working [`codesandbox#demo`](https://codepen.io/riyajk/pen/MVmzMb?editors=0011) Upvotes: 3 <issue_comment>username_5: Will chime in with an option where you dont want to manually update your index.html and add extra markup, this snippet will dynamically create a div for you, then insert the children. ```js export const Portal = ({ children, className = 'root-portal', el = 'div' }) => { const [container] = React.useState(() => { // This will be executed only on the initial render // https://reactjs.org/docs/hooks-reference.html#lazy-initial-state return document.createElement(el); }); React.useEffect(() => { container.classList.add(className) document.body.appendChild(container) return () => { document.body.removeChild(container) } }, []) return ReactDOM.createPortal(children, container) } ``` Upvotes: 6 <issue_comment>username_6: Portal with SSR (NextJS) ------------------------ If you are trying to use any of the above with SSR (for example NextJS) you may run into difficulty. The following should get you what you need. This methods allows for passing in an id/selector to use for the portal which can be helpful in some cases, otherwise it creates a default using **`__ROOT_PORTAL__`**. If it can't find the selector then it will create and attach a div. **NOTE**: you could also statically add a div and specify a known id in `pages/_document.tsx` (or .jsx) if again using NextJS. Pass in that id and it will attempt to find and use it. ``` import { PropsWithChildren, useEffect, useState, useRef } from 'react'; import { createPortal } from 'react-dom'; export interface IPortal { selector?: string; } const Portal = (props: PropsWithChildren) => { props = { selector: '\_\_ROOT\_PORTAL\_\_', ...props }; const { selector, children } = props; const ref = useRef() const [mounted, setMounted] = useState(false); const selectorPrefixed = '#' + selector.replace(/^#/, ''); useEffect(() => { ref.current = document.querySelector(selectorPrefixed); if (!ref.current) { const div = document.createElement('div'); div.setAttribute('id', selector); document.body.appendChild(div); ref.current = div; } setMounted(true); }, [selector]); return mounted ? createPortal(children, ref.current) : null; }; export default Portal; ``` Usage ----- The below is a quickie example of using the portal. It does NOT take into account position etc. Just something simple to show you usage. Sky is limit from there :) ``` import React, { useState, CSSProperties } from 'react'; import Portal from './path/to/portal'; // Path to above const modalStyle: CSSProperties = { padding: '3rem', backgroundColor: '#eee', margin: '0 auto', width: 400 }; const Home = () => { const [visible, setVisible] = useState(false); return ( <> Hello World [setVisible(true)}>Show Modal](#) {visible ? Hello Modal! [setVisible(false)}>Close](#) : null} ); }; export default Home; ``` Upvotes: 2 <issue_comment>username_7: TSX version based on @username_5's answer (React 17, TS 4.1): ``` // portal.tsx import * as React from 'react' import * as ReactDOM from 'react-dom' interface IProps { className? : string el? : string children : React.ReactNode } /** * React portal based on https://stackoverflow.com/a/59154364 * @param children Child elements * @param className CSS classname * @param el HTML element to create. default: div */ const Portal : React.FC = ( { children, className, el = 'div' } : IProps ) => { const [container] = React.useState(document.createElement(el)) if ( className ) container.classList.add(className) React.useEffect(() => { document.body.appendChild(container) return () => { document.body.removeChild(container) } }, []) return ReactDOM.createPortal(children, container) } export default Portal ``` Upvotes: 3 <issue_comment>username_8: Sharing my solution: ``` // PortalWrapperModal.js import React, { useRef, useEffect } from 'react'; import ReactDOM from 'react-dom'; import $ from 'jquery'; const PortalWrapperModal = ({ children, onHide, backdrop = 'static', focus = true, keyboard = false, }) => { const portalRef = useRef(null); const handleClose = (e) => { if (e) e.preventDefault(); if (portalRef.current) $(portalRef.current).modal('hide'); }; useEffect(() => { if (portalRef.current) { $(portalRef.current).modal({ backdrop, focus, keyboard }); $(portalRef.current).modal('show'); $(portalRef.current).on('hidden.bs.modal', onHide); } }, [onHide, backdrop, focus, keyboard]); return ReactDOM.createPortal( <>{children(portalRef, handleClose)}, document.getElementById('modal-root') ); }; export { PortalWrapperModal }; ``` Upvotes: 0 <issue_comment>username_9: IMPORTANT useRef/useState to prevent bugs ========================================= It's important that you use useState or useRef to store the element you created via document.createElement because otherwise it gets recreated on every re-render ``` //This div with id of "overlay-portal" needs to be added to your index.html or for next.js _document.tsx const modalRoot = document.getElementById("overlay-portal")!; //we use useRef here to only initialize el once and not recreate it on every rerender, which would cause bugs const el = useRef(document.createElement("div")); useEffect(() => { modalRoot.appendChild(el.current); return () => { modalRoot.removeChild(el.current); }; }, []); return ReactDOM.createPortal( {renderImages()} , el.current ); ``` Upvotes: 2
2018/03/22
1,809
3,806
<issue_start>username_0: I tried to filter some signal with fft. The signal I am working on is quite complicated and im not really experienced in this topic. That's why I created a simple sin wave 3Hz and tried to cut off the 3 Hz. and so far, so good ``` import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fftfreq, irfft, rfft t = np.linspace(0, 2*np.pi, 1000, endpoint=True) f = 3.0 # Frequency in Hz A = 100.0 # Amplitude in Unit s = A * np.sin(2*np.pi*f*t) # Signal dt = t[1] - t[0] # Sample Time W = fftfreq(s.size, d=dt) f_signal = rfft(s) cut_f_signal = f_signal.copy() cut_f_signal[(np.abs(W)>3)] = 0 # cut signal above 3Hz cs = irfft(cut_f_signal) fig = plt.figure(figsize=(10,5)) plt.plot(s) plt.plot(cs) ``` What i expected [![expected output](https://i.stack.imgur.com/aI27L.png)](https://i.stack.imgur.com/aI27L.png) What i got [![Result](https://i.stack.imgur.com/U8rWY.png)](https://i.stack.imgur.com/U8rWY.png) I don't really know where the noise is coming from. I think it is some basic stuff, but i dont get it. Can someone explain to to me? **Edit** Just further information Frequency ``` yf = fft(s) N = s.size xf = np.linspace(0, fa/2, N/2, endpoint=True) fig, ax = plt.subplots() ax.plot(xf,(2.0/N * np.abs(yf[:N//2]))) plt.xlabel('Frequency ($Hz$)') plt.ylabel('Amplitude ($Unit$)') plt.show() ``` [![enter image description here](https://i.stack.imgur.com/xLBSJ.png)](https://i.stack.imgur.com/xLBSJ.png)<issue_comment>username_1: You could change the way you create your signal and use a sample frequency: ``` fs = 1000 t = np.linspace(0, 1000 / fs, 1000, endpoint=False) # 1000 samples f = 3.0 # Frequency in Hz A = 100.0 # Amplitude in Unit s = A * np.sin(2*np.pi*f*t) # Signal dt = 1/fs ``` And here the whole code: ``` import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fftfreq, irfft, rfft fs = 1000 t = np.linspace(0, 1000 / fs, 1000, endpoint=False) f = 3.0 # Frequency in Hz A = 100.0 # Amplitude in Unit s = A * np.sin(2*np.pi*f*t) # Signal dt = 1/fs W = fftfreq(s.size, d=dt) f_signal = rfft(s) cut_f_signal = f_signal.copy() cut_f_signal[(np.abs(W)>3)] = 0 # cut signal above 3Hz cs = irfft(cut_f_signal) fig = plt.figure(figsize=(10,5)) plt.plot(s) plt.plot(cs) ``` And with `f = 3.0` Hz and `(np.abs(W) >= 3)`: [![enter image description here](https://i.stack.imgur.com/0rNsU.png)](https://i.stack.imgur.com/0rNsU.png) And with `f = 1.0` Hz: [![enter image description here](https://i.stack.imgur.com/YsTSt.png)](https://i.stack.imgur.com/YsTSt.png) Upvotes: 4 [selected_answer]<issue_comment>username_2: Just some additional information about why A. As solution works better than yours: A. A's model doesn't include any non-integer frequencies in its Solution and after filtering out the higher frequencies the result looks like: ``` 1.8691714842589136e-12 * exp(2*pi*n*t*0.0) 1.033507502555532e-12 * exp(2*pi*n*t*1.0) 2.439774536202658e-12 * exp(2*pi*n*t*2.0) -8.346741339115191e-13 * exp(2*pi*n*t*3.0) -5.817427588021649e-15 * exp(2*pi*n*t*-3.0) 4.476938066992472e-14 * exp(2*pi*n*t*-2.0) -3.8680170177940454e-13 * exp(2*pi*n*t*-1.0) ``` while your solution includes components like: ``` ... 177.05936105690256 * exp(2*pi*n*t*1.5899578814880346) 339.28717376420747 * exp(2*pi*n*t*1.7489536696368382) 219.76658524130005 * exp(2*pi*n*t*1.9079494577856417) 352.1094590251063 * exp(2*pi*n*t*2.0669452459344453) 267.23939871205346 * exp(2*pi*n*t*2.2259410340832484) 368.3230130593005 * exp(2*pi*n*t*2.384936822232052) 321.0888818355804 * exp(2*pi*n*t*2.5439326103808555) ... ``` Please refer to [this](https://dsp.stackexchange.com/questions/6220/why-is-it-a-bad-idea-to-filter-by-zeroing-out-fft-bins) question regarding possible side effects of zeroing FFT bins out. Upvotes: 2
2018/03/22
279
1,053
<issue_start>username_0: Is there an easy, built-in way to monitor threads of an Java app in AWS? Like thread count, running time, etc. Or do I need a profiling tool? Can I see thread metrics in AWS X-RAY or is there a way to export JVM metrics to cloudwatch?<issue_comment>username_1: Cloudwatch monitoring cannot see "inside" an EC2 instance. You can send custom metrics to Cloudwatch, or use something like New Relic APM, to get more information on what is happening on your instance. Upvotes: 1 <issue_comment>username_2: There is no totally built-in metric for that, but using the CloudWatch PutMetricData API it's possible to monitor anything. Some folks did that for JMX: <https://github.com/mojn/jmx-cloudwatch-reporter> For Tomcat, for example, it would be ``` Thread Usage JMX Bean: Catalina:type=Executor,name=[executor name] Attributes: poolSize, activeCount ``` <https://wiki.apache.org/tomcat/FAQ/Monitoring> X-Ray is for realtime application monitoring, with different instrumentation alternatives. Upvotes: 3 [selected_answer]
2018/03/22
483
1,673
<issue_start>username_0: I'm calling a REST WS with a JSON payload to subscribe certains events. The server answer with HTTP-Code 201 and a field named **Location** in the HTTP-Header with the ID of the subscription. As an example, in curl (-v) we get: ``` [...] < HTTP/1.1 201 Created < Connection: Keep-Alive < Content-Length: 0 < Location: /v2/subscriptions/5ab386ad4bf6feec37ffe44d [...] ``` In C++ using curlpp we want to retrieve that id looking at the response header. Now we have only the body response (in this case empty). ``` std::ostringstream response; subRequest.setOpt(new curlpp::options::WriteStream(&response)); // Send request and get a result. subRequest.perform(); cout << response.str() << endl; ``` How can we obtain the **Location** header's field (whose content in the example is "/v2/subscriptions/5ab386ad4bf6feec37ffe44d") in C++ using curlpp?<issue_comment>username_1: Cloudwatch monitoring cannot see "inside" an EC2 instance. You can send custom metrics to Cloudwatch, or use something like New Relic APM, to get more information on what is happening on your instance. Upvotes: 1 <issue_comment>username_2: There is no totally built-in metric for that, but using the CloudWatch PutMetricData API it's possible to monitor anything. Some folks did that for JMX: <https://github.com/mojn/jmx-cloudwatch-reporter> For Tomcat, for example, it would be ``` Thread Usage JMX Bean: Catalina:type=Executor,name=[executor name] Attributes: poolSize, activeCount ``` <https://wiki.apache.org/tomcat/FAQ/Monitoring> X-Ray is for realtime application monitoring, with different instrumentation alternatives. Upvotes: 3 [selected_answer]
2018/03/22
792
2,398
<issue_start>username_0: Suppose I have a list of elements: ``` my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] ``` and I want to convert this list to a list of indexes of unique elements. So `CatA` is assigned to index 0, `CatB` to index 1 and `CatC` to index 2. My desired result would be: ``` result = [0, 1, 2, 0, 0, 2] ``` Currently I'm doing this by creating a dictionary that assigns to each element it's unique `id` and then using a list comprehension to create the final list of indexes: ``` unique_classes = np.unique(my_list) conversion_dict = dict(unique_classes, range(len(unique_classes)) result = [conversion_dict[i] for i in my_list] ``` My question is: Is there an easier and straightforward way of doing this? I am thinking about having a big list of categories so it needs to be efficient but preventing me to manually create the unique list, the dictionary and the list comprehension.<issue_comment>username_1: This will do the trick: ``` my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] first_occurances = dict() result = [] for i, v in enumerate(my_list): try: index = first_occurances[v] except KeyError: index = i first_occurances[v] = i result.append(index) ``` Complexity will be *O(n)*. Basically what you do is storing in `dict` indexes of first value occurance. If `first_occurances` don't have value `v`, then we save current index `i`. Upvotes: 2 <issue_comment>username_2: ``` result = [my_list.index(l) for l in my_list] print(result) [0, 1, 2, 0, 0, 2] ``` list.index() returns the index of first occurrence as required for your task. For more details check [list.index()](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) Upvotes: -1 <issue_comment>username_3: You can do this by using Label encoder from scikit learn.It will assign labels to each unique values in a list. Example code : ``` from sklearn.preprocessing import LabelEncoder my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] le = LabelEncoder() print(le.fit(my_list).transform(my_list)) ``` Upvotes: 1 <issue_comment>username_4: As suggested by @mikey, you can use `np.unique`, as below: ``` import numpy as np my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] res = np.unique(my_list, return_inverse=True)[1] ``` Result: ``` [0 1 2 0 0 2] ``` Upvotes: 2 [selected_answer]
2018/03/22
627
1,955
<issue_start>username_0: We have tried approach mentioned in the [IBM developers works](http://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/sdk/web/) to add the MobileFirst Web SDK. We have created Angular 5 web application and added Web SDK into it. After that, we are not able to figure out where to put MFP server IP or hostname? Currently, our web application stays in the different web server and MFP on the different. Thanks in advance.<issue_comment>username_1: This will do the trick: ``` my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] first_occurances = dict() result = [] for i, v in enumerate(my_list): try: index = first_occurances[v] except KeyError: index = i first_occurances[v] = i result.append(index) ``` Complexity will be *O(n)*. Basically what you do is storing in `dict` indexes of first value occurance. If `first_occurances` don't have value `v`, then we save current index `i`. Upvotes: 2 <issue_comment>username_2: ``` result = [my_list.index(l) for l in my_list] print(result) [0, 1, 2, 0, 0, 2] ``` list.index() returns the index of first occurrence as required for your task. For more details check [list.index()](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) Upvotes: -1 <issue_comment>username_3: You can do this by using Label encoder from scikit learn.It will assign labels to each unique values in a list. Example code : ``` from sklearn.preprocessing import LabelEncoder my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] le = LabelEncoder() print(le.fit(my_list).transform(my_list)) ``` Upvotes: 1 <issue_comment>username_4: As suggested by @mikey, you can use `np.unique`, as below: ``` import numpy as np my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] res = np.unique(my_list, return_inverse=True)[1] ``` Result: ``` [0 1 2 0 0 2] ``` Upvotes: 2 [selected_answer]
2018/03/22
808
2,536
<issue_start>username_0: Say I have streaming text data coming in to my Bash script, with one record per line, and I want to append to each line some function of that line and spit that to `stdout`: ``` record1 record1 fn(record1) record2 -> record2 fn(record2) ... ... ``` This would be relatively easy to do with, say, Awk. However, say the function I'm applying to my input data is orders of magnitude more efficient if it's applied to streamed data (and I've got a lot of it, so the linewise Awk processing is definitely not an option). This is the solution I've come up with: ``` input="$(mktemp)" trap "rm -rf ${input}" EXIT cat > "${input}" paste "${input}" <(some_function "${input}") ``` This works by redirecting `stdin` into a temporary file (the `cat` line), then `paste`ing the files together, using process substitution. However, this seems a bit messy to me (e.g., UUOC) and I'm thinking there's probably a "better" way to do it with `exec` (for redirection) and `tee`, but I'm not really sure how. Could this be done better?<issue_comment>username_1: This will do the trick: ``` my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] first_occurances = dict() result = [] for i, v in enumerate(my_list): try: index = first_occurances[v] except KeyError: index = i first_occurances[v] = i result.append(index) ``` Complexity will be *O(n)*. Basically what you do is storing in `dict` indexes of first value occurance. If `first_occurances` don't have value `v`, then we save current index `i`. Upvotes: 2 <issue_comment>username_2: ``` result = [my_list.index(l) for l in my_list] print(result) [0, 1, 2, 0, 0, 2] ``` list.index() returns the index of first occurrence as required for your task. For more details check [list.index()](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) Upvotes: -1 <issue_comment>username_3: You can do this by using Label encoder from scikit learn.It will assign labels to each unique values in a list. Example code : ``` from sklearn.preprocessing import LabelEncoder my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] le = LabelEncoder() print(le.fit(my_list).transform(my_list)) ``` Upvotes: 1 <issue_comment>username_4: As suggested by @mikey, you can use `np.unique`, as below: ``` import numpy as np my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] res = np.unique(my_list, return_inverse=True)[1] ``` Result: ``` [0 1 2 0 0 2] ``` Upvotes: 2 [selected_answer]
2018/03/22
347
1,344
<issue_start>username_0: We host a CakePHP site for someone. They would like to change the password for their account and unfortunately the original developers didn't build this functionality into the site so I was going to update the password in PHPMyAdmin. I have tried entering the password and then hashing it using the MD5 dropdown in the database. I've also tried SHA1 but when I try logging in on the frontend, it fails. How can I tell what type of hash method is used on the system?<issue_comment>username_1: Cake is using blowfish to generate password hashes. It generates a different hash every time because it's able to store a randomly generated salt as part of the hash. I've written an explanation of how it works over here: <https://stackoverflow.com/a/22699357/2719538> Upvotes: -1 <issue_comment>username_2: Cakephp uses PHP's built in `password_hash` method in it's DefaultPasswordHasher. You can override this by implementing the \Cake\Auth\AbtrasctPasswordHasher and configuring the Auth component with your implementation <http://php.net/manual/en/function.password-hash.php> <https://github.com/cakephp/cakephp/blob/master/src/Auth/DefaultPasswordHasher.php#L49> Implementing Custom Hasher <https://book.cakephp.org/3.0/en/controllers/components/authentication.html#creating-custom-password-hasher-classes> Upvotes: 0
2018/03/22
354
1,297
<issue_start>username_0: I'm facing an issue with a textbox to only allow whole numeric value, not dot/decimal value in razor view. I looked around SO but unfortunately I can't find an answer. JavaScript validation exists for *accept numeric value with dot*, but I want without dot/decimal. cshtml: ``` @Html.TextBoxFor(Employee => Employee.AlternateNumber, new { @id = "txtAlternateNumber", @class = "form-control", @type = "number" }) ```<issue_comment>username_1: Cake is using blowfish to generate password hashes. It generates a different hash every time because it's able to store a randomly generated salt as part of the hash. I've written an explanation of how it works over here: <https://stackoverflow.com/a/22699357/2719538> Upvotes: -1 <issue_comment>username_2: Cakephp uses PHP's built in `password_hash` method in it's DefaultPasswordHasher. You can override this by implementing the \Cake\Auth\AbtrasctPasswordHasher and configuring the Auth component with your implementation <http://php.net/manual/en/function.password-hash.php> <https://github.com/cakephp/cakephp/blob/master/src/Auth/DefaultPasswordHasher.php#L49> Implementing Custom Hasher <https://book.cakephp.org/3.0/en/controllers/components/authentication.html#creating-custom-password-hasher-classes> Upvotes: 0
2018/03/22
1,011
2,665
<issue_start>username_0: Let's say I have a 4x3 linear array of integers stored in row-major order. The layout (indexes) are shown below. Let's say the value at each index is the same as the index. ``` 00 01 02 03 04 05 06 07 08 09 10 11 ``` I can loop through this array as follows: ``` for(int y = 0; y < 3; ++y) for(int x = 0; x < 4; ++x) std::cout << array[y*4+x] << ","; ``` I would get ``` 00,01,02,03,04,05,06,07,08,09,10,11, ``` And, of course, I can loop in a slightly different way: ``` for(int x = 0; x < 4; ++x) for(int y = 0; y < 3; ++y) std::cout << array[y*4+x] << ","; ``` And get ``` 00,04,08,01,05,09,02,06,10,03,07,11, ``` But is there a way, without first sorting the array, to loop through it getting the following (or similar) result: ``` 05,04,01,06,09,00,02,10,08,07,03,11 ``` That is, to start at some specified location `[x=1,y=1]` and iterate outwards in (sort of) a spiral, that is sorted by distance. ``` 05 02 06 10 01 00 03 09 08 04 07 11 ``` I know I can achieve that by first sorting the array by some predicate that returns the distance from `[x=1,y=1]`, but (for performance) is it possible to do without first sorting? --- **Edit:** To elaborate, I just want to start at point `[x=1,y=1]` and iterate as if the points had been sorted via Manhatten (`|x1-x2| + |y1-y2|`) or even Euclidean (`sqrt((x1-x2)^2 + (y1-y2)^2)`). Here's a larger array. It doesn't have to be exactly like this, since it can satisfy the sort, with a different output (for example, it could be CCW rather than CW). ``` 05 01 06 11 17 04 00 02 09 15 08 03 07 14 18 13 10 12 16 19 ```<issue_comment>username_1: Make a sequence of offsets in the correct order for a spiral, long enough for any starting position. Either as a static table, or as a generating function. Loop through that offset sequence, adding each to the starting co-ordinate. Skip any out of bounds co-ordinates. Stop when you have found `width * height` valid co-ordinates Upvotes: 2 <issue_comment>username_2: With Manhattan distance, you might use something like: ``` visit(center); for (int distance = 1; distance != max_distance; ++distance) { for (int i = 0; i != distance; ++i) { visit(center - {-distance + i, i}); } for (int i = 0; i != distance; ++i) { visit(center - {i, distance - i}); } for (int i = 0; i != distance; ++i) { visit(center - {distance - i, -i}); } for (int i = 0; i != distance; ++i) { visit(center - {-i, -distance + i}); } } ``` You might add bound checking in `visit`, or adjust each boundary (You will have to split each inner loop). Upvotes: 1
2018/03/22
332
1,216
<issue_start>username_0: I been trying to find a way to loop through each rows of a table using foreach loop. is that something possible? I am not asking for an alternative of foreach loop, I am wondering if I can loop using foreach, I know I can do other ways, so please keep that in mind when trying to answer. I have tried the followings: ``` var table_rows = document.getElementById("table_information_layout_id"); table_rows.forEach(function (val){ } var table_rows = document.getElementById("table_information_layout_id").rows; table_rows.forEach(function (val){ } ``` None of the above works, as I get the error **UncaughtTypeError table\_rows.foreach is not a function**<issue_comment>username_1: You can iterate table using jquery .each method Upvotes: 0 <issue_comment>username_2: `document.getElementById("table_information_layout_id").rows` returns a HTMLCollection that does not contains the `.forEach` method. If you really want to have all Array properties you can use `Array.from(rows)` ``` Array.from(document.getElementById("teste").rows).forEach((row) => { console.log(row); }); ``` For more details see this: <https://stackoverflow.com/a/22754453/4120554> Upvotes: 2 [selected_answer]
2018/03/22
617
2,637
<issue_start>username_0: Here i am using bhar chat onloading it is working , my question is onclick the button also i want to call the same function , from this code where they are calling the function i am not able to get, if any one know means update my snippet.which purpose i am asking means clicking button that time i will pass the AJAX and again i will display the results ```js $(function () { Highcharts.setOptions({ colors: ['#67BCE6'], chart: { style: { fontFamily: 'sans-serif', color: '#fff' } } }); $('#barchat').highcharts({ chart: { type: 'column', backgroundColor: '#36394B' }, title: { text: 'Trip Details', style: { color: '#fff' } }, xAxis: { tickWidth: 0, labels: { style: { color: '#fff', } }, categories: ['Project', 'Escort', 'Adhoc'] }, yAxis: { gridLineWidth: .5, gridLineDashStyle: 'dash', gridLineColor: 'black', title: { text: '', style: { color: '#fff' } }, labels: { formatter: function() { return '$'+Highcharts.numberFormat(this.value, 0, '', ','); }, style: { color: '#fff', } } }, legend: { enabled: false, }, credits: { enabled: false }, tooltip: { //valuePrefix: '$' }, plotOptions: { column: { borderRadius: 2, pointPadding: 0, groupPadding: 0.1 } }, series: [{ name: 'No of trip used', data: [1000, 2000, 2300] }] }); }); ``` ```html CLick Me ```<issue_comment>username_1: You can iterate table using jquery .each method Upvotes: 0 <issue_comment>username_2: `document.getElementById("table_information_layout_id").rows` returns a HTMLCollection that does not contains the `.forEach` method. If you really want to have all Array properties you can use `Array.from(rows)` ``` Array.from(document.getElementById("teste").rows).forEach((row) => { console.log(row); }); ``` For more details see this: <https://stackoverflow.com/a/22754453/4120554> Upvotes: 2 [selected_answer]
2018/03/22
452
1,697
<issue_start>username_0: I am new to Kong. I am using Kong version 0.12.1. I have configured my api with Kong using basic-auth and it works as per the [document](https://getkong.org/docs/0.11.x/admin-api/), I am able to GET the host url with authentication using Kong Proxy in command window curl -i -X GET --url <https://localhost:8443/> -H 'Host: example.com' -H 'Authorization: Basic XXXXXXXXXX' . But I need to secure my API using kong in a way that anyone who makes an api call needs to be authenticated via Kong. Your suggestions are much appreciated...... Thank you<issue_comment>username_1: From your description, it sounds like you ***have*** secured your API using Kong :) What problem are you experiencing? Upvotes: 0 <issue_comment>username_2: Use [key-auth](https://getkong.org/plugins/key-authentication/) plugin with [ACL](https://getkong.org/plugins/acl/). Check documentation for configuration. Upvotes: 0 <issue_comment>username_3: Step to Configure your API with Kong. 1. To secure your Upstream API(your backend APIs), you need to expose it locally (127.0.0.1) only, not global so no one directly hit your API. 2. Register your Upstream API with Kong Service/Route object. Kong 1.0 has Service and route object. 3. Configure and add Kong JWT or other Authentication plugins in your Kong Service/Route object 4. Now your API is completely protected by Kong. It is only accessible through Kong proxy. Expose your Kong proxy point globally using kong.conf Upvotes: 1 <issue_comment>username_4: Enable JWT plugin against service if you want to have all secure routes for a given service. If Use case is secure a specific route, enable the JWT plugin against route. Upvotes: 0
2018/03/22
350
1,359
<issue_start>username_0: In My Project I have a Two Buttons 1.`click here` button 2.`save` button First i need to display only `click here` button, when user click `click here` button then `save` button will need to display on ionic3<issue_comment>username_1: From your description, it sounds like you ***have*** secured your API using Kong :) What problem are you experiencing? Upvotes: 0 <issue_comment>username_2: Use [key-auth](https://getkong.org/plugins/key-authentication/) plugin with [ACL](https://getkong.org/plugins/acl/). Check documentation for configuration. Upvotes: 0 <issue_comment>username_3: Step to Configure your API with Kong. 1. To secure your Upstream API(your backend APIs), you need to expose it locally (127.0.0.1) only, not global so no one directly hit your API. 2. Register your Upstream API with Kong Service/Route object. Kong 1.0 has Service and route object. 3. Configure and add Kong JWT or other Authentication plugins in your Kong Service/Route object 4. Now your API is completely protected by Kong. It is only accessible through Kong proxy. Expose your Kong proxy point globally using kong.conf Upvotes: 1 <issue_comment>username_4: Enable JWT plugin against service if you want to have all secure routes for a given service. If Use case is secure a specific route, enable the JWT plugin against route. Upvotes: 0
2018/03/22
1,014
3,440
<issue_start>username_0: I am currently trying to update a workbook connection which has the format of Messergebnisse-2018-3-22 and I link a file everyday, so id like to update the most recent connection only. This is the code I have been using, but it always comes up with an error: ``` Sub Refresh() Dim LDate As String LDate = Date If Day(Today) >= 10 Then Application.ScreenUpdating = False ActiveWorkbook.Connections("Messergebnisse-" & format(Date,"yyyy-m-dd")).Refresh Sheets("OK").Select ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh Sheets("Summary").Select Else Application.ScreenUpdating = False ActiveWorkbook.Connections("Messergebnisse-" & LDate).Refresh Sheets("OK").Select ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh Sheets("Summary").Select End If End sub ``` Tried both using a variable for the date and the actual format function. But format function comes with the error: Compile error: > > Wrong number of arguments or invalid property assignment > > > Any ideas?<issue_comment>username_1: The compile error is because of `If Day(Today) >= 10 Then`. It should be `If Day(Now) >= 10 Then` To avoid compile errors, write `Option Explicit` on the top of your module/class/worksheet and before running the code select `Debug>Compile` from the VB Ribbon. It will always tell you whether your code can compile and where are the errors. --- Check this small sample: ``` Sub TestMe() MsgBox Day(Now) End Sub ``` Upvotes: 2 <issue_comment>username_2: You need to replace ``` If Day(Today) >= 10 Then ``` with ``` If Day(Date) >= 10 Then ``` **Note**: you should avoid using `Select` and `ActiveSheet`, and instead fully define and `Set` all your object. You can do so by adapting the code below: ``` Dim OKSht As Worksheet Dim PvtTbl As PivotTable ' set the worksheet object Set OKSht = ThisWorkbook.Sheets("OK") ' set the Pivot-Table object Set PvtTbl = OKSht.PivotTables("PivotTable1") ' refresh the Pivot-Table PivotCache PvtTbl.PivotCache.Refresh ``` Upvotes: 1 <issue_comment>username_3: 1. In this statement `LDate = Date` you rely on locale. It's wrong. 2. You must take timestamp only one time. The rule it is. But you take it again `Day(Today)` (is meant `Date` or `Now`) and again `format(Date,"yyyy-m-dd")` once more. 3. As I see, you try to avoid problem of representation of 1- & 2-digits calendar day number. OK. But such problem is waiting of you with monthes :) However format pattern of "yyyy-m-d" give you the desired. 4. `ScreenUpdating` not restored. 5. Extra duplicated code At all, it must look like this (without taking into account all other important notes posted before me): ``` Sub Refresh() Dim dDate As Date Dim sDate$, sCncStr$ dDate = Date sCncStr = "Messergebnisse-" ' Select Case (Day(Today) >= 10) ' remained for the case of I misunderstand you ' Case True ' Format it on your choice ' sDate = 'Format$(dDate, "yyyy-m-dd") ' Case False ' sDate = 'CStr(dDate) ' End Select sDate = Format$(dDate, "yyyy-m-d") sCncStr = sCncStr & sDate Application.ScreenUpdating = False ActiveWorkbook.Connections(sCncStr).Refresh Sheets("OK").Select ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh Sheets("Summary").Select Application.ScreenUpdating = True End Sub ``` . Upvotes: 1 [selected_answer]
2018/03/22
760
2,757
<issue_start>username_0: im trying to filter the articles i have in my program to a search in jquery that is working, the problem is that i only want it to search in a determineted div but instead this is searching tro all my articles, like if i search in the div "processador", this is searching in "grafica" for example. <http://prntscr.com/iuqsxu> <http://prntscr.com/iuqsnl> Jquery ``` var divs = $('.expandContent'); $('.expand').each(function () { $(this).find('.product-removal').slice(2).hide(); $(".search").on("keyup", function() { var value = $(this).val().toLowerCase(); $('div.product-removal article.product').each(function() { $(this).toggle($(this).html().toLowerCase().indexOf(value) > -1); }); }); }); ``` Processador code ``` ### Processador {% for item in processador %} ![]({{ item.img|e }}) × {{ item.marca|e }} ================== {{ item.descr|e }} {{ item.preco\_unit|e }}€ --------------------------- {{ item.preco\_unit|e }}€ --------------------------- {{ item.preco\_unit|e }} -------------------------- {% endfor %} mostrar ``` /grafic card code ``` ### Graficas {% for item in placagrafica %} ![]({{ item.img|e }}) × {{ item.marca|e }} ================== {{ item.descr|e }} - 1 + {{ item.preco\_unit|e }}€ --------------------------- {{ item.preco\_unit|e }}€ --------------------------- {{ item.preco\_unit|e }} -------------------------- {% endfor %} mostrar ```<issue_comment>username_1: > > The class selector returns a group of elements. > > > The id selector returns single element with first element with matching id. > > > Both the divs are having the same class and you are applying your `JQuery` functions on class. Instead you give unique ids for each div. i.e., on search you are manipulating using `$('div.product-removal article.product')` which is applying for both the matched elements. Upvotes: 0 <issue_comment>username_2: From the code, you are trying to search from all the products. $('div.product-removal article.product') will return all the .products from #processador and #grafica because all are having the same class names. You should update your code to search only within that particular section. ``` $(".expand .search").on("keyup", function() { var value = $(this).val().toLowerCase(); $(this).parent().find('article.product').each(function() { if ($(this).html().toLowerCase().indexOf(value) > -1)) { $(this).show(); } else { $(this).hide(); } }); }); ``` I've also optimised your code a little. $(this).parent().find('article.product') will only select the products within that section. Upvotes: 3 [selected_answer]
2018/03/22
514
1,945
<issue_start>username_0: Is it possible to check if an ApplicationUser has a Claim? I know it is possible to check if an ApplicationUser is in a role ``` userManager.IsInRoleAsync(applicationUser,"admin"); ``` And i know it could be possible to check if a user has a Claim like this: ``` userManager.GetClaimsAsync(applicationUser)).Any(c=>c.Type == "userType" && c.Vaue == "admin"); ``` But i'd like to use something like with a ClaimsPrincipal object: ``` User.HasClaim("userType", "admin"); ``` But i don't have a ClaimsPrincipal, i just have the ApplicationUser. So i also would like to know the way of getting the ClaimsPrincipal of an ApplicationUser, if it is possible.<issue_comment>username_1: > > The class selector returns a group of elements. > > > The id selector returns single element with first element with matching id. > > > Both the divs are having the same class and you are applying your `JQuery` functions on class. Instead you give unique ids for each div. i.e., on search you are manipulating using `$('div.product-removal article.product')` which is applying for both the matched elements. Upvotes: 0 <issue_comment>username_2: From the code, you are trying to search from all the products. $('div.product-removal article.product') will return all the .products from #processador and #grafica because all are having the same class names. You should update your code to search only within that particular section. ``` $(".expand .search").on("keyup", function() { var value = $(this).val().toLowerCase(); $(this).parent().find('article.product').each(function() { if ($(this).html().toLowerCase().indexOf(value) > -1)) { $(this).show(); } else { $(this).hide(); } }); }); ``` I've also optimised your code a little. $(this).parent().find('article.product') will only select the products within that section. Upvotes: 3 [selected_answer]
2018/03/22
627
2,175
<issue_start>username_0: I have a div that is a css grid container. When the page width drops below a certain size, I would like all elements of the grid to be placed on a line. I think you should be able to change the display type to flex box, I tried doing this and the grid stays the same. Here is the code I am using: See the Pen [NYjOmL](https://codepen.io/MeaningOf42/pen/NYjOmL/) by <EMAIL> ([@MeaningOf42](https://codepen.io/MeaningOf42)) on [CodePen](https://codepen.io). ``` /* The important part of the CSS*/ @media (max-width: 40em) { .image { visibility:hidden; } .grid-container { display: inline-flex; } } /* The Styling of the container class: */ .grid-container { display: grid; width: 75%; margin: auto; padding: 10px; height: 100px; grid-template-columns: 16.6% 16.6% 33% 16% 16%; grid-template-rows: 2fr 3fr 3fr 1fr; grid-template-areas: ". . Image . ." "blog bikes Image about links" "shop events Image contact team" ". . Image . ." } ``` For context, I am trying to replicate deaf pigeon's website ( <http://www.deafpigeon.co.uk>) using as close to pure vanilla HTML and CSS to practice laying out pages. I want my div to do the same thing as the deaf pigeon navigation bar. Does anyone have solutions? I might be going about this the wrong way if so be sure to let me know.<issue_comment>username_1: Just move your media query declaration to the end of the file. The media query rule you defined is getting executed but it is getting overwritten by the `.grid-container` rule that comes after it. Upvotes: -1 <issue_comment>username_2: As Pete said, your media query needs to follow your base rules in order to override when the condition is met. The preferred approach would be to declare your mobile styles first followed by a desktop override in your media query. ``` .grid-container { display: inline-flex; } @media all and (min-width: 40em) { .grid-container { display: grid; } } ``` Notice the change from max-width to min-width to ensure that this override kicks in when the viewport is larger than 40em Upvotes: 1
2018/03/22
691
2,186
<issue_start>username_0: I'm getting an error using amazon advertising API. I'm currently trying to request performance report using `https://advertising-api.amazon.com/v1/campaigns/report`. But the server reply `Cannot consume content type` here is my request header and body. End point : `https://advertising-api.amazon.com/v1/campaigns/report` Method Type: `POST` Header : ``` { Authorization: 'Bearer xxxxxx', Amazon-Advertising-API-Scope: '11111111111', Content-Type: 'application/json' } ``` Body : ``` { campaignType:'sponsoredProducts', reportDate:'20180320', metrics:'impressions,clicks' } ``` I think I did everything correctly as API document but it says `{ "code": "415", "details": "Cannot consume content type" }` Please help me. [![enter image description here](https://i.stack.imgur.com/ckYYS.png)](https://i.stack.imgur.com/ckYYS.png)<issue_comment>username_1: Just copy the body from the documentation and paste it in the raw area (of postman) and choose JSON format. For me it works fine. Upvotes: 0 <issue_comment>username_2: Try this way ``` curl -X POST \ https://advertising-api.amazon.com/v1/campaigns/report \ -H 'Amazon-Advertising-API-Scope: REPLACE_YOUR_PROFILE_ID' \ -H 'Authorization: REPLACE_YOUR_ACCESS_TOKEN' \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \ -H 'Host: advertising-api.amazon.com' \ -H 'cache-control: no-cache' \ -d '{ "campaignType": "sponsoredProducts", "metrics": "impressions,clicks", "reportDate": "20181101" } ``` And you will get a response like ``` { "reportId": "amzn1.clicksAPI.v1.p1.......", "recordType": "campaign", "status": "IN_PROGRESS", "statusDetails": "Report is being generated." } ``` You can put this curl command in Postman also. Upvotes: 1 <issue_comment>username_3: I think your Body may be missing a parameter. When I successfully make a similar POST I need my body to have at least what you have written as well as the segment type. Try adding this to your body: ``` { campaignType:'sponsoredProducts', reportDate:'20180320', metrics:'impressions,clicks' segment:'query' } ``` Upvotes: 1
2018/03/22
505
1,551
<issue_start>username_0: My Dataset looks like that: ``` { "A_asdsd" : "1", "A_fghf" : "1", "B_tzzz" : "1", "B_ghh" : "1",.... } ``` How do I have to specify my find() Function, that all fields that start with A\_ are excluded? (There are thousand of them).<issue_comment>username_1: Just copy the body from the documentation and paste it in the raw area (of postman) and choose JSON format. For me it works fine. Upvotes: 0 <issue_comment>username_2: Try this way ``` curl -X POST \ https://advertising-api.amazon.com/v1/campaigns/report \ -H 'Amazon-Advertising-API-Scope: REPLACE_YOUR_PROFILE_ID' \ -H 'Authorization: REPLACE_YOUR_ACCESS_TOKEN' \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \ -H 'Host: advertising-api.amazon.com' \ -H 'cache-control: no-cache' \ -d '{ "campaignType": "sponsoredProducts", "metrics": "impressions,clicks", "reportDate": "20181101" } ``` And you will get a response like ``` { "reportId": "amzn1.clicksAPI.v1.p1.......", "recordType": "campaign", "status": "IN_PROGRESS", "statusDetails": "Report is being generated." } ``` You can put this curl command in Postman also. Upvotes: 1 <issue_comment>username_3: I think your Body may be missing a parameter. When I successfully make a similar POST I need my body to have at least what you have written as well as the segment type. Try adding this to your body: ``` { campaignType:'sponsoredProducts', reportDate:'20180320', metrics:'impressions,clicks' segment:'query' } ``` Upvotes: 1
2018/03/22
470
1,567
<issue_start>username_0: I'm trying to make tests with a different variation of data but with the same test case (JUnit, Selenium). I just want to know if there is any way to have the result of each set of data individually as if a set of data failed I want to know which one.<issue_comment>username_1: Just copy the body from the documentation and paste it in the raw area (of postman) and choose JSON format. For me it works fine. Upvotes: 0 <issue_comment>username_2: Try this way ``` curl -X POST \ https://advertising-api.amazon.com/v1/campaigns/report \ -H 'Amazon-Advertising-API-Scope: REPLACE_YOUR_PROFILE_ID' \ -H 'Authorization: REPLACE_YOUR_ACCESS_TOKEN' \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \ -H 'Host: advertising-api.amazon.com' \ -H 'cache-control: no-cache' \ -d '{ "campaignType": "sponsoredProducts", "metrics": "impressions,clicks", "reportDate": "20181101" } ``` And you will get a response like ``` { "reportId": "amzn1.clicksAPI.v1.p1.......", "recordType": "campaign", "status": "IN_PROGRESS", "statusDetails": "Report is being generated." } ``` You can put this curl command in Postman also. Upvotes: 1 <issue_comment>username_3: I think your Body may be missing a parameter. When I successfully make a similar POST I need my body to have at least what you have written as well as the segment type. Try adding this to your body: ``` { campaignType:'sponsoredProducts', reportDate:'20180320', metrics:'impressions,clicks' segment:'query' } ``` Upvotes: 1
2018/03/22
786
2,929
<issue_start>username_0: I'm trying to momentjs to format dates in my component controllers where matInput datepicker components are used, but I'm getting the following error in the console when I try to load pages where these are present: > > Error: MatDatepicker: No provider found for DateAdapter. You must import one of the following modules at your application root: MatNativeDateModule, MatMomentDateModule, or provide a custom implementation. > > > Problem is that I've tried including this in my app module, main app component and child components where I'm trying to reference the `moment()` method, but I still get the error. I've also tried using MatNativeDateModule with the same result. This is the module dependency that I'm importing: ``` import { MatMomentDateModule } from '@angular/material-moment-adapter'; ``` Datepicker element: ``` ```<issue_comment>username_1: Have you added it to your module's imports? ``` import { MatMomentDateModule } from "@angular/material-moment-adapter"; @NgModule({ /* etc. */ imports: [ BrowserModule, /* etc. */, MatMomentDateModule, /* etc. */ ], /* etc. */ } ``` I've installed it with ``` npm i @angular/material-moment-adapter --save ``` and everything works. Upvotes: 5 <issue_comment>username_2: I had a similar error with MatDatepickerModule and MatNativeDateModule which said > > ERROR Error: "MatDatepicker: No provider found for DateAdapter. You must import one of the following modules at your application root: MatNativeDateModule, MatMomentDateModule, or provide a custom implementation." > > > I solved the issue by doing ``` import { MatDatepickerModule, MatNativeDateModule } from '@angular/material'; @NgModule({ imports:[ MatDatepickerModule, MatNativeDateModule], providers: [MatNativeDateModule, MatDatepickerModule], }) ``` Upvotes: 3 <issue_comment>username_3: Just import both below modules in `app.module.ts` ``` import { MatDatepickerModule, MatNativeDateModule} from '@angular/material'; imports: [ MatDatepickerModule, MatNativeDateModule ] ``` That's it. Upvotes: 0 <issue_comment>username_4: Angullar 8,9 ``` import { MatDatepickerModule } from '@angular/material/datepicker'; import { MatNativeDateModule } from '@angular/material/core'; ``` Angular 7 and below ``` import { MatDatepickerModule, MatNativeDateModule } from '@angular/material'; ``` You need to import both MatDatepickerModule and MatNativeDateModule under imports and add MatDatepickerModule under providers ``` imports: [ MatDatepickerModule, MatNativeDateModule ], providers: [ MatDatepickerModule, MatNativeDateModule ], ``` Upvotes: 4 <issue_comment>username_5: Add ``` import { MatMomentDateModule } from "@angular/material-moment-adapter"; ``` and install ``` npm i @angular/material-moment-adapter --save ``` and the dependency also ``` npm i moment --save ``` Upvotes: 3
2018/03/22
1,992
5,862
<issue_start>username_0: I am building Apache Zeppelin 0.8.0 from maven and I have to use advanced features provided by Zeppelin e.g. Apache Zeppelin Notebook Authorization allow "Runners" But I am trying while different versions of node and npm but still getting the following error during `mvn clean package -DskipTests` for building Building Zeppelin: web Application. Following is the error log from debug log: `/root/.npm/_logs/2018-03-22T10_38_10_265Z-debug.log` Also when this new version( 0.8.0) will release? ``` 1 verbose cli [ '/root/zeppelin/zeppelin-web/node/node', 1 verbose cli '/root/zeppelin/zeppelin-web/node/node_modules/npm/bin/npm-cli.js', 1 verbose cli 'run', 1 verbose cli 'build:dist' ] 2 info using [email protected] 3 info using [email protected] 4 verbose run-script [ 'prebuild:dist', 'build:dist', 'postbuild:dist' ] 5 info lifecycle [email protected]~prebuild:dist: [email protected] 6 info lifecycle [email protected]~build:dist: [email protected] 7 verbose lifecycle [email protected]~build:dist: unsafe-perm in lifecycle true 8 verbose lifecycle [email protected]~build:dist: PATH: /root/zeppelin/zeppelin-web/node/node_modules/npm/bin/node-gyp-bin:/root/zeppelin/zeppelin-web/node_modules/.bin:/root/zeppelin/zeppel$9 verbose lifecycle [email protected]~build:dist: CWD: /root/zeppelin/zeppelin-web 10 silly lifecycle [email protected]~build:dist: Args: [ '-c', 10 silly lifecycle 'npm-run-all prebuild && grunt pre-webpack-dist && webpack && grunt post-webpack-dist' ] 11 silly lifecycle [email protected]~build:dist: Returned: code: 3 signal: null 12 info lifecycle [email protected]~build:dist: Failed to exec build:dist script 13 verbose stack Error: [email protected] build:dist: `npm-run-all prebuild && grunt pre-webpack-dist && webpack && grunt post-webpack-dist` 13 verbose stack Exit status 3 13 verbose stack at EventEmitter. (/root/zeppelin/zeppelin-web/node/node\_modules/npm/node\_modules/npm-lifecycle/index.js:280:16) 13 verbose stack at emitTwo (events.js:126:13) 13 verbose stack at EventEmitter.emit (events.js:214:7) 13 verbose stack at ChildProcess. (/root/zeppelin/zeppelin-web/node/node\_modules/npm/node\_modules/npm-lifecycle/lib/spawn.js:55:14) 13 verbose stack at emitTwo (events.js:126:13) 13 verbose stack at ChildProcess.emit (events.js:214:7) 13 verbose stack at maybeClose (internal/child\_process.js:925:16) 13 verbose stack at Process.ChildProcess.\_handle.onexit (internal/child\_process.js:209:5) 14 verbose pkgid [email protected] 15 verbose cwd /root/zeppelin/zeppelin-web 16 verbose Linux 4.4.0-87-generic 17 verbose argv "/root/zeppelin/zeppelin-web/node/node" "/root/zeppelin/zeppelin-web/node/node\_modules/npm/bin/npm-cli.js" "run" "build:dist" 18 verbose node v8.9.3 19 verbose npm v5.5.1 20 error code ELIFECYCLE 21 error errno 3 22 error [email protected] build:dist: `npm-run-all prebuild && grunt pre-webpack-dist && webpack && grunt post-webpack-dist` 22 error Exit status 3 23 error Failed at the [email protected] build:dist script. ```<issue_comment>username_1: You need to run maven build with non-root user. Bower will break the install if used with root user. Do any admin task (prerequisite) with root, place git repo under user space and build it there with the user. Below should work with a normal user: ``` #Prerequisites sudo yum update -y sudo yum install -y java-1.8.0-openjdk-devel git gcc-c++ make #Using NODE.JS Version 8 (Version 10 / Actual also works). curl -sL https://rpm.nodesource.com/setup_8.x | sudo -E bash - sudo yum install -y nodejs fontconfig curl -sL https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d /yarn.repo sudo yum install -y yarn npm config set strict-ssl false npm install -g bower #Maven Enviroment mkdir /usr/local/maven cd /usr/local/maven wget http://apache.rediris.es/maven/maven-3/3.5.4/binaries/apache-maven-3.5.4-bin.tar.gz tar xzvf apache-maven-3.5.4-bin.tar.gz --strip-components=1 sudo ln -s /usr/local/maven/bin/mvn /usr/local/bin/mvn #Configure Maven to use more resources export MAVEN_OPTS="-Xmx2g -XX:MaxPermSize=1024m" #Proxy Configs #git config --global http.proxy http://your.company.proxy:port git config --global #npm config set proxy http://your.company.proxy:8080 #npm config set https-proxy http://your.company.proxy:8080 #nano ~/.bowerrc #{ #"proxy":"http ://: #", "https-proxy":"http ://: #" #} #Zeppelin Install sudo useradd zeppelin sudo su zeppelin cd /home/zeppelin git clone https://github.com/apache/zeppelin.git cd zeppelin mvn clean package -Dmaven.test.skip=true ``` Hope it helps. Upvotes: 1 <issue_comment>username_2: The issue might be caused by building Zeppelin as root user but 'bower' can't be run as root. Try to edit the file below to add `bower install --silent --allow-root` for both "postinstall", "build:dist", and "build:ci" build steps then re-build. Edit `zeppelin/zeppelin-web/package.json`: ``` "scripts": { "clean": "rimraf dist && rimraf .tmp", "postinstall": "bower install --silent --allow-root", "prebuild": "npm-run-all clean lint:once", "build:dist": "npm-run-all prebuild && bower install --silent --allow-root && grunt pre-webpack-dist && webpack && grunt post-webpack-dist", "build:ci": "npm-run-all prebuild && bower install --silent --allow-root && grunt pre-webpack-ci && webpack && grunt post-webpack-dist", ``` Upvotes: 0 <issue_comment>username_3: test based on my env: root cause: 1. bower not ALLOW root to process command. Although we can set `--allow-root` manually in CLI. but if you call it in MAVN it will be defined in package.json without `--allow-root`. So, same like @YuanXu, set allow root to `package.json` will make it working. ![enter image description here](https://i.stack.imgur.com/6ihnk.png) ![enter image description here](https://i.stack.imgur.com/e528k.png) Upvotes: 0
2018/03/22
525
1,875
<issue_start>username_0: I have one url that passes a parameter through the `as_view` function: ``` url( r'^$', ChangeListView.as_view( columns=('username', 'email') ), name="user-list" ), ``` When i try to access the columns attribute in the view it returns None instead of the tuple that i have passed through the url ``` class ChangeListView(generic.ListView): columns = None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(self.columns) # Returns None instead of tuple return context ```<issue_comment>username_1: You don't have anything that actually sets `self.columns` from the data you pass in. But this isn't the right way to do it. Instead, pass it as an [extra option](https://docs.djangoproject.com/en/2.0/topics/http/urls/#views-extra-options), and access it from the kwargs. ``` url( r'^$', ChangeListView.as_view(), {'columns': ('username', 'email')} name="user-list" ), ``` ... ``` print(self.kwargs['columns']) ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: I'm a bit confused by your question - any arguments passed to `as_view` should have been set as attributes on the view instance, so `self.columns` should be set to `('username', 'email')`. (See the source for [Django's base View class](https://github.com/django/django/blob/master/django/views/generic/base.py#L49%20Django's%20base%20View%20class)) However, the `context` variable (which is what you're returning) *should* be `None` in this case - what you pass to `as_view()` does not affect what is returned from `self.get_context_data()` (which is `None` by default). Maybe you meant to write `return self.columns`? On the other hand, if you meant that `print(self.columns)` unexpectedly prints nothing then I'm not sure what's going on. Upvotes: 0
2018/03/22
735
1,992
<issue_start>username_0: The idea is as follows: Suppose I have a list `P = [(1,0),(4,3)]` or similar. I want to evaluate the polynomial that's defined by this list in the manner: `1X^0 + 4X^3`. To do this, I've written the following: ``` evaluate(P,X,Y) :- evaluate(P,X,Y,0). evaluate([],_,S,S). evaluate([P1,P2|Ps],X,Y,S) :- S1 is S+P1*X^P2, evaluate(Ps,X,Y,S1). ``` Which is supposed to succeed when `Y` is the sum of the polynomial `P`, given `x=X`. The problem is that when I try and run this code, I get the error: > > is/2: Arithmetic: `(',')/2' is not a function > > > But I have no idea where this is coming from or how to fix it. I did try splitting the `S1` is up in to its segments, but doing that didn't help. **EDIT:** Ok, I found out that it's about the way the list is written down. How do I work with tuples in this way within the bounds of Prolog?<issue_comment>username_1: Your problem is that your data structure for each item in the list is a tuple as you noted and where you access the values of tuple in the list is not correct. This ``` evaluate([P1,P2|Ps],X,Y,S) :- ``` should be ``` evaluate([(P1,P2)|Ps],X,Y,S) :- ``` Notice the parenthesis around P1,P2. When I run with the change I get ``` ?- evaluate([(1,0),(4,3)],5,Y). Y = 501. ``` Also it is common to put the output arguments at the end, ``` evaluate_01(P,X,Y,0). ``` as ``` evaluate_01(P,X,0,Y). ``` and then change the other predicates as necessary. ``` evaluate_02(P,X,Y) :- evaluate_02(P,X,0,Y). evaluate_02([],_,S,S). evaluate_02([(P1,P2)|Ps],X,S,Y) :- S1 is S+P1*X^P2, evaluate_02(Ps,X,S1,Y). ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: As an interesting option, this can be done with `maplist/3` and `sumlist/2`: ``` evaluate_poly(Poly, X, R) :- maplist(evaluate_term(X), Poly, EvaluatedTerms), sumlist(EvaluatedTerms, R). evaluate_term(X, (Coeff, Power), TermValue) :- TermValue is Coeff * (X ^ Power). ``` Upvotes: 2
2018/03/22
507
2,058
<issue_start>username_0: how to start third activity if url is same in webview for example i have webview in my webview if url is like this <http://example.com/access.html> then start thirdactivity how can i do this please help me to fix this issue thanks in advance here is my webview code ``` public class SecondActivity extends AppCompatActivity { private WebView wv1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); String url = getIntent().getStringExtra("url"); wv1=(WebView)findViewById(R.id.webView); wv1.setWebViewClient(new WebViewClient()); wv1.getSettings().setLoadsImagesAutomatically(true); wv1.getSettings().setJavaScriptEnabled(true); wv1.loadUrl(url); } } ``` here is xml file of secondactivity ``` xml version="1.0" encoding="utf-8"? ```<issue_comment>username_1: ``` webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); // write your logic here. if (url.equals(pdfWebURL)) { loadingIndicator.setVisibility(View.VISIBLE); } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); loadingIndicator.setVisibility(View.GONE); } }); ``` please write your logic in onPageStarted. Upvotes: 1 <issue_comment>username_2: Please try below code ``` public class WebView extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String weburl) { if (weburl.equals("YOURLINK")) { Intent i = new Intent(getContext(), YourActivity.class); startActivity(i); return true; } else { view.loadUrl(url); return true; } } } ``` Upvotes: 0