date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/21
423
1,714
<issue_start>username_0: I am new in node.js, i want to fetch the data from table of the postgresql using sequelize ORM in node.js. I am using below code but its not working. ``` const apisListModel = sequelize.define('apisList', {}); apisListModel.findAll().then((data)=>{ JSON.stringify(data,undefined,2); },(e)=>{ console.log(e); }); ``` Its give me error ``` Executing (default): SELECT "id", "createdAt", "updatedAt" FROM "apisLists" AS "apisList"; { SequelizeDatabaseError: relation "apisLists" does not exist ``` But apiList table exist in my DATABASE<issue_comment>username_1: I haven't evaluated your code, but if the problem is that you try to set an attribute on `NULL`, then the solution is simple. Don't do that. The `NULL` object is not really an object. It is the *absence* of an object. You cannot modify it or set attributes to it; you cannot have `NULL` objects of different classes; `NULL` is nothing. You can set attributes to `NA` because that *is* an object -- just a missing value, but of a specific type. It is an explicit representation of the lack of a value. But `NULL` is different. It is R's way of representing that you do not have an object. There is no way to assign attributes to `NULL`. If you want a value that represents nothing but has classes or attributes, you need `NA` or some other representation. `NULL` isn't going to work. Upvotes: 1 <issue_comment>username_2: I had the same issue and found this old thread without a solution. In my case, I had rules defined with not matching characteristics as the defined variables. So check your variables and your rules. Upvotes: 0
2018/03/21
559
2,336
<issue_start>username_0: I'm having problems SSH'ing between ESXi guests that are on different hosts within the cluster. I've one guest that is on the routable cluster virtual network that I am using as a bastion server to access guests on a private network - the distributed port group spans all hosts. I'm using SSH ProxyJump to route through the bastion host to the other guest VM's. When the guests on the private network are on the same cluster host as the bastion there is no problem. When the guests are on a different host, I get a connect refused by the remote server error. If I manually migrate the VM to the same cluster as the bastion, the error goes away. I found [this](https://communities.vmware.com/thread/425852) answer which relates to SSH'ing between ESXi hosts, not guests on hosts, and suggests that SSH Client needs to be allowed on the outgoing firewall of each host. It seems like it could be relevant, but my vSphere knowledge is limited and I don't have sufficient admin rights to make this change myself. I'd be grateful if anyone could confirm if my inability to SSH between guests on different hosts is as a result of not having SSH Client enabled in the outbound firewall or if there is some other reason why I can't get an SSH connection?<issue_comment>username_1: I haven't evaluated your code, but if the problem is that you try to set an attribute on `NULL`, then the solution is simple. Don't do that. The `NULL` object is not really an object. It is the *absence* of an object. You cannot modify it or set attributes to it; you cannot have `NULL` objects of different classes; `NULL` is nothing. You can set attributes to `NA` because that *is* an object -- just a missing value, but of a specific type. It is an explicit representation of the lack of a value. But `NULL` is different. It is R's way of representing that you do not have an object. There is no way to assign attributes to `NULL`. If you want a value that represents nothing but has classes or attributes, you need `NA` or some other representation. `NULL` isn't going to work. Upvotes: 1 <issue_comment>username_2: I had the same issue and found this old thread without a solution. In my case, I had rules defined with not matching characteristics as the defined variables. So check your variables and your rules. Upvotes: 0
2018/03/21
455
1,626
<issue_start>username_0: I used the following code to connect to a asp.net core signalR server. But I could not manage to have a connection. Is there something I am doing wrong? I am getting this error, > > Error: The "promise" option must be a Promise > > > ``` var hubUrl = "http://localhost:52273/logNotifierHub"; var connection = new signalR.HubConnection(hubUrl ); var hub = connection.invoke("LogNotifierHub"); var hubStart = connection.start({ jsonp: true }); connection.on("streamStarted", function () { startStreaming(); }); var dataSource = new kendo.data.DataSource({ type: "signalr", schema: {}, transport: { signalr: { promise: hubStart, hub: hub, server: {read: "read"}, client: {read: "read"} } } }); $("#grid").kendoGrid({ dataSource: dataSource, height: 850, columns: [], }); ```<issue_comment>username_1: ASP.NET Core uses completely new SignalR version and it is still in alpha stage. That said, it is not supported with the Kendo components. Upvotes: 0 <issue_comment>username_2: The structure of the SignalR promise object has changed, but you can solve this problem by adjusting the kendo plugin. **kendo.data.signalr.js** ``` //if (typeof promise.done != 'function' || typeof promise.fail != 'function') if (typeof promise.then != 'function') ... //this.promise.done(function () { // hub.invoke.apply(hub, args).done(options.success).fail(options.error); //}); this.promise.then(function() { hub.invoke.apply(hub, args).then(options.success); }); ``` Upvotes: 1
2018/03/21
581
2,032
<issue_start>username_0: I've tried to get the value of **selectOneMenu** of Primefaces but it gives an error of not found property. My method in *UserBean* class return an **UserDTO** object and login is not **case-sensitive** in **Entity** class but it still catches an error. **UserBean** class; ``` public List getIds() { Object[] array = userService.getWrapperData().toArray(); List values = new ArrayList(); for (Object temp : array) { for (String s : temp.toString().split(",")) { if (("id").equals(s.split("=")[0])) values.add(s.split("=")[1]); } } String[] loginVals = new String[ values.size() ]; values.toArray( loginVals ); @SuppressWarnings("unchecked") List valuesLogin = (List) values; return valuesLogin; } ``` **UserDTO** entity class; ``` @Entity @Table(name="USERDTO") public class UserDTO implements Serializable { private String login; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } } ``` **indexDTO.xhtml** ``` ``` **Error log;** ``` javax.el.PropertyNotFoundException: Property 'login' not found on type java.lang.String ```<issue_comment>username_1: You are casting `List` to `List`: ``` List values = new ArrayList(); ... @SuppressWarnings("unchecked") List valuesLogin = (List) values; return valuesLogin; ``` You need to create `UserDTO` objects from those strings manually: ``` for(String login : values){ UserDTO dto = new UserDTO(); dto.setLogin(login); valuesLogin.add(dto); } ``` Additionally if you would add constructor `UserDTO(String login)` you could map `values` to `valuesLogin` easily: ``` valuesLogin = values.stream().map(UserDTO::new).collect(Collectors.toList()); ``` Upvotes: 1 <issue_comment>username_2: I solved my problem in a really weird way. I changed my UserBean method to this; ``` public List getIds() { return userService.getWrapperData(); } ``` And I can pull the ids from **indexDTO.xhtml** after that. Upvotes: 1 [selected_answer]
2018/03/21
1,085
3,878
<issue_start>username_0: I try to store the current time and date but get the following error: > > incompatible types: String cannot be converted to Date > > > This is the code: ``` DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); time.setUpdateDt(dtf.format(now)); public Date getUpdateDt() { return time; } public void setUpdateDt(Date time) { this.time = time; } ```<issue_comment>username_1: `dtf.format(now)` will return a `String`. You are getting the incompatible type error since you are trying to pass this value to the setter which accepts a `Date` object. Instead of `time.setUpdateDt(dtf.format(now));` You could use the `java.util.Date` class to create a new `Date` as follows - ``` DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); Date now = new Date(); time.setUpdateDt(dtf.format(now)); public Date getUpdateDt() { return time; } public void setUpdateDt(Date time) { this.time = time; } ``` Or, if you want use the existing `LocalDateTime`, you can convert it to `Date` by - ``` LocalDateTime now = LocalDateTime.now(); Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant()); time.setUpdateDt(dtf.format(date)); ``` Upvotes: 0 <issue_comment>username_2: dtf.format(now) returns a string. not a date object. if you just want to convert from LocalDate to Date, you could use this method: ``` LocalDateTime now = LocalDateTime.now(); Date yourDate = Date.from(datetime.atZone(ZoneId.systemDefault()).toInstant()); ``` however if you still need to parse a string, you could inject a parser and assign a date object in your class. for example: ``` public class Time { Date time; public Date getUpdateDt() { return time; } public void setUpdateDt(Date time) { this.time = time; } //this method will accept a string and inject a date format parser public void setUpdateDt(String timeStr,DateTimeFormatter dtf) { LocalDateTime datetime =LocalDateTime.parse(timeStr, dtf); this.time = Date.from(datetime.atZone(ZoneId.systemDefault()).toInstant()); } public static void main(String args[]) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); Time time = new Time(); time.setUpdateDt(dtf.format(now),dtf); System.out.println(time.getUpdateDt()); } ``` Upvotes: 0 <issue_comment>username_3: You are using a [`DateTimeFormatter`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.htm) to transform a `LocalDateTime` into a `String` with [`DateTimeFormatter.format`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#format-java.time.temporal.TemporalAccessor-). Then you send that result as a parameter to `setUpdateDt`. ``` public void setUpdateDt(Date time) ``` The problem is that you send a `String` instead of a `Date`. FYI: you are mixing the time technologies here. `Date` and `LocalDateTIme` are two distinct time API, you should not mix those. If you want your POJO to store a date, store it as `LocalDateTime`. ``` public void setUpdateDt(LocalDateTime time) ``` If you really want to get it as a `Date` from the `LocalDateTime`, check this answer: [Converting between java.time.LocalDateTime and java.util.Date](https://stackoverflow.com/a/23885950/4391450) Upvotes: 2 [selected_answer]<issue_comment>username_4: ``` initComponents(); ``` jDateChooser.setDate(new Date(fecha())); //Formato de Fecha public String fecha() { ``` Date fecha=new Date(); SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/YYYY", new Locale("es", "EC")); return formatoFecha.format(fecha); } ``` Upvotes: 0
2018/03/21
1,201
2,992
<issue_start>username_0: I have a csv file from which I have to get rows which have more then 2 characters from a specific coloumn. My csv file look like this ``` "Name" "Age" "ID" "RefID" "ABC" "12" "Abccc" "xyzw" "AAA" "14" "A" "X" "BBB" "18" "DEfff" "dfg" "CCY" "10" "F" "XY" "CCZ" "20" "R" "XYC" ``` So from column 3 and 4 I have take rows which have >= two characters. I tried following way ``` data = read.table(file ='res.csv', header = T) dat2 = as.character(data[,3]) ind = dat2[(which(nchar(dat2) >=2)),] ``` But its giving me error and I am not able to find out how can I proceed with both cols at once. My result should be like below ``` "Name" "Age" "ID" "RefID" "ABC" "12" "Abccc" "xyzw" "BBB" "18" "DEfff" "dfg" "CCY" "10" "F" "XY" "CCZ" "20" "R" "XYC" ``` Any help would be appriciated<issue_comment>username_1: We can avoid multiple steps, i.e. conversion to `character` class by specifying `stringsAsFactors = FALSE` in the `read.table` to avoid converting the character columns to `factor` class. Then, get the number of characters of the third column with `nchar` and create the logical condition by comparing if it is greater than or equal to 2 ``` data[nchar(data[,3])>=2,] # Name Age ID RefID #1 ABC 12 Abccc xyzw #3 BBB 18 DEfff dfg ``` For multiple columns, use `&` ``` data[nchar(data[,3])>=2 & data[,4] >=2,] ``` But, it would become a bit difficult when there are 100s of columns. For this purpose, we loop through the columns of interest, do the comparison and `Reduce` it to a single logical `vector` ``` data[Reduce(`&`, lapply(data[3:4], function(x) nchar(x) >=2)),] # Name Age ID RefID #1 ABC 12 Abccc xyzw #3 BBB 18 DEfff dfg ``` If the condition needs to be TRUE for `any` of the columns, then change the `&` to `|` in the `Reduce` ``` data[Reduce(`|`, lapply(data[3:4], function(x) nchar(x) >=2)),] # Name Age ID RefID #1 ABC 12 Abccc xyzw #3 BBB 18 DEfff dfg #4 CCY 10 F XY #5 CCZ 20 R XYC ``` ### data ``` data <- read.table(file ='res.csv', header = TRUE, stringsAsFactors = FALSE) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is a solution based on data.table. `stringsAsFactors = FALSE` is the default in `data.table::fread`. ``` require(data.table) x= fread('"Name" "Age" "ID" "RefID" "ABC" "12" "Abccc" "xyzw" "AAA" "14" "A" "X" "BBB" "18" "DEfff" "dfg" "CCY" "10" "F" "XY" "CCZ" "20" "R" "XYC"') x[nchar(ID)>2 | nchar(RefID)>2] Name Age ID RefID 1: ABC 12 Abccc xyzw 2: BBB 18 DEfff dfg ``` For the `OR` (`|`) case you could also melt by Name and Age and subset based on nchar. here is a one-liner: ``` z = melt(x, id.vars = c('Name', 'Age'))[nchar(value) > 2 ] z Name Age variable value 1: ABC 12 ID Abccc 2: BBB 18 ID DEfff 3: ABC 12 RefID xyzw 4: BBB 18 RefID dfg 5: CCZ 20 RefID XYC ``` Upvotes: 0
2018/03/21
900
3,650
<issue_start>username_0: I have written custom type with implicit cast operator ``` public class TcBool : TcDataTypeBase { public TcBool() : base(1, false) { } //For somewhat reason without this callin new TcBool() fails public TcBool(bool value = false) : base(1, value) { } public static implicit operator bool(TcBool var) => (bool)var.Value; public static implicit operator TcBool(bool value) => new TcBool(value); } public abstract class TcDataTypeBase { public readonly byte Size; public readonly object Value; public string Name { get; set; } public int IndexGroup { get; set; } public int IndexOffset { get; set; } internal TcDataTypeBase(byte size, object value) { Size = size; Value = value; } internal TcDataTypeBase(string name, byte size, object value) : this(size, value) { Name = name; } } ``` Then when I try to write it into a boolean property of an object using PropertyInfo.SetValue() it throws an exception saying it can't cast TcBool to System.Boolean. Is there something preventing the reflection mechanisms from using the implicit conversion or am I missing something?<issue_comment>username_1: Conversion operators have to be used by the compiler. Or rather, the compiler figures out that a conversion can be applied and inserts the appropriate call. At runtime this does not happen and you're left with incompatible types here, since `PropertyInfo.SetValue` just takes an `object`, so from the compiler's point of view no conversion is necessary. Upvotes: 1 <issue_comment>username_2: The compiler doesn't know it has to cast anything, because SetValue accepts an `object`, which is type-compatible with `TcBool` without any cast (and indeed, you cannot define an implicit cast operator to an ancestor type). To force a cast, you can do this: ``` property.SetValue(instance, (bool)TcBool); ``` This will trigger your implicit cast operator and create a Boolean, which is then boxed into an object and passed to SetValue. Upvotes: 4 [selected_answer]<issue_comment>username_3: Disclaimer: I realize that this is possibly overkill and will not work in case you don't know the types at compile time. --- The important thing to know is that the **implicit conversion operators are compiled into methods called [`"op_Implicit"`](https://www.codeproject.com/Articles/15191/Understanding-Implicit-Operator-Overloading-in-C)** and will therefore **not automatically be called**. So I created this (rather long) and hacky helper method which converts an object of type `TObject` to an object of type `TTo` while taking into account implicit conversion operators: ``` public static object Convert(TObject obj) { IEnumerable implicitConversionOperators = obj.GetType() .GetMethods() .Where(mi => mi.Name == "op\_Implicit"); MethodInfo fittingImplicitConversionOperator = null; foreach (MethodInfo methodInfo in implicitConversionOperators) { if (methodInfo.GetParameters().Any(parameter => parameter.ParameterType == typeof(TObject))) { fittingImplicitConversionOperator = methodInfo; } } if (fittingImplicitConversionOperator != null) { return fittingImplicitConversionOperator.Invoke(null, new object[] {obj}); } return (TTo) System.Convert.ChangeType(obj, typeof(TTo)); } ``` Of course it is far from being perfect, but it can be used like this ``` propertyInfo.SetValue(this, Helper.Convert(new TcBool(true))); ``` to set the property. Of course, if you don't know the types at compile time / don't want to have to be that verbose you could try `dynamic` etc. as it is shown in the other answers. Upvotes: 1
2018/03/21
406
1,172
<issue_start>username_0: I want to remove decimal point from the price. My HTML: ``` ₹399.00 ``` How can I remove .00 ?<issue_comment>username_1: You can use below method to remove decimal value. `Math.round();` Hope this can help you. Upvotes: 2 <issue_comment>username_2: You can use `substr` on the price value: ```js $(document).ready(function(){ var price = $('.price').text(); var numPrice = price.substr(0, price.indexOf('.')); $('.price').text(numPrice) }); ``` ```html ₹399.00 ``` Upvotes: 0 <issue_comment>username_3: Try this ``` var x = '399.00'; console.log(x); console.log(parseInt(x)); ``` Upvotes: 0 <issue_comment>username_4: Try this ```js var string = '₹399.00' var thenum = string.replace( /^\D+/g, ''); thenum = Math.trunc(thenum) alert(thenum) ``` Upvotes: 0 <issue_comment>username_5: Try using this jQuery code: ``` $(document).ready(function() { var text = $('.price').text(); $('.price').text("₹" + parseInt(text)); }); ``` Upvotes: 0 <issue_comment>username_6: ``` $('.price').html(Math.floor($('.price').html())); ``` use floor to remove it completely. using Math.round will result 1.5 to 2 Upvotes: 2
2018/03/21
486
1,485
<issue_start>username_0: Before the addition of the below code ![The list shows name and number](https://i.stack.imgur.com/0cxwx.png) After addition of the following lines of code ``` self.tableView.register(ContactListTableViewCell.self, forCellReuseIdentifier: "ContactCell") self.tableView.rowHeight = UITableViewAutomaticDimension ``` number disappears. ![After the addition of code](https://i.stack.imgur.com/wNGr9.png)<issue_comment>username_1: You can use below method to remove decimal value. `Math.round();` Hope this can help you. Upvotes: 2 <issue_comment>username_2: You can use `substr` on the price value: ```js $(document).ready(function(){ var price = $('.price').text(); var numPrice = price.substr(0, price.indexOf('.')); $('.price').text(numPrice) }); ``` ```html ₹399.00 ``` Upvotes: 0 <issue_comment>username_3: Try this ``` var x = '399.00'; console.log(x); console.log(parseInt(x)); ``` Upvotes: 0 <issue_comment>username_4: Try this ```js var string = '₹399.00' var thenum = string.replace( /^\D+/g, ''); thenum = Math.trunc(thenum) alert(thenum) ``` Upvotes: 0 <issue_comment>username_5: Try using this jQuery code: ``` $(document).ready(function() { var text = $('.price').text(); $('.price').text("₹" + parseInt(text)); }); ``` Upvotes: 0 <issue_comment>username_6: ``` $('.price').html(Math.floor($('.price').html())); ``` use floor to remove it completely. using Math.round will result 1.5 to 2 Upvotes: 2
2018/03/21
510
1,655
<issue_start>username_0: I'm having a problem ordering numbers that are saved as string in CRM, Its working fine until 10, then it says that 9 > 10 I know a simple solution where I can append zeros to the strings into a fixed length. Wondering if there is a way to order by a string by int in some way. My code: ``` QueryExpression query = new QueryExpression(entity); query.ColumnSet.AddColumn(ID); query.AddOrder(ID, OrderType.Descending); //there is a problem because the type is string. EntityCollection entityCollection = organizationService.RetrieveMultiple(query); ```<issue_comment>username_1: You can use below method to remove decimal value. `Math.round();` Hope this can help you. Upvotes: 2 <issue_comment>username_2: You can use `substr` on the price value: ```js $(document).ready(function(){ var price = $('.price').text(); var numPrice = price.substr(0, price.indexOf('.')); $('.price').text(numPrice) }); ``` ```html ₹399.00 ``` Upvotes: 0 <issue_comment>username_3: Try this ``` var x = '399.00'; console.log(x); console.log(parseInt(x)); ``` Upvotes: 0 <issue_comment>username_4: Try this ```js var string = '₹399.00' var thenum = string.replace( /^\D+/g, ''); thenum = Math.trunc(thenum) alert(thenum) ``` Upvotes: 0 <issue_comment>username_5: Try using this jQuery code: ``` $(document).ready(function() { var text = $('.price').text(); $('.price').text("₹" + parseInt(text)); }); ``` Upvotes: 0 <issue_comment>username_6: ``` $('.price').html(Math.floor($('.price').html())); ``` use floor to remove it completely. using Math.round will result 1.5 to 2 Upvotes: 2
2018/03/21
406
1,217
<issue_start>username_0: For the following code used in jquery, how can i code them in a reactjs function ? Can anyone help? ``` $('.row_1').css('display','none'); ```<issue_comment>username_1: You can use below method to remove decimal value. `Math.round();` Hope this can help you. Upvotes: 2 <issue_comment>username_2: You can use `substr` on the price value: ```js $(document).ready(function(){ var price = $('.price').text(); var numPrice = price.substr(0, price.indexOf('.')); $('.price').text(numPrice) }); ``` ```html ₹399.00 ``` Upvotes: 0 <issue_comment>username_3: Try this ``` var x = '399.00'; console.log(x); console.log(parseInt(x)); ``` Upvotes: 0 <issue_comment>username_4: Try this ```js var string = '₹399.00' var thenum = string.replace( /^\D+/g, ''); thenum = Math.trunc(thenum) alert(thenum) ``` Upvotes: 0 <issue_comment>username_5: Try using this jQuery code: ``` $(document).ready(function() { var text = $('.price').text(); $('.price').text("₹" + parseInt(text)); }); ``` Upvotes: 0 <issue_comment>username_6: ``` $('.price').html(Math.floor($('.price').html())); ``` use floor to remove it completely. using Math.round will result 1.5 to 2 Upvotes: 2
2018/03/21
982
2,991
<issue_start>username_0: How could I remove the vertical space between the objects while using `inline-book` ? [jsfiddle](http://jsfiddle.net/e6raLLc5/35/) I want keep different height for the cards, and make a fixed vertical space between them : Update : I want make the space of blue's circles exactly same gold's circles without change any thing else: ![enter image description here](https://i.stack.imgur.com/YLEyO.png)<issue_comment>username_1: Don not use `display:inline-block;` try to use `float:left;` and see if it works. I hope it will. Upvotes: 0 <issue_comment>username_2: New line is treated as one space when `display:inline-block` is used. You can either 1. Put everything in a single line without any spacing in between ```css .btn { padding: 0px; border: 1px solid red; display: inline-block; margin-bottom: 5px; } .txt { width: 120px; height: 120px; border: none; padding: 0; margin: 0; background: #77FF77; display: inline-block; } ``` 2. Add comments in between and (again without any spacing in between) ```css .btn { padding: 0px; border: 1px solid red; display: inline-block; margin-bottom: 5px; } .txt { width: 120px; height: 120px; border: none; padding: 0; margin: 0; background: #77FF77; display: inline-block; } ``` For the vertical space, you can add `margin-bottom: 5px;` to `.btn` Upvotes: 1 <issue_comment>username_3: Add `margin-bottom` property to `btn` class ``` .btn { border: 1px solid red; display: inline-block; margin-bottom:5px; } ``` Upvotes: 0 <issue_comment>username_4: Add these 3 lines to .txt class. ``` content: ""; display: table; clear: both; ``` <http://jsfiddle.net/e6raLLc5/67/> Upvotes: 0 <issue_comment>username_5: You can use CSS columns: <http://jsfiddle.net/e6raLLc5/112/> In this case I wrapped all boxes in another `div`: ``` ``` And set it to columns: ``` .wrapper { column-width:14px; /* 12px width + 2px border */ column-gap: 0; /* you can use 4px for some space between columns */ } ``` Another option is to use flexbox: <http://jsfiddle.net/e6raLLc5/79/> - but I think it is less robust: you have to set the height of the wrapper element, and the width of the boxes may vary. Either way, this changes the order in which your elements are displayed - instead of line by line, the second box will be *under* the first box. Upvotes: 0 <issue_comment>username_6: Would this work for you? <https://codepen.io/anon/pen/VXpxbo> I was unable to use the built in code snippet as your html is too long so instead I used codepen. Hopefully this helps. ``` .btn { padding: 0px; border: 1px solid red; display: inline-block; } .font-size-0 { font-size: 0; } .txt { width: 12px; height: 12px; border: none; padding: 0; margin: 0; background: #77FF77; } :matches( .btn, .font-size-0, .txt){ box-sizing: border-box; } ``` Upvotes: 1
2018/03/21
963
2,947
<issue_start>username_0: Can we use MERGE statement between 2 tables with different columns? I need to update few columns in target table T1 from source table T2 based on one condition(where T2.Song\_code=T1.Song\_code). But t1 has some columns which are not available in Source table. So did not exactly get how it could be used to see if the rows match. Can someone please explain?<issue_comment>username_1: Don not use `display:inline-block;` try to use `float:left;` and see if it works. I hope it will. Upvotes: 0 <issue_comment>username_2: New line is treated as one space when `display:inline-block` is used. You can either 1. Put everything in a single line without any spacing in between ```css .btn { padding: 0px; border: 1px solid red; display: inline-block; margin-bottom: 5px; } .txt { width: 120px; height: 120px; border: none; padding: 0; margin: 0; background: #77FF77; display: inline-block; } ``` 2. Add comments in between and (again without any spacing in between) ```css .btn { padding: 0px; border: 1px solid red; display: inline-block; margin-bottom: 5px; } .txt { width: 120px; height: 120px; border: none; padding: 0; margin: 0; background: #77FF77; display: inline-block; } ``` For the vertical space, you can add `margin-bottom: 5px;` to `.btn` Upvotes: 1 <issue_comment>username_3: Add `margin-bottom` property to `btn` class ``` .btn { border: 1px solid red; display: inline-block; margin-bottom:5px; } ``` Upvotes: 0 <issue_comment>username_4: Add these 3 lines to .txt class. ``` content: ""; display: table; clear: both; ``` <http://jsfiddle.net/e6raLLc5/67/> Upvotes: 0 <issue_comment>username_5: You can use CSS columns: <http://jsfiddle.net/e6raLLc5/112/> In this case I wrapped all boxes in another `div`: ``` ``` And set it to columns: ``` .wrapper { column-width:14px; /* 12px width + 2px border */ column-gap: 0; /* you can use 4px for some space between columns */ } ``` Another option is to use flexbox: <http://jsfiddle.net/e6raLLc5/79/> - but I think it is less robust: you have to set the height of the wrapper element, and the width of the boxes may vary. Either way, this changes the order in which your elements are displayed - instead of line by line, the second box will be *under* the first box. Upvotes: 0 <issue_comment>username_6: Would this work for you? <https://codepen.io/anon/pen/VXpxbo> I was unable to use the built in code snippet as your html is too long so instead I used codepen. Hopefully this helps. ``` .btn { padding: 0px; border: 1px solid red; display: inline-block; } .font-size-0 { font-size: 0; } .txt { width: 12px; height: 12px; border: none; padding: 0; margin: 0; background: #77FF77; } :matches( .btn, .font-size-0, .txt){ box-sizing: border-box; } ``` Upvotes: 1
2018/03/21
603
2,267
<issue_start>username_0: I have the following table: ``` CREATE TABLE [T_Manufacture]( [ManufactureID] [int] IDENTITY(-2147483648,1) NOT NULL, [Manufacture] [varchar](25) NULL, [ManufactureDescription] [varchar](50) NULL) ``` As we can see that the `ManufactureID` is identity column which is start from `-2147483648`. So if the identity reach -1 then the next record shoud be `0 (zero)`. Is it possible to skip this record? I mean, I don't wanna have an ID with value `zero`. Please help. Thank you.<issue_comment>username_1: You can control this with a trigger... ``` CREATE TRIGGER SkipZeroManufacture ON T_Manufacture AFTER INSERT AS BEGIN IF EXISTS (SELECT 'zero record inserted' FROM inserted AS I WHERE I.ManufactureID = 0) BEGIN INSERT INTO T_Manufacture ( Manufacture, ManufactureDescription) SELECT I.Manufacture, I.ManufactureDescription FROM inserted AS I WHERE i.ManufactureID = 0 DELETE T_Manufacture WHERE ManufactureID = 0 END END ``` Although this is an awful idea since it will be triggered on each insert, only check for one value and will need maintenance for new or updated columns. It will also switch the 0 ID'd record with another ID. Upvotes: 0 <issue_comment>username_2: This is an elaboration on Deepak's comment. Why would anyone use negative numbers for an id column? And, if you are concerned about having 2 billion values, then you should be concerned about 4 billion and use a `bigint`: ``` CREATE TABLE T_Manufacture ( ManufactureID bigint IDENTITY(1, 1) PRIMARY KEY, -- might as well declare it Manufacture varchar(25), ManufactureDescription varchar(50) ); ``` This is the simplest way to solve your problem and to ensure that the table can grow as large as you want. In other words, the right way to "skip" an particular value is to start the identity enumeration *after* that value. Or, if you really wanted: ``` CREATE TABLE T_Manufacture ( ManufactureID int IDENTITY(-1, -1) PRIMARY KEY, -- might as well declare it Manufacture varchar(25), ManufactureDescription varchar(50) ); ``` But once again, negative ids seem absurd. Upvotes: 2 [selected_answer]
2018/03/21
1,679
6,747
<issue_start>username_0: I want to show All pdf files present in internal as well as external storage, So on tapping that particular file, i want to open that file in full screen dialog.<issue_comment>username_1: So in order to do that you need to: * Grant access to external storage in a directory where there are your PDF file. Let's call that folder `/pdf`. * List all file of that directory a display them to the user. * Open the selected file with an application that can visualize PDF. In order to do all that thinks I suggest you to use those flutter packages: * [path\_provider](https://pub.dartlang.org/packages/path_provider) * [simple\_permission](https://pub.dartlang.org/packages/simple_permissions) With path\_provider you can get the external storage directory of an Android device. ``` Directory extDir = await getExternalStorageDirectory(); String pdfPath = extDir + "/pdf/"; ``` In order to access external storage you need to set this permission request in the `ApplicationManifest.xml`: ``` ``` You could also only use `READ_EXTERNAL_STORAGE` but then the simple\_permission plugin won't work. With the simple\_permission plugin then you go and ask user to be granted external storage access: ``` bool externalStoragePermissionOkay = false; _checkPermissions() async { if (Platform.isAndroid) { SimplePermissions .checkPermission(Permission.WriteExternalStorage) .then((checkOkay) { if (!checkOkay) { SimplePermissions .requestPermission(Permission.WriteExternalStorage) .then((okDone) { if (okDone) { debugPrint("${okDone}"); setState(() { externalStoragePermissionOkay = okDone; debugPrint('Refresh UI'); }); } }); } else { setState(() { externalStoragePermissionOkay = checkOkay; }); } }); } } ``` Once we have been granted external storage access we an list our PDF directory: ``` List \_files; \_files = dir.listSync(recursive: true, followLinks: false); ``` And show them in a ListView: ``` return new ListView.builder( padding: const EdgeInsets.all(16.0), itemCount: _files.length, itemBuilder: (context, i) { return _buildRow(_files.elementAt(i).path); }); ``` Than you have to open them with a viewer when the user tap on them. To do that there isn't an easy way, because with Android we need to build a ContentUri and give access to this URI to the exteranl application viewer. So we do that in Android and we use [flutter platform channels](https://flutter.io/platform-channels/) to call the Android native code. **Dart:** ``` static const platform = const MethodChannel('it.versionestabile.flutterapp000001/pdfViewer'); var args = {'url': fileName}; platform.invokeMethod('viewPdf', args); ``` **Native Java Code:** ``` public class MainActivity extends FlutterActivity { private static final String CHANNEL = "it.versionestabile.flutterapp000001/pdfViewer"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler( new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) { if (call.method.equals("viewPdf")) { if (call.hasArgument("url")) { String url = call.argument("url"); File file = new File(url); //* Uri photoURI = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider", file); //*/ Intent target = new Intent(Intent.ACTION_VIEW); target.setDataAndType(photoURI,"application/pdf"); target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(target); result.success(null); } } else { result.notImplemented(); } } }); } } ``` And after all we can have our PDF list and viewable on Android. [![enter image description here](https://i.stack.imgur.com/XXXtG.png)](https://i.stack.imgur.com/XXXtG.png) [![enter image description here](https://i.stack.imgur.com/puzPH.png)](https://i.stack.imgur.com/puzPH.png) [![enter image description here](https://i.stack.imgur.com/E3sR5.png)](https://i.stack.imgur.com/E3sR5.png) You have a lot to study. I hope this could be an useful playground for you. This is for External Storage, but you can get Also the Internal and Temporary directory and act similarly as here. If you wanna do the same thing on iOS you need to create the same Native Code `pdfViewer` also on iOS project. Refer alway to [flutter platform channels](https://flutter.io/platform-channels/) in order to do it. And remember that the external storage doesn't exists on iOS devices. So you could use only the application sandbox document folder or the temporary one. [GitHub repo](https://github.com/username_11/flutter_app_000001). Happy coding. Upvotes: 5 [selected_answer]<issue_comment>username_2: > > i use this code for list files and directories > > > ``` Future> dirContents(Directory dir) { var files = []; var completer = Completer>(); var lister = dir.list(recursive: false); lister.listen((file) async { FileStat f = file.statSync(); if (f.type == FileSystemEntityType.directory) { await dirContents(Directory(file.uri.toFilePath())); } else if (f.type == FileSystemEntityType.file && file.path.endsWith('.pdf')) { \_files.add(file); } }, onDone: () { completer.complete(files); setState(() { // }); }); return completer.future; } Directory dir = Directory('/storage/emulated/0'); var files = await dirContents(dir); print(files); ``` Upvotes: 0 <issue_comment>username_3: *Here is my code to list files from the download folder* ``` List filesList = []; Future listDir() async { Directory dir = Directory( '/storage/emulated/0/Download'); await for (FileSystemEntity entity in dir.list(recursive: true, followLinks: false)) { FileSystemEntityType type = await FileSystemEntity.type(entity.path); if (type == FileSystemEntityType.file && entity.path.endsWith('.pdf')) { filesList.add(entity.path); } } return filesList;} ``` Upvotes: 0
2018/03/21
330
1,358
<issue_start>username_0: I have created maven project with selenium and TestNG. When I run the project using pom file it does not generate TestNG results (test-output folder). But when I run the project as testng.xml->(right click) run as -> TestNG suite, it generates the results<issue_comment>username_1: While working with multiple frameworks e.g. *TestNG*, *Maven*, *Gradle* due to synchronization issues within your *IDE* sometimes the **test-output folder** doesn't gets populated with the intended test *results/output* and the *output* tends to remain **buffered**. In these cases once the *Test Execution* gets completed *Refresh* the *Maven Project* and your *test-output folder* would get populated with the intended *results/output*. Upvotes: 2 <issue_comment>username_2: As you are running testng tests from Maven (Surefire), your output folder will be `target` instead of `test-output` as defined by the surefire plugin, so if you are looking for file `testng-results.xml` or any other testng files then check at `\target\surefire-reports\testng-results.xml` Upvotes: 1 <issue_comment>username_3: In Run from testNg.xml directly -By default in maven project html reports get created into test-output folder In case we run from pom.xml using surefire plugin - Reports will get created into target\surefire-reports. Upvotes: 3 [selected_answer]
2018/03/21
534
2,104
<issue_start>username_0: I am trying to get results from two tables by filter. I want to get all the properties and if there is an agreement I also want to include the renters first and last name. Below is a simple model. ``` class Property(models.Model): name = models.CharField(max_length=70, blank=True, verbose_name="Property Name") class Agreement(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE, related_name="prop") firstname = models.CharField(max_length=40, verbose_name="First Name") lastname = models.CharField(max_length=40, verbose_name="Last Name") ``` Normally I get all the properties with ``` properties = Properties.objects.all() ``` Is there some way like below: ``` properties = Properties.objects.all() \ .somemethod(get values of firstname and lastname from aggreement if related record exists.) ``` I can loop at properties results and get the values from agreements. But I think this is not the preferred way as it will make many SQL calls.<issue_comment>username_1: While working with multiple frameworks e.g. *TestNG*, *Maven*, *Gradle* due to synchronization issues within your *IDE* sometimes the **test-output folder** doesn't gets populated with the intended test *results/output* and the *output* tends to remain **buffered**. In these cases once the *Test Execution* gets completed *Refresh* the *Maven Project* and your *test-output folder* would get populated with the intended *results/output*. Upvotes: 2 <issue_comment>username_2: As you are running testng tests from Maven (Surefire), your output folder will be `target` instead of `test-output` as defined by the surefire plugin, so if you are looking for file `testng-results.xml` or any other testng files then check at `\target\surefire-reports\testng-results.xml` Upvotes: 1 <issue_comment>username_3: In Run from testNg.xml directly -By default in maven project html reports get created into test-output folder In case we run from pom.xml using surefire plugin - Reports will get created into target\surefire-reports. Upvotes: 3 [selected_answer]
2018/03/21
2,424
7,393
<issue_start>username_0: I have a below properties file and would like to parse it as mentioned below. Please help in doing this. .ini file which I created : ``` [Machine1] app=version1 [Machine2] app=version1 app=version2 [Machine3] app=version1 app=version3 ``` I am looking for a solution in which ini file should be parsed like ``` [Machine1]app = version1 [Machine2]app = version1 [Machine2]app = version2 [Machine3]app = version1 [Machine3]app = version3 ``` Thanks.<issue_comment>username_1: Try: ``` $ awk '/\[/{prefix=$0; next} $1{print prefix $0}' file.ini [Machine1]app=version1 [Machine2]app=version1 [Machine2]app=version2 [Machine3]app=version1 [Machine3]app=version3 ``` How it works * `/\[/{prefix=$0; next}` If any line begins with `[`, we save the line in the variable `prefix` and then we skip the rest of the commands and jump to the `next` line. * `$1{print prefix $0}` If the current line is not empty, we print the prefix followed by the current line. ### Adding spaces To add spaces around any occurrence of `=`: ``` $ awk -F= '/\[/{prefix=$0; next} $1{$1=$1; print prefix $0}' OFS=' = ' file.ini [Machine1]app = version1 [Machine2]app = version1 [Machine2]app = version2 [Machine3]app = version1 [Machine3]app = version3 ``` This works by using `=` as the field separator on input and `=` as the field separator on output. Upvotes: 5 [selected_answer]<issue_comment>username_2: You can try using `awk`: ``` awk '/\[[^]]*\]/{ # Match pattern like [...] a=$1;next # store the pattern in a } NF{ # Match non empty line gsub("=", " = ") # Add space around the = character print a $0 # print the line }' file ``` Upvotes: 2 <issue_comment>username_3: I love [username_1's answer](https://stackoverflow.com/a/49400353/13376511). I was looking for exactly that. I have created a bash function that allows me to lookup sections or specific keys based on his idea: ``` function iniget() { if [[ $# -lt 2 || ! -f $1 ]]; then echo "usage: iniget [--list| [key]]" return 1 fi local inifile=$1 if [ "$2" == "--list" ]; then for section in $(cat $inifile | grep "\[" | sed -e "s#\[##g" | sed -e "s#\]##g"); do echo $section done return 0 fi local section=$2 local key [ $# -eq 3 ] && key=$3 # https://stackoverflow.com/questions/49399984/parsing-ini-file-in-bash # This awk line turns ini sections => [section-name]key=value local lines=$(awk '/\[/{prefix=$0; next} $1{print prefix $0}' $inifile) for line in $lines; do if [[ "$line" = \[$section\]\* ]]; then local keyval=$(echo $line | sed -e "s/^\[$section\]//") if [[ -z "$key" ]]; then echo $keyval else if [[ "$keyval" = $key=\* ]]; then echo $(echo $keyval | sed -e "s/^$key=//") fi fi fi done } ``` So given this as file.ini ``` [Machine1] app=version1 [Machine2] app=version1 app=version2 [Machine3] app=version1 app=version3 ``` then the following results are produced ``` $ iniget file.ini --list Machine1 Machine2 Machine3 $ iniget file.ini Machine3 app=version1 app=version3 $ iniget file.ini Machine1 app version1 $ iniget file.ini Machine2 app version2 version3 ``` Again, thanks to @username_1 for his answer, I was pulling my hair out trying to create a simple bash ini parser that supported sections. Tested on Mac using GNU bash, version 5.0.0(1)-release (x86\_64-apple-darwin18.2.0) Upvotes: 3 <issue_comment>username_4: Excellent answers here. I made some modifications to @username_3's function to fit it better to my use case. This version is largely the same except it allows for whitespace before and after `=` characters, and allows values to have spaces in them. ``` # Get values from a .ini file function iniget() { if [[ $# -lt 2 || ! -f $1 ]]; then echo "usage: iniget [--list| [key]]" return 1 fi local inifile=$1 if [ "$2" == "--list" ]; then for section in $(cat $inifile | grep "^\\s\*\[" | sed -e "s#\[##g" | sed -e "s#\]##g"); do echo $section done return 0 fi local section=$2 local key [ $# -eq 3 ] && key=$3 # This awk line turns ini sections => [section-name]key=value local lines=$(awk '/\[/{prefix=$0; next} $1{print prefix $0}' $inifile) lines=$(echo "$lines" | sed -e 's/[[:blank:]]\*=[[:blank:]]\*/=/g') while read -r line ; do if [[ "$line" = \[$section\]\* ]]; then local keyval=$(echo "$line" | sed -e "s/^\[$section\]//") if [[ -z "$key" ]]; then echo $keyval else if [[ "$keyval" = $key=\* ]]; then echo $(echo $keyval | sed -e "s/^$key=//") fi fi fi done <<<"$lines" } ``` Upvotes: 2 <issue_comment>username_5: For taking disparate sectional and tacking the section name (including 'no-section'/Default together) to each of its related keyword (along with `=` and its keyvalue), this one-liner AWK will do the trick coupled with a few clean-up regex. ```sh ini_buffer="$(echo "$raw_buffer" | awk '/^\[.*\]$/{obj=$0}/=/{print obj $0}')" ``` Will take your lines and output them like you wanted: ``` +++ awk '/^\[.*\]$/{obj=$0}/=/{print obj $0}' ++ ini_buffer='[Machine1]app=version1 [Machine2]app=version1 [Machine2]app=version2 [Machine3]app=version1 [Machine3]app=version3' ``` A complete solution to the INI-format File ========================================== As [Clonato, INI-format expert](https://cloanto.com/specs/ini/#escapesequences) said that for the latest INI version 1.4 (2009-10-23), there are several other tricky aspects to the INI file: 1. character set constraint for section name 2. character set constraint for keyword 3. And lastly is for the keyvalue to be able to handle pretty much anthing that is not used in the section and keyword name; that includes nesting of quotes inside a pair of same single/double-quote. Except for the nesting of quotes, a [INI-format Github](https://github.com/egberts/bash-ini-file) complete solution to parsing INI-format file with default section: ```sh # syntax: ini_file_read # outputs: formatted bracket-nested "[section]keyword=keyvalue" ini\_file\_read() { local ini\_buffer raw\_buffer hidden\_default raw\_buffer="$1" # somebody has to remove the 'inline' comment # there is a most complex SED solution to nested # quotes inline comment coming ... TBA raw\_buffer="$(echo "$raw\_buffer" | sed ' s|[[:blank:]]\*//.\*||; # remove //comments s|[[:blank:]]\*#.\*||; # remove #comments t prune b :prune /./!d; # remove empty lines, but only those that # become empty as a result of comment stripping' )" # awk does the removal of leading and trailing spaces ini\_buffer="$(echo "$raw\_buffer" | awk '/^\[.\*\]$/{obj=$0}/=/{print obj $0}')" # original ini\_buffer="$(echo "$ini\_buffer" | sed 's/^\s\*\[\s\*/\[/')" ini\_buffer="$(echo "$ini\_buffer" | sed 's/\s\*\]\s\*/\]/')" # finds all 'no-section' and inserts '[Default]' hidden\_default="$(echo "$ini\_buffer" \ | egrep '^[-0-9A-Za-z\_\$\.]+=' | sed 's/^/[Default]/')" if [ -n "$hidden\_default" ]; then echo "$hidden\_default" fi # finds sectional and outputs as-is echo "$(echo "$ini\_buffer" | egrep '^\[\s\*[-0-9A-Za-z\_\$\.]+\s\*\]')" } ``` The unit test for this StackOverflow post is included in this file: * <https://github.com/egberts/bash-ini-file> Source: * <https://github.com/egberts/easy-admin/blob/main/test/section-regex.sh> * <https://cloanto.com/specs/ini/#escapesequences> Upvotes: 0
2018/03/21
2,417
7,382
<issue_start>username_0: I have got a project for which I need to translate the urls from wikispaces format to the wordpress. What I am looking for is to replace > > .html > > > with > > / > > > where the text is in the following format ``` <a class="identifier-class" href="<some_variable_url>.html>...... ``` with ``` <a class="identifier-class" href="<some_variable_url>/>...... ``` What string replacement regex can I use to replace it in Notepad++<issue_comment>username_1: Try: ``` $ awk '/\[/{prefix=$0; next} $1{print prefix $0}' file.ini [Machine1]app=version1 [Machine2]app=version1 [Machine2]app=version2 [Machine3]app=version1 [Machine3]app=version3 ``` How it works * `/\[/{prefix=$0; next}` If any line begins with `[`, we save the line in the variable `prefix` and then we skip the rest of the commands and jump to the `next` line. * `$1{print prefix $0}` If the current line is not empty, we print the prefix followed by the current line. ### Adding spaces To add spaces around any occurrence of `=`: ``` $ awk -F= '/\[/{prefix=$0; next} $1{$1=$1; print prefix $0}' OFS=' = ' file.ini [Machine1]app = version1 [Machine2]app = version1 [Machine2]app = version2 [Machine3]app = version1 [Machine3]app = version3 ``` This works by using `=` as the field separator on input and `=` as the field separator on output. Upvotes: 5 [selected_answer]<issue_comment>username_2: You can try using `awk`: ``` awk '/\[[^]]*\]/{ # Match pattern like [...] a=$1;next # store the pattern in a } NF{ # Match non empty line gsub("=", " = ") # Add space around the = character print a $0 # print the line }' file ``` Upvotes: 2 <issue_comment>username_3: I love [username_1's answer](https://stackoverflow.com/a/49400353/13376511). I was looking for exactly that. I have created a bash function that allows me to lookup sections or specific keys based on his idea: ``` function iniget() { if [[ $# -lt 2 || ! -f $1 ]]; then echo "usage: iniget [--list| [key]]" return 1 fi local inifile=$1 if [ "$2" == "--list" ]; then for section in $(cat $inifile | grep "\[" | sed -e "s#\[##g" | sed -e "s#\]##g"); do echo $section done return 0 fi local section=$2 local key [ $# -eq 3 ] && key=$3 # https://stackoverflow.com/questions/49399984/parsing-ini-file-in-bash # This awk line turns ini sections => [section-name]key=value local lines=$(awk '/\[/{prefix=$0; next} $1{print prefix $0}' $inifile) for line in $lines; do if [[ "$line" = \[$section\]\* ]]; then local keyval=$(echo $line | sed -e "s/^\[$section\]//") if [[ -z "$key" ]]; then echo $keyval else if [[ "$keyval" = $key=\* ]]; then echo $(echo $keyval | sed -e "s/^$key=//") fi fi fi done } ``` So given this as file.ini ``` [Machine1] app=version1 [Machine2] app=version1 app=version2 [Machine3] app=version1 app=version3 ``` then the following results are produced ``` $ iniget file.ini --list Machine1 Machine2 Machine3 $ iniget file.ini Machine3 app=version1 app=version3 $ iniget file.ini Machine1 app version1 $ iniget file.ini Machine2 app version2 version3 ``` Again, thanks to @username_1 for his answer, I was pulling my hair out trying to create a simple bash ini parser that supported sections. Tested on Mac using GNU bash, version 5.0.0(1)-release (x86\_64-apple-darwin18.2.0) Upvotes: 3 <issue_comment>username_4: Excellent answers here. I made some modifications to @username_3's function to fit it better to my use case. This version is largely the same except it allows for whitespace before and after `=` characters, and allows values to have spaces in them. ``` # Get values from a .ini file function iniget() { if [[ $# -lt 2 || ! -f $1 ]]; then echo "usage: iniget [--list| [key]]" return 1 fi local inifile=$1 if [ "$2" == "--list" ]; then for section in $(cat $inifile | grep "^\\s\*\[" | sed -e "s#\[##g" | sed -e "s#\]##g"); do echo $section done return 0 fi local section=$2 local key [ $# -eq 3 ] && key=$3 # This awk line turns ini sections => [section-name]key=value local lines=$(awk '/\[/{prefix=$0; next} $1{print prefix $0}' $inifile) lines=$(echo "$lines" | sed -e 's/[[:blank:]]\*=[[:blank:]]\*/=/g') while read -r line ; do if [[ "$line" = \[$section\]\* ]]; then local keyval=$(echo "$line" | sed -e "s/^\[$section\]//") if [[ -z "$key" ]]; then echo $keyval else if [[ "$keyval" = $key=\* ]]; then echo $(echo $keyval | sed -e "s/^$key=//") fi fi fi done <<<"$lines" } ``` Upvotes: 2 <issue_comment>username_5: For taking disparate sectional and tacking the section name (including 'no-section'/Default together) to each of its related keyword (along with `=` and its keyvalue), this one-liner AWK will do the trick coupled with a few clean-up regex. ```sh ini_buffer="$(echo "$raw_buffer" | awk '/^\[.*\]$/{obj=$0}/=/{print obj $0}')" ``` Will take your lines and output them like you wanted: ``` +++ awk '/^\[.*\]$/{obj=$0}/=/{print obj $0}' ++ ini_buffer='[Machine1]app=version1 [Machine2]app=version1 [Machine2]app=version2 [Machine3]app=version1 [Machine3]app=version3' ``` A complete solution to the INI-format File ========================================== As [Clonato, INI-format expert](https://cloanto.com/specs/ini/#escapesequences) said that for the latest INI version 1.4 (2009-10-23), there are several other tricky aspects to the INI file: 1. character set constraint for section name 2. character set constraint for keyword 3. And lastly is for the keyvalue to be able to handle pretty much anthing that is not used in the section and keyword name; that includes nesting of quotes inside a pair of same single/double-quote. Except for the nesting of quotes, a [INI-format Github](https://github.com/egberts/bash-ini-file) complete solution to parsing INI-format file with default section: ```sh # syntax: ini_file_read # outputs: formatted bracket-nested "[section]keyword=keyvalue" ini\_file\_read() { local ini\_buffer raw\_buffer hidden\_default raw\_buffer="$1" # somebody has to remove the 'inline' comment # there is a most complex SED solution to nested # quotes inline comment coming ... TBA raw\_buffer="$(echo "$raw\_buffer" | sed ' s|[[:blank:]]\*//.\*||; # remove //comments s|[[:blank:]]\*#.\*||; # remove #comments t prune b :prune /./!d; # remove empty lines, but only those that # become empty as a result of comment stripping' )" # awk does the removal of leading and trailing spaces ini\_buffer="$(echo "$raw\_buffer" | awk '/^\[.\*\]$/{obj=$0}/=/{print obj $0}')" # original ini\_buffer="$(echo "$ini\_buffer" | sed 's/^\s\*\[\s\*/\[/')" ini\_buffer="$(echo "$ini\_buffer" | sed 's/\s\*\]\s\*/\]/')" # finds all 'no-section' and inserts '[Default]' hidden\_default="$(echo "$ini\_buffer" \ | egrep '^[-0-9A-Za-z\_\$\.]+=' | sed 's/^/[Default]/')" if [ -n "$hidden\_default" ]; then echo "$hidden\_default" fi # finds sectional and outputs as-is echo "$(echo "$ini\_buffer" | egrep '^\[\s\*[-0-9A-Za-z\_\$\.]+\s\*\]')" } ``` The unit test for this StackOverflow post is included in this file: * <https://github.com/egberts/bash-ini-file> Source: * <https://github.com/egberts/easy-admin/blob/main/test/section-regex.sh> * <https://cloanto.com/specs/ini/#escapesequences> Upvotes: 0
2018/03/21
221
937
<issue_start>username_0: Just came to my attention that there are now more regions supporting Cognito. Is it possible to move a user pool from one region to another?<issue_comment>username_1: AWS Cognito, does not replicate ( moving or sharing) the user pools across the regions at the moment, if your users / clients are closer to the region then there will be a minimum propagation delays and users will have a better speed to get the resources from the data center. If you want to authenticate your users across the region that will be possible by the API they have provided (For example, in javascript sdk you need to mention the region while setting up API for authentication and accessing resources). Upvotes: 2 <issue_comment>username_2: For the folks tuning in now , As of June 2020 cognito supports multi-region user pools. <https://aws.amazon.com/about-aws/whats-new/2020/04/introducing-multi-region-user-pools/> Upvotes: 0
2018/03/21
1,092
3,597
<issue_start>username_0: I have EF model class and I've decided to extend that class with one `bool` property: ``` class A { public int Id { get; set; } public string Value { get; set; } } class A_DTO : A { public bool BoolProp { get; set; } } class C { public int Id { get; set; } public int A_Id { get; set; } } ``` Then I wrote a method, which will return that `A` collection joined with some other `C` collection, which contains A <=> C mapping (well, in real world example it contains some `SystemId` and linq query will be joined by 2 columns) and returns `A_DTO` collection: ``` internal IQueryable MyMethod() => from a in dbContext.A join c in dbContext.A\_C\_Mapping on a.Id equals c.A\_Id into g from cc in gg.DefaultIfEmpty() select new A\_DTO { Id = a.Id, Value = a.Value, BoolProp = cc.A\_Id != null //<- will be always true, well, that what says warning message } ``` (`dbContext` is my EF context object) and of course because of `cc.A_Id` is not a nullable `int` the warning message will appear, saying that > > *"The result of expression will be always `'true'` since the value of type `int` is never equal to `null` value of type `int?`"* > > > which is true, but in fact I get results perfectly correct, because of my left outer join return `null`s when mapping missing in `C` collection. So the question: is it correct approach to do so and leave it as it is, or I need to implement it another way?<issue_comment>username_1: If the cc.A\_Id is never going to become null and you want to set the value for BoolProp then you can remove the warning by changing your select to be the following: ``` select new A_DTO { Id = a.Id, Value = a.Value, BoolProp = true } ``` Upvotes: 0 <issue_comment>username_2: `Value Types` will always have a default value (exception when declaring them as `Nullable`) even when they are not initalized, even if you are using a [LEFT OUTER JOIN](https://learn.microsoft.com/en-us/dotnet/csharp/linq/perform-left-outer-joins) through `LINQ`. Thus `A_ID` will always have a value, and `BoolProp` will always be true. On the other hand, `Reference Types` will default to `NULL`. Upvotes: 0 <issue_comment>username_3: According to the [DefaultIfEmpty method definition](https://msdn.microsoft.com/en-us/library/bb360179(v=vs.110).aspx), the following code snippets are equivalent: ``` List list = new List() { }; // empty list List listDefault = list.DefaultIfEmpty().ToList(); ``` and ``` List listDefault = new List() { null }; // Since default(C) is null ``` Thus when you use g.DefaultIfEmpty() you will get a unique cc object which is null, consequently the line: ``` BoolProp = cc.A_Id != null ``` will throw a NullReferenceException because cc is null. At the end it seems that the condition should be: ``` BoolProp = cc != null ``` Besides here is a small example which demonstrates the difference through a unit test: ``` [TestMethod] public void TestMethod_DefaultifEmpty() { ListA = new List() { new A { Id=1, Value="111" }, new A { Id=2, Value="222" }, }; ListC = new List() { new C { Id=1, A\_Id=1 } }; Assert.AreEqual(2, MyMethod().Count()); } public ListListA { get; set; } public List ListC { get; set; } public IEnumerable MyMethod() => from a in ListA join c in ListC on a.Id equals c.A\_Id into g from cc in g.DefaultIfEmpty() select new A\_DTO { Id = a.Id, Value = a.Value, //BoolProp = cc.A\_Id != null BoolProp = cc != null // replace by previous line to see the difference }; ``` Upvotes: 3 [selected_answer]
2018/03/21
260
1,069
<issue_start>username_0: It takes UTC + 0 for the application to work, but the exact minutes and seconds are needed. Since access to the network is not permanent, The exact time can not always be determined. If the method is still like that, determine the exact time.<issue_comment>username_1: use **System.currentTimeMillis()** to get current timestamp and then convert it to minutes with following method ``` public long getCurrentMinOfHour() { Calendar c = Calendar.getInstance(); c.setTimeInMillis(System.currentTimeMillis()); return (long)((c.get(Calendar.MINUTE) * 60 * 1000)) ; } ``` Upvotes: 0 <issue_comment>username_2: If your application is dependent on the network time, what you can do is the following. When network becomes available: 1. use the network to get the time 2. get system time 3. calculate the difference 4. store the difference 5. use the network time When network is not available: 1. get the stored difference 2. get system time 3. calculate the needed time 4. use the calculated time Upvotes: 2
2018/03/21
721
2,721
<issue_start>username_0: In my use case i want to show side menu as well as tabs in my ionic 3 angular app. The use case is: showing tabs initially with side menu hidden (set as enable(false)). The first page shows a button to add to cart, doing this shows a cart in the header area and clicking the cart shows a login page. Once u login the order summary page comes up. At this point i want to show the side menu. So in `ionviwedidload` i am setting the `menu.enable(true)`. Though it shows the menu icon but actual menu does not appear. The minimal test case is <https://www.dropbox.com/s/tq202w3p6yf32fj/tab-menu_app.zip?dl=0> To Try: 1. Run the app 2. Click on the add to cart button 3. Click on the shopping cart in the header in right side 4. This brings login page model. click on login button 5. Summary page shows up with menu icon. clicking it does nothing though<issue_comment>username_1: I have checked your code and based on my understanding you need to change your navigation flow. As you are setting `OrderSummaryPage` page as **root** view due to this App unable to show the menu on your screen. To solve this issue you need to Push `OrderSummaryPage` from the Home page and over there you have 2 options 1. Hide back button and show the menu button. 2. Don't show menu button over there just show default back button and while user clicks on back it will come back on the home screen where you will get your menu button. By click on the menu button, you will get your menu screen. Check this code: **Step1:** Update your OpenCart method: ``` openCart(){ let loginModal = this.modalCtrl.create(LoginPage, { userId: 8675309 }); loginModal.onDidDismiss(data => { console.log(data); this.navCtrl.push(OrderSummaryPage); }); loginModal.present(); } ``` **Step2:** Update your login method in LoginPage ``` login(){ this.viewCtrl.dismiss() } ``` Now if you want to hide back button on OrderSummeryPage use below code in ``` // for hiding back button. ``` Hope you can understand the above changes. Upvotes: 4 [selected_answer]<issue_comment>username_2: If you are navigating to the to the first Page (HomePage) from any page and you use navCtrl.setRoot(HomePage); first of all remove all other page before that one with navCtrl.remove(indexOfFirstPageAfterHomePage,numberOfPagesToRemove) Example: HomePage => ViewprofilePage => EditprofilePage => ConfirmationPage To navigate from ConfirmationPage back to HomePage with navCtrl.setRoot(HomePage); remove ViewprofilePage, EditprofilePage first, else the sidemenu will not open on the HomePage. Remove both with navCtrl.remove(1,2). It worked for me. I hope its helpful Upvotes: 0
2018/03/21
984
2,711
<issue_start>username_0: I need to get the float number inside brackets.. I tried this `'([0-9]*[.])?[0-9]+'` but it returns the first number like 6 in the first example. Also I tried this ``` '/\((\d+)\)/' ``` but it returns 0. Please note that I need the extracted number either int or float. Can u plz help [![enter image description here](https://i.stack.imgur.com/R6I8V.png)](https://i.stack.imgur.com/R6I8V.png)<issue_comment>username_1: You could escape brackets: ``` $str = 'Serving size 6 pieces (41.5)'; if (preg_match('~\((\d+.?\d*)\)~', $str, $matches)) { print_r($matches); } ``` Outputs: ``` Array ( [0] => (41.5) [1] => 41.5 ) ``` Regex: ``` \( # open bracket ( # capture group \d+ # one or more numbers .? # optional dot \d* # optional numbers ) # end capture group \) # close bracket ``` You could also use this to get only one digit after the dot: ``` '~\((\d+.?\d?)\)~' ``` Upvotes: 0 <issue_comment>username_2: As you need to match bracket also, You need to add `()` in regular expression: ``` $str = 'Serving size 6 pieces (40)'; $str1 = 'Per bar (41.5)'; preg_match('#\(([0-9]*[.]?[0-9]+)\)#', $str, $matches); print_r($matches); preg_match('#\(([0-9]*[.]?[0-9]+)\)#', $str1, $matches); print_r($matches); ``` Output: ``` Array ( [0] => (40) [1] => 40 ) Array ( [0] => (41.5) [1] => 41.5 ) ``` [DEMO](https://3v4l.org/BcoIh) Upvotes: 1 <issue_comment>username_3: You need to escape the brackets ``` preg_match('/\((\d+(?:\.\d+)?)\)/', $search, $matches); ``` explanation ``` \( escaped bracket to look for ( open subpattern \d a number + one or more occurance of the character mentioned ( open Group ?: dont save data in a subpattern \. escaped Point \d a number + one or more occurance of the character mentioned ) close Group ? one or no occurance of the Group mentioned ) close subpattern \) escaped closingbracket to look for ``` matches numbers like 1, 1.1, 11, 11.11, 111, 111.111 but NOT .1, . <https://regex101.com/r/ei7bIM/1> Upvotes: 0 <issue_comment>username_4: You could match an opening parenthesis, use `\K` to reset the starting point of the reported match and then match your value: [`\(\K\d+(?:\.\d+)?(?=\))`](https://regex101.com/r/aHOG2V/1) That would match: * `\(` Match ( * `\K` Reset the starting point of the reported match * `\d+` Match one or more digits * `(?: Non capturing group` + `\.\d+` Match a dot and one or more digits * `)?` Close non capturing group and make it optional * `(?=` Positive lookahead that asserts what follows is + `\)` Match ) * `)` Close posive lookahead [Demo php](https://3v4l.org/bmhMo) Upvotes: 0
2018/03/21
431
1,319
<issue_start>username_0: I want to set the `order id` on the very left and set the rest of the two to the very right of the div. The `total` and `view` elements should have equal space between them but should be to the right. `justify-content:space-between` sets equal space in between them and flex-grow or shrink is not working in my case. Am i doing something wrong? please help. ``` ORDER ID TOTAL VIEW ```<issue_comment>username_1: You can't split into *66%+33%+33%* ,You could give `flex` 2+1+1 ```css .text-center { text-align:center; } ``` ```html ORDER ID TOTAL VIEW ``` Upvotes: 2 <issue_comment>username_2: Try to use `margin` on flex items to align them `left` and `right` ```css div { display: flex; } .orders-table-text { border: 1px solid red; } .orders-table-text.right { margin-left: auto; } .orders-table-text.left { margin-right: auto; } ``` ```html ORDER ID TOTAL VIEW ``` Upvotes: 1 <issue_comment>username_3: If you wrap your two right items into a div, `justify-content: space-between` will work as you are expecting: ```css .orders-table-header { display: flex; justify-content: space-between; } .orders-table-text { border: 1px solid red; } .right { display: flex; } ``` ```html ORDER ID TOTAL VIEW ``` Upvotes: 0
2018/03/21
523
1,920
<issue_start>username_0: I'm having trouble figuring out how to customize console.log() so that it automatically prints out the label for each argument I pass into it. For example, I often do something like this, so that it's clear what each log is printing out: `console.log('firstName: ', firstName);` I would love to be able to simplify this to: `my.log(firstName);` Is there any way to pass the variable names of the caller args into `console.log()`? Or is there another way to do this? My wish is that I don't have to type out the variable name twice, just the once. And ideally print out multiple arguments each with its own label on its own line in the console. I'm aware that I can access the arguments list, but I don't know how to un-eval() each argument to get just its variable name, if that makes sense. I'm hoping it's something super-easy I missed.<issue_comment>username_1: You could use [console.table()](https://developer.mozilla.org/en-US/docs/Web/API/Console/table) to print things in a more readable form: (Look in the real console to see it.) ```js var obj = { firstName: "name", lastName: "smith" }; function log(obj) { console.table(obj); } log(obj); ``` Upvotes: 2 <issue_comment>username_2: Doing it the way you want is impossible (the log function doesn't know what name you called things.) The way I work around this is to use the object shorthand `{firstName}`to create a temporary object. You can then either use `.log` or `.table` to display it: ```js const firstName = 'bob'; console.log({firstName}); console.table({firstName}); // It also works for multiple variables: const lastName = 'smith'; console.log({firstName, lastName}); ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: **Try this :** ```js var my = { log : function(name) { console.log('firstName: ', name); } }; my.log("Rohit"); ``` Upvotes: 0
2018/03/21
8,863
25,795
<issue_start>username_0: I'm trying to configure Elasticsearch for Shopizer and get the below error. I configured Elasticsearch as best I could. `elasticsearch.cluster.name=shopizer` so in elasticsearch.yml I set `cluster.name: shopizer`. I also renamed shopizer-core.properties to configs.properties. That innitial error I reported was because I wasn't running Elasticsearch. I have it installed on my Mac. When its running I now get the below error. I checked in /usr/local/var/lib/elasticsearch and found that there is a folder with the same name as the default Elasticsearch cluster name but none named shopizer. > > 2018-03-20 20:40:12.780 ERROR 76380 --- [nio-8080-exec-6] c.s.s.services.impl.SearchDelegateImpl : An error occured while searching {"root\_cause":[{"type":"index\_not\_found\_exception","reason":"no such index","resource.type":"index\_or\_alias","resource.id":"keyword\_en\_default","index\_uuid":"*na*","index":"keyword\_en\_default"}],"type":"index\_not\_found\_exception","reason":"no such index","resource.type":"index\_or\_alias","resource.id":"keyword\_en\_default","index\_uuid":"*na*","index":"keyword\_en\_default"} > 2018-03-20 20:40:12.788 ERROR 76380 --- [nio-8080-exec-6] c.s.c.b.s.search.SearchServiceImpl : Error while searching keywords {"query":{"match":{"keyword":{"analyzer":"standard","query":"cre"}}}} > > > java.lang.NullPointerException: null > at com.shopizer.search.services.worker.KeywordSearchWorkerImpl.execute(KeywordSearchWorkerImpl.java:24) ~[sm-search-2.2.0.1.jar:na] > at com.shopizer.search.services.workflow.SearchWorkflow.searchAutocomplete(SearchWorkflow.java:48) ~[sm-search-2.2.0.1.jar:na] > at com.shopizer.search.services.SearchService.searchAutoComplete(SearchService.java:89) ~[sm-search-2.2.0.1.jar:na] > at com.salesmanager.core.business.services.search.SearchServiceImpl.searchForKeywords(SearchServiceImpl.java:184) ~[classes/:na] > at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0\_121] > at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0\_121] > at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0\_121] > at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0\_121] > at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302) [spring-aop-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) [spring-aop-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at com.sun.proxy.$Proxy159.searchForKeywords(Unknown Source) [na:na] > at com.salesmanager.shop.store.controller.search.SearchController.autocomplete(SearchController.java:113) [classes/:na] > at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0\_121] > at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0\_121] > at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0\_121] > at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0\_121] > at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) [spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832) [spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743) [spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961) [spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895) [spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967) [spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858) [spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843) [spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at com.salesmanager.shop.store.security.AuthenticationTokenFilter.doFilterInternal(AuthenticationTokenFilter.java:66) [classes/:na] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:162) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:68) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:184) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:162) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) [spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE] > at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE] > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502) [tomcat-embed-core-8.0.33.jar:8.0.33] > at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458) [tomcat-embed-core-8.0.33.jar:8.0.33] > at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0\_121] > at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0\_121] > at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.0.33.jar:8.0.33] > at java.lang.Thread.run(Thread.java:745) [na:1.8.0\_121] > > > 2018-03-20 20:40:12.789 ERROR 76380 --- [nio-8080-exec-6] c.s.s.s.c.search.SearchController : Exception while autocomplete com.salesmanager.core.business.exception.ServiceException: java.lang.NullPointerException > > ><issue_comment>username_1: Shopizer currently only supports Elasticsearch 2.x and I was running 6. Once I switched to 2.4 my problem was resolved. Upvotes: 1 [selected_answer]<issue_comment>username_2: I installed 2.4.0 version and then in the admin section I opened a product and click submit again. you have to do that for all the products. Do not forget to start the elastic search service. The search function works. Upvotes: 1 <issue_comment>username_3: Shopizer supports Elastic Search < 6. Works with version 5.X Upvotes: 1
2018/03/21
616
2,245
<issue_start>username_0: I am new to `javascript` and `jquery`. I have a **form** which has only one **text box** and **type is email** and I have a **submit button**. After clicking the submit button value in text box will not disappear and I don't want to(Not clearing form). Now my problem is **Button should disable after clicking on it and it should active only value in text box changes.** My code is ``` Send message ``` And jquery is ``` $(document).ready(function(){ $("input[name='email']").change(function(){ if ($(this).val() != $(this).val()) { $("input[name='submit']").removeAttr('disabled'); } }); }); ``` please help to solve this issue.<issue_comment>username_1: Because following statement `$(this).val() != $(this).val()` will always be false. You don't need to do this because `change` function already does what you need. ``` $(document).ready(function(){ $('#g-email').on('input', function(){ $("button[name='submit']").removeAttr('disabled'); }); }); ``` Working example ```js $(document).ready(function(){ $('#g-email').on('input', function(){ $("button[name='submit']").removeAttr('disabled'); }); }); ``` ```html Send message ``` Upvotes: 2 <issue_comment>username_2: Use jQuery `.prop()` method to change submit button `disabled` value: ```js var submit = $("#messageButton"); var input = $("#g-email"); input.on("keyup", function(ev) { var isDisabled = submit.data("submitted") && submit.data("submitted") === input.val(); submit.prop("disabled", isDisabled); }); submit.on("click", function(ev) { submit.prop("disabled", true); submit.data("submitted", input.val()); }); ``` ```html Send message ``` Upvotes: 2 <issue_comment>username_3: You can set the `messageButton` disabled initially and listen for the `keyup` event in the `g-email` input. Then, if the input `g-email` has text enable the button else disabled it: ```js $(document).ready(function(){ $('#g-email').on('keyup', function(){ if($(this).val()){ $("#messageButton").removeAttr('disabled'); } else { $("#messageButton").attr('disabled', true); } }); }); ``` ```html Send message ``` Upvotes: 3 [selected_answer]
2018/03/21
781
2,869
<issue_start>username_0: Basically I am trying to code a `onClickListener` for a button in MainActivity.java . This Button is defined in a **resource file : main\_resource.xml** inside a `ListView` and not in **activity\_main.xml**. I am getting the error : > > Trying to define a onClick Listener on null item. > > > ``` Button btn = (Button) findViewById(R.id.mybutton); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myFancyMethod(v); } }); ``` Here is my main\_resource.xml : ``` xml version="1.0" encoding="utf-8"? ``` Here is my activity\_main.xml : ``` xml version="1.0" encoding="utf-8"? ``` Here I am not using any Custom Adapter Class : I am injecting the data into my list view using the following ArrayAdapter code written in onRefresh() of Swipe Refresh Widget :: ``` final ArrayAdapter adapter=new ArrayAdapter(getApplicationContext(), R.layout.home\_resource, R.id.ridedetails, allNames); l1.setAdapter(adapter); // L1 is the listView Reference ```<issue_comment>username_1: you should put your onClickListener in Adapter Not in Main Activity **Your Adapter** ``` public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { Button btn = (Button ) v.findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myFancyMethod(v); } }) } ``` Upvotes: 0 <issue_comment>username_2: You have to create custom class for adapter Here is sample code for adapter. ``` public class MyAdapter extends ArrayAdapter { private int resourceId; private List sites = null; private Context context; public MyAdapter(Context context, int resource, List objects) { super(context, resource, objects); this.context = context; this.resourceId = resource; this.sites = objects; } @Override public String getItem(int position) { return sites.get(position); } @Override public int getCount() { return sites.size(); } @Override public View getView(int position, View convertView, ViewGroup parent) { String name = getItem(position); View view = convertView; if (view == null) { LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT\_INFLATER\_SERVICE); view = vi.inflate(resourceId, null); } TextView mTextView = (TextView) view.findViewById(R.id.ridedetails); mTextview.setText(name); Button mButton = (Button) view.findViewById(R.id.button); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(context, name, Toast.LENGTH\_SHORT).show(); } }); return view; } } ``` set adapter in listview like below code. ``` l1.setAdapter(new MyAdapter(getApplicationContext(), R.layout.home_resource, allNames)); ``` Upvotes: 3 [selected_answer]
2018/03/21
271
1,036
<issue_start>username_0: I am using angular 4 and I want to reload all the tabs in the browser(google chrome). I am using the following code but it only reload the current tab. ```html location.reload(); ```<issue_comment>username_1: try this ``` chrome.tabs.getAllInWindow(null, function(tabs) { for(var i = 0; i < tabs.length; i++) { chrome.tabs.update(tabs[i].id, {url: tabs[i].url}); } }); ``` [Check this](https://developer.chrome.com/extensions/windows#method-getAll) I have one question, are you trying to develop any chrome extension? Upvotes: 0 <issue_comment>username_2: You don't actually seem to be developing a Chrome extension, so my answer is based on this assumption. Unless you have no control over JavaScript running in other tabs, you won't be able to refresh these tabs due to security constraints. Imagine it would be possible to access other tabs, then any webpage could easily steal any sensitive data by just changing forms' action property to any hacker controlled host. Upvotes: 2 [selected_answer]
2018/03/21
657
2,305
<issue_start>username_0: ``` php class Dashboard extends CI_Controller { private $menu; public function __construct() { parent::__construct(); $this-load->model('menu_model'); $this->$menu = $this->menu_model->generateTree($items = array()); } public function index() { $data['menu'] = $this->$menu; $this->load->view('dashboard/dashboard', $data); } } ``` Hi guys, I get menu details at the constructor like this.I can get the result also. but it comes with the error "A PHP Error was encountered Severity: Notice Message: Undefined variable: menu "<issue_comment>username_1: You need to remove the dollar sign before menu, because you're referencing local variables ``` $this->menu = $this->menu_model->generateTree($items=array()); ``` Upvotes: 1 <issue_comment>username_2: `class Dashboard extends CI_Controller {` ``` private $menu; public function __construct() { parent::__construct(); $this->load->model('menu_model'); $this->menu = $this->menu_model->generateTree($items = array()); } public function index() { $data['menu'] = $this->menu; $this->load->view('dashboard/dashboard', $data); } ``` } Upvotes: 0 <issue_comment>username_3: Remove `$` from `$this->$menu` ``` public function __construct() { parent::__construct(); $this->load->model('menu_model'); $this->menu = $this->menu_model->generateTree($items=array()); } public function index() { $data['menu'] = $this->menu; $this->load->view('dashboard/dashboard', $data); } ``` Upvotes: 0 <issue_comment>username_4: Use `$menu` as below in your file, hope this solution help you. ``` $this->menu ``` Upvotes: 0 <issue_comment>username_5: while accessing the class variable you need not to use **$** for second time after **$this** so it would be like below code for example ``` $this->variable_name ``` your code would be as follows ``` php class Dashboard extends CI_Controller { private $menu; public function __construct() { parent::__construct(); $this-load->model('menu_model'); $this->menu = $this->menu_model->generateTree($items = array()); } public function index() { $data['menu'] = $this->menu; $this->load->view('dashboard/dashboard', $data); } ``` } Upvotes: 0
2018/03/21
3,771
14,806
<issue_start>username_0: I am working on a shopping cart in Angular 2.There are 2 components (category and products listing ) that included in app component(3rd one).Now problem is that I am unable to get communicate both child components.I have tried two solutions as below.. **Solution1:** I have used products component as provider in category compoment and everything working except on category select, view of products's component is not updating/refreshing. **Solution2:** I have use "rxjs/Subject" in shared service and passing selected categories to products component but don't know how to call a function(getProducts()) of product component on category select/change.Any help will be highly appreciated.Thanks<issue_comment>username_1: Create a new service, for example sibling-data-exchange.service.ts and put this code inside: ``` import { Observable } from 'rxjs/Rx'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Injectable } from '@angular/core'; @Injectable() export class SiblingDataExchangeService { private info = new BehaviorSubject('information'); getInfo(): Observable { return this.info.asObservable(); } getInfoValue(): string { return this.info.getValue(); } setInfo(val: string) { this.info.next(val); } } ``` In both of your components import and subscribe to this service and add a method to store the value in the service. ``` import { SiblingDataExchangeService } from 'sibling-data-exchange.service'; constructor( private siblingDataExchangeService: SiblingDataExchangeService ) { // stay updated whenever your sibling changes value this.siblingDataExchangeService.getInfo().subscribe(value => { // do something with this value this.copyOfValue = value; }); } // update value for your sibling private communicateValue(value: string): void { siblingDataExchangeService.setInfo(value); } ``` PS: Don't forget to PROVIDE the new service in your corresponding module! ``` import { SiblingDataExchangeService } from 'sibling-data-exchange.service'; @NgModule({ imports: [ ... ], exports: [ ... ], declarations: [ ... ], providers: [ SiblingDataExchangeService ] ``` Now your components communicate via a service due to the subscription to the BehaviorSubject. You said, that your CategoryComponent passes a list to the ProductsComponent and as soon as this list arrives the getProducts()-method is to be called. Well, to do this I really recommend to use the service-communication I described above. In your ProductsComponent you then have to modify the subscription as follows: ``` this.siblingDataExchangeService.getInfo().subscribe(value => { // pass the value to your local list. (supposed you have one) this.categories = value; // then call your method this.getProducts(); }); ``` This variant is also possible. Here you use 'value' directly as a parameter. But therefor the signature of getProducts() has to match e.g. ``` getProducts(categories: Array) ``` And then ``` this.siblingDataExchangeService.getInfo().subscribe(value => { this.getProducts(value); }); ``` Please note, that this subscription means, that your method gets called every time CategoryComponent passes in a new list. This ought to be exactly what you are searching for. Upvotes: 0 <issue_comment>username_2: You need to use `@Input()` and `@Output()` for category(as a child component) and product(as a parent component) to interact. > > Parent html- [product.component.html] > > > ```html ``` > > Parent component - [product.component.ts] > > > ``` import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; @Component({ moduleId: module.id, selector: 'all-products', templateUrl: 'all-products.component.html', changeDetection: ChangeDetectionStrategy.Default }) export class AllProductsComponent implements OnInit { constructor(private _productsService: ProductsService,, private _router: Router) { } ngOnInit() { this.fillAllProducts(0); } fillAllProducts(pageIndex) { this.loadingProgress = true; var searchParams = new SearchParametersCategoryModel(); searchParams.CategoryFilter = this.categoryFilterValue; searchParams.PageIndex = pageIndex; //TODO - service call } onClickedCategoryFilter(filterValue: any) { this.categoryFilterValue = filterValue; this.allProductData$ = []; this.currentPageIndex = 0; this.fillAllProducts(this.currentPageIndex); } selectProduct(productId: any, selectedProductCart) { //TODO } } ``` > > Child html- [category.component.html] > > > ```html ``` > > Child component - [category.component.ts] > > > ``` // libs import { Component, Input, Output, EventEmitter, OnInit, AfterViewInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/debounceTime'; import { CategoriesService } from '../service/categories.service'; @Component({ moduleId: module.id, selector: 'app-filter-categories', templateUrl: 'category.component.html' }) export class CategoryFilterComponent implements OnInit, AfterViewInit { toggle = true; @Input() categoryResult: any = ''; @Output() clicked = new EventEmitter(); Category = []; SelectedCategoryItems = []; categoryFilterList: DictionaryFilter = {}; //here u will add list of selected categories with key-value constructor(private \_categoriesService : CategoriesService) { } ngOnInit() { //todo - fill categories list } onClickSelectCategory(searchType: any, event: any): any { if (!(event.target.parentElement.className.search('active') > 1)) { //this.removeFilterElementWithKey(searchType); //above line to add logic for remove deselected data from categoryFilterList } else { this.categoryFilterList.push(element); } this.clicked.emit(this.categoryFilterList); } } ``` I think, this will solve your problem. Upvotes: 1 <issue_comment>username_1: Okay, so here comes my demo app. This is just an example to show you how your app should be structured to work properly. I know that you call web services but it should be no problem for you to adapt it though: I have a CategoryComponent that subscribes to the CategoryService. The template ``` Category Component ------------------ {{category?.name}} ``` The typescript file ``` import { Component, OnInit, OnDestroy } from '@angular/core'; import { CategoryService } from '../services/category.service'; import { Category } from '../models/models'; @Component({ moduleId: module.id, selector: 'pm-category', templateUrl: 'category.component.html', styleUrls: ['category.component.scss'] }) export class CategoryComponent implements OnInit, OnDestroy { private categories: Array = []; constructor(private categoryService: CategoryService) { } ngOnInit() { this.categoryService.getCategories().subscribe(list => { if (list) { this.categories = list; } }); } ngOnDestroy() { } private emitChange(): void { this.categoryService.setCategories(this.categories); } } ``` Whenever a Category gets clicked the service gets updated. Next I have a ProductsComponent that subscribes to the CategoryService and the ProductsService and contains a child component ProductComponent. The template ``` Products Component ------------------ {{product?.name}} ``` The typescript file ``` import { Component, OnInit, OnDestroy } from '@angular/core'; import { ProductsService } from '../services/products.service'; import { CategoryService } from '../services/category.service'; import { Product } from '../models/models'; @Component({ moduleId: module.id, selector: 'pm-products', templateUrl: 'products.component.html', styleUrls: ['products.component.scss'] }) export class ProductsComponent implements OnInit, OnDestroy { public product: Product; private products: Array = []; constructor( private productsService: ProductsService, private categoryService: CategoryService ) { } ngOnInit() { this.productsService.getProducts().subscribe(list => { if (list) { this.products = list; } }); this.categoryService.getCategories().subscribe(list => { const allProducts = this.productsService.getProductsValue(); const filteredProducts: Array = []; let tempProducts: Array = []; list.forEach(cat => { tempProducts = allProducts.filter(prod => (prod.categoryId === cat.id) && (cat.selected === true)); if (tempProducts.length > 0) { tempProducts.forEach(el => { filteredProducts.push(el); }); } }); this.products = filteredProducts; }); } ngOnDestroy() { } private setSelectedProduct(product: Product): void { this.product = product; } } ``` When you chose a product its details get displayed in the ProductComponent through Input Binding between ProductComponent and ProductsComponent. And when a category gets changed in the CategoryComponent your list of products gets widened or narrowed depending on the selected checkboxes. Here comes the ProductComponent The template ``` Product Component ----------------- Price: {{product?.details?.price}} Age: {{product?.details?.age}} ``` and the typescript file ``` import { Component, Input, OnInit, OnDestroy } from '@angular/core'; import { Product } from '../models/models'; @Component({ moduleId: module.id, selector: 'pm-product', templateUrl: 'product.component.html', styleUrls: ['product.component.scss'] }) export class ProductComponent implements OnInit, OnDestroy { @Input() product: Product; ngOnInit() { } ngOnDestroy() { } } ``` Please note that I left out all the sass files als they are empty. But you have to have them in order to have your app compile! Here are both of the services and the model.ts I used. The CategoryService ``` import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Observable } from 'rxjs/Observable'; import { Category } from '../models/models'; @Injectable() export class CategoryService { private categories: BehaviorSubject> = new BehaviorSubject([]); constructor() { const list: Array = []; const categoryA: Category = new Category('CategoryA', false); categoryA.id = 1000; list.push(categoryA); const categoryB: Category = new Category('CategoryB', false); categoryB.id = 2000; list.push(categoryB); const categoryC: Category = new Category('CategoryC', false); categoryC.id = 3000; list.push(categoryC); this.setCategories(list); } getCategories(): Observable> { return this.categories.asObservable(); } getCategoriesValue(): Array { return this.categories.getValue(); } setCategories(val: Array) { this.categories.next(val); } } ``` The ProductsService ``` import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Observable } from 'rxjs/Observable'; import { Product, Details } from '../models/models'; @Injectable() export class ProductsService { private products: BehaviorSubject> = new BehaviorSubject([]); constructor() { const list: Array = []; const detailsA: Details = new Details(33, 12); const productA: Product = new Product('ProductA', detailsA, 1000); productA.id = 200; list.push(productA); const detailsB: Details = new Details(1002, 56); const productB: Product = new Product('ProductB', detailsB, 1000); productB.id = 400; list.push(productB); const detailsC: Details = new Details(9, 4); const productC: Product = new Product('ProductC', detailsC, 2000); productC.id = 600; list.push(productC); this.setProducts(list); } getProducts(): Observable> { return this.products.asObservable(); } getProductsValue(): Array { return this.products.getValue(); } setProducts(val: Array) { this.products.next(val); } } ``` And my models.ts ``` export class Category { constructor( public name: string, public selected: boolean, public id?: number ) { } } export class Details { constructor( public price: number, public age: number ) { } } export class Product { constructor( public name: string, public details: Details, public categoryId: number, public id?: number ) { } } ``` Finally, my main-page.module.ts, which I imported into the app.module.ts. ``` import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { MainPageComponent } from './main-page.component'; import { CategoryComponent } from '../category/category.component'; import { ProductComponent } from '../product/product.component'; import { ProductsComponent } from '../products/products.component'; import { CategoryService } from '../services/category.service'; import { ProductsService } from '../services/products.service'; @NgModule({ imports: [ FormsModule, BrowserModule, HttpClientModule, RouterModule.forRoot([ { path: 'pm-main-page', component: MainPageComponent }, ]), ], declarations: [ MainPageComponent, CategoryComponent, ProductComponent, ProductsComponent ], exports: [ MainPageComponent, CategoryComponent, ProductComponent, ProductsComponent ], providers: [ CategoryService, ProductsService ] }) export class MainPageModule { } ``` If you put all this together you'll have a small working app which exactly does what you described in your post. I hope you this helps. PS: it's of course optimizable in case of what happens to already made selections when the category list changes and such, but it's only supposed to be a demo. ;) Upvotes: 1 <issue_comment>username_1: Referring to your today's question ***I have a code in javascript as below var Output1; window.setInterval(function () { Output1 = Math.random(); },1000); console.log(Output1); and want to access Output1 outside but its not working. Can please tell me any way I could access Output1 outside ?*** I'd suggest the following solution: ``` var output1; function setCurrentValue() {output1 = Math.random();} function sendNumber(){ $.post( "test.php", {rng: output1} ); } var currInterval = window.setInterval(function () { setCurrentValue(); },1000); Send ``` And if you want to monitor output1 (for console only!) just do it this way: ``` var monitor = window.setInterval(function () { console.log(output1); },500); ``` Upvotes: 2 [selected_answer]
2018/03/21
1,055
4,144
<issue_start>username_0: Coming from the knockoutJs background. If you don't specific the binding to an element. You can use the model to cover the whole page of elements. For example, i can make a div visible if a click event happened. I'm learning VueJs and from the documentation. I see the vue instance required you to speicif an element with el. like this: ```js var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }) ``` what if my button is not in the same div as the '#app' div. How do i communicate between two vue instance or can I use one vue instance to cover more than one element. what's the vuejs way?<issue_comment>username_1: It's very common to bind to the first element inside . Vue won't let you bind to `body`, because there are all sorts of other things that put their event listeners on it. If you do that, Vue is managing your whole page, and away you go. The docs cover the case where you have more than one Vue instance on a page, but I haven't come across this outside the docs, and I can't think of a good reason off the top of my head. More commonly, you will be constantly chopping bits out of your root Vue instance and refactoring them into "child" components. This is how you keep file sizes manageable and structure your app. This is where a lot of folk needlessly complicate things, by over-using `props` to pass stuff to components. When you start refactoring into components, you will have a much easier time if you keep all your state in a store, outside vue, then have your components talk directly to your store. (put the store in the `data` element of all components). This pattern (MVVM) is fabulous, because many elements of state will end up having more than one representation on screen, and having a "single source of truth", normalized, with minimal relationships between items in the store, radically reduces the complexity and the amount of code for most common purposes. It lets you structure your app state independently of your DOM. So, to answer your question, Vue instances (and vue components), don't need to (and shouldn't) talk much to each other. When they do need to (third party components and repeated components), you have [props and events](https://v2.vuejs.org/v2/guide/components.html#Composing-Components), [refs and method calls](https://v2.vuejs.org/v2/api/#ref) (state outside the store), and the [$parent and $root](https://v2.vuejs.org/v2/api/#vm-parent) properties (usage frowned on!). You can also create [an event bus](https://medium.com/patrickleenyc/vue-js-simple-event-bus-for-cross-component-communication-85dd8f0fc750). [This page](https://alligator.io/vuejs/component-communication/) is a really good summary of the options. Should your store be Flux/Redux? Vuex is the official implementation of the flux/redux pattern for vue. The common joke goes: when you realize you need it, it's too late. If you do decide to leave Vuex for now, don't just put state in Vue components. Use a plain javascript object in window scope. The right way is easier than the wrong way, and when you do transition to Vuex, your job will be much simpler. Your downstream references might be alright as they are. Good luck. Enjoy the ride. Upvotes: 4 [selected_answer]<issue_comment>username_2: You usually put the main Vue instance on the first tag inside the body, then build the rest of your site within it. Everything directly inside that instance (not in a nested component) will have access to the same `data`. You can then do this in your HTML: ```html {{message}} ``` And set your data to something like this: ```js var app = new Vue({ el: '#app', data: { message: 'Hello Vue!', showMessage: true } }) ``` If you want to pass data between components later on you'll have to look up how to emit events, use props, or possibly use Vuex if you got Vue running with the Vue-CLI (which I highly recommend). If you want to reach tags (such as head tags) outside of the main Vue instance, then there are tools for that. For example you could try: <https://github.com/ktquez/vue-head> I haven't tested it thought. Upvotes: 1
2018/03/21
193
611
<issue_start>username_0: I want to let users select multiple layers of folders. Once they select a version folder (Folder name similar as: 1.0.0) I will continue to do next steps. How can I match the format like 1.0.0?<issue_comment>username_1: You can use regular expressions: ``` folderName="1.2.3"; matchPattern="^[0-9]\.[0-9]\.[0-9]$"; # if regex match, execute the command after "&&" [[ $folderName =~ $matchPattern ]] && echo "Folder name matches pattern" ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You may try the below command. ``` grep -Po '(?foldername)\d.\d.\d' ``` Upvotes: 1
2018/03/21
785
2,957
<issue_start>username_0: I am using facebook SDK. I am getting the following error: ``` Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https:// ``` After studying I came to know that I have to set 'Enforce HTTPS' as NO under 'facebook login> Setting> '. But I can not set Enforce HTTPS as NO. Is this problem is from mine? OR I facebook restrict to use https instead of http?<issue_comment>username_1: > > But I can not set Enforce HTTPS as NO. Is this problem is from mine? > > > <https://developers.facebook.com/docs/facebook-login/security>: > > Enforce HTTPS. This setting requires HTTPS for OAuth Redirects and pages getting access tokens with the JavaScript SDK. **All new apps created as of March 2018 have this setting on by default** and you should plan to migrate any existing apps to use only HTTPS URLs by March 2019. > > > Sounds to me, like they don’t want you to be able to even start without HTTPS, when you are creating a new app now. --- Plus, Chrome has recently announced that they will mark all HTTP sites as insecure soon, from version 68 on, that will be released in July 2018. So you’re gonna have to go HTTPS rather sooner than later anyway. The “big players” of the industry are currently pushing for this big time, whether we want it or not. Upvotes: 4 [selected_answer]<issue_comment>username_2: If you're developing locally with **create-react-app**, a quick solution is to add ``` HTTPS=true ``` to your .env file and just comment it out when you're not testing Facebook login. Upvotes: 2 <issue_comment>username_3: If you just enable `Client OAuth Login` and write just `localhost:{port}` to Valid OAuth Redirect URIs, it will work. Upvotes: 3 <issue_comment>username_4: enable Client OAuth Login and write "localhost:3000" in Valid OAuth Redirect URIs. Save changes. it will automatically change to <https://localhost:3000> , but it doesn't matter... And set **Status**: In Development (THIS IS IMPORTANT!) Then it will work in your http localhost. Upvotes: 4 <issue_comment>username_5: It seems like Business apps do not have app modes and instead rely exclusively on access levels. Because of this, you can't set the app to the "Development mode". * All newly created apps start out in Development mode and you should avoid changing it until you have completed all development and testing. <https://developers.facebook.com/docs/development/build-and-test/> <https://developers.facebook.com/docs/development/build-and-test/app-modes> However, if you wanna try out your app in a localhost, you need to create a test app, like you can check out in this thread: [How to fix 'Facebook has detected MyApp isn't using a secure connection to transfer information.' error in Laravel](https://stackoverflow.com/questions/57372648/how-to-fix-facebook-has-detected-myapp-isnt-using-a-secure-connection-to-trans) Upvotes: 0
2018/03/21
952
3,471
<issue_start>username_0: I can't install Express through npm install express. Actually I get an error if it try to install the dev dependency called content-type. <https://www.npmjs.com/package/content-type> I tried to install the content-type package, it doesn't work. Here is the error: ``` 60 error path C:\Users\kv\workspace\test\node_modules\content-type 61 error code ENOENT 62 error errno -4058 63 error syscall rename 64 error enoent ENOENT: no such file or directory, rename 'C:\Users\kv\workspace\test\node_modules\content-type' -> 'C:\Users\kv\workspace\test\node_modules\.content-type.DELETE' 65 error enoent This is related to npm not being able to find a file. ``` I use Windows 7 64 bit. I already installed Express once, 1 week ago, worked well. Here is the full log file: <https://pastebin.com/7S4MYLed> Does someone knows this issue and how to solve it? I already tried to reinstall Node.js/npm. I also cleared the cache and restarted my computer.<issue_comment>username_1: > > But I can not set Enforce HTTPS as NO. Is this problem is from mine? > > > <https://developers.facebook.com/docs/facebook-login/security>: > > Enforce HTTPS. This setting requires HTTPS for OAuth Redirects and pages getting access tokens with the JavaScript SDK. **All new apps created as of March 2018 have this setting on by default** and you should plan to migrate any existing apps to use only HTTPS URLs by March 2019. > > > Sounds to me, like they don’t want you to be able to even start without HTTPS, when you are creating a new app now. --- Plus, Chrome has recently announced that they will mark all HTTP sites as insecure soon, from version 68 on, that will be released in July 2018. So you’re gonna have to go HTTPS rather sooner than later anyway. The “big players” of the industry are currently pushing for this big time, whether we want it or not. Upvotes: 4 [selected_answer]<issue_comment>username_2: If you're developing locally with **create-react-app**, a quick solution is to add ``` HTTPS=true ``` to your .env file and just comment it out when you're not testing Facebook login. Upvotes: 2 <issue_comment>username_3: If you just enable `Client OAuth Login` and write just `localhost:{port}` to Valid OAuth Redirect URIs, it will work. Upvotes: 3 <issue_comment>username_4: enable Client OAuth Login and write "localhost:3000" in Valid OAuth Redirect URIs. Save changes. it will automatically change to <https://localhost:3000> , but it doesn't matter... And set **Status**: In Development (THIS IS IMPORTANT!) Then it will work in your http localhost. Upvotes: 4 <issue_comment>username_5: It seems like Business apps do not have app modes and instead rely exclusively on access levels. Because of this, you can't set the app to the "Development mode". * All newly created apps start out in Development mode and you should avoid changing it until you have completed all development and testing. <https://developers.facebook.com/docs/development/build-and-test/> <https://developers.facebook.com/docs/development/build-and-test/app-modes> However, if you wanna try out your app in a localhost, you need to create a test app, like you can check out in this thread: [How to fix 'Facebook has detected MyApp isn't using a secure connection to transfer information.' error in Laravel](https://stackoverflow.com/questions/57372648/how-to-fix-facebook-has-detected-myapp-isnt-using-a-secure-connection-to-trans) Upvotes: 0
2018/03/21
701
2,566
<issue_start>username_0: I have a question about how to select all tag elements in HTML page with JavaScript and apply an Event listener to them. With jQuery we can do like this ``` $('td').on('click', function(){...}); ``` But how can I do it with pure JavaScript? I have this code: ``` const el = document.getElementsByTagName('td'); el.addEventListener("click", function(){ let cellColor = document.getElementById("colorPicker").value; this.backgroundColor = cellColor; }); ``` But this gives an error in console: > > Uncaught TypeError: el.addEventListener is not a function > at makeGrid (designs.js:34) > at designs.js:42 > > ><issue_comment>username_1: `getElementsByTagName()` returns collection. You have to iterate over all the element to add the event: Try with `querySelectorAll()` and `forEach()`: ``` const el = document.querySelectorAll('td'); el.forEach(function(td){ td.addEventListener("click", function(){ let cellColor = document.getElementById("colorPicker").value; this.style.backgroundColor = cellColor; }); }); ``` **Please Note:** `querySelectorAll()` is supported by all the modern browsers. Some older browsers does not support it. Try the following with [Array.prototype.forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) if you want to work with older browsers: ```js const el = document.getElementsByTagName('td'); [].forEach.call(el, function(td){ td.addEventListener("click", function(){ let cellColor = document.getElementById("colorPicker").value; this.style.backgroundColor = cellColor; }); }); ``` ```html Cell Color: | | | | | --- | --- | --- | | 11 | 12 | 13 | | 21 | 22 | 23 | | 31 | 32 | 33 | ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: `el` is a nodeList & it will not have any addEventListener method. Access each element in this list by first converting to array and use `forEach`. Then attach addEventListener to each of the element ``` const el = document.getElementsByTagName('td'); [].slice.call(el).forEach(function(item){ item.addEventListener("click", function(){ let cellColor = document.getElementById("colorPicker").value; this.backgroundColor = cellColor; }); }) ``` Upvotes: 0 <issue_comment>username_3: You need to loop through the `el` so that we can add listener to each element in `el`. Also, to organise your code properly you can separate out the listener function. ``` const el = document.getElementsByTagName('td'); for(var i=0; i ``` Upvotes: 0
2018/03/21
489
1,344
<issue_start>username_0: I want to get the **name** value from the below RESTful response ``` { "login": "mdo", "id": 98681, "url": "https://api.github.com/users/mdo", "html_url": "https://github.com/mdo", "type": "User", "site_admin": true, "name": "<NAME>", "company": "GitHub", "blog": "http://mdo.fm", "location": "San Francisco, CA", } ``` Here is my code. So far, I have only manage to retrieve the complete result. ``` php //step1 $cSession = curl_init(); //step2 curl_setopt($cSession, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0'); curl_setopt($cSession,CURLOPT_URL,"https://api.github.com/users/mdo"); curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true); curl_setopt($cSession,CURLOPT_HEADER, false); //step3 $result=curl_exec($cSession); //step4 curl_close($cSession); //step5 echo $result; ? ```<issue_comment>username_1: Just use [json\_decode](http://php.net/manual/en/function.json-decode.php) method like so: ``` $obj = json_decode($result); echo $obj->{'name'}; ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can first decode your result with `json_decode` using below statement. ``` $arr = json_decode($result, true); ``` And then you can access name via `$arr['name'];` ``` echo $arr['name']; ``` It's very simple, Try out this. Upvotes: 1
2018/03/21
1,347
4,512
<issue_start>username_0: I got this error when trying to get data from **API** using **retrofit**. **Model** ``` public class Movie { @SerializedName("id") @Expose private Integer id; @SerializedName("title") @Expose private String title; @SerializedName("image") @Expose private String image; @SerializedName("link") @Expose private String link; @SerializedName("description") @Expose private String description; @SerializedName("category") @Expose private String category; @SerializedName("actor") @Expose private String actor; @SerializedName("director") @Expose private String director; @SerializedName("manufacturer") @Expose private String manufacturer; @SerializedName("duration") @Expose private String duration; @SerializedName("year") @Expose private String year; @SerializedName("created_at") @Expose private String createdAt; @SerializedName("updated_at") @Expose private String updatedAt; @SerializedName("views") @Expose private Integer views; @SerializedName("type") @Expose private String type; //get and set.... } ``` **APIservice.class** ``` @Headers("app_token:<PASSWORD>") @POST("training-movie/movie/list") Call> getMovie(); ``` **MainActivity** ``` Retrofit retrofit = new Retrofit.Builder() .baseUrl(" http://dev.bsp.vn:8081/") .addConverterFactory(GsonConverterFactory.create()) .client(oBuilder.build()) .build(); APIService service = retrofit.create(APIService.class); Call> call = service.getMovie(); call.enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { if(response.isSuccessful()){ Toast.makeText(MainActivity.this, ""+response.body().toString(), Toast.LENGTH\_SHORT).show(); } } @Override public void onFailure(Call> call, Throwable t) { Toast.makeText(MainActivity.this, ""+t.getMessage(), Toast.LENGTH\_SHORT).show(); } }); ``` I got error here, I think I'm not understand how retrofit work. Someone can tell me more about it. Update: JSON ``` { "error": false, "code": 0, "message": "", "paging": { "total_item": 31, "per_page": 10, "current_page": 1, "total_pages": 4 }, "data": [ { "id": 1, "title": "DON'T BREATHE / SÁT NHÂN TRONG BÓNG TỐI", "image": "http://dev.bsp.vn:8081/training-movie/upload/movie/sdasdasda.jpg", "link": "https://www.youtube.com/watch?v=TRusW3VPLaI", "description": "Ba tên trộm liều lĩnh đột nhập vào nhà một người đàn ông giàu có bị mù. Lũ trộm cho rằng bản thân sẽ vớ bở, thế nhưng chúng đã sai. Trong bóng tối, kẻ mù làm vua. Người đàn ông tưởng chừng yếu đuối nay lại trở thành ác quỷ đưa bọn chúng xuống địa ngục.", "category": "Kinh dị, Hành động", "actor": "<NAME>, <NAME>", "director": "<NAME>", "manufacturer": "Sony Pictures", "duration": "88", "year": "2016-08-30", "created_at": "2016-08-30 15:45:37", "updated_at": "0000-00-00 00:00:00", "views": 896, "type": "showing" } ] } ``` Update: model ``` public class Data { @SerializedName("error") @Expose private Boolean error; @SerializedName("code") @Expose private Integer code; @SerializedName("message") @Expose private String message; @SerializedName("paging") @Expose private Paging paging; @SerializedName("data") @Expose private List data = null; public class Paging { @SerializedName("total\_item") @Expose private Integer totalItem; @SerializedName("per\_page") @Expose private Integer perPage; @SerializedName("current\_page") @Expose private Integer currentPage; @SerializedName("total\_pages") @Expose private Integer totalPages; ```<issue_comment>username_1: Just use [json\_decode](http://php.net/manual/en/function.json-decode.php) method like so: ``` $obj = json_decode($result); echo $obj->{'name'}; ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can first decode your result with `json_decode` using below statement. ``` $arr = json_decode($result, true); ``` And then you can access name via `$arr['name'];` ``` echo $arr['name']; ``` It's very simple, Try out this. Upvotes: 1
2018/03/21
685
2,376
<issue_start>username_0: Is there a way to write a common code or a configuration which can remove trailing or leading spaces from any strings which are input from form submission in web application so that we should not get NumberFormatException at java code level while parsing those strings to Integer or number. For example " 15246 ". Because in case of spring command object if it has a integer field then it tries to convert it into integer implicitly. Except IE browser other browser do not let number field has leading or trailing space.<issue_comment>username_1: Try with java inbuilt trim method ``` " 15246".trim() ``` Then cast into `Integer.valueOf(" 15246".trim())` Upvotes: 2 <issue_comment>username_2: If you use Spring-Boot 2 it will just work out of the box: Test.java ``` package hello; public class Test { private Integer test; public Integer getTest() { return test; } public void setTest(Integer test) { this.test = test; } @Override public String toString() { return "Test{test=" + test + '}'; } } ``` TestController.java ``` package hello; @RestController public class TestController { @RequestMapping(value = "/test", method = RequestMethod.GET) public String testGet(@RequestParam("test") Integer integer) { return "" + integer; } @RequestMapping(value = "/test_p", method = RequestMethod.POST) public String testPost(@RequestBody Test test) { return "" + test; } } ``` Test the POST with curl ``` curl -X POST \ http://localhost:8080/test_p \ -H 'Content-Type: application/json' \ -d '{"test": " 876867"}' ``` > > Test{test=876867} > > > Test the GET with curl ``` curl -X GET \ 'http://localhost:8080/test?test=%20542543' \ -H 'Content-Type: application/json' \ ``` > > 542543 > > > The reason this works originates from the [class StringToNumberConverterFactory](https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/core/convert/support/StringToNumberConverterFactory.java#L62) Which uses [NumberUtils which indeed trims all whitespace](https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/util/NumberUtils.java#L201) ``` String trimmed = StringUtils.trimAllWhitespace(text); ``` Upvotes: 1
2018/03/21
462
1,600
<issue_start>username_0: I want to display the number of rows from database using Go. How do I display number of rows? ``` count, err := db.Query("SELECT COUNT(*) FROM main_table") ```<issue_comment>username_1: The query will return a row into the variable count. So the next you have to do is to read this row and assign the result into a new variable, using the function `Scan()`. This is how it works. ``` rows, err := db.Query("SELECT COUNT(*) FROM main_table") if err != nil { log.Fatal(err) } defer rows.Close() var count int for rows.Next() { if err := rows.Scan(&count); err != nil { log.Fatal(err) } } fmt.Printf("Number of rows are %s\n", count) ``` The best option thought would be to use `QueryRow()` as you expect to read just one row. The code then will be. ``` var count int err := db.QueryRow("SELECT COUNT(*) FROM main_table").Scan(&count) switch { case err != nil: log.Fatal(err) default: fmt.Printf("Number of rows are %s\n", count) } ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: I signed up just to share this as my large datasets were slowing down the program with the constant appends. I wanted to put the `rowcount` in the rows and figured that something like that must exist, just had to find it. ``` SELECT count(1) OVER(PARTITION BY domain_id) AS rowcount, subscription_id, domain_id, ... FROM mytable WHERE domain_id = 2020 ``` Never used this command before, but it will add the count of the result set that share this parameter. Setting it to one of the query `WHERE`'s makes it the total rows. Upvotes: 0
2018/03/21
1,387
5,215
<issue_start>username_0: I have developed a shiny app, where we are using various box object in the ui. Currently the boxes expand/Collapse by clicking on the "+/-" sign on the right of the box header, but we need the expand/collapse on click on the header (anywhere on the box header). Below code (sample code) If you look at the box with chart, I want the expansion & collapse to be performed on clicking the header i.e. "Histogram box title" and not just the "+/-" sign on right side of the header: ``` ## Only run this example in interactive R sessions if (interactive()) { library(shiny) # A dashboard body with a row of infoBoxes and valueBoxes, and two rows of boxes body <- dashboardBody( # Boxes fluidRow( box(title = "Histogram box title", status = "warning", solidHeader = TRUE, collapsible = TRUE, plotOutput("plot", height = 250) ) ) ) server <- function(input, output) { output$plot <- renderPlot({ hist(rnorm(50)) }) } shinyApp( ui = dashboardPage( dashboardHeader(), dashboardSidebar(), body ), server = server ) } ```<issue_comment>username_1: This is easily achievable using javascript. You just have to create a javascript function and call the same in your header code. Refer to below code for better understanding. I have provided 3 options, let me know if this works for you. ``` ## Only run this example in interactive R sessions if (interactive()) { library(shiny) # javascript code to collapse box jscode <- " shinyjs.collapse = function(boxid) { $('#' + boxid).closest('.box').find('[data-widget=collapse]').click(); } " # A dashboard body with a row of infoBoxes and valueBoxes, and two rows of boxes body <- dashboardBody( # Including Javascript useShinyjs(), extendShinyjs(text = jscode), # Boxes fluidRow( box(id="box1",title = actionLink("titleId", "Histogram box title",icon =icon("arrow-circle-up")), status = "warning", solidHeader = TRUE, collapsible = T, plotOutput("plot", height = 250) ), box(id="box2",title = p("Histogram box title", actionButton("titleBtId", "", icon = icon("arrow-circle-up"), class = "btn-xs", title = "Update")), status = "warning", solidHeader = TRUE, collapsible = T, plotOutput("plot1", height = 250) ), box(id="box3",title = actionButton("titleboxId", "Histogram box title",icon =icon("arrow-circle-up")), status = "warning", solidHeader = TRUE, collapsible = T, plotOutput("plot2", height = 250) ) ) ) server <- function(input, output) { output$plot <- renderPlot({ hist(rnorm(50)) }) output$plot1 <- renderPlot({ hist(rnorm(50)) }) output$plot2 <- renderPlot({ hist(rnorm(50)) }) observeEvent(input$titleId, { js$collapse("box1") }) observeEvent(input$titleBtId, { js$collapse("box2") }) observeEvent(input$titleboxId, { js$collapse("box3") }) } shinyApp( ui = dashboardPage( dashboardHeader(), dashboardSidebar(), body ), server = server ) } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can do this for all boxes in an app with a few lines of external css and javascript. The JS triggers a click on the widget when you click on the header title. It has to be the h3 element because the widget is inside .box-header, which would cause infinite recursion. ``` $('.box').on('click', '.box-header h3', function() { $(this).closest('.box') .find('[data-widget=collapse]') .click(); }); ``` But then we need to make the h3 element fill the full .box-header, so get rid of the header padding (except on the right), add it to the h3, and make the h3 fill 100% of the width of the box. ``` .box-header { padding: 0 10px 0 0; } .box-header h3 { width: 100%; padding: 10px; } ``` Upvotes: 0 <issue_comment>username_3: I think username_2 answer is the better one since you can click the whole header and not just the title. Pasted it into a small example: ``` if (interactive()) { body <- dashboardBody( useShinyjs(), tags$style(HTML(" .box-header { padding: 0 10px 0 0; } .box-header h3 { width: 100%; padding: 10px; }")), fluidRow( box(id="box1", title = "Histogram box title", status = "warning", solidHeader = TRUE, collapsible = T, plotOutput("plot", height = 250) ) ) ) server <- function(input, output) { output$plot <- renderPlot({ hist(rnorm(50)) }) runjs(" $('.box').on('click', '.box-header h3', function() { $(this).closest('.box') .find('[data-widget=collapse]') .click(); });") } shinyApp( ui = dashboardPage( dashboardHeader(), dashboardSidebar(), body ), server = server ) } ``` Upvotes: 0
2018/03/21
416
1,459
<issue_start>username_0: ``` var func1 = function() {} console.log(func1.name); // func1 ``` Is there any real-time usage of this property from the javascript developer's perspective?<issue_comment>username_1: You can use it for debugging purposes when you pass function as a parameter to another function, for instance: ```js var fun1 = function(){}; function fun2(){}; var g = function(f){ console.log("Invoking " + f.name); f(); } if(Math.random() > 0.5){ g(fun1); } else { g(fun2); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The answer to this question will be quite broad, since there are hundreds of examples for the usage of property called `name`. They are covered in detail in JavaScript [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name). Few of the examples are following. **Changing the function name.** ``` var newName = "xyzName"; var f = function () {}; Object.defineProperty(f, 'name', {value: newName}); console.log(f.name); // will output xyzName ``` **For logging the class stack we can get the constructor name as in the following example.** ``` function a() {}; var b = new a(); console.log(b.constructor.name); // will output a ``` **Get the function name if it's not anonymous.** ``` var getRectArea = function area(width, height) { return width * height; } getRectArea.name; //will output area ``` Upvotes: 1
2018/03/21
1,267
3,765
<issue_start>username_0: I'm trying to write a quicksort function in JavaScript. My code is below: ``` function test_quicksort(){ var arr = [0, 9, 8, 7, 6, 5, 4, 3, 2, 1]; arr = quicksort_by_percent_filled(arr); Logger.log(arr); } function quicksort_setup(arr){ var high = arr.size - 1; arr = quicksort_by_percent_filled(arr, 0, high); return arr } function quicksort_by_percent_filled(arr, low, high){ if (low < high){ var pi = partition(arr, low, high); quicksort_by_percent_filled(arr, low, pi - 1); quicksort_by_percent_filled(arr, pi + 1, high); } return arr; } function partition(arr, low, high){ var pivot = arr[high]; var smaller_boundary = low - 1; var curr_elem = low; for (; curr_elem <= high; curr_elem++){ if (ar[curr_elem] < pivot){ smaller_boundary++; swap(arr, curr_elem, smaller_boundary); } } swap(arr, high, smaller_boundary + 1); return smaller_boundary + 1; } function swap(arr, a, b){ var temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; Logger.log(arr); } ``` Assuming `Logger.log(arr)` is a function that prints out the contents of the array, it should print out the array properly sorted. However, whenever I run `test_quicksort`, the `[0, 9, 8, 7, 6, 5, 4, 3, 2, 1]` is printed out instead. It seems to me that I am somehow unable to edit the array `arr` when it is passed as an argument. How can I work around this issue?<issue_comment>username_1: If you want to mutate the array passed to `test_quicksort`, you souldn't reassign a new array to it to avoid loosing it's reference (avoid `arr = newArr;`). Instead of reassigning, you can empty the array with `arr.prototype.splice` then push all elements of the sorted array into it: ```js function test_quicksort(arr){ var newArr = quicksort_by_percent_filled(arr); arr.splice(0, arr.length); arr.push(...newArr); } function quicksort_by_percent_filled() { return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; } var arr = [0, 9, 8, 7, 6, 5, 4, 3, 2, 1]; test_quicksort(arr); console.log(arr); ``` Upvotes: 1 <issue_comment>username_2: You could 1. add a swap function, 2. take `quicksort_setup` instead of calling `quicksort_by_percent_filled` directly, 3. take the `length` instead of `size`, 4. skip call of `get_percent_filled()`, which is missing and the return value is never used, 5. use `arr` instead of `ar` in `for` loop. ```js function swap(array, i, j) { // 1 var temp = array[i]; array[i] = array[j]; array[j] = temp; } function test_quicksort() { var arr = [0, 9, 8, 7, 6, 5, 4, 3, 2, 1]; arr = quicksort_setup(arr); // 2 console.log(arr); } function quicksort_setup(arr) { var high = arr.length - 1; // 3 var percent_filled; // = get_percent_filled(); // 4 arr = quicksort_by_percent_filled(arr, 0, high, percent_filled); return arr } function quicksort_by_percent_filled(arr, low, high, percent_filled) { if (low < high) { var pi = partition(arr, low, high, percent_filled); quicksort_by_percent_filled(arr, low, pi - 1, percent_filled); quicksort_by_percent_filled(arr, pi + 1, high, percent_filled); } return arr; } function partition(arr, low, high, percent_filled) { var pivot = arr[high]; var smaller_boundary = low - 1; var curr_elem = low; for (; curr_elem <= high; curr_elem++) { if (arr[curr_elem] < pivot) { // 5 //if (percent_filled[arr[curr_elem]] < percent_filled[pivot]){ smaller_boundary++; swap(arr, curr_elem, smaller_boundary); } } swap(arr, high, smaller_boundary + 1); return smaller_boundary + 1; } test_quicksort(); ``` Upvotes: 0
2018/03/21
919
2,866
<issue_start>username_0: When I retrieve the history price of spot for "us-east-f1" or any region in "us-east-1", the result always less than 200 price, I need for single region and single instance type. How can I retrieve a huge number of results? EX: ``` ec2 = boto3.client('ec2') t=datetime.datetime.now() - datetime.timedelta(0) f=datetime.datetime.now() - datetime.timedelta(90) response= ec2.describe_spot_price_history(InstanceTypes =['c3.4xlarge'],ProductDescriptions = ['Linux/UNIX'], AvailabilityZone = 'us-east-1a', StartTime= f, EndTime = t, MaxResults=1000) response =response['SpotPriceHistory'] ``` I mean for a single region and instance type, I need the max result to be larger than this. **Edit:** I use paginator to get all result for all available pages: ``` paginator = ec2.get_paginator('describe_spot_price_history') page_iterator = paginator.paginate(StartTime= t, EndTime = f, MaxResults=2000 ) for page in page_iterator: output = page['SpotPriceHistory'] ``` However, I still get the same number of results! When I fetch the results of 90 days, I still got have the same amount of results? How to get all results or to get the max amount of price values?<issue_comment>username_1: To make an API call to another region, specify the `region_name`: ``` ec2 = boto3.client('ec2', region_name='ap-southeast-2') ``` When `MaxResults` is exceeded, obtain the next set of results by making the same call, but set `NextToken` to the value returned by `NextToken` in the previous result set. Upvotes: 1 <issue_comment>username_1: Your code appears to be working just fine, but the start and end timestamps were backwards. I ran this code: ``` import boto3 import datetime start_date = datetime.datetime.now() - datetime.timedelta(90) end_date = datetime.datetime.now() - datetime.timedelta(0) ec2 = boto3.client('ec2', region_name='us-east-1') paginator = ec2.get_paginator('describe_spot_price_history') page_iterator = paginator.paginate(InstanceTypes =['c3.4xlarge'],ProductDescriptions = ['Linux/UNIX'], AvailabilityZone = 'us-east-1a', StartTime= start_date, EndTime = end_date, MaxResults=2000 ) for page in page_iterator: print page['SpotPriceHistory'] ``` I got back one page that had 122 entries. The first entry was for 2018-04-01: ``` {u'Timestamp': datetime.datetime(2018, 4, 1, 4, 40, 44, tzinfo=tzutc()), u'AvailabilityZone': 'us-east-1a', u'InstanceType': 'c3.4xlarge', u'ProductDescription': 'Linux/UNIX', u'SpotPrice': '0.840000' }, ``` The last entry was for 2018-01-02: ``` {u'Timestamp': datetime.datetime(2018, 1, 2, 0, 28, 35, tzinfo=tzutc()), u'AvailabilityZone': 'us-east-1a', u'InstanceType': 'c3.4xlarge', u'ProductDescription': 'Linux/UNIX', u'SpotPrice': '0.840000' } ``` This cover the maximum 90 days of data that is available. Upvotes: 2
2018/03/21
618
2,154
<issue_start>username_0: A commit in the C implementation of the Nokogumbo gem is causing the build to fail on Gentoo Linux, however, the modification is minor and shouldn't cause any trouble. Unfortunately, I know next to zilch about C. Here's the commit: <https://github.com/rubys/nokogumbo/commit/8b4446847dea5c614759684ebcae4c580c47f4ad> It simply replaces the `<>` with `""`: ``` -#include -#include -#include +#include "gumbo.h" +#include "error.h" +#include "parser.h" ``` According to the [GCC docs](https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html) this shouldn't cause any trouble since it falls back to the previous behaviour: > > `#include "file"` > > > This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for . You can prepend directories to the list of quote directories with the -iquote option. > > > Unfortunately, while it compiles just fine with `<>`, the build fails with `""`: ``` compiling nokogumbo.c nokogumbo.c:24:20: fatal error: parser.h: No such file or directory #include "parser.h" ``` I'm wondering to what degree the way `<>` and `""` behaves depends on the toolchain, environment and other settings. Thanks a lot for your hints!<issue_comment>username_1: I checked your git repository and I noticed that you compile code with `--std=c99`. I think this may cause the problem, Because I found this in `C99` draft: > > The named source file is searched for in an implementation-defined > manner .If this search is not supported, or if the search fails, the > directive is reprocessed as if it read > > > ``` #include ``` So it means process is first implementation defined, and **if not supported** it uses `#include<>` mode. But this means if it defines that `#include""` searches current directory, it will stop searching like `#include<>`. Upvotes: -1 <issue_comment>username_2: Re-installing "gumbo" on the Gentoo box has fixed the problem. Apparently, a local installation mess has produced this weird behaviour. Upvotes: 0
2018/03/21
596
1,921
<issue_start>username_0: i have a page "deposits" here are plans are availble with the use of "foreach" now i wnt to show only plan number 3 here. mean plan of id 3. ``` @foreach($plan as $p) ### **{{ $p->name }}** **{{ $p->minimum }} {{ $basic->currency }} - {{ $p->maximum }} {{ $basic->currency }}** * Commission - {{ $p->percent }} * Time - {{ $p->time }} times * Compound - {{ $p->compound->name }} Invest Under This Package @endforeach ```<issue_comment>username_1: You can simply extract the plan from your `$plan` collection , does not need loop in below case ``` $p = $plan ->find(3); ``` Upvotes: 2 <issue_comment>username_2: if you want to use `foreach` and show plan id 3 , then try this : ``` @foreach($plan as $p) @if($p == 3) ### **{{ $p->name }}** **{{ $p->minimum }} {{ $basic->currency }} - {{ $p->maximum }} {{ $basic->currency }}** * Commission - {{ $p->percent }} * Time - {{ $p->time }} times * Compound - {{ $p->compound->name }} Invest Under This Package @endif @endforeach ``` But i suggest not to use `foreach` as you already know you need to show only plan id 3 . Try this : ``` php $p = $plan["your\_desired\_id"]; ? // means 2 or 3 .. whatever your desired id ### **{{ $p->name }}** **{{ $p->minimum }} {{ $basic->currency }} - {{ $p->maximum }} {{ $basic->currency }}** * Commission - {{ $p->percent }} * Time - {{ $p->time }} times * Compound - {{ $p->compound->name }} Invest Under This Package ``` Upvotes: 0 <issue_comment>username_3: If you need to find out a single value of plan from the collection . You can just find it by it's plan id ``` $plan = Plan::find(3); ``` Write this in your controller and then pass it down to your view blade file by using with. Example : ``` return view("blade file name")->with(['plan'=>$plan]) ``` Later in your blade file just access it's fields. ``` {{$plan->field_name}} ``` Upvotes: 0
2018/03/21
339
1,344
<issue_start>username_0: When I start writing a question on Stackoverflow without finishing, I can leave the page, and when I return the input still is keeping what I had entered. How can this be done? Is a database absolutely necessary? I would like to do something similar for a small webapp. Its a question-app where users answer questions with "No"/"Maybe"/"Yes". Depending on the answer, different points are awarded. When the user quits the test and returns, I would like to be still able to return the results of the last time he used it. Can this be done completely in JavaScript? [What the test looks like](https://martinhediger.000webhostapp.com/flexbox.html)<issue_comment>username_1: You can store persistent information in `localStorage` - which is obviously local on the computer they're using. Reference: <https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage> Upvotes: 2 <issue_comment>username_2: If you want this to across many systems/browser, you should use Database and store results and get back when access again. If this feature restricted to the browser that you logged in, browsers [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) alone will do the job. > > Can this be done completely in JavaScript? > > > Yes if you are using localstorage. Upvotes: 0
2018/03/21
8,982
26,539
<issue_start>username_0: Within a java spring-boot service (using Gradle), which provides a REST API to get data from the h2 database, I'll face the problem that the database always gets corrupted after a period of time. Sadly I'm not able to reconstruct the process in which the database gets corrupted. It always happens in "production". A client uses the endpoints / API to get several data. The service queries the data out of the database and returns it to the client. Further, a scheduled job is exectued within the context which gets data from another service and inserts this data to the h2 database. Exceptions I face when database is corrupted ``` org.h2.jdbc.JdbcSQLException: Allgemeiner Fehler: "java.lang.RuntimeException: rowcount remaining=2 SYS" General error: "java.lang.RuntimeException: rowcount remaining=2 SYS" [50000-196] ``` and ``` org.h2.jdbc.JdbcSQLException: Datei fehlerhaft beim Lesen des Datensatzes: "index not found 1020". Mögliche Lösung: Recovery Werkzeug verwenden File corrupted while reading record: "index not found 1020". Possible solution: use the recovery tool [90030-194] ``` The h2 connection settings in the application.properties file: ``` dataBaseFile=./db/file.db spring.datasource.url=jdbc:h2:file:${dataBaseFile};DB_CLOSE_ON_EXIT=TRUE;LOCK_TIMEOUT=30000;MVCC=TRUE;MV_STORE=FALSE;LOCK_MODE=0 spring.datasource.username=yyyy spring.datasource.password=<PASSWORD> spring.h2.console.enabled=true spring.h2.console.path=/console ``` Please let me know if you need further information as I currently don't know what exactly leads to this problem. Update #1 Full exception ``` 2018-01-23 13:40:13.687 INFO [MyService,,,] 6172 --- [main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default' 2018-01-23 13:40:18.359 ERROR [MyService,,,] 6172 --- [main] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool. org.h2.jdbc.JdbcSQLException: Datei fehlerhaft beim Lesen des Datensatzes: "index not found 358". Mögliche Lösung: Recovery Werkzeug verwenden File corrupted while reading record: "index not found 358". Possible solution: use the recovery tool [90030-194] at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) ~[h2-1.4.194.jar!/:na] at org.h2.message.DbException.get(DbException.java:179) ~[h2-1.4.194.jar!/:na] at org.h2.message.DbException.get(DbException.java:155) ~[h2-1.4.194.jar!/:na] at org.h2.store.PageStore.getPage(PageStore.java:769) ~[h2-1.4.194.jar!/:na] at org.h2.index.PageDataIndex.getPage(PageDataIndex.java:232) ~[h2-1.4.194.jar!/:na] at org.h2.index.PageDataNode.getNextPage(PageDataNode.java:232) ~[h2-1.4.194.jar!/:na] at org.h2.index.PageDataLeaf.getNextPage(PageDataLeaf.java:397) ~[h2-1.4.194.jar!/:na] at org.h2.index.PageDataCursor.nextRow(PageDataCursor.java:94) ~[h2-1.4.194.jar!/:na] at org.h2.index.PageDataCursor.next(PageDataCursor.java:52) ~[h2-1.4.194.jar!/:na] at org.h2.table.RegularTable.addIndex(RegularTable.java:273) ~[h2-1.4.194.jar!/:na] at org.h2.engine.Database.open(Database.java:748) ~[h2-1.4.194.jar!/:na] at org.h2.engine.Database.openDatabase(Database.java:276) ~[h2-1.4.194.jar!/:na] at org.h2.engine.Database.(Database.java:270) ~[h2-1.4.194.jar!/:na] at org.h2.engine.Engine.openSession(Engine.java:64) ~[h2-1.4.194.jar!/:na] at org.h2.engine.Engine.openSession(Engine.java:176) ~[h2-1.4.194.jar!/:na] at org.h2.engine.Engine.createSessionAndValidate(Engine.java:154) ~[h2-1.4.194.jar!/:na] at org.h2.engine.Engine.createSession(Engine.java:137) ~[h2-1.4.194.jar!/:na] at org.h2.engine.Engine.createSession(Engine.java:27) ~[h2-1.4.194.jar!/:na] at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:354) ~[h2-1.4.194.jar!/:na] at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:116) ~[h2-1.4.194.jar!/:na] at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:100) ~[h2-1.4.194.jar!/:na] at org.h2.Driver.connect(Driver.java:69) ~[h2-1.4.194.jar!/:na] at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:310) ~[tomcat-jdbc-8.5.14.jar!/:na] at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:203) ~[tomcat-jdbc-8.5.14.jar!/:na] at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:735) [tomcat-jdbc-8.5.14.jar!/:na] at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:667) [tomcat-jdbc-8.5.14.jar!/:na] at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:482) [tomcat-jdbc-8.5.14.jar!/:na] at org.apache.tomcat.jdbc.pool.ConnectionPool.(ConnectionPool.java:154) [tomcat-jdbc-8.5.14.jar!/:na] at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) [tomcat-jdbc-8.5.14.jar!/:na] at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) [tomcat-jdbc-8.5.14.jar!/:na] at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) [tomcat-jdbc-8.5.14.jar!/:na] at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:228) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) [hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847) [hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874) [hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final] at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) [spring-orm-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) [spring-orm-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) [spring-orm-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) [spring-orm-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) [spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) [spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) [spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) [spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) [spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) [spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) [spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at de.ica.tms.ka.etims.MessageServiceApplication.main(MessageServiceApplication.java:25) [classes!/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0\_131] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0\_131] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0\_131] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0\_131] at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) [MyService-2.5.4-RELEASE.jar:na] at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) [MyService-2.5.4-RELEASE.jar:na] at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) [MyService-2.5.4-RELEASE.jar:na] at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51) [MyService-2.5.4-RELEASE.jar:na] 2018-01-23 13:40:18.374 WARN [MyService,,,] 6172 --- [main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] 2018-01-23 13:40:18.390 INFO [MyService,,,] 6172 --- [main] o.apache.catalina.core.StandardService : Stopping service Tomcat 2018-01-23 13:40:18.452 WARN [MyService,,,] 6172 --- [main] o.s.boot.SpringApplication : Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]: Factory method 'transactionAdvisor' threw exception; nested exception is java.lang.NullPointerException) 2018-01-23 13:40:18.484 ERROR [MyService,,,] 6172 --- [main] o.s.boot.SpringApplication : Application startup failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar!/:1.5.3.RELEASE] at de.ica.tms.ka.etims.MessageServiceApplication.main(MessageServiceApplication.java:25) [classes!/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0\_131] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0\_131] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0\_131] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0\_131] at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) [MyService-2.5.4-RELEASE.jar:na] at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) [MyService-2.5.4-RELEASE.jar:na] at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) [MyService-2.5.4-RELEASE.jar:na] at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51) [MyService-2.5.4-RELEASE.jar:na] Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:264) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:228) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final] at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.8.RELEASE.jar!/:4.3.8.RELEASE] ... 24 common frames omitted Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254) ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final] ... 40 common frames omitted ``` EDIT I have investigated older log files and found following error(s) (timeout on locking table) before the DB gets in corrupted state and runs into the other exceptions. Maybe this is the root cause? ``` 2018-01-19 14:57:28.843 ERROR [MyService,2e06f077ff5d3a94,2e06f077ff5d3a94,false] 3432 --- [http-nio-8091-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : Zeitüberschreitung beim Versuch die Tabelle "TXBASETYPE_0" zu sperren Timeout trying to lock table "TXBASETYPE_0"; SQL statement: select txamltype0_.hjid as hjid1_117_0_, txamltype0_1_.txbase_txbasetype_0_hjid as txbase_t2_117_0_, txamltype0_.amlisteempfaengerid as amlistee1_97_0_, txamltype0_.amlistenummer as amlisten2_97_0_, txamltype0_.amlistesenderid as amlistes3_97_0_, txamltype0_.amlistezeitstempelitem as amlistez4_97_0_, iontxheade1_.hjid as hjid1_18_1_, iontxheade1_.device_id as device_i2_18_1_, iontxheade1_.transauftrag as transauf3_18_1_, iontxheade1_.transempfaengerid as transemp4_18_1_, iontxheade1_.transempfaengerrolle as transemp5_18_1_, iontxheade1_.transsignatur as transsig6_18_1_, iontxheade1_.transsignaturtyp as transsig7_18_1_, iontxheade1_.transsignaturzertifikat as transsig8_18_1_, iontxheade1_.transstatus as transsta9_18_1_, iontxheade1_.transtransaktionid_iontxhead_1 as transtr14_18_1_, iontxheade1_.transtransaktionstyp as transtr10_18_1_, iontxheade1_.transtransaktionszeitpunktit_0 as transtr11_18_1_, iontxheade1_.transversion as transve12_18_1_, iontxheade1_.transwiederholungszaehler as transwi13_18_1_, iontxheade1_1_.symmetrickeylist_txsymkeylty_0 as symmetri2_272_1_, iontxheade1_2_.symmetrickey_txsymkeyacktype_0 as symmetri2_271_1_, iontxheade1_3_.cvcertificatelist_txcvcertlt_0 as cvcertif2_124_1_, case when iontxheade1_1_.hjid is not null then 1 when iontxheade1_2_.hjid is not null then 2 when iontxheade1_3_.hjid is not null then 3 when iontxheade1_.hjid is not null then 0 end as clazz_1_, iontransak2_.hjid as hjid1_17_2_, iontransak2_.transsenderid as transsen2_17_2_, iontransak2_.transsenderrolle as transsen3_17_2_, iontransak2_.transsequenznummer as transseq4_17_2_, txsymkeylt3_.hjid as hjid1_66_3_, txcvcertlt4_.hjid as hjid1_9_4_, txsymkeyac5_.hjid as hjid1_65_5_, txsymkeyac5_.samid as samid2_65_5_, txsymkeyac5_.sequencenumber as sequence3_65_5_ from txamltype_0 txamltype0_ inner join txbasetype_0 txamltype0_1_ on txamltype0_.hjid=txamltype0_1_.hjid left outer join iontxheadertype_0 iontxheade1_ on txamltype0_1_.txbase_txbasetype_0_hjid=iontxheade1_.hjid left outer join txsymkeyltype iontxheade1_1_ on iontxheade1_.hjid=iontxheade1_1_.hjid left outer join txsymkeyacktype iontxheade1_2_ on iontxheade1_.hjid=iontxheade1_2_.hjid left outer join txcvcertltype iontxheade1_3_ on iontxheade1_.hjid=iontxheade1_3_.hjid left outer join iontransaktionidtype_0 iontransak2_ on iontxheade1_.transtransaktionid_iontxhead_1=iontransak2_.hjid left outer join symmetrickeylist txsymkeylt3_ on iontxheade1_1_.symmetrickeylist_txsymkeylty_0=txsymkeylt3_.hjid left outer join cvcertificatelist txcvcertlt4_ on iontxheade1_3_.cvcertificatelist_txcvcertlt_0=txcvcertlt4_.hjid left outer join symmetrickey_0 txsymkeyac5_ on iontxheade1_2_.symmetrickey_txsymkeyacktype_0=txsymkeyac5_.hjid where txamltype0_.hjid=? [50200-194] 2018-01-19 14:57:28.874 ERROR [MyService,,,] 3432 --- [http-nio-8091-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.PessimisticLockingFailureException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.PessimisticLockException: could not extract ResultSet] with ```<issue_comment>username_1: Is it possible that a connection is not being returned to the pool? You should always close a `java.sql.Connection` or a `org.hibernate.Session` in a `finally { ... }` block. Perhaps this is what's causing the lock timeout because there's another transaction blocking which will never be committed (maybe an error occurred on another thread but the connection/hibernate session wasn't closed) Upvotes: 1 <issue_comment>username_2: You have used `LOCK_MODE=0`. That's documented to be very dangerous in the [FAQ](http://www.h2database.com/html/faq.html#reliable), "dangerous features are: ... LOCK\_MODE 0 ...". Upvotes: 0
2018/03/21
1,342
5,650
<issue_start>username_0: ``` class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = '__all__' class ParentSerializer(serializers.ModelSerializer): """ Serializer for task """ def validate_title(self, data): if not data.get('title'): raise serializers.ValidationError('Please set title') return data ``` Validate Function is not called when Post ,Also how can i give custom errors to ChildSerializer ,<issue_comment>username_1: Your ParentSerializer validation method has some issues. Assumes that there is a `title` field in your `ParentSerializer` model. For field level validation, you will get the field instead of whole data. That is `validate_title` function should have `title`(title field of the data) as parameter not `data`. So you dont have to check `data.get('title')` for the existance of `title`. [Reference](http://www.django-rest-framework.org/api-guide/serializers/#field-level-validation) ``` class ParentSerializer(serializers.ModelSerializer): """ Serializer for task """ def validate_title(self, title): if not title: raise serializers.ValidationError('Please set title') return title ``` Upvotes: 3 <issue_comment>username_2: I ran into a similar problem where my custom validation field was not being called. I was writing it to bypass an incorrect DRF validation (more details shown below, but not necessary for the answer). Looking into the DRF source code I found my problem: DRF always validates your field using its code before validating with your custom code. ``` ''' rest-framework/serializers.py ''' for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: # DRF validation always runs first! # If DRF validator throws, then custom validation is not called validated_value = field.run_validation(primitive_value) if validate_method is not None: # this is your custom validation validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) ``` **Answer:** Custom validators cannot be used to bypass DRF's validators, as they will always run first and will raise an exception before you can say it is valid. (for those interested, the validation error I hit was like this: ModelSerializer used for ModelA, which has a OneToOne relation to ModelB. ModelB has a UUID for its pk. DRF throws the error `'53abb068-0286-411e-8729-0174635c5d81' is not a valid UUID.` when validating, which is incorrect, and really infuriating.) Upvotes: 3 <issue_comment>username_3: In addition to @username_2's answer I was trying to figure out how to override the child serializer validation. It might be possible to "skip" or more accurately ignore children serializer validation errors, by overriding `to_internal_value` of the ParentSerialzer: ``` class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer(many=True) def to_internal_value(self, *args, **kwargs): try: # runs the child serializers return super().to_internal_value(*args, **kwargs) except ValidationError as e: # fails, and then overrides the child errors with the parent error return self.validate(self.initial_data) def validate(self, attrs): errors = {} errors['custom_override_error'] = 'this ignores and overrides the children serializer errors' if len(errors): raise ValidationError(errors) return attrs class Meta: model = Parent ``` Upvotes: 1 <issue_comment>username_4: My problem was that I had my own custom `to_internal_value` method. Removing it fixed the issue. ``` class EventSerializer(serializers.Serializer): end_date = serializers.DateTimeField(format=DATE_FORMAT, required=True) start_date = serializers.DateTimeField(format=DATE_FORMAT, required=True) description = serializers.CharField(required=True) def validate_start_date(self, start_date): return start_date def validate_end_date(self, end_date): return end_date # def to_internal_value(self, data): # if data.get('start_date', False): # data['start_date'] = datetime.strptime(data['start_date'], DATE_FORMAT) # if data.get('end_date', False): # data['end_date'] = datetime.strptime(data['end_date'], DATE_FORMAT) # return data ``` Upvotes: 1 <issue_comment>username_5: I would like to add what the official documentation says, I hope it can be of help. **Field-level validation** You can specify custom field-level validation by adding .validate\_ methods to your Serializer subclass. These are similar to the .clean\_ methods on Django forms. These methods take a single argument, which is the field value that requires validation. Your validate\_ methods should return the validated value or raise a serializers.ValidationError. For example: ``` from rest_framework import serializers class BlogPostSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) content = serializers.CharField() def validate_title(self, value): """ Check that the blog post is about Django. """ if 'django' not in value.lower(): raise serializers.ValidationError("Blog post is not about Django") return value` ``` Upvotes: 1
2018/03/21
1,355
5,588
<issue_start>username_0: In my main component, I am fetching the api data and setting it to a state. Rather than an object, I'd prefer it to be in an array. Is there any way I can do this during the fetch and just make the object the first index(and only) index in an array? ``` fetch('https://api.aes/latest') .then(response => { return response.json(); }) .then(json => { this.setState({ launchData: json, }); ```<issue_comment>username_1: Your ParentSerializer validation method has some issues. Assumes that there is a `title` field in your `ParentSerializer` model. For field level validation, you will get the field instead of whole data. That is `validate_title` function should have `title`(title field of the data) as parameter not `data`. So you dont have to check `data.get('title')` for the existance of `title`. [Reference](http://www.django-rest-framework.org/api-guide/serializers/#field-level-validation) ``` class ParentSerializer(serializers.ModelSerializer): """ Serializer for task """ def validate_title(self, title): if not title: raise serializers.ValidationError('Please set title') return title ``` Upvotes: 3 <issue_comment>username_2: I ran into a similar problem where my custom validation field was not being called. I was writing it to bypass an incorrect DRF validation (more details shown below, but not necessary for the answer). Looking into the DRF source code I found my problem: DRF always validates your field using its code before validating with your custom code. ``` ''' rest-framework/serializers.py ''' for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: # DRF validation always runs first! # If DRF validator throws, then custom validation is not called validated_value = field.run_validation(primitive_value) if validate_method is not None: # this is your custom validation validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) ``` **Answer:** Custom validators cannot be used to bypass DRF's validators, as they will always run first and will raise an exception before you can say it is valid. (for those interested, the validation error I hit was like this: ModelSerializer used for ModelA, which has a OneToOne relation to ModelB. ModelB has a UUID for its pk. DRF throws the error `'53abb068-0286-411e-8729-0174635c5d81' is not a valid UUID.` when validating, which is incorrect, and really infuriating.) Upvotes: 3 <issue_comment>username_3: In addition to @username_2's answer I was trying to figure out how to override the child serializer validation. It might be possible to "skip" or more accurately ignore children serializer validation errors, by overriding `to_internal_value` of the ParentSerialzer: ``` class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer(many=True) def to_internal_value(self, *args, **kwargs): try: # runs the child serializers return super().to_internal_value(*args, **kwargs) except ValidationError as e: # fails, and then overrides the child errors with the parent error return self.validate(self.initial_data) def validate(self, attrs): errors = {} errors['custom_override_error'] = 'this ignores and overrides the children serializer errors' if len(errors): raise ValidationError(errors) return attrs class Meta: model = Parent ``` Upvotes: 1 <issue_comment>username_4: My problem was that I had my own custom `to_internal_value` method. Removing it fixed the issue. ``` class EventSerializer(serializers.Serializer): end_date = serializers.DateTimeField(format=DATE_FORMAT, required=True) start_date = serializers.DateTimeField(format=DATE_FORMAT, required=True) description = serializers.CharField(required=True) def validate_start_date(self, start_date): return start_date def validate_end_date(self, end_date): return end_date # def to_internal_value(self, data): # if data.get('start_date', False): # data['start_date'] = datetime.strptime(data['start_date'], DATE_FORMAT) # if data.get('end_date', False): # data['end_date'] = datetime.strptime(data['end_date'], DATE_FORMAT) # return data ``` Upvotes: 1 <issue_comment>username_5: I would like to add what the official documentation says, I hope it can be of help. **Field-level validation** You can specify custom field-level validation by adding .validate\_ methods to your Serializer subclass. These are similar to the .clean\_ methods on Django forms. These methods take a single argument, which is the field value that requires validation. Your validate\_ methods should return the validated value or raise a serializers.ValidationError. For example: ``` from rest_framework import serializers class BlogPostSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) content = serializers.CharField() def validate_title(self, value): """ Check that the blog post is about Django. """ if 'django' not in value.lower(): raise serializers.ValidationError("Blog post is not about Django") return value` ``` Upvotes: 1
2018/03/21
493
1,563
<issue_start>username_0: I am trying to add class `first` to the first div of a row and class `last` to the last div of a row. The number of divs in a row is user selectable and stored in a variable. the total number of divs is also user selectable and stored in a variable. Here's what I have tried, but it adds the class only to the first row and not repeating for the rest. ``` $number_of_cols = 4; //User Selectable $posts_per_page = 16; //User Selectable $mas_query = new WP_Query( $args ); if ( $mas_query->have_posts() ) : $count = 0; while ( $mas_query->have_posts() ) : $mas_query->the_post(); $count++; ?> php if ( has\_post\_thumbnail() ) { the\_post\_thumbnail('medium\_large'); } ? php the\_title( '<h3 class="entry-title grid-entry-title"', '' );?> php endwhile; endif; ? ``` How do I make it repeat for all divs pragmatically? Thanks<issue_comment>username_1: You can take advantage of the modulos operator, the remainder after a division: ``` while ( $mas_query->have_posts() ) : $mas_query->the_post(); $count++; // Boolean values $firstOfRow = ($count % $number_of_cols === 1); $lastOfRow = ($count % $number_of_cols === 0); ``` When count is `1`, `5`, etc., the remainder is `1` and when count is `4`, `8`, etc. the remainder is `0`. Upvotes: 3 [selected_answer]<issue_comment>username_2: Use this code it will work for you: ``` php if ( has\_post\_thumbnail() ) { the\_post\_thumbnail('medium\_large'); } ? php the\_title( '<h3 class="entry-title grid-entry-title"', '' );?> ``` Upvotes: 0
2018/03/21
1,308
4,507
<issue_start>username_0: I am trying to download files to disk from squeak. My method worked fine for small text/html files, but due to lack of buffering, it was very slow for the large binary file <https://mirror.racket-lang.org/installers/6.12/racket-6.12-x86_64-win32.exe>. Also, after it finished, the file was much larger (113 MB) than shown on download page (75MB). My code looks like this: ``` download: anURL "download a file over HTTP and save it to disk under a name extracted from url." | ios name | name := ((anURL findTokens: '/') removeLast findTokens: '?') removeFirst. ios := FileStream oldFileNamed: name. ios nextPutAll: ((HTTPClient httpGetDocument: anURL) content). ios close. Transcript show: 'done'; cr. ``` I have tried `[bytes = stream next bufSize. bytes printTo: ios]` for fixed size blocks in HTTP response's `contentStream` using a `[stream atEnd] whileFalse:` loop, but that garbled the output file with single quotes around each block, and also extra content after the blocks, which looked like all characters of the stream, each single quoted. How can I implement buffered writing of an HTTP response to a disk file? Also, is there a way to do this in squeak while showing download progress?<issue_comment>username_1: As Leandro already wrote the issue is with `#binary`. Your code is nearly correct, I have taken the liberty to run it - now it downloads the whole file correctly: ``` | ios name anURL | anURL := ' https://mirror.racket-lang.org/installers/6.12/racket-6.12-x86_64-win32.exe'. name := ((anURL findTokens: '/') removeLast findTokens: '?') removeFirst. ios := FileStream newFileNamed: 'C:\Users\user\Downloads\_squeak\', name. ios binary. ios nextPutAll: ((HTTPClient httpGetDocument: anURL) content). ios close. Transcript show: 'done'; cr. ``` As for the freezing, I think the issue is with the one thread for the whole environment while you are downloading. That means that means till you download the whole file you won't be able to use Squeak. Just tested in Pharo (easier install) and the following code works as you want: ``` ZnClient new url: 'https://mirror.racket-lang.org/installers/6.12/racket-6.12-x86_64-win32.exe'; downloadTo: 'C:\Users\user\Downloads\_squeak'. ``` Upvotes: 2 <issue_comment>username_2: The `WebResponse` class, when building the response content, creates a buffer large enough to hold the entire response, even for huge responses! I think this happens due to code in `WebMessage>>#getContentWithProgress:`. I tried to copy data from the input `SocketStream` of `WebResponse` directly to an output `FileStream`. I had to subclass `WebClient` and `WebResponse`, and write a two methods. Now the following code works as required. ``` | client link | client := PkWebClient new. link := 'http://localhost:8000/racket-6.12-x86_64-linux.sh'. client download: link toFile: '/home/yo/test'. ``` I have verified block by block update and integrity of the downloaded file. I include source below. The method `streamContentDirectToFile: aFilePathString` is the one that does things differently and solves the problem. ``` WebClient subclass: #PkWebClient instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'PK'! !PkWebClient commentStamp: 'pk 3/28/2018 20:16' prior: 0! Trying to download http directly to file.! !PkWebClient methodsFor: 'as yet unclassified' stamp: 'pk 3/29/2018 13:29'! download: urlString toFile: aFilePathString "Try to download large files sensibly" | res | res := self httpGet: urlString. res := PkWebResponse new copySameFrom: res. res streamContentDirectToFile: aFilePathString! ! WebResponse subclass: #PkWebResponse instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'PK'! !PkWebResponse commentStamp: 'pk 3/28/2018 20:49' prior: 0! To make getContentwithProgress better.! ]style[(38)f1! !PkWebResponse methodsFor: 'as yet unclassified' stamp: 'pk 3/29/2018 13:20'! streamContentDirectToFile: aFilePathString "stream response's content directly to file." | buffer ostream | stream binary. buffer := ByteArray new: 4096. ostream := FileStream oldFileNamed: aFilePathString. ostream binary. [stream atEnd] whileFalse: [buffer := stream nextInBuffer: 4096. stream receiveAvailableData. ostream nextPutAll: buffer]. stream close. ostream close! ! ``` Upvotes: 2 [selected_answer]
2018/03/21
939
3,442
<issue_start>username_0: I made a script that reads an Excel document en checks if the first row contains "UPDATED". If so it writes the whole row to another Excel document with the same Tab name. My Excel document is 23 sheets with 1000 lines on each sheet, and now it takes more than 15 minutes to complete this. Is there a way to speed this up? I was thinking about multithreading or multiprocessing but i don't know which one is better. **UPDATE: the fact that my program took 15 minutes to run was al caused by the READ-ONLY mode, when i removed it, it only took 2 seconds to run the program** ``` import openpyxl import os from datetime import datetime titles = ["Column1", "Column2", "Column3", "Column4", "Column5","Column6", "Column7", "Column8", "Column9", "Column10", "Column11", "Column12", "Column13", "Column14", "Column15", "Column16"] def main(): oldFilePath= os.getcwd() + "\oldFile.xlsx" newFilePath= os.getcwd() + "\newFile.xlsx" wb = openpyxl.load_workbook(filename=oldFilePath, read_only=True) wb2 = openpyxl.Workbook() sheets = wb.get_sheet_names() sheets2 = wb2.get_sheet_names() #removes all sheets in newFile.xlsx for sheet in sheets2: temp = wb2.get_sheet_by_name(sheet) wb2.remove_sheet(temp) for tab in sheets: print("Sheet: " + str(tab)) rowCounter = 2 sheet = wb[tab] for row in range(sheet.max_row): if sheet.cell(row=row + 1, column=1).value == "": #if cell is empty stop reading break elif sheet.cell(row=row + 1, column=1).value == "UPDATED": if tab not in sheets2: sheet2 = wb2.create_sheet(title=tab) sheet2.append(titles) for x in range(1, 17): sheet2.cell(row=rowCounter, column=x).value = sheet.cell(row=row + 1, column=x).value rowCounter += 1 sheets2 = wb2.get_sheet_names() wb2.save(filename=newFilePath) if __name__ == "__main__": startTime = datetime.now() main() print("Script finished in: " + str(datetime.now() - startTime)) ```<issue_comment>username_1: You should have a look at some great multiprocessing tutorials, e.g.: <https://www.blog.pythonlibrary.org/2016/08/02/python-201-a-multiprocessing-tutorial/> Also, the Python documentation will give you some great examples: <https://docs.python.org/3.6/library/multiprocessing.html> You should give special attention to topics like using Pools and Queues. Multiprocessing will help you get around the limitations of the Global Interpreter Lock, so that might be a good way to improve your performance. Tuning the performance of I/O processes can be a tricky topic, so you'll need to find out more details about the bottleneck. If you can't improve its performance, you might try to find an alternative way to getting the same data. Upvotes: 1 <issue_comment>username_2: For such small workbooks there is no need to use read-only mode and by using it injudiciously you are causing the problem yourself. Every call to `ws.cell()` will force openpyxl to parse the worksheet again. So, either you stop using read-only mode, or use `ws.iter_rows()` as I advised on your previous question. In general, if you think something is running slow you should always profile it rather than just trying somethng out and hoping for the best. Upvotes: 3 [selected_answer]
2018/03/21
730
2,853
<issue_start>username_0: I have spring boot application which used spring rest controller . This is the controller , below is the response an getting. Am using postman tool for sending request to this controller. And am sending content type as application/json ``` @RequestMapping(value = "/test", method = RequestMethod.POST) public String test(@RequestBody WebApp webapp, @RequestBody String propertyFiles, @RequestBody String) { System.out.println("webapp :"+webapp); System.out.println("propertyFiles :"+propertyFiles); System.out.println("propertyText :"+propertyText); return "ok good"; } ``` 2018-03-21 12:18:47.732  WARN 8520 --- [nio-8099-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed This is my postman request ``` { "webapp":{"webappName":"cavion17","path":"ud1","isQA":true}, "propertyFiles":"vchannel", "propertytText":"demo property"} ``` I tried by removing the RequestBody annotation, then able to hit the service , but param objects are received as null. So please suggest how to retrieve objects in the restcontroller?<issue_comment>username_1: You cannot use multiple `@RequestBody` annotations in Spring. You need to wrap all these in an object. Some like this ``` // some imports here public class IncomingRequestBody { private Webapp webapp; private String propertryFiles; private String propertyText; // add getters and setters here } ``` And in your controller ``` @RequestMapping(value = "/test", method = RequestMethod.POST) public String test(@RequestBody IncomingRequestBody requestBody) { System.out.println(requestBody.getPropertyFiles()); // other statement return "ok good"; } ``` Read more here [Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax](https://stackoverflow.com/questions/12893566/passing-multiple-variables-in-requestbody-to-a-spring-mvc-controller-using-ajax) Upvotes: 4 [selected_answer]<issue_comment>username_2: Based on the sample postman payload you gave, you will need: ``` public class MyObject { private MyWebapp webapp; private String propertyFiles; private String propertytText; // your getters /setters here as needed } ``` and ``` public class MyWebapp { private String webappName; private String path; private boolean isQA; // getters setters here } ``` Then on your controller change it to: ``` @RequestMapping(value = "/test", method = RequestMethod.POST) public String test(@RequestBody MyObject payload) { // then access the fields from the payload like payload.getPropertyFiles(); return "ok good"; } ``` Upvotes: 1
2018/03/21
1,366
6,497
<issue_start>username_0: I want to stop the second click on a `RadioButton`, when someone has already clicked on a `RadioButton` in a `RadioGroup`. If someone clicks 2 times, the user not able to change that selected click. I am trying to prevent that with a `boolean` but it doesn't work. Where am I wrong? **This is my code:** ``` radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // checkedId is the RadioButton selected rb = (RadioButton) findViewById(checkedId); user_radio_answer = (String) rb.getText(); rb.setOnClickListener(new View.OnClickListener() { private boolean isChecked = true; @Override public void onClick(View v) { if (isChecked) { if (rb.isChecked() ) { isChecked = false; } } if (correct_answer1.equals(user_radio_answer)) { rb.setBackgroundColor(Color.GREEN); // Toast.makeText(getApplicationContext(), "Correct ☺ : " + user_radio_answer, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Incorrect Answer :( ..Correct Answer : " + correct_answer1, Toast.LENGTH_LONG).show(); rb.setBackgroundColor(Color.parseColor("#FF5733")); answer1 = rb_answer1.getText().toString(); answer2 = rb_answer2.getText().toString(); answer3 = rb_answer3.getText().toString(); answer4 = rb_answer4.getText().toString(); if (answer1.equals(correct_answer1)) { rb_answer1.setBackgroundColor(Color.GREEN); } if (answer2.equals(correct_answer1)) { rb_answer2.setBackgroundColor(Color.GREEN); } if (answer3.equals(correct_answer1)) { rb_answer3.setBackgroundColor(Color.GREEN); } if (answer4.equals(correct_answer1)) { rb_answer4.setBackgroundColor(Color.GREEN); } } new RadioHttpAsyncTask().execute("http:xxxxxx-xxxxxxxxxx-xxxxxxxx"); } }); } }); ```<issue_comment>username_1: You can disable it after click to stop listening to click events ``` rb.setEnabled(false); ``` Edit: Or you can remove click listener once it is already clicked ``` rb.setOnClickListener(null); ``` Upvotes: 0 <issue_comment>username_2: You can add two methods and then call them when needed. You can add a condition, if the radiobutton is checked then disable the group and if it is not checked then set it to enabled. When you clear your radiogroup you can also set buttons enabled. ``` public void disableRG() { for(int i = 0; i < radioGroup.getChildCount(); i++){ ((RadioButton)radioGroup.getChildAt(i)).setEnabled(false); } } public void enableRG() { for(int i = 0; i < radioGroup.getChildCount(); i++){ ((RadioButton)radioGroup.getChildAt(i)).setEnabled(true); } } ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: Just remember if they have answered the question, and remember the view (RadioButton) that spawned the first answer, and check that RadioButton again whenever a RadioButton is clicked. This assumes all RadioButtons in the RadioGroup have the same `onClick` method. ``` boolean answered = false; RadioButton radioAnswer; public void answer1(View view) { if (!answered) { radioAnswer = (RadioButton) view; answered = true; } else { radioAnswer.setChecked(true); } } ``` Upvotes: 2 <issue_comment>username_4: Maybe you can set a global boolean flag. ``` `private boolean alreadyChecked = false; radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // checkedId is the RadioButton selected rb = (RadioButton) findViewById(checkedId); user_radio_answer = (String) rb.getText(); if (!alreadyChecked) { rb.setOnClickListener(new View.OnClickListener() { private boolean isChecked = true; @Override public void onClick(View v) { if (isChecked) { if (rb.isChecked() ) { isChecked = false; } } if (correct_answer1.equals(user_radio_answer)) { rb.setBackgroundColor(Color.GREEN); // Toast.makeText(getApplicationContext(), "Correct ☺ : " + user_radio_answer, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Incorrect Answer :( ..Correct Answer : " + correct_answer1, Toast.LENGTH_LONG).show(); rb.setBackgroundColor(Color.parseColor("#FF5733")); answer1 = rb_answer1.getText().toString(); answer2 = rb_answer2.getText().toString(); answer3 = rb_answer3.getText().toString(); answer4 = rb_answer4.getText().toString(); if (answer1.equals(correct_answer1)) { rb_answer1.setBackgroundColor(Color.GREEN); } if (answer2.equals(correct_answer1)) { rb_answer2.setBackgroundColor(Color.GREEN); } if (answer3.equals(correct_answer1)) { rb_answer3.setBackgroundColor(Color.GREEN); } if (answer4.equals(correct_answer1)) { rb_answer4.setBackgroundColor(Color.GREEN); } } new RadioHttpAsyncTask().execute("http:xxxxxx-xxxxxxxxxx-xxxxxxxx"); } alreadyChecked = true; }); } } });` ``` Upvotes: 0
2018/03/21
969
4,250
<issue_start>username_0: Can anyone explain how it return "C" and not report error in "b = false"? ``` class A { public static void main(String[] args) { boolean b; if (b = false) {System.out.print("A"); } else if (b) {System.out.print("B"); } else if (!b) {System.out.print("C"); } else {System.out.print("D");} } } ``` Thank for helping me<issue_comment>username_1: You can disable it after click to stop listening to click events ``` rb.setEnabled(false); ``` Edit: Or you can remove click listener once it is already clicked ``` rb.setOnClickListener(null); ``` Upvotes: 0 <issue_comment>username_2: You can add two methods and then call them when needed. You can add a condition, if the radiobutton is checked then disable the group and if it is not checked then set it to enabled. When you clear your radiogroup you can also set buttons enabled. ``` public void disableRG() { for(int i = 0; i < radioGroup.getChildCount(); i++){ ((RadioButton)radioGroup.getChildAt(i)).setEnabled(false); } } public void enableRG() { for(int i = 0; i < radioGroup.getChildCount(); i++){ ((RadioButton)radioGroup.getChildAt(i)).setEnabled(true); } } ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: Just remember if they have answered the question, and remember the view (RadioButton) that spawned the first answer, and check that RadioButton again whenever a RadioButton is clicked. This assumes all RadioButtons in the RadioGroup have the same `onClick` method. ``` boolean answered = false; RadioButton radioAnswer; public void answer1(View view) { if (!answered) { radioAnswer = (RadioButton) view; answered = true; } else { radioAnswer.setChecked(true); } } ``` Upvotes: 2 <issue_comment>username_4: Maybe you can set a global boolean flag. ``` `private boolean alreadyChecked = false; radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // checkedId is the RadioButton selected rb = (RadioButton) findViewById(checkedId); user_radio_answer = (String) rb.getText(); if (!alreadyChecked) { rb.setOnClickListener(new View.OnClickListener() { private boolean isChecked = true; @Override public void onClick(View v) { if (isChecked) { if (rb.isChecked() ) { isChecked = false; } } if (correct_answer1.equals(user_radio_answer)) { rb.setBackgroundColor(Color.GREEN); // Toast.makeText(getApplicationContext(), "Correct ☺ : " + user_radio_answer, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Incorrect Answer :( ..Correct Answer : " + correct_answer1, Toast.LENGTH_LONG).show(); rb.setBackgroundColor(Color.parseColor("#FF5733")); answer1 = rb_answer1.getText().toString(); answer2 = rb_answer2.getText().toString(); answer3 = rb_answer3.getText().toString(); answer4 = rb_answer4.getText().toString(); if (answer1.equals(correct_answer1)) { rb_answer1.setBackgroundColor(Color.GREEN); } if (answer2.equals(correct_answer1)) { rb_answer2.setBackgroundColor(Color.GREEN); } if (answer3.equals(correct_answer1)) { rb_answer3.setBackgroundColor(Color.GREEN); } if (answer4.equals(correct_answer1)) { rb_answer4.setBackgroundColor(Color.GREEN); } } new RadioHttpAsyncTask().execute("http:xxxxxx-xxxxxxxxxx-xxxxxxxx"); } alreadyChecked = true; }); } } });` ``` Upvotes: 0
2018/03/21
1,243
5,005
<issue_start>username_0: While writing a simple code using STL queue and `for` loop, I faced a problem. My procedure is simple: take a number as a string, convert them into queue elements and show them. My code is below : ``` #include #include #include //#include using namespace std; //int to\_words(int i); //int to\_words\_one(queue &q); int main() { queue q; string s; cout << "Enter a number not more than 12 digits : "; getline(cin, s, '\n'); for (int i = 0; i < s.length(); i++) { if (!isdigit(s[i])) { cout << "Not a valid number." << endl; s.clear(); break; } } if(s.size() > 0) for (int i = 0; i < s.length(); i++) q.push(s[i] - '0'); while (!q.empty()) { cout << q.front(); q.pop(); } system("PAUSE"); } ``` It works fine. No problem. But instead of `while(!q.empty())`, if I use ``` for(int j=0;j < q.size(); j++) { cout << q.front(); q.pop(); } ``` It doesn't work properly! It just shows and pops some first elements , and NOT ALL elements of the queue and prompts for `Press any key to continue`. Please tell me why is this happening? Shouldn't `while(!q.empty())` and and that `for()` loop work similar?<issue_comment>username_1: You can disable it after click to stop listening to click events ``` rb.setEnabled(false); ``` Edit: Or you can remove click listener once it is already clicked ``` rb.setOnClickListener(null); ``` Upvotes: 0 <issue_comment>username_2: You can add two methods and then call them when needed. You can add a condition, if the radiobutton is checked then disable the group and if it is not checked then set it to enabled. When you clear your radiogroup you can also set buttons enabled. ``` public void disableRG() { for(int i = 0; i < radioGroup.getChildCount(); i++){ ((RadioButton)radioGroup.getChildAt(i)).setEnabled(false); } } public void enableRG() { for(int i = 0; i < radioGroup.getChildCount(); i++){ ((RadioButton)radioGroup.getChildAt(i)).setEnabled(true); } } ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: Just remember if they have answered the question, and remember the view (RadioButton) that spawned the first answer, and check that RadioButton again whenever a RadioButton is clicked. This assumes all RadioButtons in the RadioGroup have the same `onClick` method. ``` boolean answered = false; RadioButton radioAnswer; public void answer1(View view) { if (!answered) { radioAnswer = (RadioButton) view; answered = true; } else { radioAnswer.setChecked(true); } } ``` Upvotes: 2 <issue_comment>username_4: Maybe you can set a global boolean flag. ``` `private boolean alreadyChecked = false; radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // checkedId is the RadioButton selected rb = (RadioButton) findViewById(checkedId); user_radio_answer = (String) rb.getText(); if (!alreadyChecked) { rb.setOnClickListener(new View.OnClickListener() { private boolean isChecked = true; @Override public void onClick(View v) { if (isChecked) { if (rb.isChecked() ) { isChecked = false; } } if (correct_answer1.equals(user_radio_answer)) { rb.setBackgroundColor(Color.GREEN); // Toast.makeText(getApplicationContext(), "Correct ☺ : " + user_radio_answer, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Incorrect Answer :( ..Correct Answer : " + correct_answer1, Toast.LENGTH_LONG).show(); rb.setBackgroundColor(Color.parseColor("#FF5733")); answer1 = rb_answer1.getText().toString(); answer2 = rb_answer2.getText().toString(); answer3 = rb_answer3.getText().toString(); answer4 = rb_answer4.getText().toString(); if (answer1.equals(correct_answer1)) { rb_answer1.setBackgroundColor(Color.GREEN); } if (answer2.equals(correct_answer1)) { rb_answer2.setBackgroundColor(Color.GREEN); } if (answer3.equals(correct_answer1)) { rb_answer3.setBackgroundColor(Color.GREEN); } if (answer4.equals(correct_answer1)) { rb_answer4.setBackgroundColor(Color.GREEN); } } new RadioHttpAsyncTask().execute("http:xxxxxx-xxxxxxxxxx-xxxxxxxx"); } alreadyChecked = true; }); } } });` ``` Upvotes: 0
2018/03/21
1,247
4,020
<issue_start>username_0: I'm trying to understand how to update my Ionic Framework Version. ``` ionic info Your system information: Cordova CLI: 8.0.0 Gulp version: CLI version 3.9.1 Gulp local: Local version 3.9.1 Ionic Framework Version: 1.1.0 Ionic CLI Version: 1.7.16 Ionic App Lib Version: 0.7.3 OS: Node Version: v6.9.1 ``` So the current Ionic Framework Version is "1.1.0" I updated my bower.json: ``` { "name": "hello-ionic", "private": "true", "devDependencies": { "ionic": "driftyco/ionic-bower#1.3.3" } } ``` and run `bower install` but the new files are being stored at 'bower\_components' folder My folder structure: [![enter image description here](https://i.stack.imgur.com/Lii70.png)](https://i.stack.imgur.com/Lii70.png) I also copied the files from 'bower\_components' to 'lib' folder and still after `ionic info` the 'Ionic Framework Version' is still '1.1.0'<issue_comment>username_1: Try to upgrade the project to the new versions: ``` npm install -g ionic@latest npm install [email protected] --save npm install @ionic/[email protected] --save-dev npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install [email protected] --save npm install [email protected] --save ``` In addition to improving `ionic-angular 3.x`. Also, if you're using animations, run the command: ``` npm install @angular/[email protected] --save ``` It looks like you might actually want ``` npm update packagename ``` which does try to honor semver, and does recursively update all the dependencies of packagename. Of course, it does them all recursively asynchronously at once. If you can give up the need for updating deps-of-deps, then you can get pretty far with ``` npm --depth 0 update grunt ``` After a research: > > npm will correctly handle version conflicts between shared > dependencies by downloading the correct one for each. So, if Dep A > depends on Dep C v1.0.0 and Dep B depends on Dep C v2.0.0, they will > each be installed and used appropriately. Therefore, you are free to > install the latest of any packages you would like. > > > Then, feel free to update update package by package or use (AFTER UPDATE YOUR ANGULAR PACKAGES) and exclude for a while the `ionic packages` from the `packages.json` to don't update them: ``` npm i -g npm-check-updates ncu -u npm install ``` Upvotes: 0 <issue_comment>username_2: Try with ``` npm install -g [email protected] ``` After the CLI has been updated you have a few options when it comes to updating your base library install, goto the root of your project and run this command: ``` ionic lib update ``` [Here](https://www.thepolyglotdeveloper.com/2014/10/updating-ionic-framework-project-cli/) for more details. hope it helps. Upvotes: 4 [selected_answer]<issue_comment>username_3: The ultimate version of IONIC v1 is `1.3.5`, I guess. You'd better make a global install of `ionic`, first. `sudo npm i -g ionic` Then, install new **Ionic v1 CLI Utility** locally for CLI commands as it has been released for v1 project maintenance. `npm i @ionic/v1-toolkit` Upvotes: 0 <issue_comment>username_4: try command: npm install -g cordova ionic. Upvotes: 0 <issue_comment>username_5: simple run ``` ionic lib update ``` See official [Docs](https://github.com/ionic-team/ionic-cli#update-ionic-lib) Upvotes: 0 <issue_comment>username_6: While the other answers are correct only on updating ionic version with experience I can say you might have old dependencies which might crash with your upgrade so best is to use, <https://www.npmjs.com/package/npm-check-updates> after installing the package run `npx npm-check-updates` this will recommend and update all your packages to latest stable. Upvotes: 0
2018/03/21
1,224
4,077
<issue_start>username_0: I try to pass a JSON as String from my Spring Controller to the React Frontend. ***JSON:*** ``` { "name": ".", "size": 0, "children": [ { "name": "setup.bat", "size": 6, "children": [] }, { "name": "src", "size": 0, "children": [ { "name": "main", "size": 0, "children": [ { "name": "java", "size": 0, "children": [ ... ``` I try it with Thymeleaf and the console output on my site worked: ***index.html*** ``` $( document ).ready(function() { var jsondata = /*[[${jsondata}]]*/; console.debug(jsondata); }); ``` but now i try to used it in react I get an error: ***app.js:*** ``` class App extends Component { render() { return( {jsondata} ) } } ``` > > Uncaught ReferenceError: jsondata is not defined > > > What is the Problem in React ?<issue_comment>username_1: Try to upgrade the project to the new versions: ``` npm install -g ionic@latest npm install [email protected] --save npm install @ionic/[email protected] --save-dev npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install @angular/[email protected] --save npm install [email protected] --save npm install [email protected] --save ``` In addition to improving `ionic-angular 3.x`. Also, if you're using animations, run the command: ``` npm install @angular/[email protected] --save ``` It looks like you might actually want ``` npm update packagename ``` which does try to honor semver, and does recursively update all the dependencies of packagename. Of course, it does them all recursively asynchronously at once. If you can give up the need for updating deps-of-deps, then you can get pretty far with ``` npm --depth 0 update grunt ``` After a research: > > npm will correctly handle version conflicts between shared > dependencies by downloading the correct one for each. So, if Dep A > depends on Dep C v1.0.0 and Dep B depends on Dep C v2.0.0, they will > each be installed and used appropriately. Therefore, you are free to > install the latest of any packages you would like. > > > Then, feel free to update update package by package or use (AFTER UPDATE YOUR ANGULAR PACKAGES) and exclude for a while the `ionic packages` from the `packages.json` to don't update them: ``` npm i -g npm-check-updates ncu -u npm install ``` Upvotes: 0 <issue_comment>username_2: Try with ``` npm install -g [email protected] ``` After the CLI has been updated you have a few options when it comes to updating your base library install, goto the root of your project and run this command: ``` ionic lib update ``` [Here](https://www.thepolyglotdeveloper.com/2014/10/updating-ionic-framework-project-cli/) for more details. hope it helps. Upvotes: 4 [selected_answer]<issue_comment>username_3: The ultimate version of IONIC v1 is `1.3.5`, I guess. You'd better make a global install of `ionic`, first. `sudo npm i -g ionic` Then, install new **Ionic v1 CLI Utility** locally for CLI commands as it has been released for v1 project maintenance. `npm i @ionic/v1-toolkit` Upvotes: 0 <issue_comment>username_4: try command: npm install -g cordova ionic. Upvotes: 0 <issue_comment>username_5: simple run ``` ionic lib update ``` See official [Docs](https://github.com/ionic-team/ionic-cli#update-ionic-lib) Upvotes: 0 <issue_comment>username_6: While the other answers are correct only on updating ionic version with experience I can say you might have old dependencies which might crash with your upgrade so best is to use, <https://www.npmjs.com/package/npm-check-updates> after installing the package run `npx npm-check-updates` this will recommend and update all your packages to latest stable. Upvotes: 0
2018/03/21
685
3,263
<issue_start>username_0: in my app, I am connecting my app to BLE device. and I am fetching BLE data from BLE device at every 1 second. it working fine when I do this in the foreground.but I want to do same in the background even when the app will be in the background I need to fetch data continuously from BLE device. right now its stoped automatically after 2 minutes. Please let me know if it's feasible or not? Thanks in advance<issue_comment>username_1: You need to enable Background Mode in your project settings under capabilities tab. Under background modes you will find a few modes that satisfy various purposes of running an app in background. From these you have to enable the ones that you think are suitable according to the task that your app will perform in background. I think, you should enable external accessory communication and background fetch. Also you need to implement a background task when your app enters background. This is done in app delegate's didEnterBackground method. Upvotes: 2 <issue_comment>username_2: **Apple documentation** Apps that work with Bluetooth peripherals can ask to be woken up if the peripheral delivers an update when the app is suspended. This support is important for **Bluetooth-LE** accessories that deliver data at regular intervals, such as a Bluetooth heart rate belt. You enable support for using bluetooth accessories from the Background modes section of the Capabilities tab in your Xcode project. (You can also enable this support by including the `UIBackgroundModes` key with the bluetooth-central value in your app’s Info.plist file.) When you enable this mode, the Core Bluetooth framework keeps open any active sessions for the corresponding peripheral. In addition, new data arriving from the peripheral causes the system to wake up the app so that it can process the data. The system also wakes up the app to process accessory connection and disconnection notifications. In iOS 6, an app can also operate in peripheral mode with Bluetooth accessories. To act as a Bluetooth accessory, you must enable support for that mode from the Background modes section of the Capabilities tab in your Xcode project. (You can also enable this support by including the UIBackgroundModes key with the bluetooth-peripheral value in your app’s Info.plist file.) Enabling this mode lets the Core Bluetooth framework wake the app up briefly in the background so that it can handle accessory-related requests. Apps woken up for these events should process them and return as quickly as possible so that the app can be suspended again. Any app that supports the background processing of Bluetooth data must be session-based and follow a few basic guidelines: **Apps must provide an interface that allows the user to start and stop the delivery of Bluetooth events. That interface should then open or close the session as appropriate.** **Upon being woken up, the app has around 10 seconds to process the data. Ideally, it should process the data as fast as possible and allow itself to be suspended again. However, if more time is needed, the app can use the beginBackgroundTaskWithExpirationHandler: method to request additional time; it should do so only when absolutely necessary, though.** Upvotes: 1
2018/03/21
653
2,168
<issue_start>username_0: I have tried solutions in other questions but that is not solving my issue. I have made **strict** from **true** to **false**. Used modes ``` 'modes' => [ 'STRICT_TRANS_TABLES', 'NO_ZERO_IN_DATE', 'NO_ZERO_DATE', 'ERROR_FOR_DIVISION_BY_ZERO', 'NO_AUTO_CREATE_USER', 'NO_ENGINE_SUBSTITUTION' ] ``` as well. But I am getting the same error. ``` $orders = Order::orderBy('id', 'desc')->groupBy('order_id')->get(); dd($orders); ``` This is throwing the error > > Syntax error or access violation: 1055 'my\_db.orders.id' isn't in GROUP BY (SQL: select \* from `orders` group by `order_id` order by `id` desc) > > > (I am using Laravel 5.6)<issue_comment>username_1: In *config/database.php* Change `'strict' => true` To `'strict' => false` and clear the cache > > php artisan config:cache > > > OR In MySql settings change ``` mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: **Short answer** This is a MySQL issue that can be resolved changing Laravel config as @username_1 wrote, modifying `strict => true` to `strict => false` in `config/database.php`. **Long Answer** MySQL 5.7 introduced something we are calling "strict mode," which is a combination of new modes that, in sum, make MySQL process your queries a little more strictly than before. "Strict mode" is a list of modes MySQL 5.7 enables by default, comprised of the following modes: ``` ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ZERO_IN_DATE NO_ZERO_DATE ERROR_FOR_DIVISION_BY_ZERO NO_AUTO_CREATE_USER NO_ENGINE_SUBSTITUTION ``` So, what if you want to disable / enable just few of this stricts mode? Laravel help us. ``` 'connections' => [ 'mysql' => [ // Ignore this key and rely on the strict key 'modes' => null, // Explicitly disable all modes, overriding strict setting 'modes' => [], // Explicitly enable specific modes, overriding strict setting 'modes' => [ 'STRICT_TRANS_TABLES', 'ONLY_FULL_GROUP_BY', ], ] ] ``` Upvotes: 2
2018/03/21
492
1,936
<issue_start>username_0: In AWS Lambda, there is no need of provisioning done by us. But I was wondering how AWS Lambda might be provisioning machines to run for the requests. Is it creating a EC2 server for each request and execute the request and then kill the server? Or it keeps some EC2 servers always on to serve the request by executing the lambda function? If its doing the former point, then I am wondering it would also affect performance of AWS Lambda to serve the request. Can anyone guide me on this?<issue_comment>username_1: AWS Lambda is known to reuse the resources. It will not create an EC2 server for each request so that will not be a performance concern But you should note that the disk space provided for your function sometimes not cleanup properly. [As some users reported](https://forums.aws.amazon.com/thread.jspa?threadID=209428) You can read more on the execution life cycle of Lambda here: <https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html> Upvotes: 0 <issue_comment>username_2: Lambdas run inside of a [docker-like container](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html), on EC2 servers ([using Firecracker](https://aws.amazon.com/about-aws/whats-new/2018/11/firecracker-lightweight-virtualization-for-serverless-computing/)) that are highly, highly optimized. AWS has thousands of servers running full time to serve all of the Lambda functions that are running. A cold start Lambda (one that's never been run before) starts up in a few seconds, depending on how big it is. An EC2 server takes 30+ seconds to startup. If it had to startup an EC2 server, you'd never be able to use a Lambda through API gateway (because API Gateway has a 30 second timeout). But obviously you can. If you want your Lambdas to startup super duper fast (100ms), use [Provisioned Concurrency](https://docs.aws.amazon.com/lambda/latest/dg/provisioned-concurrency.html). Upvotes: 2
2018/03/21
484
1,840
<issue_start>username_0: I have two localhost addresses. One has an ID field and the other has a definition field. I combined the ID numbers with the definition, but now I want to calculate the number of repetitions of each activity. I will draw a graph based on the number of repetitions of each activity. I think my code has an error in the if cycle, but I do not know what it is. How can ı fix my code? Thank you.<issue_comment>username_1: AWS Lambda is known to reuse the resources. It will not create an EC2 server for each request so that will not be a performance concern But you should note that the disk space provided for your function sometimes not cleanup properly. [As some users reported](https://forums.aws.amazon.com/thread.jspa?threadID=209428) You can read more on the execution life cycle of Lambda here: <https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html> Upvotes: 0 <issue_comment>username_2: Lambdas run inside of a [docker-like container](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html), on EC2 servers ([using Firecracker](https://aws.amazon.com/about-aws/whats-new/2018/11/firecracker-lightweight-virtualization-for-serverless-computing/)) that are highly, highly optimized. AWS has thousands of servers running full time to serve all of the Lambda functions that are running. A cold start Lambda (one that's never been run before) starts up in a few seconds, depending on how big it is. An EC2 server takes 30+ seconds to startup. If it had to startup an EC2 server, you'd never be able to use a Lambda through API gateway (because API Gateway has a 30 second timeout). But obviously you can. If you want your Lambdas to startup super duper fast (100ms), use [Provisioned Concurrency](https://docs.aws.amazon.com/lambda/latest/dg/provisioned-concurrency.html). Upvotes: 2
2018/03/21
1,231
5,044
<issue_start>username_0: Can someone please help me? How I can force user to enter the `numberDecimal` in `EditText` field in XX.XX format(Eg.56.75). I used max length attribute to restrict max length to 5.<issue_comment>username_1: try this: ``` edittext.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) {} @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { DecimalFormat formatter = new DecimalFormat("##.##"); String yourFormattedString = formatter.format(s.toString()); edittext.setText(yourFormattedString); } }); ``` Upvotes: 0 <issue_comment>username_2: Try this ``` exitText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if(charSequence.length() == 2){ exitText.setText(""); exitText.setText(charSequence+"."); } } @Override public void afterTextChanged(Editable editable) { } }); ``` Upvotes: 0 <issue_comment>username_3: you can try ``` TextWatcher t1; EditText e; t1=new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length()==3 && !s.toString().contains(".")) { e.removeTextChangedListener(t1); e.setText(s.subSequence(0,1)+"."+s.charAt(2)); e.addTextChangedListener(t1); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }; e.addTextChangedListener(t1); ``` Upvotes: 1 <issue_comment>username_4: If you want to have decimal number format, you can use this in XML: ``` ``` To limit the number of digits, you might need to use `InputFilter` mentioned in other answers or here: [Limit Decimal Places in Android EditText](https://stackoverflow.com/questions/5357455/limit-decimal-places-in-android-edittext) Upvotes: 0 <issue_comment>username_5: You can go the easiest way ``` // set inputformat ``` You can use `InputFilter` if you need to make sure there are 2 digits before `.` and after. Try this under onCreate ``` youreditText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter()}); ``` this is just a class for this **EDIT:** Had to rewrite the pattern as it seems that matcher matches the input starting with the first character and checks each one so you need to add a lot of optional parts in the patterns so that it passes each check that is being made. Now it doesn't allow 222 as it did in your case ``` public class DecimalDigitsInputFilter implements InputFilter { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (end > start) { String destTxt = dest.toString(); String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend); if (!resultingTxt.matches("^\\d(\\d(\\.\\d{0,2})?)?")) { return ""; } } return null; } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_6: This following code is also working : **Inside OnCreateView :** ``` myEditText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(2,2)}); ``` **Java Class :** ``` public class DecimalDigitsInputFilter implements InputFilter { final int maxDigitsBeforeDecimalPoint ; final int maxDigitsAfterDecimalPoint ; public DecimalDigitsInputFilter(int digitsBeforeDecimal,int digitsAfterDecimal ){ maxDigitsBeforeDecimalPoint = digitsBeforeDecimal; maxDigitsAfterDecimalPoint = digitsAfterDecimal; } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { StringBuilder builder = new StringBuilder(dest); builder.replace(dstart, dend, source .subSequence(start, end).toString()); if (!builder.toString().matches( "(([1-9]{1})([0-9]{0," + (maxDigitsBeforeDecimalPoint - 1) + "})?)?(\\.[0-9]{0," + maxDigitsAfterDecimalPoint + "})?" )) { if (source.length() == 0) return dest.subSequence(dstart, dend); return ""; } return null; } } ``` Upvotes: 0
2018/03/21
512
1,602
<issue_start>username_0: In my html file I'm passing an array of objects with a date time to javascript like this ``` var TimerEvents = @Html.Raw(Json.Encode(Model.PendingTimerEvents)); ``` my 'TimerEvents' has an EventTime property that when I read in Javascript looks like this > > "/Date(1521617700000)/" > > > and I want to get this value, whatever it is, into a Javascript Date() object. like this ``` var countDownDate = new Date(date here).getTime(); ``` What is that format, and how would I do this?<issue_comment>username_1: the value you get is a milisecond representation of the date, I think the count starts at 1/1/1970. Anyway here is a solution for formatting it: [Converting milliseconds to a date (jQuery/JavaScript)](https://stackoverflow.com/questions/4673527/converting-milliseconds-to-a-date-jquery-javascript) Upvotes: 0 <issue_comment>username_2: You can extract the date with regex if you need to: ``` var TimerEvents = @Html.Raw(Json.Encode(Model.PendingTimerEvents)); //"/Date(1521617700000)/" var dateString = TimerEvents.match(/\d+/)[0] // "1521617700000" var date = new Date(+dateString); //convert to number console.log(date); // Wed Mar 21 2018 08:35:00 GMT+0100 (Mitteleuropäische Zeit) ``` Upvotes: -1 <issue_comment>username_3: Assuming that Model.PendingTimerEvents is a DateTime, you could just do: ``` var TimerDate = new Date(@Model.PendingTimerEvents.Year, @Model.PendingTimerEvents.Month, @Model.PendingTimerEvents.Day, @Model.PendingTimerEvents.Hour, @Model.PendingTimerEvents.Minute, @Model.PendingTimerEvents.Second); ``` Upvotes: 0
2018/03/21
565
1,835
<issue_start>username_0: I am trying to use `QOpenGLWidget` without subclassing. When I try to make OpenGL calls outside of `QOpenGLWidget`'s methods or signals, nothing seems to happen. For example, following code clears window black despite me setting `glClearColor`: ``` MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { auto glw = new QOpenGLWidget( this ); glw->makeCurrent(); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glw->doneCurrent(); connect( glw, &QOpenGLWidget::aboutToCompose, [=] { glClear( GL_COLOR_BUFFER_BIT ); }); setCentralWidget( glw ); } ``` However, when I move `glClearColor` inside the lambda connected to the `aboutToCompose` signal, widget is cleared with white color.<issue_comment>username_1: the value you get is a milisecond representation of the date, I think the count starts at 1/1/1970. Anyway here is a solution for formatting it: [Converting milliseconds to a date (jQuery/JavaScript)](https://stackoverflow.com/questions/4673527/converting-milliseconds-to-a-date-jquery-javascript) Upvotes: 0 <issue_comment>username_2: You can extract the date with regex if you need to: ``` var TimerEvents = @Html.Raw(Json.Encode(Model.PendingTimerEvents)); //"/Date(1521617700000)/" var dateString = TimerEvents.match(/\d+/)[0] // "1521617700000" var date = new Date(+dateString); //convert to number console.log(date); // Wed Mar 21 2018 08:35:00 GMT+0100 (Mitteleuropäische Zeit) ``` Upvotes: -1 <issue_comment>username_3: Assuming that Model.PendingTimerEvents is a DateTime, you could just do: ``` var TimerDate = new Date(@Model.PendingTimerEvents.Year, @Model.PendingTimerEvents.Month, @Model.PendingTimerEvents.Day, @Model.PendingTimerEvents.Hour, @Model.PendingTimerEvents.Minute, @Model.PendingTimerEvents.Second); ``` Upvotes: 0
2018/03/21
247
935
<issue_start>username_0: I am running codes that were running on php5 that support mysql\_connect and I have migrated to another server that has php7.0. I realized that php7.0 does no longer support mysql\_connect but it supports mysqli\_connect. I don't want to go back to edit the codes and I don't want to go back to php5. I know that it's possible to install a patch that will support mysql\_connect but I don't know how to do it. I am using ubuntu server 16.04.<issue_comment>username_1: `mysql_connect` is no longer supported in modern PHP versions for a reason. I really recommend you to use `PDOs`. Here's a really great, detailed tutorial: <https://phpdelusions.net/pdo> Upvotes: -1 <issue_comment>username_2: For these purposes, there is exactly this package: <https://github.com/dshafik/php7-mysql-shim> to make it working without code modification, you can include it in `auto_prepend_file` php.ini directive Upvotes: 2
2018/03/21
591
1,457
<issue_start>username_0: I have zeros, ones, NAs and negative ones in my dataframe, but I would like to remove rows having all zeros. Apparently, I can not use rowSums because I have negative ones and positive ones in the data frame. ``` > dd <- data.frame(a=c(0,0,0,0),b=c(0,-1,NA,1),c=c(0,1,0,-1),d=c(0,NA,0,0), e=c(0,0,NA,1)) > rownames(dd)<-paste("row",seq(1,nrow(dd),by=1),sep="") > dd a b c d e row1 0 0 0 0 0 row2 0 -1 1 NA 0 row3 0 NA 0 0 NA row4 0 1 -1 0 1 ``` I would like to get ``` a b c d e row2 0 -1 1 NA 0 row3 0 NA 0 0 NA row4 0 1 -1 0 1 ```<issue_comment>username_1: You can figure out which rows are all zeros using `apply` and then subset the negation. In the code below I have made explicit functions for the steps, but you could use lambda expressions if you want to avoid that. ``` all_are_zero <- function(row) all(row == 0) not_all_are_zero <- function(row) ! all_are_zero(row) dd[apply(dd, 1, not_all_are_zero),] ``` Upvotes: 0 <issue_comment>username_2: Another option is to use `apply` with `function(x) any(x != 0 | is.na(x))` to return rows that any of the values are not 0. ``` dd[apply(dd, 1, function(x) any(x != 0 | is.na(x))), ] # a b c d e # row2 0 -1 1 NA 0 # row3 0 NA 0 0 NA # row4 0 1 -1 0 1 ``` Upvotes: 2 <issue_comment>username_3: You can still use `rowSums`, checking the number of values equal to `0`: ``` dd[rowSums(dd==0, na.rm=TRUE) ``` Upvotes: 3
2018/03/21
1,054
2,717
<issue_start>username_0: My Command output is something like `0x53 0x48 0x41 0x53 0x48 0x49`. Now i need to store this in a hex value and then convert it to ASCII as `SHASHI`. What i tried- 1. I tried to store the values in hex as `int("0x31",16)` then decode this to ASCII using `decode("ascii")` but no luck. 2. `"0x31".decode("utf16")`this throws an error `AttributeError: 'str' object has no attribute 'decode'` Some other stuffs with random encoding and decoding whatever found through `Google`. But still no luck. Question :- How can i store a value in Hex like `0x53 0x48 0x41 0x53 0x48 0x49` and convert it's value as `SHASHI` for verification. Note: Not so friendly with Python, so please excuse if this is a novice question.<issue_comment>username_1: The `int("0x31", 16)` part is correct: ``` >>> int("0x31",16) 49 ``` But to convert that to a character, you should use the [`chr(...)` function](https://docs.python.org/2/library/functions.html#chr) instead: ``` >>> chr(49) '1' ``` Putting both of them together (on the first letter): ``` >>> chr(int("0x53", 16)) 'S' ``` And processing the whole list: ``` >>> [chr(int(i, 16)) for i in "0x53 0x48 0x41 0x53 0x48 0x49".split()] ['S', 'H', 'A', 'S', 'H', 'I'] ``` And finally turning it into a string: ``` >>> hex_string = "0x53 0x48 0x41 0x53 0x48 0x49" >>> ''.join(chr(int(i, 16)) for i in hex_string.split()) 'SHASHI' ``` I hope this helps! Upvotes: 4 [selected_answer]<issue_comment>username_2: Suppose you have this input: `s = '0x53 0x48 0x41 0x53 0x48 0x49'` You can **store** values in list like follow: `l = list(map(lambda x: int(x, 16), s.split()))` To **convert** it to ASCII use [chr()](https://docs.python.org/3.6/library/functions.html#chr "chr"): `res = ''.join(map(chr, l))` Upvotes: 1 <issue_comment>username_3: ``` >>> import binascii >>> s = b'SHASHI' >>> myWord = binascii.b2a_hex(s) >>> myWord b'534841534849' >>> binascii.a2b_hex(myWord) b'SHASHI' >>> bytearray.fromhex("534841534849").decode() 'SHASHI' ``` Upvotes: 2 <issue_comment>username_4: I don't know if this solution is OK for your problem but it's a nice way to convert HEX to ASCII. The code snippet is below: ```py # Your raw data, the hex input raw_data = '0x4D6172697573206120636974697420637520707974686F6E21' # Slice string to remove leading `0x` hex_string = raw_data[2:] # Convert to bytes object. bytes_object = bytes.fromhex(hex_string) # Convert to ASCII representation. ascii_string = bytes_object.decode("ASCII") # print the values for comparison print("\nThe input data is: {} \nwhile the string is: {} \n".format(raw_data,ascii_string)) ``` Upvotes: 0
2018/03/21
1,059
2,762
<issue_start>username_0: I am using Truffle [MetaCoin](https://github.com/katopz/truffle-metacoin-example "MetaCoin") box in **truffle develop** mode. The front end tries to get the balance of an account but gets a huge number. The front end code is the following: ``` var coinbase = web3.eth.coinbase; var balance = web3.eth.getBalance(coinbase).toNumber(); ``` More specifically, by default the first account truffle generates should has 10k balance. After running one test as in the link above. Its balance should be 9990. This works correctly if I `console.log` it in test file. But the `balance` variable I got from front end is 100000000000000000000. After test it goes to 99917820100000000000. This difference is clearly not 10 or its exponential. Why and how to fix this?<issue_comment>username_1: The `int("0x31", 16)` part is correct: ``` >>> int("0x31",16) 49 ``` But to convert that to a character, you should use the [`chr(...)` function](https://docs.python.org/2/library/functions.html#chr) instead: ``` >>> chr(49) '1' ``` Putting both of them together (on the first letter): ``` >>> chr(int("0x53", 16)) 'S' ``` And processing the whole list: ``` >>> [chr(int(i, 16)) for i in "0x53 0x48 0x41 0x53 0x48 0x49".split()] ['S', 'H', 'A', 'S', 'H', 'I'] ``` And finally turning it into a string: ``` >>> hex_string = "0x53 0x48 0x41 0x53 0x48 0x49" >>> ''.join(chr(int(i, 16)) for i in hex_string.split()) 'SHASHI' ``` I hope this helps! Upvotes: 4 [selected_answer]<issue_comment>username_2: Suppose you have this input: `s = '0x53 0x48 0x41 0x53 0x48 0x49'` You can **store** values in list like follow: `l = list(map(lambda x: int(x, 16), s.split()))` To **convert** it to ASCII use [chr()](https://docs.python.org/3.6/library/functions.html#chr "chr"): `res = ''.join(map(chr, l))` Upvotes: 1 <issue_comment>username_3: ``` >>> import binascii >>> s = b'SHASHI' >>> myWord = binascii.b2a_hex(s) >>> myWord b'534841534849' >>> binascii.a2b_hex(myWord) b'SHASHI' >>> bytearray.fromhex("534841534849").decode() 'SHASHI' ``` Upvotes: 2 <issue_comment>username_4: I don't know if this solution is OK for your problem but it's a nice way to convert HEX to ASCII. The code snippet is below: ```py # Your raw data, the hex input raw_data = '0x4D6172697573206120636974697420637520707974686F6E21' # Slice string to remove leading `0x` hex_string = raw_data[2:] # Convert to bytes object. bytes_object = bytes.fromhex(hex_string) # Convert to ASCII representation. ascii_string = bytes_object.decode("ASCII") # print the values for comparison print("\nThe input data is: {} \nwhile the string is: {} \n".format(raw_data,ascii_string)) ``` Upvotes: 0
2018/03/21
993
2,730
<issue_start>username_0: When I add a claim to an identity in a controller on ``` HttpContext.User.Identities.First( i => i.AuthenticationType == IdentityConstants.ApplicationScheme) ``` with ``` Addclaim(new Claim(type, value)) ``` and try to retrieve that claim from the ActionExecutingContext in my custom actionfilterattribute on the next request, why is it not present there? I'm using the code below to access the claims: ``` [AttributeUsage(AttributeTargets.Method)] public class ClaimActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { var claims = context.HttpContext.User.Claims; base.OnActionExecuting(context); } } ``` What am I missing?<issue_comment>username_1: The `int("0x31", 16)` part is correct: ``` >>> int("0x31",16) 49 ``` But to convert that to a character, you should use the [`chr(...)` function](https://docs.python.org/2/library/functions.html#chr) instead: ``` >>> chr(49) '1' ``` Putting both of them together (on the first letter): ``` >>> chr(int("0x53", 16)) 'S' ``` And processing the whole list: ``` >>> [chr(int(i, 16)) for i in "0x53 0x48 0x41 0x53 0x48 0x49".split()] ['S', 'H', 'A', 'S', 'H', 'I'] ``` And finally turning it into a string: ``` >>> hex_string = "0x53 0x48 0x41 0x53 0x48 0x49" >>> ''.join(chr(int(i, 16)) for i in hex_string.split()) 'SHASHI' ``` I hope this helps! Upvotes: 4 [selected_answer]<issue_comment>username_2: Suppose you have this input: `s = '0x53 0x48 0x41 0x53 0x48 0x49'` You can **store** values in list like follow: `l = list(map(lambda x: int(x, 16), s.split()))` To **convert** it to ASCII use [chr()](https://docs.python.org/3.6/library/functions.html#chr "chr"): `res = ''.join(map(chr, l))` Upvotes: 1 <issue_comment>username_3: ``` >>> import binascii >>> s = b'SHASHI' >>> myWord = binascii.b2a_hex(s) >>> myWord b'534841534849' >>> binascii.a2b_hex(myWord) b'SHASHI' >>> bytearray.fromhex("534841534849").decode() 'SHASHI' ``` Upvotes: 2 <issue_comment>username_4: I don't know if this solution is OK for your problem but it's a nice way to convert HEX to ASCII. The code snippet is below: ```py # Your raw data, the hex input raw_data = '0x4D6172697573206120636974697420637520707974686F6E21' # Slice string to remove leading `0x` hex_string = raw_data[2:] # Convert to bytes object. bytes_object = bytes.fromhex(hex_string) # Convert to ASCII representation. ascii_string = bytes_object.decode("ASCII") # print the values for comparison print("\nThe input data is: {} \nwhile the string is: {} \n".format(raw_data,ascii_string)) ``` Upvotes: 0
2018/03/21
377
1,291
<issue_start>username_0: I want to get the list of all the labels available in the graph, but I am unaware of the schema. Is there any way to find out the list of all the labels? I have tried the following: ``` g.V().Label().values() g.V().hasLabel().values() ``` but they are not working.<issue_comment>username_1: In Gremlin you would do: ``` g.V().label().dedup() ``` but that would require a scan of all vertices in the graph which would be expensive. JanusGraph has schema you can query with the `JanusGraphManagement` class. ``` JanusGraphManagement mgmt = graph.openManagement(); Iterable labels = mgmt.getVertexLabels(); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: In Scala, if all you have is a GraphTraversalSource from a JanusGraph, you can do: ``` import org.janusgraph.core.JanusGraph val graph: JanusGraph = g.getGraph.asInstanceOf[JanusGraph] val mgmt: JanusGraphManagement = graph.openManagement() ``` and then from there get your iterable of vertex labels: ``` val vLabels: Iterable[VertexLabel] = mgmt.getVertexLabels.asScala ``` (The .asScala only works if you have imported [gremlin-scala](https://mvnrepository.com/artifact/com.michaelpollmeier/gremlin-scala_2.13); otherwise you can omit it and you'll get a Java iterator.) Upvotes: 0
2018/03/21
681
2,203
<issue_start>username_0: I want to parse a xml file during build time in `build.gradle` file and want to modify some values of xml, i follow this SO question and answer [Load, modify, and write an XML document in Groovy](https://stackoverflow.com/questions/2245641/load-modify-and-write-an-xml-document-in-groovy) but not able to get any change in my xml file. can anyone help me out. Thanks code in `build.gradle` : ``` def overrideLocalyticsValues(String token) { def xmlFile = "/path_to_file_saved_in_values/file.xml" def locXml = new XmlParser().parse(xmlFile) locXml.resources[0].each { it.@ll_app_key = "ll_app_key" it.value = "123456" } XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))) nodePrinter.preserveWhitespace = true nodePrinter.print(locXml) } ``` xml file : ``` MY\_APP\_KEY MY\_GCM\_SENDER\_ID ```<issue_comment>username_1: In your code : Is it right ...? Where is node name and attribute ..? ``` locXml.resources[0].each { // Wrongly entered without node name it.@ll_app_key = "ll_app_key" // Attribute name @name it.value = "123456" // you can't change or load values here } ``` You tried to read and write a same file. Try this code which replaces the exact node of the xml file. `XmlSlurper` provides this facility. Updated : ``` import groovy.util.XmlSlurper import groovy.xml.XmlUtil def xmlFile = "test.xml" def locXml = new XmlSlurper().parse(xmlFile) locXml.'**'.findAll{ if (it.name() == 'string' && it.@name == "ll_app_key") it.replaceBody 12345 } new File (xmlFile).text = XmlUtil.serialize(locXml) ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Groovy has a better method for this than basic replacement like you're trying to do - the [SimpleTemplateEngine](http://docs.groovy-lang.org/docs/latest/html/api/groovy/text/SimpleTemplateEngine.html "SimpleTemplateEngine") ``` static void main(String[] args) { def templateEngine = new SimpleTemplateEngine() def template = '${someValue}' def templateArgs = [someValue: "Hello world!"] println templateEngine.createTemplate(template).make(templateArgs).toString() } ``` Output: `Hello world!` Upvotes: 0
2018/03/21
988
3,454
<issue_start>username_0: I've got a PWA set up using angular (5.2.9) service-worker. The following is my configuration: ``` { "index": "/index.html", "assetGroups": [{ "name": "app", "installMode": "prefetch", "updateMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.html" ], "versionedFiles": [ "/*.bundle.css", "/*.bundle.js", "/*.chunk.js" ] } }, { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/assets/**" ], "urls": [ "https://fonts.googleapis.com/**", "https://fonts.gstatic.com/**" ] } }], "dataGroups": [{ "name": "api-freshness", "urls": [ "!/api/event" ], "cacheConfig": { "strategy": "freshness", "maxSize": 30, "maxAge": "20m", "timeout": "9s" } }] } ``` What I'm trying to achieve under `dataGroups.urls[]` is to cache every fetch using network-first principle **except** calls to `/api/event`, which is a ServerSentEvents endpoint using a long-lived connection. Sadly, the setup above does *not* acheive this. This endpoint is used on two central routes in my application, but listen for the same type of event calling for a data-refresh. Inspecting my app under DevTools `Application`>`Clear Storage`, I can tail the storage size as the client caches requests. It's all nice and minimal until I open a route using `api/event`. Then the cache suddenly jumps 3-4 Mb, and I'm guessing this is because it's a stream... ? After caching the call, every call to `api/event` comes in two times, one from network and one from service-worker and the service-worker call is always pending. By closing the SSE connection, only the network call is canceled. The effect of this is that after navigating back and forth between the two routes using this endpoint a couple of times, it would seem that chrome runs out of available sockets - making further calls to any endpoint stuck in a *Pending* state, which in turn leaves my app in a useless state. :-( Any input on this is greatly appreciated.<issue_comment>username_1: if you want to prevent duplicate service worker call then please do few steps as below. 1. build your project production mode. 2. goto build folder (default is /dist) 3. open ngsw-worker.js file under /dist directory. 4. find `onFetch(event) {` function 5. modify the onfetch function like below ``` onFetch(event) { ``` `/* your api endpouint url or domain url here*/` ``` var blackListDomain=["www.xyz.com/api","www.abc.com/v2/api"]; for (var i = 0; i < blackListDomain.length; i++) { if (event.request.url.indexOf(blackListDomain[i])>-1) { console.log("revent " + event.request.url); return; } } ``` **Hint** [![enter image description here](https://i.stack.imgur.com/24sZp.png)](https://i.stack.imgur.com/24sZp.png) Upvotes: -1 <issue_comment>username_2: I've read the code of generated `ngsw-worker.js` file, and found this line: ``` if (req.headers.has('ngsw-bypass') || /[?&]ngsw-bypass(?:[=&]|$)/i.test(requestUrlObj.search)) { return; } ``` So I just changed my connection URL to this one: ``` this.sse = new EventSource(`${EVENTS_API}?accessToken=${token}&ngsw-bypass=true`); ``` And it helped, now my Angular app can connect to Server Sent Events API every time with no errors. Upvotes: 1
2018/03/21
901
2,980
<issue_start>username_0: I have an issue with white space appearing above div when inserted in between text. I have tried margin & padding things, but it hasn't worked out. I figure this must be a quite common issue, but I cannot seem to find an answer. Here's a [jsfiddle](http://jsfiddle.net/1hj4akqa/7/). ```css div.appear { background-color:rgba(29,29,29,0.9); position: absolute; display:none; padding: 0 10px 10px 10px ; z-index: 1000000; color: white; font-size:13px; } div.hover { cursor:pointer; color: #666; display: inline-block; } div.hover:hover div.appear { display:block; } ``` ```html There is no exact definition on when a short story is too long, thus anovellaA novella is a text that is longer than a short story, but not quite long enough to be a novel. or a novelA novel is relatively long piece of fiction. What we often refer to as "a book". on the other hand too short, becoming merely an anecdotean anecdote is a short tale, to fit into the genre, but most short stories that we work with in the lessons are less than ten pages. ```<issue_comment>username_1: You shouldn't put divs inside tags. If you take a look at what you did with developer tools you will see that Chrome inserts a tag after the word "thus", and that is where the padding/margin is coming from. Just make all of your tags tags and that's it. ``` There is no exact definition on when a short story is too long, thus anovellaA novella is a text that is longer than a short story, but not quite long enough to be a novel. or a novelA novel is relatively long piece of fiction. What we often refer to as "a book". on the other hand too short, becoming merely an anecdotean anecdote is a short tale, to fit into the genre, but most short stories that we work with in the lessons are less than ten pages. ``` Upvotes: 0 <issue_comment>username_2: That's because you use incorrect HTML tags. * Don't use inside * are, by default, `display:block` thus they will try to expand all the way across the view. Instead of for your words and tooltips, use that don't modify the layout : ```css .appear { background-color: rgba(29, 29, 29, 0.9); position: absolute; display: none; padding: 0 10px 10px 10px; z-index: 1000000; color: white; font-size: 13px; } .hover { cursor: pointer; color: #666; display: inline-block; } .hover:hover .appear { display: block; } ``` ```html There is no exact definition on when a short story is too long, thus a novella A novella is a text that is longer than a short story, but not quite long enough to be a novel. or a novel A novel is relatively long piece of fiction. What we often refer to as "a book". on the other hand too short, becoming merely an anecdote an anecdote is a short tale , to fit into the genre, but most short stories that we work with in the lessons are less than ten pages. ``` Upvotes: 2 [selected_answer]
2018/03/21
565
1,766
<issue_start>username_0: I need to change my navbar hover color to something else. I managed to change navbar text color on my own, but I couldn't find the correct one to change in inspect element for hover color. Then I looked it up on stackoverflow for previous asnwers but they didn't work for my code. Any input would be greatly appreciated! ```html Bootstrap 4 Basic template html, body { overflow-x: hidden; } .navbar-light .navbar-brand { color: #FFFFFF; } .navbar-light .navbar-nav .active>.nav-link, .navbar-light .navbar-nav .nav-link.active, .navbar-light .navbar-nav .nav-link.show, .navbar-light .navbar-nav .show>.nav-link { color: #FFFFFF; } .navbar-light .navbar-nav .nav-link { color: #FFFFFF; } [Navbar](#) * [Home (current)](#) * [Features](#) * [Pricing](#) * [Dropdown link](#) [Action](#) [Another action](#) [Something else here](#) Place sticky footer content here. ```<issue_comment>username_1: ``` html, body { overflow-x: hidden; } .navbar-light .navbar-brand { color: #FFFFFF; } .navbar-light .navbar-nav .active>.nav-link, .navbar-light .navbar-nav .nav-link.active, .navbar-light .navbar-nav .nav-link.show, .navbar-light .navbar-nav .show>.nav-link { color: #FFFFFF; } .navbar-light .navbar-nav .nav-link { color: #FFFFFF; } .navbar-light .navbar-nav .nav-link:focus, .navbar-light .navbar-nav .nav-link:hover { color: #ccc !important; } } ``` and html : ``` [Navbar](#) * [Home (current)](#) * [Features](#) * [Pricing](#) * [Dropdown link](#) [Action](#) [Another action](#) [Something else here](#) ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: Bootstrap has default color for < a> tag. So by using !important you over write the color Upvotes: 3
2018/03/21
345
1,125
<issue_start>username_0: My profile image that made rounded with `RoundedCorners` method in glid4 is very flatted and my profile it has not any shadow. How can i set shadow to my image profile ?glid4 hase any method for this or i have to create one? [![enter image description here](https://i.stack.imgur.com/GexBi.png)](https://i.stack.imgur.com/GexBi.png)<issue_comment>username_1: Alternate Solution:- Use a custom drawable and set it to imageview background `shadow.xml` ``` xml version="1.0" encoding="utf-8"? //your background color here ``` Use it like this way:- ``` android:background="@drawable/shadow" ``` Another solution u can try :- <https://github.com/Pkmmte/CircularImageView> This library can be used for your requirement Upvotes: 3 [selected_answer]<issue_comment>username_2: *implementation "com.github.bumptech.glide:glide:4.10.0"* **XML** ``` ``` **Shape drawable** ``` xml version="1.0" encoding="utf-8"? ``` **Glide Configuration** ``` Glide.with(this) .asBitmap() .load(item.image) .apply(RequestOptions.circleCropTransform()) .into(iv_item_employee) ``` Upvotes: 2
2018/03/21
387
1,237
<issue_start>username_0: `val x: Int=> Int = { y => y }` // ① This is correct `( x1: Int) => Int = { y => y}` // ② This is wrong I understand a simple scala function like this :`x:Int => x` or this :`val f =(x: Int) => x` but how to explain the role of "x" in the sentence ①<issue_comment>username_1: Here: ``` val x: Int=> Int = { y => y } ``` Above can be written as: `val x: Int=> Int = { identity}` x is a function which receives an integer and returns the same integer. ``` scala> x(5) res4: Int = 5 ``` Upvotes: 1 <issue_comment>username_2: In `val x: Int=> Int = { y => y }`, `Int=> Int` is used to *define the return type* of `x` *immutable variable which takes Int as input and returns an Int value*. `(x1: Int) => Int = { y => y}` is wrong because a function cannot be assigned to another function as `(x1: Int) => Int` is a function and `{ y => y}` is another function `val f =(x: Int) => x` is correct as you are assigning `(x: Int) => x` function which takes an integer value as input and returns as it is and is assigned to a immutable variable f. **Defining x in one line** would be *x is a immutable input variable passed in to a function where manipulation on x is performed*. Upvotes: 3 [selected_answer]
2018/03/21
538
1,738
<issue_start>username_0: I'm trying to implement the autoload feature using `psr-4` with composer but I get this error, even if I've already require it in the index. Please see the error and code below: **Error** > > Fatal error: Class 'Blog\Classes\Database\Connection' not found in C:\wamp\www\blog-oop\index.php on line 7 > > > **Code** *composer.json* ``` { "autoload": { "psr-4": { "Blog\\": "app/classes/Database" } } } ``` *Connection.php* ``` php namespace Blog\Classes\Database; class Connection{ } </code ``` *index.php* ``` php require "vendor/autoload.php"; use Blog\Classes\Database\Connection; $connection = new Connection; </code ``` *Structure* ``` >app >classes >Database >Connection.php ```<issue_comment>username_1: Here: ``` val x: Int=> Int = { y => y } ``` Above can be written as: `val x: Int=> Int = { identity}` x is a function which receives an integer and returns the same integer. ``` scala> x(5) res4: Int = 5 ``` Upvotes: 1 <issue_comment>username_2: In `val x: Int=> Int = { y => y }`, `Int=> Int` is used to *define the return type* of `x` *immutable variable which takes Int as input and returns an Int value*. `(x1: Int) => Int = { y => y}` is wrong because a function cannot be assigned to another function as `(x1: Int) => Int` is a function and `{ y => y}` is another function `val f =(x: Int) => x` is correct as you are assigning `(x: Int) => x` function which takes an integer value as input and returns as it is and is assigned to a immutable variable f. **Defining x in one line** would be *x is a immutable input variable passed in to a function where manipulation on x is performed*. Upvotes: 3 [selected_answer]
2018/03/21
551
2,137
<issue_start>username_0: In Javascript I can do the following to get a value according to their respective order of appearance in the assignment.. ``` var myString = source1 || source2 || source3 || source4 || source5; ``` If any of the sources has value, it will be assigned to myString. If all sources have value, it will take the first one. In Java, the `java.util.Optional` seems limited to only just `Optional.of("value").orElse( "another" )` and it cannot chain anymore as the the return of orElse() is already a string.<issue_comment>username_1: While it can be argued that there are lot of approaches, I prefer the following approach: ``` Integer i = Stream.of(null, null, null, null, null, null, null, null, 1, 2) .filter(Objects::nonNull) // filter out null's .findFirst().orElse(10); // default to 10 // Objects::nonNull is same as e -> e != null System.out.println(i); ``` Upvotes: 2 <issue_comment>username_2: I would probably use something simple like: ``` public static T first(T... values) { for (T v : values) { if (v != null) return v; } return null; } ``` Upvotes: 3 <issue_comment>username_3: Just to post a non streams alternative to the stream api If you have only very small sets of strings you want to compare against non empty values, you might want to save the overhead of initializing the streams, the lambdas etc.. what happens under the hood. You can use the three dots `...` to indicate "any number of arguments" which in your method will effectively be turned into a `String[] arguments` Then iterate them and compare them with your custom compare function. In this case I chose to emulate javascript with non null strings and not empty strings. Modify as you see fit. ``` public String sourceFilter(String... input) { for(String test : input) { if(test != null && !test.isEmpty()) { return test; } } return ""; } ``` I don't know what the break even point is that the streams are more efficient in this case, but I'd imagine it would be a pretty high number to cover the initialization cost for it. Upvotes: 2
2018/03/21
470
1,719
<issue_start>username_0: I store card information in database e.g card-id `card_*****` and customer id `cus_****` on customer first payment for use it later on. user choose his card e.g in form of radio button `visa****4242` and charge takes with card id or customer id. now i am using stripe modal box for payment. every payment new customer and card id create . how do i charge with card id or customer id on second payment ? here is my stripe code ``` $customer =Stripe_Customer::create(array( 'email' => $_SESSION['userEmail'],)); $charge = Stripe_Charge::create(array( "amount" => $amount_cents,"currency" => "usd","source" => $_POST['stripeToken'],"description" => $description, )); ``` Possible this question may duplicate.But i can not find best answer .<issue_comment>username_1: Line 1, you are creating a new customer every time. You should store the identifier of the customer and source and bind it onto your local customer account. Next time you can pass those two into Charge. Upvotes: 1 <issue_comment>username_2: Once you create a customer you can charge their default card with: ``` \Stripe\Charge::create(array( "amount" => $amount_cents, "currency" => "usd", "customer" => $customer )); ``` If the customer has more than one card and you want to charge a card that isn't the default card, you have to pass in the customer and card id (when the card has already been saved to the customer): ``` \Stripe\Charge::create(array( "amount" => $amount_cents, "currency" => "usd", "customer" => $customer, "source" => $card_id )); ``` You can read more about this in Stripe's API docs: <https://stripe.com/docs/api/php#create_charge-source> Upvotes: 4 [selected_answer]
2018/03/21
529
1,936
<issue_start>username_0: I read the **Node SDK tutorial** ( <https://fabric-sdk-node.github.io/tutorial-app-dev-env-setup.html> ) and their were these lines: > > user identities provisioned this way are only of the **MEMBER role**, which means it won't be able to perform certain operations reserved for the **ADMIN role**: > > > create/update channel > > > install/instantiate chaincode > > > **query installed/instantiated chaincodes** > > > For these **privileged operations**, the **client must use an ADMIN user to submit the request.** > > > And I have a question that ***why only ADMIN have the permission to query installed/instantiated chaincodes***? Calling a **ADMIN users** only for **query** will cause the **extra latency** in the **network / Response** instead of other **MEMBER users** ( reducing the load on one user that is ADMIN user ) in a given channel. If there is any ***security implications*** for the above statement that I referenced then what are they.<issue_comment>username_1: Line 1, you are creating a new customer every time. You should store the identifier of the customer and source and bind it onto your local customer account. Next time you can pass those two into Charge. Upvotes: 1 <issue_comment>username_2: Once you create a customer you can charge their default card with: ``` \Stripe\Charge::create(array( "amount" => $amount_cents, "currency" => "usd", "customer" => $customer )); ``` If the customer has more than one card and you want to charge a card that isn't the default card, you have to pass in the customer and card id (when the card has already been saved to the customer): ``` \Stripe\Charge::create(array( "amount" => $amount_cents, "currency" => "usd", "customer" => $customer, "source" => $card_id )); ``` You can read more about this in Stripe's API docs: <https://stripe.com/docs/api/php#create_charge-source> Upvotes: 4 [selected_answer]
2018/03/21
750
3,009
<issue_start>username_0: I can run multiple Chrome browser sessions **without** `@BeforeSuite` annotation , but sometimes I need to assign some variables or do something in `@BeforeSuite` before going to `@BeforeClass` and `@BeforeTest` , and the same time I need to start multiple browsers session parallel. How can I do that ? This is a simplified example of my codes where I use `@BeforeSuite` to assigned some variables and then calling 2 parallel tests from `TestNG.xml` . It will only call 1 test (not 2). But if I don't use `@BeforeSuite` , it will work perfectly fine (2 tests will run parallel). Is it possible to run parallel tests and at the same time still using `@BeforeSuite` ? Sometimes we do need to use `@BeforeSuite` in some test scenarios and call multiple browsers sessions. Thank You. ```java public class MyClass { String baseURL; String browser; @BeforeSuite private void setTheVariables() { //Some codes here //Some codes here this.browser = "chrome"; } @BeforeClass private void myBeforeClass() { //Some codes here //Some codes here } @BeforeTest private void myBeforeClass() { //Some codes here //Some codes here } @Test @Parameters("baseURL") public void f(String baseURL) { if (this.browser == "chrome") { System.setProperty("webdriver.chrome.driver", "C:\\\\Selenium\\\\chromedriver.exe"); DesiredCapabilities caps = DesiredCapabilities.chrome(); LoggingPreferences logPrefs = new LoggingPreferences(); logPrefs.enable(LogType.BROWSER, Level.ALL); caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs); WebDriver driver = new ChromeDriver(caps); System.out.println("I am going to " + baseURL); driver.get(baseURL); } } } ``` This is my `testNG.xml` file ```xml xml version="1.0" encoding="UTF-8"? ```<issue_comment>username_1: You can pass by Browser value in .xml file, instead of passing it in Java class file, and execution can be handle through .java file. Example: and it can implement wherever its preferable, Before Suite/Class/Test/Method ``` @Parameters("parameter name") @BeforeTest public void xyz(String myBrowser) throws MalformedURLException { if (myBrowser.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", driverpathofchrome); driver = new ChromeDriver(); } else if (myBrowser.equals("firefox")) { System.setProperty("webdriver.gecko.driver", driverpathoffirefox); driver = new FirefoxDriver(); } } ``` Upvotes: 0 <issue_comment>username_2: **Beforesuite** annotated method run before testNG XML. So you have to use another annotation just below this order i.e. ***BeforeClass*** annotation for setting the browser type in your java class. Add a parameter named **browser** in your testNG xml to pass on the type of browser. That shall make the parallel execution possible. ``` xml version="1.0" encoding="UTF-8"? ``` Upvotes: 2 [selected_answer]
2018/03/21
366
1,010
<issue_start>username_0: I have problem with opcache. I'm running laravel 5.6 on IIS server with php 7.2 and when I enable opcache the app is crash. > > Fatal error: composerRequire1a7493bfe79afb8c03f982a7ea4d4348(): could not obtain parameters for parsing in Unknown on line 0 > > PHP Fatal error: composerRequire1a7493bfe79afb8c03f982a7ea4d4348(): could not obtain parameters for parsing in Unknown on line 0 > > > This issue is only on laravel (yii2 app with opcache on the same server is ok). I tried: ``` composer update ```<issue_comment>username_1: > > If you use xammp go to Config > Select Apache (httpd.conf). > > > ``` ServerName localhost:8080 ``` Change everything 80 to 8080, it will become like this. ``` http://localhost:8080/phpmyadmin ``` Upvotes: 1 <issue_comment>username_2: It's a bug in PHP 7.2 Opcache system: <https://bugs.php.net/bug.php?id=77092> please read carefully. You can fix it: 1) via patch 2) downgrade to 7.1 3) wait until new releases Upvotes: 0
2018/03/21
1,632
4,267
<issue_start>username_0: I want to fill an array with req.params, so i can edit my code easily right now the code is like this . ``` let test = [req.query.t0,req.query.t1,req.query.t2,req.query.t3,req.query.t4,req.query.t5,req.query.t6,req.query.t7,req.query.t8,req.query.t9,req.query.t10,req.query.t11] ``` Is there a way to fill easily my array with a loop or a fill map ? something like this. ``` let init = 0; let end = 19; let test = Array(req.query.init-req.query.end+1) .fill() .map(() => init++); ```<issue_comment>username_1: Actually your API should take an array instead, like: ``` yourapi?t=one&t=two&t=three ``` And you can get the array like this: ``` req.query.t // ["one", "two", "three"] ``` [More info](https://stackoverflow.com/questions/22080770/i-need-to-create-url-for-get-which-is-going-to-accept-array-how-in-node-js-expr) Upvotes: 1 <issue_comment>username_2: If you can use `Object.values`: ```js var req = { query: { t0: 't0', t1: 't1', t2: 't2' }}; var params = Object.values(req.query); console.log(params); ``` Or with `Object.keys` if you cannot: ```js var req = { query: { t0: 't0', t1: 't1', t2: 't2' }}; var params = Object.keys(req.query).map(key => req.query[key]); console.log(params); ``` In case you want to retrieve a limited number of parameters, you can add `array.prototype.filter`: ```js var req = { query: { t0: 't0', t1: 't1', t2: 't2', t3: 't3', t4: 't4' }}; var nbParams = 3; var params = Object.keys(req.query).filter((key, i) => i < nbParams).map(key => req.query[key]); console.log(params); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Assuming rep.query properties reliably start with `t` and end with numbers: ```js function fillArrayFromReq(query, start, end) { return Array.from({ length: end - start }, (_, i) => { const propNum = i + start; return query[`t${propNum}`]; }); } const query = { t0: 0, t1: 1, t2: 2, t3: 3, t4: 4, t5: 5, t6: 6, t7: 7, t8: 8, t9: 9, } console.log(fillArrayFromReq(query, 4, 7)); ``` `Object.values` isn't entirely reliable because you can't always count on properties to have been added in order. Upvotes: 1 <issue_comment>username_4: Let me just aggregate and expand on the other nice answers. To get *all* the params values: ```js const query = { a: 'a val', num: 4, t0: 't0 val', t1: 't1 val' }; let array = Object.values(query); // -> [ val1, val2, val3 ...] console.log(array); // or with [{key: value}] pairs array = Object.keys(query) .map(key => ({[key]: query[key]})); // -> [ { param: val1 }, { anotherParam: val2 }, ... ] console.log(array); ``` But you had a different example, your params were starting with 't' followed by number: ```js const query = { a: 'a val', num: 4, t0: 't0 val', t1: 't1 val' }; const array = Object.keys(query) .filter(key => /^t\d+$/.test(key)) // only take params whose keys start with a letter t, followed only by a number. .map(key => query[key]); console.log(array); ``` Finally, you also had a limit, from t0 to t19: ```js const query = { a: 'a val', num: 4, t0: 't0 val', t1: 't1 val', t19: 't19 val', t20: 't20 val' }; const array = Object.keys(query) .filter(key => /^t([0-9]|[01][0-9])$/.test(key)) // match keys starting with a t, followed by a number between 0 and 19 .map(key => query[key]); // or .map(key => ({[key]: query[key]})) console.log(array); ``` Or a bit more generic, take all `t params`, but slice between `init` and `end`: ```js const query = { a: 'a', num: 4, t0: 't0', t1: 't1' }; let init = 0; let end = 19; const array = Object.keys(query) .filter(key => /^t\d+$/.test(key)) .map(key => query[key]) // or .map(key => ({[key]: query[key]})) .slice(init, end); console.log(array); ``` This doesn't check that the order is correct, e.g. if you skip t2, we go from t0 to t20, so once more: ```js const query = { a: 'a', num: 4, t0: 't0', t1: 't1' }; let init = 0; let end = 19; const array = Object.keys(query) .filter(key => /^t\d+$/.test(key)) .filter(key => { let num = parseInt(key.substring(1), 10); return num >= init && num <= end; }) .map(key => query[key]); // or .map(key => ({[key]: query[key]})); console.log(array); ``` Upvotes: 0
2018/03/21
540
1,913
<issue_start>username_0: I am trying to invoke a Job in AWS Glue from my Lambda code written in Java. But I am not able to get the Glue Client. Like we have DynamoClient like this - ``` AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withRegion("us-east-1").build(); ``` What would be the equivalent for Glue Client ? ``` AWSGlueClient glue = null; // how to instantiate client StartJobRunRequest jobRunRequest = new StartJobRunRequest(); jobRunRequest.setJobName("TestJob"); StartJobRunResult jobRunResult = glue.startJobRun(jobRunRequest); ``` I am not seeing the AmazonGlueClientBuilder class. As I am new to glue, please let me know if I am doing it wrong or it there any other way I can use to invoke the glue job. Also I am using the following Maven Dependency - ``` com.amazonaws aws-java-sdk-glue 1.11.289 ```<issue_comment>username_1: The equivalent would be ``` AWSGlueClient.builder().withRegion("us-east-1").build() ``` Upvotes: 2 <issue_comment>username_2: Most AWS Java SDK client 'builders' follow the below convention: *ServiceName* serviceName = *ServiceName*ClientBuilder.standard()/default()... There is one Glue 'instance' available per-account, per-region so something along the following lines should get you up and running. ``` AWSGlue awsGlueClient = AWSGlueClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); ``` Upvotes: 0 <issue_comment>username_3: If your lambda is in the same region as Glue resources then simply use ``` AWSGlue glueClient = AWSGlueClientBuilder.defaultClient() ``` Upvotes: 1 <issue_comment>username_4: AWS Glue Client initalization and sample use in Java: ``` AWSGlue glueClient = AWSGlueClient.builder().withRegion("us-east-1").build(); StartJobRunRequest job = new StartJobRunRequest(); job.setJobName("ETLJob"); StartJobRunResult jobResult = glueClient.startJobRun(job); ``` Upvotes: 0
2018/03/21
1,101
3,705
<issue_start>username_0: Is it possible if i have an enumerable ``` Input :[1,2,3,4] Output :([1,3],[2,4]) ``` to iterate once over it and start putting odd numbers in a sequence/list/whatever and even in another and at the end placing the two sequences in a tuple? I have tried something like: ``` class Elem { int x; } (rez1,rez2)=from value in Generator() let odds=Enumerable.Empty() let evens=Enumerable.Empty() select(value%2==0?odds.\*\*append\*\*(value):odds.\*\*append\*\*(value)) ``` How can i direct the select over one element of the tuple or the other for each element?Can i have two mutable lists inside a linq query? P.S I am trying to achieve something like (similar to Haskell) : ``` select element -> predicate True -> goes to first element of result tuple predicate False-> goes to second element of result tuple ``` Everything in 0(n)<issue_comment>username_1: Create tuple like the following. Run two queries for odd and even values. ``` Tuple.Create(input.Where(c => c % 2 == 1).ToArray(), input.Where(c => c % 2 == 0).ToArray()); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: If you want to do it like in Haskell, then do it like in Haskell. Haskell does not iterate over a sequence, it defines a tuple elements as sets with certain properties. You should do the same: ``` var values = Generator(); Tuple.Create( values.Where( /* define what you want for the first set */ ), values.Where( /* define what you want for the second set */ )); ``` Upvotes: 1 <issue_comment>username_3: Here a approach with 2 `List` and only one iteration ``` List input = new List() { 1, 2, 3, 4 }; List> result = new List>() { new List(), new List() }; input.ForEach(x => result[x % 2 == 0 ? 0 : 1].Add(x)); ``` --- Another approach with Linq - a bit slower because of the extra grouping - I would choose the first one ``` int[][] result = input.GroupBy(x => x % 2).Select(x => x.ToArray()).ToArray(); ``` Upvotes: 3 <issue_comment>username_4: Something very complicated: ``` var list = new[] { 1, 2, 3, 4 }; var result = list.Select( o => new { A = o % 2 == 1 ? o : (int?)null, B = o % 2 == 0 ? o : (int?)null }) .GroupBy(o => o.A != null) .Select(o => o.Select(t => t.A ?? t.B ?? 0).ToList()) .ToArray(); Console.WriteLine(result[0]); Console.WriteLine(result[1]); ``` Upvotes: 1 <issue_comment>username_5: For a list input (not a `List>`) we can use `GroupBy` to group it by predicate function and `Select` to project the `IGrouping` to `List`: ``` List> buckets = input.GroupBy(func).Select(g => g.ToList()).ToList(); ``` For a `List>` input we would need to flatten the list with `.SelectMany` before using the samae method as above: ``` var func = new Func(x => x % 2 == 0); List> buckets = input.SelectMany(e => e).GroupBy(func).Select(g => g.ToList()).ToList(); ``` This approach: ``` var tuple = Tuple.Create(new List(), new List()); var func = new Func(x => x % 2 == 0); List> buckets = input.Select(e => { func(e)? tuple.Item1.Add(e) : tuple.Item2.Add(e); return e; }).ToList(); ``` Is not really a good one. LINQ is a query language and query is something that should return result not *create* result. So there is no reason to use `Select` for creating elements or adding them to collection, instead we can run our query get the result and save it to whatever object/format we need. If you need Tuple then save query result of the first two Lists to `Tuple`: ``` var tuple = Tuple.Create(buckets[0], buckets[1]); ``` Upvotes: 2
2018/03/21
665
2,508
<issue_start>username_0: When I try to Deploy my application with Capistrano, it gives error > > An error occurred while installing pg (1.0.0), and Bundler cannot > continue. > > > Make sure that `gem install pg -v '1.0.0'` succeeds before bundling. > > > I've already installed pg version 1.0.0 and its pre-requisite dependencies. What other changes need to be made in order to overcome with issue?<issue_comment>username_1: When Capistrano runs bundler, it specifies a configuration that installs the gems in a location that is separate from your global gems location. That means that even if you had run `gem install pg` successfully before, bundler will still need to do it again when you `cap deploy`. To figure out why bundler is failing, you could try a few different standard Capistrano troubleshooting techniques: 1. Check the Capistrano console output or `log/capistrano.log` for details on what went wrong. Bundler will sometimes point you to a temporary file where the results of the gem install process were recorded, and you can look there as well. 2. SSH into your server, change into the failed release directory, and manually run the bundler command that is failing. See if this provides more information. Make sure to enter the bundler command exactly as you see it in `log/caipstrano.log` (although I suggest removing the `--quiet` flag). It typically looks like: ``` bundle install --deployment --without development test --path /path/to/shared/bundle ``` 3. Capistrano uses a non-login shell, so things like `$PATH` may be different when Capistrano runs bundler vs when you run it interactively. Those differences could cause bundler to succeed in one environment but fail in the other. You can write a task like this inspect the environment that Capistrano sees: ``` # Add this to deploy.rb and then run `cap production env` task :env do on roles(:all) do puts capture("env") end end ``` Refer to this explanation of Capistrano's environment: <http://capistranorb.com/documentation/faq/why-does-something-work-in-my-ssh-session-but-not-in-capistrano/> Upvotes: 0 <issue_comment>username_2: I setup a capistrano task to bundle config the pg\_config location: `namespace :bundler do before 'bundler:install', :config desc 'bundle config options' task :config do on roles(:all), in: :groups, limit: 3, wait: 10 do # Required for pg gem to be installed execute 'bundle config build.pg --with-pg-config=/usr/pgsql-10/bin/pg_config' end end end` Upvotes: 2
2018/03/21
613
2,341
<issue_start>username_0: Is it possible to change a Class (by ID) after clicking a link that jumps to that page? I've page 01, and when I click a link in Page 01, I want it to jump to Page 02 and then change a Class in Page 02. Is it possible?<issue_comment>username_1: When Capistrano runs bundler, it specifies a configuration that installs the gems in a location that is separate from your global gems location. That means that even if you had run `gem install pg` successfully before, bundler will still need to do it again when you `cap deploy`. To figure out why bundler is failing, you could try a few different standard Capistrano troubleshooting techniques: 1. Check the Capistrano console output or `log/capistrano.log` for details on what went wrong. Bundler will sometimes point you to a temporary file where the results of the gem install process were recorded, and you can look there as well. 2. SSH into your server, change into the failed release directory, and manually run the bundler command that is failing. See if this provides more information. Make sure to enter the bundler command exactly as you see it in `log/caipstrano.log` (although I suggest removing the `--quiet` flag). It typically looks like: ``` bundle install --deployment --without development test --path /path/to/shared/bundle ``` 3. Capistrano uses a non-login shell, so things like `$PATH` may be different when Capistrano runs bundler vs when you run it interactively. Those differences could cause bundler to succeed in one environment but fail in the other. You can write a task like this inspect the environment that Capistrano sees: ``` # Add this to deploy.rb and then run `cap production env` task :env do on roles(:all) do puts capture("env") end end ``` Refer to this explanation of Capistrano's environment: <http://capistranorb.com/documentation/faq/why-does-something-work-in-my-ssh-session-but-not-in-capistrano/> Upvotes: 0 <issue_comment>username_2: I setup a capistrano task to bundle config the pg\_config location: `namespace :bundler do before 'bundler:install', :config desc 'bundle config options' task :config do on roles(:all), in: :groups, limit: 3, wait: 10 do # Required for pg gem to be installed execute 'bundle config build.pg --with-pg-config=/usr/pgsql-10/bin/pg_config' end end end` Upvotes: 2
2018/03/21
513
2,105
<issue_start>username_0: Just setup a Dynamics 365 on-premises instance and had barely started customizing the Contact entity. After adding a new field and publishing I am unable to open the Editor for Contact entity form. I am also unable to access the Contacts view as it shows a message "An error has occurred". The error log has the following message. > > System.Web.HttpUnhandledException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #4A9A4D93 > > > [![enter image description here](https://i.stack.imgur.com/6QeNY.png)](https://i.stack.imgur.com/6QeNY.png)<issue_comment>username_1: 1) Usually that happens when FormXML was corrupted during save, this is very rare thing. 2) To investigate: a) download log file - it might give you some clue. b) enable tracing on the instance and check the logs. 3) Possible fix: a) Create a solution specifically for account entity. Only include corrupted form into it b) download solution, open customization.xml file and find corrupted form. If there's not much customization done - simpleist thing is to wipe form out completely, if lot's of work done you might try to compare form against FormXML.xsd (found in sdk: SDK\SDK365\Schemas\FormXml.xsd) and fix corrupted element. In future better never edit "managed" forms, instead create your own form and modify it. In that case you would at least have an option to delete the form, instead of trying to fix it. Upvotes: 2 <issue_comment>username_2: Alternatively, take that form only from another environment & import it. Granular components can be moved as part of solution. Guessing that you might have done removing the last field added & tried again. This is my experience. When we upgraded to v9, account form got corrupted. On investigation, noticed that even preview from form editor failed. Probable reason was a custom control (star rating) in form. Removing that solved the preview problem. But not the original issue. Reached out to MS, Simply “Publish All customizations” from Default solution fixed it. Upvotes: 0
2018/03/21
1,238
4,105
<issue_start>username_0: I'm looking into binary serialization and deserialization via VBA. For this, I would need to be able to create and fill arrays of an arbitrary number of dimensions dynamically. For example, let's say you want to do something like ``` Dim sample(0 To 3, 0 To 4, 0 To 2, 0 To 2) As Integer sample(3,1,1,0) = 12345 ``` so create and fill a 4-dimensional array. It's easy if you know the dimensions at compile time of course, but what if you don't? ``` Sub Deserialize() ' Dynamic equiavalent of: Dim sample(0 To 3, 0 To 4, 0 To 2, 0 To 2) As Integer Dim dimensions(0 To 3) As Integer dimensions(0) = 3 dimensions(1) = 4 dimensions(2) = 2 dimensions(3) 2 Dim sample As Variant sample = CreateArrayWithDimensions(dimensions) ' Dynamic equivalent of sample(3,1,1,0) = 12345 Dim index(0 To 3) As Integer index(0) = 3 index(1) = 1 index(2) = 1 index(3) = 0 Call SetArrayValue(sample, index, 12345) End Sub ``` Is this possible in any way? Or in other words, is there any way to implement the pseuod-functions CreateArrayWithDimensions and SetArrayValue ? Thanks<issue_comment>username_1: How about using a 'dictionary' instead of a multidimensional array. The key could be a concatenation of all indexes. Add a reference to the `Microsoft Scripting Runtime` or change this to late binding. ``` Option Explicit Dim sample As New Scripting.Dictionary Sub test() Dim index(0 To 3) As Integer index(0) = 3 index(1) = 1 index(2) = 1 index(3) = 0 Call SetArrayValue(sample, index, 12345) Debug.Print GetArrayValue(sample, index) End Sub Sub SetArrayValue(sample As Dictionary, index() As Integer, val As Variant) Dim key As String key = createIndexKey(index) If sample.Exists(key) Then sample(key) = val Else Call sample.Add(key, val) End If End Sub Function GetArrayValue(sample As Dictionary, index() As Integer) As Variant Dim key As String key = createIndexKey(index) If sample.Exists(key) Then GetArrayValue = sample(key) Else GetArrayValue = Null End If End Function Function createIndexKey(index() As Integer) Dim i As Integer createIndexKey = "" For i = LBound(index) To UBound(index) createIndexKey = IIf(createIndexKey = "", "", ":") & index(i) Next i End Function ``` Upvotes: 0 <issue_comment>username_2: There is no elegant solution. `Redim` can not accept variable number of argument. However, if you can limit "arbitrary", you can try something like this: ``` Sub DimTest() Dim sample() As Integer Dim dimensions(0 To 3) As Integer Dim index(0 To 3) As Integer dimensions(0) = 10 dimensions(1) = 20 dimensions(2) = 40 dimensions(3) = 70 index(0) = 1 index(1) = 2 index(2) = 4 index(3) = 7 sample = CreateArrayWithDimensions(dimensions) SetArrayValue sample, index, 12345 End Sub Function CreateArrayWithDimensions(dimensions() As Integer) As Integer() Dim b() As Integer Select Case UBound(dimensions) Case 1: ReDim b(dimensions(0)) Case 2: ReDim b(dimensions(0), dimensions(1)) Case 3: ReDim b(dimensions(0), dimensions(1), dimensions(2)) Case 4: ReDim b(dimensions(0), dimensions(1), dimensions(2), dimensions(3)) Case 5: ReDim b(dimensions(0), dimensions(1), dimensions(2), dimensions(3), dimensions(4)) End Select CreateArrayWithDimensions = b End Function Sub SetArrayValue(sample() As Integer, idx() As Integer, value As Integer) Select Case UBound(idx) Case 1: sample(idx(0)) = value Case 2: sample(idx(0), idx(1)) = value Case 3: sample(idx(0), idx(1), idx(2)) = value Case 4: sample(idx(0), idx(1), idx(2), idx(3)) = value Case 5: sample(idx(0), idx(1), idx(2), idx(3), idx(4)) = value End Select End Sub ``` An alternative (and more flexible) solution is to use the good old 1 dimensional linear storage concept (just the way the system stores the arrays in fact), and calculate the real position of the actual entry. Upvotes: 1
2018/03/21
1,929
6,719
<issue_start>username_0: I just create a dialog with a recycle view on it. Then how to get value from selected recycle view and set it into editext on the same acticity [this is the dialog and the value from recycle view](https://i.stack.imgur.com/WvbN9.jpg) [and this is the value will be set](https://i.stack.imgur.com/RbBYS.jpg) My code for calling the dialog, and set addOnItemTouchListener for recycle view. And when i run it my application get force close ``` @SuppressLint("ResourceType") @OnClick(R.id.button_choose) void chooseLOV() { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); LayoutInflater inflater = this.getLayoutInflater(); View dialogView = inflater.inflate(R.layout.lov_kodepos, null); dialogBuilder.setView(dialogView); final RecyclerView recyclerView = (RecyclerView) dialogView.findViewById(R.id.rv_lov_kodepos); API.getKodePos().enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { if (response.code()== 200){ Log.i("bella", "onResponse: "+response); data = response.body(); recyclerView.setHasFixedSize(true); recyclerView.addItemDecoration(new DividerItemDecoration(AddCustomerActivity.this, DividerItemDecoration.VERTICAL)); recyclerView.setLayoutManager(new LinearLayoutManager(AddCustomerActivity.this)); recyclerView.setAdapter(new KodePosAdapter(data)); } } @Override public void onFailure(Call> call, Throwable t) { Toast.makeText(AddCustomerActivity.this, "Failed", Toast.LENGTH\_SHORT).show(); } }); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.show(); recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(AddCustomerActivity.this, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent = new Intent(AddCustomerActivity.this,AddCustomerActivity.class); intent.putExtra(DATA\_KODEPOS, tempDatas.get(position).getPoscodeId()); startActivity(intent); if(dataKodePos.getPoscodeId()==DATA\_KODEPOS){ API.setKodePos(getIntent().getStringExtra(DATA\_KODEPOS)).enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { KodePos hehe = response.body(); et\_provinsi.setText(hehe.getPosProp()); et\_kota.setText(hehe.getPosKota()); et\_kecamatan.setText(hehe.getPosCamat()); et\_kelurahan.setText(hehe.getPosLurah()); et\_kodepos.setText(hehe.getPosKode()); } @Override public void onFailure(Call call, Throwable t) { } }); }else { } } })); ``` My Adapter ``` public class KodePosAdapter extends RecyclerView.Adapter { ArrayList datasSet; public KodePosAdapter(ArrayList data) { this.datasSet = data; } @Override public KodePosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.lov\_recyclerview, parent, false); return new KodePosViewHolder(itemView); } @Override public void onBindViewHolder(KodePosViewHolder holder, int position) { KodePos kdModel = datasSet.get(position); holder.kodePos.setText(kdModel.getPosKode()); holder.kecamatan.setText(kdModel.getPosCamat().toLowerCase()); holder.kelurahan.setText(kdModel.getPosLurah().toLowerCase()); } @Override public int getItemCount() { return datasSet.size(); } public class KodePosViewHolder extends RecyclerView.ViewHolder { public TextView kodePos, kecamatan, kelurahan; public KodePosViewHolder(View itemView) { super(itemView); kodePos = (TextView)itemView.findViewById(R.id.tv\_lov\_kodepos); kecamatan = (TextView)itemView.findViewById(R.id.tv\_lov\_kecamatan); kelurahan = (TextView)itemView.findViewById(R.id.tv\_lov\_kelurahan); } } ``` }<issue_comment>username_1: How about using a 'dictionary' instead of a multidimensional array. The key could be a concatenation of all indexes. Add a reference to the `Microsoft Scripting Runtime` or change this to late binding. ``` Option Explicit Dim sample As New Scripting.Dictionary Sub test() Dim index(0 To 3) As Integer index(0) = 3 index(1) = 1 index(2) = 1 index(3) = 0 Call SetArrayValue(sample, index, 12345) Debug.Print GetArrayValue(sample, index) End Sub Sub SetArrayValue(sample As Dictionary, index() As Integer, val As Variant) Dim key As String key = createIndexKey(index) If sample.Exists(key) Then sample(key) = val Else Call sample.Add(key, val) End If End Sub Function GetArrayValue(sample As Dictionary, index() As Integer) As Variant Dim key As String key = createIndexKey(index) If sample.Exists(key) Then GetArrayValue = sample(key) Else GetArrayValue = Null End If End Function Function createIndexKey(index() As Integer) Dim i As Integer createIndexKey = "" For i = LBound(index) To UBound(index) createIndexKey = IIf(createIndexKey = "", "", ":") & index(i) Next i End Function ``` Upvotes: 0 <issue_comment>username_2: There is no elegant solution. `Redim` can not accept variable number of argument. However, if you can limit "arbitrary", you can try something like this: ``` Sub DimTest() Dim sample() As Integer Dim dimensions(0 To 3) As Integer Dim index(0 To 3) As Integer dimensions(0) = 10 dimensions(1) = 20 dimensions(2) = 40 dimensions(3) = 70 index(0) = 1 index(1) = 2 index(2) = 4 index(3) = 7 sample = CreateArrayWithDimensions(dimensions) SetArrayValue sample, index, 12345 End Sub Function CreateArrayWithDimensions(dimensions() As Integer) As Integer() Dim b() As Integer Select Case UBound(dimensions) Case 1: ReDim b(dimensions(0)) Case 2: ReDim b(dimensions(0), dimensions(1)) Case 3: ReDim b(dimensions(0), dimensions(1), dimensions(2)) Case 4: ReDim b(dimensions(0), dimensions(1), dimensions(2), dimensions(3)) Case 5: ReDim b(dimensions(0), dimensions(1), dimensions(2), dimensions(3), dimensions(4)) End Select CreateArrayWithDimensions = b End Function Sub SetArrayValue(sample() As Integer, idx() As Integer, value As Integer) Select Case UBound(idx) Case 1: sample(idx(0)) = value Case 2: sample(idx(0), idx(1)) = value Case 3: sample(idx(0), idx(1), idx(2)) = value Case 4: sample(idx(0), idx(1), idx(2), idx(3)) = value Case 5: sample(idx(0), idx(1), idx(2), idx(3), idx(4)) = value End Select End Sub ``` An alternative (and more flexible) solution is to use the good old 1 dimensional linear storage concept (just the way the system stores the arrays in fact), and calculate the real position of the actual entry. Upvotes: 1
2018/03/21
1,548
6,425
<issue_start>username_0: Hi I am failry new to iOS development and wanted to know if there is a equivalent of asynctask in iOS? I want my web service to finish and then I want to pass the contents of my web service to nextview controller ``` @IBAction func searchAction(_ sender: Any) { let airportName: String = airportCode.text! let minutesBefore: String = minutesBehind.text! let minutesAfter: String = minutesAhead.text! //web service request self.data = FlightWebService().getFlightData(airportCode: airportName, minutesBehind: minutesBefore, minutesAhead: minutesAfter) print(self.data) //how to pass data to the next view controller performSegue(withIdentifier: "goToSearch", sender: self) } ```<issue_comment>username_1: You Can use URLSession available from ios 7.0 and later. In your method you can run async task ``` func searchAction() { let defaultSessionConfiguration = URLSessionConfiguration.default let defaultSession = URLSession(configuration: defaultSessionConfiguration) let url = URL(string: "typeHereYourURL") var urlRequest = URLRequest(url: url!) let params = ""// json or something else let data = params.data(using: .utf8) urlRequest.httpMethod = "POST" urlRequest.httpBody = data let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in performSegue(withIdentifier: "YourVCIdentifier", sender: self) } dataTask.resume() } ``` or you can create serial queue and run FlightWebService request in another thread ``` func searchAction() { let newQueue = DispatchQueue(label: "queue_label") newQueue.async { self.data = FlightWebService().getFlightData(airportCode: airportName, minutesBehind: minutesBefore, minutesAhead: minutesAfter) print(self.data) DispatchQueue.main.async { performSegue(withIdentifier: "YourVCIdentifier", sender: self) } } } ``` and override this to send parameters to the next ViewController ``` override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "YourVCIdentifier" { if let destinationVC = segue.destination as? YourVC { destinationVC.exampleStringProperty = //send data here recived earlier } } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Based upon @SH\_Khan's request I've placed your `URLRequest` call inside the `FlightWebService` class. That should do the trick. ``` class FlightWebService { // Change the method's signature to accept a completion block static func getFlightData(airportCode: String, minutesBehind: String, minutesAhead: String, completion: (Data?, Response?, Error?) -> Void) { let defaultSessionConfiguration = URLSessionConfiguration.default let defaultSession = URLSession(configuration: defaultSessionConfiguration) let url = URL(string: "typeHereYourURL") var urlRequest = URLRequest(url: url!) let params = ""// json or something else let data = params.data(using: .utf8) urlRequest.httpMethod = "POST" urlRequest.httpBody = data // Launch the task **IN BACKGROUND** with the provided completion handler block DispatchQueue.global(qos: .background).async { let dataTask = defaultSession.dataTask(with: urlRequest, completionHandler: completion) dataTask.resume() } } } @IBAction func searchAction(_ sender: Any) { let airportName: String = airportCode.text! let minutesBefore: String = minutesBehind.text! let minutesAfter: String = minutesAhead.text! //web service request FlightWebService().getFlightData(airportCode: airportName, minutesBehind: minutesBefore, minutesAhead: minutesAfter) { (data, response, error) in self.data = data print(self.data) // Always perform view-related stuff on the main thread DispatchQueue.main.async { performSegue(withIdentifier: "goToSearch", sender: self) } } } ``` Upvotes: 0 <issue_comment>username_3: Your FlightService functions need to be doing the async tasks and using completionHandlers to pass the response back to the calling code. See the below code ``` // model class Flight {} // flight service class FlightService: NSObject { func getFlightData(airportCode: String, minutesBehind: Int, minutesAhead: Int, completion: @escaping (Bool, [Flight]?) -> Void) { // main thread still let url = NSURL(string: "http://..........")! let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "Get" // This always runs in the background, so no need to specifically put it there let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in guard error == nil else { completion(false, nil) return } // parse response data instead I'll create blank array var parsedFlights = [Flight]() completion(true, parsedFlights) } task.resume() } } // USAGE @IBAction func searchAction(_ sender: Any) { let airportName: String = "airportCode.text!" let minutesBefore: String = "minutesBehind.text!" let minutesAfter: String = "minutesAhead.text!" FlightWebService().getFlightData(airportCode: airportName, minutesBehind: minutesBefore, minutesAhead: minutesAfter) { [weak self] success, flights in // we are still in a background thread here and would need to Dispatch to the main thread to update any UI guard let strongSelf = self, success else { return } print(flights.count) strongSelf.flightSearchResults = flights strongSelf.performSegue(withIdentifier: "goToSearch", sender: self) } } ``` `NSURLSession` always runs in the background thread so there is no need to manually dispatch into it. In the searchFunction once the completionHandler returns we are still running in the background thread at this point but we have parsed our response data and passed back the flight data, if we need to update any UI from here we would need to dispatch into the main thread. **NOTE:** you should generally also use a `weak self` in a closure because during the async task, we may have lost the reference to the calling class (self). Upvotes: 0
2018/03/21
1,139
3,985
<issue_start>username_0: I am trying to write a loop which tests each cell in for the number 1, when one is present I want to store the value in the adjacent cell (column A) and transpose all of these in a separate sheet. However, VBA is not one of my strong points and I'm struggling with getting the first part to work, my code: ``` Sub test_loop() Dim Needed_range As Long Needed_range = Cells(Rows.Count, "B").End(xlUp).Row For Each cell In Range(Needed_range) If cell = 1 Then MsgBox "Yes" Exit Sub End If Next cell End Sub ``` Sorry if this is really basic, I don't use VBA often and am going to need to take a refresher to finish this project!<issue_comment>username_1: (neededRange doesn't stock a range but just the last non empty row in column B) try this code : ``` Sub test_loop() lastRow = Cells(Rows.Count, "B").End(xlUp).Row For i = 1 To lastRow If Cells(i, 2).Value = 1 Then Cells(i, 2).Select MsgBox "Yes" Exit Sub End If Next i End Sub ``` Upvotes: 1 <issue_comment>username_2: Loop Column B and return Yes with row number, then save value of Column B to Column A ``` Sub test_loop() Dim i As Long For i = 1 To Cells(Rows.Count, "B").End(xlUp).Row If Cells(i, "B").Value = 1 Then MsgBox "Yes! Appears at row " & i Cells(i,"A").Value = Cells(i, "B").Value End If Next End Sub ``` Upvotes: 2 <issue_comment>username_3: It's fine to use a `For Each` loop, but you need to construct a `Range` object to loop through first. ``` Option Explicit Sub test_loop() Dim neededRange As Range, cell As Range 'get the range to loop through With ThisWorkbook.Worksheets("Sheet1") Set neededRange = Range(.Cells(1, "B"), .Cells(.Rows.Count, "B").End(xlUp)) End With For Each cell In neededRange If cell.Value = 1 Then cell.Offset(0,-1).Value = cell.Value 'put 1 into column A 'do something else End If Next cell End Sub ``` * Try not to underscores in variable names. Underscores have a specific meaning elsewhere in VBA * Don't forget to declare all variables -- I declared `cell` for you. If you add `Option Explicit` at the top of your code, you'll be reminded by the IDE * Rather than just `Range("A1")` try to *fully qualify* your ranges. I.e. `Workbooks("..").Worksheets("..").Range("A1")`. I've done this above in the `With` statement Upvotes: 3 [selected_answer]<issue_comment>username_4: Accessing the worksheet object, such as `Value = ..something` takes the longest for the code to process. You can avoid that, by using a "helper" range, in the code below I'm using `CopyValRng`, and every time the cell in column B equals 1 (`cell.Value = 1`), I'm adding the cell on the left (column A) to that range, using `Application.Union`. At the end, I'm just changing the values in the entire range at once using `CopyValRng.Value = 1`. ***Code*** ``` Option Explicit Sub test_loop() Dim Sht As Worksheet Dim Needed_range As Range, cell As Range, CopyValRng As Range Dim LastRow As Long ' set the worksheet object, modify "Sheet1" to your sheet's name Set Sht = ThisWorkbook.Sheets("Sheet1") With Sht ' get last row in column B LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row ' set the range Set Needed_range = .Range("B1:B" & LastRow) ' loop through the Range For Each cell In Needed_range If cell.Value = 1 Then If Not CopyValRng Is Nothing Then Set CopyValRng = Application.Union(CopyValRng, cell.Offset(0, -1)) Else Set CopyValRng = cell.Offset(0, -1) End If End If Next cell End With ' make sure there's at least 1 cell in the range, then put 1's in all the cells in column A at once If Not CopyValRng Is Nothing Then CopyValRng.Value = 1 End Sub ``` Upvotes: 2
2018/03/21
1,193
4,270
<issue_start>username_0: I'm new to Android and using Android Studio. Here is the detail of what I'm trying to do: There are 2 **devices**, 1 & 2, and there is a geofence. Whenever **device1** enter or exit geofence, a notification will be sent to **device2**. What I've already did was: got the geofence set up. A notification will be sent to **device1** locally, upon enter or exit. A FCM is set up, got **device2** token key and is able to send notification to it manually via console (I'm also looking for a way without using the console). I've tried to do another way around: install the apps on **device2** and track **device1** location, but after some research it seems to be impossible without installing a child apk in **device1**. I also tried to search solution but they are either unanswered or it is not the solution I'm looking for (I might be using the wrong keyword or not searching deep enough). So please direct me to a sample code before marking duplicate. Thanks.<issue_comment>username_1: (neededRange doesn't stock a range but just the last non empty row in column B) try this code : ``` Sub test_loop() lastRow = Cells(Rows.Count, "B").End(xlUp).Row For i = 1 To lastRow If Cells(i, 2).Value = 1 Then Cells(i, 2).Select MsgBox "Yes" Exit Sub End If Next i End Sub ``` Upvotes: 1 <issue_comment>username_2: Loop Column B and return Yes with row number, then save value of Column B to Column A ``` Sub test_loop() Dim i As Long For i = 1 To Cells(Rows.Count, "B").End(xlUp).Row If Cells(i, "B").Value = 1 Then MsgBox "Yes! Appears at row " & i Cells(i,"A").Value = Cells(i, "B").Value End If Next End Sub ``` Upvotes: 2 <issue_comment>username_3: It's fine to use a `For Each` loop, but you need to construct a `Range` object to loop through first. ``` Option Explicit Sub test_loop() Dim neededRange As Range, cell As Range 'get the range to loop through With ThisWorkbook.Worksheets("Sheet1") Set neededRange = Range(.Cells(1, "B"), .Cells(.Rows.Count, "B").End(xlUp)) End With For Each cell In neededRange If cell.Value = 1 Then cell.Offset(0,-1).Value = cell.Value 'put 1 into column A 'do something else End If Next cell End Sub ``` * Try not to underscores in variable names. Underscores have a specific meaning elsewhere in VBA * Don't forget to declare all variables -- I declared `cell` for you. If you add `Option Explicit` at the top of your code, you'll be reminded by the IDE * Rather than just `Range("A1")` try to *fully qualify* your ranges. I.e. `Workbooks("..").Worksheets("..").Range("A1")`. I've done this above in the `With` statement Upvotes: 3 [selected_answer]<issue_comment>username_4: Accessing the worksheet object, such as `Value = ..something` takes the longest for the code to process. You can avoid that, by using a "helper" range, in the code below I'm using `CopyValRng`, and every time the cell in column B equals 1 (`cell.Value = 1`), I'm adding the cell on the left (column A) to that range, using `Application.Union`. At the end, I'm just changing the values in the entire range at once using `CopyValRng.Value = 1`. ***Code*** ``` Option Explicit Sub test_loop() Dim Sht As Worksheet Dim Needed_range As Range, cell As Range, CopyValRng As Range Dim LastRow As Long ' set the worksheet object, modify "Sheet1" to your sheet's name Set Sht = ThisWorkbook.Sheets("Sheet1") With Sht ' get last row in column B LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row ' set the range Set Needed_range = .Range("B1:B" & LastRow) ' loop through the Range For Each cell In Needed_range If cell.Value = 1 Then If Not CopyValRng Is Nothing Then Set CopyValRng = Application.Union(CopyValRng, cell.Offset(0, -1)) Else Set CopyValRng = cell.Offset(0, -1) End If End If Next cell End With ' make sure there's at least 1 cell in the range, then put 1's in all the cells in column A at once If Not CopyValRng Is Nothing Then CopyValRng.Value = 1 End Sub ``` Upvotes: 2
2018/03/21
619
2,117
<issue_start>username_0: I am upgrading rails application fro **3.2.2** to rails **5.1.4**. I am having issue with strong params with attr\_accessor. **Console params output: Why i am getting permitted: false** ``` "✓", "authenticity\_token"=>"<KEY> "journal"=>"1", "subject"=>"sdf", "body"=>"sdf", "recipients"=>["<EMAIL>"]} permitted: false>, "commit"=>"Submit", "controller"=>"journals", "action"=>"create", "assignment\_id"=>"9081"} permitted: false> ``` Here is my controller create action: **journals\_controller.rb** ``` def create @facility = Facility.find(params[:facility_id]) @journal = @facility.journals.new(journal_params) @journal.save end private def journal_params params.require(:journal).permit(:user_id, :body, :recipients, :subject) end ``` **journal.rb** ``` attr_accessor :recipients ``` **journal/views/\_form.html.erb** ``` <%= form_for [@assignments, @journal] do |f| %> <%= form_legend %> <%= f.error_messages %> <%= f.label :subject %><%= required\_field %> <%= f.text\_field :subject, :size => 80 %> <%= f.label :body %><%= required\_field %> <%= f.text\_area :body, :cols => 80, :rows => 5 %> <% unless params[:action] == 'edit' %> <% for group in Journal.possible\_recipients.in\_groups(3, false) %> <% for recipient in group %> <%= check\_box\_tag "journal[recipients][]", recipient.try(:email) %> <%= bold\_assignees\_helper recipient %> <% end %> | <% end %> <% end %> <%= f.submit 'Submit' %> <% end %> ``` **strong params are permitted, but still getting permitted: false on console**<issue_comment>username_1: Change your permitted parms to allow `array of recipients` like below: ``` def journal_params params.require(:journal).permit(:user_id, :body, recipients: [], :subject) end ``` Let me know if the error persists and i'll try to help you Upvotes: 3 [selected_answer]<issue_comment>username_2: `permitted = false` is the default unless you call `permit!` to allow all parameter in hash. But it will defeats the use of strong parameter. Upvotes: 0
2018/03/21
456
1,670
<issue_start>username_0: I got the following JSON string in PHP: ``` { "status":"200", "message":"Saved picklist found", "data":{ "_id":{ "$oid":"5aab871dbcdcab3ab0005cd3" }, "username":"admin", "list_count":"3", "list":[ { "id":"1", "data":"AUTOGENERATED1", "x":"33", "y":"33" }, { "id":"2", "data":"AUTOGENERATED2", "x":"22", "y":"22" }, { "id":"3", "data":"AUTO", "x":"33", "y":"33" } ] } } ``` that I decode to an array using the following: ``` json_decode($response, true); ``` I would like to loop through the array and extract for example username and list\_count. I tried the following code for that: ``` foreach ($response['data'] as $resp) { echo $resp['list_count']; } ``` which does not work. Any suggestions on how to extract username and list\_count? I would also like to loop through the `list` array and get the values for each object within that array, any suggestions on how that can be done?<issue_comment>username_1: Change your permitted parms to allow `array of recipients` like below: ``` def journal_params params.require(:journal).permit(:user_id, :body, recipients: [], :subject) end ``` Let me know if the error persists and i'll try to help you Upvotes: 3 [selected_answer]<issue_comment>username_2: `permitted = false` is the default unless you call `permit!` to allow all parameter in hash. But it will defeats the use of strong parameter. Upvotes: 0
2018/03/21
2,111
6,025
<issue_start>username_0: I have a website that uses external data from a variety of different website sources. This works pretty well but I am struggling with one specific source. The issue is that the data-string is not bound by a clear html tag `<>` which means that I somehow need to split the data manually. If have done this before as well with preg but for the example below I struggle to find a solution. Example of the html data: ``` Dagschotels =========== ![dagschotel](http://emmaseetcafe.nl/wp-content/uploads/2014/09/voorgerecht2.jpg) Elke week heeft Emma’s nieuwe dagschotels op het menu staan. Een dagschotel is te bestellen voor € 9,00-. Alle dagschotels zijn ook als kinderdagschotel te verkrijgen voor slechts €5,-. Reserveren voor een daghap is mogelijk, zolang de voorraad strekt. **28-02**<NAME> **1-03** Stampot andijvie met slavink **2-03** Gyros wrap met gebakken aardappelen **7-03** Erwtensoep met roggebrood **8-03** Köfte met friet en salade **9-03** Kipschnitzel met spinazie en gekookte aardappelen **14-03** Sjasliek met rijst **15-03** Kipsaté met nasi **16-03** Scholfilet met friet en gemengde groenten **21-03** Lente pasta ( verschillende lente groenten) **22-03** Taco’s met friet en salade **23-03** Kip kerrie met rijst **28-03** Schnitzel met friet en salade **29-03** Gehaktbal met friet en rode kool **30-03** Visstoofpotje met aardappelpuree **ZOLANG DE VOORAAD STREKT** RESERVEREN VAN DAGSCHOTELS IS MOGELIJK DAGSCHOTEL KOST € 9,00 ``` The required output I need before post processing is something like: Array = ["28-02 Pasta Tonno", "1-03 Stampot andijvie met slavink", "7-03 Erwtensoep met roggebrood"] etc. Update ------ I managed to isolate all the dates with simple dom which worked because there all enclosed by the tag. I used the following code: ``` $html = file_get_html('http://emmaseetcafe.nl/menukaarten/dagschotels/', false, $this->getStreamContext()); // start to find the meals // gets the main dish foreach ($html->find('div[class=column8 gerechten]') as $container) { foreach ($container->find('p') as $p) { $temp[] = $p->innertext; } } $temp = $temp[1]; $html = str_get_html($temp); foreach ($html->find('strong') as $strong) { $temp_dates[] = $strong->innertext; } ``` The result is an array with all the dates in dd-mm . So now what remains is to isolate the actual meals from the following text string: ``` '**02-05** Schnitzel met champignonsaus friet en salade **03-05** Mexicaanse wrap met friet **04-05** Pasta Tonno **09-05** Gegrilde paprika met couscous **10-05** <NAME> met rijst **11-05** Pasta AOP **16-05** Couscous met gegrilde kipfilet en geroosterde paprika **17-05** Tartaar met gebakken ui , frietjes en doperwten **'... (length=955)** ``` Update 2 -------- I finally managed to solve it myself. I moved away from the simple dom at the end for the last part to remove the strong and the broken tag. ``` //var_dump($meal_string); $meal_array = explode(" ",$meal_string); foreach ($meal_array as $meal){ $meals_no_tags[]= strip_tags($meal); // strip all php / html tags } // structure the data by removing emply items foreach ($meals_no_tags as $meal_item){ if (strlen($meal_item)>3){ $meal_temp[] = $meal_item; } } ```<issue_comment>username_1: This will give you an idea: ``` $string = preg_replace('/\s{1,}/', ' ', $string); preg_match_all('/**(.\*?) /', $string, $array); for($i = 0; $i < count($array[1]); $i++){ $results[] = strip\_tags($array[1][$i]); } array\_pop($results); print\_r($results);** ``` Upvotes: 0 <issue_comment>username_2: You would be best using a HTML parser rather than anything else (as pointed out in comment). This allows you to use the document structure to get at the data rather than relying on content. The following code uses DOMDocument and it's ability to load HTML. Although there are some slight problems with the document fragment you give, it's possible to ignore them as they don't form part of the structure your interested in ( tags for example). The code uses XPath to find the tags in the second paragraph as the labels and then gets the text by fetching the next element of the document. ``` $xml = new DOMDocument(); $xml->preserveWhiteSpace = false; $content = file_get_contents("e.html"); libxml_use_internal_errors(true); $xml->loadHTML('xml encoding="utf-8" ?'.$content); $xp = new DOMXPath($xml); $labels = $xp->query("//div/p[2]//strong"); foreach ( $labels as $label ) { $text = (string)$label->nextSibling->nodeValue; echo (string)$label->nodeValue."=".$text.PHP_EOL; } ``` Which outputs... ``` 28-02=Pasta Tonno 1-03= Stampot andijvie met slavink 2-03= Gyros wrap met gebakken aardappelen 7-03= Erwtensoep met roggebrood 8-03= Köfte met friet en salade 9-03= Kipschnitzel met spinazie en gekookte aardappelen 14-03= Sjasliek met rijst 15-03= Kipsaté met nasi 16-03= Scholfilet met friet en gemengde groenten 21-03= Lente pasta ( verschillende lente groenten) 22-03= Taco’s met friet en salade 23-03= Kip kerrie met rijst 28-03= Schnitzel met friet en salade 29-03= Gehaktbal met friet en rode kool 30-03= Visstoofpotje met aardappelpureeLente pasta ( verschillende lente groenten) 22-03= Taco’s met friet en salade 23-03= Kip kerrie met rijst 28-03= Schnitzel met friet en salade 29-03= Gehaktbal met friet en rode kool 30-03= Visstoofpotje met aardappelpuree ``` As the above HTML may be part of a larger document, you could change the XPath expression to make sure it fetches the right element. You can either use ``` //div[h1/text()="Dagschotels"]/p[2]//strong ``` Which is based on the title, or ``` //div[@class="column8 gerechten"]/p[2]//strong ``` Which is based on the class of the element. Upvotes: 2
2018/03/21
591
2,028
<issue_start>username_0: I playing with react-draft-wysiwyg editor. I progress quite well. But now I stuck how can I display the output of the editor. For example, let suppose body is the output of the wysiwyg editor: ``` function ShowHtml(props) { let body = 'Sample text with **bold** and *italic* ' return ( {body} ) } ``` Now the output will be exactly the same html with tags displayed without formatting. ``` Sample text with **bold** and *italic* ``` And I would like something like this: > > Sample text with **bold** and *italic* > > > In jQuery I would just set the html property of the div tag. But I do not know how to do it the proper way in React. Can I just grab a reference to the div and update it somehow just like in jQuery? Is it working with the virtual Dom?<issue_comment>username_1: Try removing the double quote or if you wanna keep the double quote you can use `dangerouslySetInnerHTML` ``` function ShowHtml(props) { let body = 'Sample text with **bold** and *italic* ' return ( ) } ``` Upvotes: 1 <issue_comment>username_2: ``` function ShowHtml() { return ( Sample text with **bold** and *italic* ) } ``` Upvotes: -1 <issue_comment>username_3: try to insert as an attribute dangerouslySetInnerHTML={{\_\_html: body}} ``` function ShowHtml(props) { let body = 'Sample text with **bold** ' return ( ) } ``` <https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml> Upvotes: 6 [selected_answer]<issue_comment>username_4: You can use `dangerouslySetInnerHTML` to render html inside react components: ``` renderBodyContents = () => { return {__html: this.state.body} } ... render(){ return( dangerouslySetInnerHTML={this.renderBodyContents()}> ) } ``` Upvotes: 0 <issue_comment>username_5: If you want to keep the double quotes, You can also setup the innerHTML dangerously: ``` function ShowHtml(props) { let body = 'Sample text with **bold** and *italic* ' return ( ) } ``` Upvotes: 2