id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
cef1314b96d47eaaccad89a162bf3d92197ed3f8
Stackoverflow Stackexchange Q: Swift Package Manager - Swift 4 syntax I'm trying to use updated SPM for Swift4 with the following Package.swift file - PackageDescription API Version 4 import PackageDescription let package = Package( name: "Name", dependencies : [ .package(url: "url", .branch("swift4")) ], exclude: ["Tests"] ) I have a correct version of SPM also: Apple Swift Package Manager - Swift 4.0.0-dev (swiftpm-13081.9) But I can not build the library by swift build command. I see the following error: ... error: type 'Version' has no member 'branch' A: You're missing the tools version specifier in your manifest; add the following as the first line of your Package.swift: // swift-tools-version:4.0 By default if that line is omitted, it'll default to manifest version 3 and also compiler version 3. For more information see SE-0152 or Swift Package Manager Manifest API Redesign on swift.org.
Q: Swift Package Manager - Swift 4 syntax I'm trying to use updated SPM for Swift4 with the following Package.swift file - PackageDescription API Version 4 import PackageDescription let package = Package( name: "Name", dependencies : [ .package(url: "url", .branch("swift4")) ], exclude: ["Tests"] ) I have a correct version of SPM also: Apple Swift Package Manager - Swift 4.0.0-dev (swiftpm-13081.9) But I can not build the library by swift build command. I see the following error: ... error: type 'Version' has no member 'branch' A: You're missing the tools version specifier in your manifest; add the following as the first line of your Package.swift: // swift-tools-version:4.0 By default if that line is omitted, it'll default to manifest version 3 and also compiler version 3. For more information see SE-0152 or Swift Package Manager Manifest API Redesign on swift.org.
stackoverflow
{ "language": "en", "length": 138, "provenance": "stackexchange_0000F.jsonl.gz:846114", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483929" }
caf909e4634e9136fbab3e3ac6fbb1cba62f3f83
Stackoverflow Stackexchange Q: Opening MySQL.Data source from Github source I am trying to build the source for the .net connector c# in Visual Studio 2017. I've tried downloading several versions of the MySQL connector from GitHub (https://github.com/mysql/mysql-connector-net/releases), but every version has an issue, I'm not sure what I'm missing. I tried downloading the latest version 7.0.7-m6 but this throws an error about inconsistent targeting frameworks for a UAP project. I couldn't find anything about what that means so I tried one of the previous versions, 6.10.1 and 6.10.0 but both of these have different problems. The error I'm getting back is Source file 'Desktop\mysql-connector-net-6.10.0\Source\MySQL.Data\X\XDevAPI\Common\ColumnTypes.cs' could not be found. There's tonnes of these types of errors, looking at the directory, these files don't exist, yet the project is still referencing them. I would have thought importing a project from a GitHub release would just work and a release definetely wouldn't have files references that don't exist, so what am I missing. A: Isnt it possible to use the nuget for mysql? The below 6.9.9 compiled at my VS2013 I have removed the tests and EF from projects. mysql 6.9.9 google drive link
Q: Opening MySQL.Data source from Github source I am trying to build the source for the .net connector c# in Visual Studio 2017. I've tried downloading several versions of the MySQL connector from GitHub (https://github.com/mysql/mysql-connector-net/releases), but every version has an issue, I'm not sure what I'm missing. I tried downloading the latest version 7.0.7-m6 but this throws an error about inconsistent targeting frameworks for a UAP project. I couldn't find anything about what that means so I tried one of the previous versions, 6.10.1 and 6.10.0 but both of these have different problems. The error I'm getting back is Source file 'Desktop\mysql-connector-net-6.10.0\Source\MySQL.Data\X\XDevAPI\Common\ColumnTypes.cs' could not be found. There's tonnes of these types of errors, looking at the directory, these files don't exist, yet the project is still referencing them. I would have thought importing a project from a GitHub release would just work and a release definetely wouldn't have files references that don't exist, so what am I missing. A: Isnt it possible to use the nuget for mysql? The below 6.9.9 compiled at my VS2013 I have removed the tests and EF from projects. mysql 6.9.9 google drive link
stackoverflow
{ "language": "en", "length": 189, "provenance": "stackexchange_0000F.jsonl.gz:846139", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484008" }
90f1e717c6df773a4817795db2bea9d9d9080280
Stackoverflow Stackexchange Q: ASP.net web api returns list of empty objects I have an action, which shoeuld return a limited list of store items from a DB, here the code below [HttpGet] public IEnumerable<ProductInfo> GetTop(int amount = 5) { var mostPopulardProductIds = dbe.SalesOrderDetail.GroupBy(p => p.ProductID) .OrderByDescending(p => p.Count()) .Take(amount) .Select(p => p.Key) .ToList(); var result = dbe.Product .Where(p => mostPopulardProductIds.Contains(p.ProductID)) .Select(p => new ProductInfo() { Id = p.ProductID, Name = p.Name } ).ToList(); return result; } and here's my ProductInfo class [DataContract] public class ProductInfo { public int Id { get; set; } public string Name { get; set; } //public } But when I try to access it via browser, I get list of empty objects, which are looking like the 1st pic But debugger shows me, that result variable containing normal objects with data I've tried to return result through Request.CreateResponse method, but this still does not work A: Please add DataMember attribute to class properties, change ProductInfo class [DataContract] public class ProductInfo { [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } } More about Data Member
Q: ASP.net web api returns list of empty objects I have an action, which shoeuld return a limited list of store items from a DB, here the code below [HttpGet] public IEnumerable<ProductInfo> GetTop(int amount = 5) { var mostPopulardProductIds = dbe.SalesOrderDetail.GroupBy(p => p.ProductID) .OrderByDescending(p => p.Count()) .Take(amount) .Select(p => p.Key) .ToList(); var result = dbe.Product .Where(p => mostPopulardProductIds.Contains(p.ProductID)) .Select(p => new ProductInfo() { Id = p.ProductID, Name = p.Name } ).ToList(); return result; } and here's my ProductInfo class [DataContract] public class ProductInfo { public int Id { get; set; } public string Name { get; set; } //public } But when I try to access it via browser, I get list of empty objects, which are looking like the 1st pic But debugger shows me, that result variable containing normal objects with data I've tried to return result through Request.CreateResponse method, but this still does not work A: Please add DataMember attribute to class properties, change ProductInfo class [DataContract] public class ProductInfo { [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } } More about Data Member
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:846145", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484027" }
24e4c5f9627327dc33ba1c3cf221af9143d3e457
Stackoverflow Stackexchange Q: Python can't find module when started with sudo I've got a script that uses the Google Assistant Library and has to import some modules from there. I figured out this only works in a Python Virtual Environment, which is really strange. In the same folder I've got a script which uses the GPIO pins and has to use root. They interact with each other, so when I start the GPIO script, the Assistant script is also started. But for some reason the modules in there can't import when the script is started with root. Does anybody know something about this? A: Normally you can active a virtual env and use the interpreter inside the env to run your script. But it is not necessary. Suppose you have a virtual env under the path /path-to-env/env the script you want to run example.py is under the path /path-to-script/example.py you can already run this example.py like sudo /path-to-env/env/bin/python /path-to-script/example.py
Q: Python can't find module when started with sudo I've got a script that uses the Google Assistant Library and has to import some modules from there. I figured out this only works in a Python Virtual Environment, which is really strange. In the same folder I've got a script which uses the GPIO pins and has to use root. They interact with each other, so when I start the GPIO script, the Assistant script is also started. But for some reason the modules in there can't import when the script is started with root. Does anybody know something about this? A: Normally you can active a virtual env and use the interpreter inside the env to run your script. But it is not necessary. Suppose you have a virtual env under the path /path-to-env/env the script you want to run example.py is under the path /path-to-script/example.py you can already run this example.py like sudo /path-to-env/env/bin/python /path-to-script/example.py A: not 100% sure but have you tried: sudo -E python myScriptName.py As mentioned here A: Try to install the module using sudo. I had the same problem with the module 'reportlab' from python. I realized that I had installed pip (the installer manager for reportlab) without sudo command. The problem is that the package (pip and reportlab) has been installed as user and not as root, so when you try to use sudo, it does not recognize the system path to reportlab because you never installed in the first place, only for the user! I recommend install pip and module with sudo always: For python 2: $ sudo add-apt-repository universe $ sudo apt update $ sudo curl https://bootstrap.pypa.io/get-pip.py --output get-pip.py $ sudo python2 get-pip.py $ sudo pip install google-assistant-library For python 3 (from Docs Google assistant library): $ sudo apt-get update $ sudo apt-get install python3-dev python3-venv $ sudo python3 -m venv env $ sudo env/bin/python -m pip install --upgrade pip setuptools $ sudo source env/bin/activate $ sudo python -m pip install --upgrade google-assistant-library Hope this helps! Regards! A: I ended up just installing the python package as sudo and it worked fine. For my case it was sudo pip3 install findpi and then executed as sudo findpi and worked.
stackoverflow
{ "language": "en", "length": 368, "provenance": "stackexchange_0000F.jsonl.gz:846160", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484082" }
b71220d651679da4e59e1457abed54b882cbfcf3
Stackoverflow Stackexchange Q: No repeat for text-labels on line? I am using "symbol-placement": "line", to add text labels over polygons (countries) using a precalculated line which spans the country bounds. However, the text label automatically repeats itself which does not look good. Example: Instead of a curved GERMANY, I get a curved unwanted repetition GERMANY GERMANY GERMANY GERMANY. I could not find any option for that... Is there a work around? Bonus question: Is it possible to have the text span the full line and have the font-size dynamically set accordingly? That would be the perfect solution. A: Setting symbol-spacing to a very high number (eg, 5000) should effectively achieve what you want. Bonus question: Is it possible to have the text span the full line and have the font-size dynamically set accordingly? No. But you could set the length of the line as a property on the feature, and use data-driven styling to set the font size from that. Data-driven styling for font-sizes is supported in Mapbox-GL-JS as of version 0.35. You could potentially also use text-letter-spacing. That one doesnt' supoprt data-driven styling, but you could use filters to set some basic classes of letter spacing.
Q: No repeat for text-labels on line? I am using "symbol-placement": "line", to add text labels over polygons (countries) using a precalculated line which spans the country bounds. However, the text label automatically repeats itself which does not look good. Example: Instead of a curved GERMANY, I get a curved unwanted repetition GERMANY GERMANY GERMANY GERMANY. I could not find any option for that... Is there a work around? Bonus question: Is it possible to have the text span the full line and have the font-size dynamically set accordingly? That would be the perfect solution. A: Setting symbol-spacing to a very high number (eg, 5000) should effectively achieve what you want. Bonus question: Is it possible to have the text span the full line and have the font-size dynamically set accordingly? No. But you could set the length of the line as a property on the feature, and use data-driven styling to set the font size from that. Data-driven styling for font-sizes is supported in Mapbox-GL-JS as of version 0.35. You could potentially also use text-letter-spacing. That one doesnt' supoprt data-driven styling, but you could use filters to set some basic classes of letter spacing.
stackoverflow
{ "language": "en", "length": 195, "provenance": "stackexchange_0000F.jsonl.gz:846178", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484125" }
f6509dcf2ef106a7cc6371564cecb22850c14ff8
Stackoverflow Stackexchange Q: Docker error The command non-zero code: 1 python i have problem when i tried to build container. And the error is : The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 i don't know why, i follow the code from documentation but always get error. Dockerfile FROM python:2.7-slim # # # Set the working directory to /app WORKDIR /app # # # Copy the current directory contents into the container at /app ADD . /app # # # Install any needed packages specified in requirements.txt RUN pip install -r requirements.txt # # # Make port 80 available to the world outside this container EXPOSE 80 # # # Define environment variable ENV NAME World # # # Run app.py when the container launches CMD ["python", "app.py"] A: Seems issue with the location of the file try to give absolute path of the file that you are referring in dockerfile
Q: Docker error The command non-zero code: 1 python i have problem when i tried to build container. And the error is : The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 i don't know why, i follow the code from documentation but always get error. Dockerfile FROM python:2.7-slim # # # Set the working directory to /app WORKDIR /app # # # Copy the current directory contents into the container at /app ADD . /app # # # Install any needed packages specified in requirements.txt RUN pip install -r requirements.txt # # # Make port 80 available to the world outside this container EXPOSE 80 # # # Define environment variable ENV NAME World # # # Run app.py when the container launches CMD ["python", "app.py"] A: Seems issue with the location of the file try to give absolute path of the file that you are referring in dockerfile
stackoverflow
{ "language": "en", "length": 154, "provenance": "stackexchange_0000F.jsonl.gz:846220", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484247" }
ec90a3095a8a0a1bd243f158e0fef43ecee7bb96
Stackoverflow Stackexchange Q: Get Google access token To get Google access token after firebase auth login, I know I can simply do this: firebase.auth().signInWithPopup(provider).then(function(result) { var token = result.credential.accessToken; } but what if the user is already authenticated and I need the token? is there any way to extract it from the Firebase auth? I've been through every value of authState but I couldn't find the google access token I've been looking for. A: You can't get the access token from the onAuthStateChanged listener or the currentUser. You can only get it immediately after authentication when calling signInWithPopup, reauthenticateWithPopup, linkWithPopup, getRedirectResult, etc. Firebase Auth does not manage OAuth tokens for users. If you feel strongly about this feature, please file a feature request for it on the Firebase forum: https://groups.google.com/forum/#!forum/firebase-talk You can also just use the GApi library to get the Google access token and pass it to Firebase to sign-in via signInWithCredential. The advantage here is that GApi will manage that OAuth token for you.
Q: Get Google access token To get Google access token after firebase auth login, I know I can simply do this: firebase.auth().signInWithPopup(provider).then(function(result) { var token = result.credential.accessToken; } but what if the user is already authenticated and I need the token? is there any way to extract it from the Firebase auth? I've been through every value of authState but I couldn't find the google access token I've been looking for. A: You can't get the access token from the onAuthStateChanged listener or the currentUser. You can only get it immediately after authentication when calling signInWithPopup, reauthenticateWithPopup, linkWithPopup, getRedirectResult, etc. Firebase Auth does not manage OAuth tokens for users. If you feel strongly about this feature, please file a feature request for it on the Firebase forum: https://groups.google.com/forum/#!forum/firebase-talk You can also just use the GApi library to get the Google access token and pass it to Firebase to sign-in via signInWithCredential. The advantage here is that GApi will manage that OAuth token for you.
stackoverflow
{ "language": "en", "length": 164, "provenance": "stackexchange_0000F.jsonl.gz:846291", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484440" }
5a4c723988514843c33500b172e19694d02bd36b
Stackoverflow Stackexchange Q: How to post nested json by SwiftyJson and Alamofire? How to post nested json like below as body of method by SwiftyJson and Alamofire?(Swift 3) { "a":{ "a1": "v1", "a2": "v2" }, "b":"bv" } I check lots of post Json post nested objects in swift using alamofire , How do I access a nested JSON value using Alamofire and SwiftyJSON? , Alamofire JSON Serialization of Objects and Collections and ... but none of them helped for this situation. A: try this func test() { var exampleParameters : [String : Any] = ["b" : "bv"] exampleParameters["a"] = ["a1": "v1","a2": "v2"] debugPrint(exampleParameters.description) let devUrlPush = URL.init(string:"yourURL") var request = URLRequest(url: devUrlPush!) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try! JSONSerialization.data(withJSONObject: exampleParameters) Alamofire.request(request).responseJSON { (response) in if( response.result.isSuccess) { }else { } } let string = String(data: request.httpBody!, encoding: .utf8) let jsonString = JSON(data: request.httpBody!) debugPrint(jsonString.rawString(.utf8, options: .prettyPrinted)) debugPrint(string) } I hope this helps
Q: How to post nested json by SwiftyJson and Alamofire? How to post nested json like below as body of method by SwiftyJson and Alamofire?(Swift 3) { "a":{ "a1": "v1", "a2": "v2" }, "b":"bv" } I check lots of post Json post nested objects in swift using alamofire , How do I access a nested JSON value using Alamofire and SwiftyJSON? , Alamofire JSON Serialization of Objects and Collections and ... but none of them helped for this situation. A: try this func test() { var exampleParameters : [String : Any] = ["b" : "bv"] exampleParameters["a"] = ["a1": "v1","a2": "v2"] debugPrint(exampleParameters.description) let devUrlPush = URL.init(string:"yourURL") var request = URLRequest(url: devUrlPush!) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try! JSONSerialization.data(withJSONObject: exampleParameters) Alamofire.request(request).responseJSON { (response) in if( response.result.isSuccess) { }else { } } let string = String(data: request.httpBody!, encoding: .utf8) let jsonString = JSON(data: request.httpBody!) debugPrint(jsonString.rawString(.utf8, options: .prettyPrinted)) debugPrint(string) } I hope this helps
stackoverflow
{ "language": "en", "length": 153, "provenance": "stackexchange_0000F.jsonl.gz:846385", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484772" }
885c1306446de6de62cc67b3db2f2361dd25d87d
Stackoverflow Stackexchange Q: Docker Startup Error on Windows 10: Object reference not set to an instance of an object When starting Docker on Windows 10, I saw the error: Object reference not set to an instance of an object. After searching for a while, I found a blog post that describes how to get rid the error: Error while starting Docker for Windows, which is to delete all the files in C:\Users\<UserName>\AppData\Roaming\Docker\ The blog post references a Docker GitHub issue (Object reference not set to an instance of an object when starting docker for windows) which has other solutions. A: For the people who are needlessly looking for a solution and the solution with removing folders under appdata did not work. I got it working for myself by removing the regkeys that contained docker.
Q: Docker Startup Error on Windows 10: Object reference not set to an instance of an object When starting Docker on Windows 10, I saw the error: Object reference not set to an instance of an object. After searching for a while, I found a blog post that describes how to get rid the error: Error while starting Docker for Windows, which is to delete all the files in C:\Users\<UserName>\AppData\Roaming\Docker\ The blog post references a Docker GitHub issue (Object reference not set to an instance of an object when starting docker for windows) which has other solutions. A: For the people who are needlessly looking for a solution and the solution with removing folders under appdata did not work. I got it working for myself by removing the regkeys that contained docker. A: Today after Docker Desktop's update on Windows 10 I got this issue (NullReferenceException). When I deleted (by previously saving it of course) the mentioned folder I stopped seeing my containers when doing docker ps -a. A deeper investigation showed that the issue was with "overrideProxyExclude": null property in my C:\Users\<UserName>\AppData\Roaming\Docker\settings.json. Simply changing its value to an empty string "overrideProxyExclude": "" fixed the problem. This way I avoided removal of the whole folder which kept my local setup.
stackoverflow
{ "language": "en", "length": 210, "provenance": "stackexchange_0000F.jsonl.gz:846391", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484794" }
e06da7486f9238fca71dc16bd4b5d09e9d925318
Stackoverflow Stackexchange Q: MySQL Select only the redundant rows and leave out the original rows I have this table ID | NAME | TICKETNO --------------------- 1 | Issa | K1 2 | kassim | K1 3 | Said | G5 4 | Maya | G5 5 | Sara | G5 6 | Kesi | J8 7 | Ima | J8 8 | Fali | O9 And I want to perform an MySQL query to select only the duplicates based on the colum TICKETNO and leave out the original rows and produce a table as follows ID | NAME | TICKETNO --------------------- 2 | kassim | K1 4 | Maya | G5 5 | Sara | G5 7 | Ima | J8 Can someone give a MySQL query to achieve this? A: You can use the following solution: SELECT * FROM table_name WHERE NOT ID IN ( SELECT MIN(ID) FROM table_name GROUP BY TICKETNO ) demo: http://sqlfiddle.com/#!9/b1941d/6/0
Q: MySQL Select only the redundant rows and leave out the original rows I have this table ID | NAME | TICKETNO --------------------- 1 | Issa | K1 2 | kassim | K1 3 | Said | G5 4 | Maya | G5 5 | Sara | G5 6 | Kesi | J8 7 | Ima | J8 8 | Fali | O9 And I want to perform an MySQL query to select only the duplicates based on the colum TICKETNO and leave out the original rows and produce a table as follows ID | NAME | TICKETNO --------------------- 2 | kassim | K1 4 | Maya | G5 5 | Sara | G5 7 | Ima | J8 Can someone give a MySQL query to achieve this? A: You can use the following solution: SELECT * FROM table_name WHERE NOT ID IN ( SELECT MIN(ID) FROM table_name GROUP BY TICKETNO ) demo: http://sqlfiddle.com/#!9/b1941d/6/0
stackoverflow
{ "language": "en", "length": 154, "provenance": "stackexchange_0000F.jsonl.gz:846416", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484866" }
aedce29c8675938072926d9223771f19236df28d
Stackoverflow Stackexchange Q: Pandas show column number is there any way to get pandas to show the column number and the column name at the same time? I'm dealing with a dataset with >30 columns, all of very long column names and some with little variation with each other. Its an absolute chore to type out the names when writing out the code. (i would still need to see the column names to know which columns to select) thanks. A: One possible solution is create MultiIndex and then select columns by DataFrame.xs: df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9], 'D':[1,3,5], 'E':[5,3,6], 'F':[7,4,3]}) print (df) A B C D E F 0 1 4 7 1 5 7 1 2 5 8 3 3 4 2 3 6 9 5 6 3 df.columns = pd.MultiIndex.from_arrays([pd.RangeIndex(len(df.columns)), df.columns]) print (df) 0 1 2 3 4 5 A B C D E F 0 1 4 7 1 5 7 1 2 5 8 3 3 4 2 3 6 9 5 6 3 print (df.xs(2, level=0, axis=1)) C 0 7 1 8 2 9
Q: Pandas show column number is there any way to get pandas to show the column number and the column name at the same time? I'm dealing with a dataset with >30 columns, all of very long column names and some with little variation with each other. Its an absolute chore to type out the names when writing out the code. (i would still need to see the column names to know which columns to select) thanks. A: One possible solution is create MultiIndex and then select columns by DataFrame.xs: df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9], 'D':[1,3,5], 'E':[5,3,6], 'F':[7,4,3]}) print (df) A B C D E F 0 1 4 7 1 5 7 1 2 5 8 3 3 4 2 3 6 9 5 6 3 df.columns = pd.MultiIndex.from_arrays([pd.RangeIndex(len(df.columns)), df.columns]) print (df) 0 1 2 3 4 5 A B C D E F 0 1 4 7 1 5 7 1 2 5 8 3 3 4 2 3 6 9 5 6 3 print (df.xs(2, level=0, axis=1)) C 0 7 1 8 2 9
stackoverflow
{ "language": "en", "length": 177, "provenance": "stackexchange_0000F.jsonl.gz:846420", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484878" }
e37b97b1dcf4efca3d088b3bf2d72641e0c78ea9
Stackoverflow Stackexchange Q: NHibernate join multiple tables i have searched the web and couldnt find a satisfying answer. I am attempting to write a QueryOver/CreateCriteria query to get a field from 1 table after joining 3 tables. The SQL query itself is simple, however i wasnt able to convert that into the above format. The query: select LOC_ID from VISITOR_VISIT vv join VISIT v on vv.VISIT_ID = v.VISIT_ID join VISITOR_LAY_ENTRY_POINTS vlep on vlep.VLEP_ID = v.VEP_ID where vv.VIS_ID = PARAMETER A: // Join aliases for ease of getting access to all parts of the query VisitorVisit visitorVisitAlias = null; Visit visitAlias = null; VisitorLayEntryPoints = visitorLayEntryPointsAlias = null; IList<int> locationIds = session.QueryOver<VisitorVisit>() .JoinAlias(() => visitorVisitAlias.VisitId, () => visitAlias) .JoinAlias(() => visitAlias.VepId, () => visitorLayEntryPointsAlias) // Depends on where your LocId is .Select(() => visitorVisit.LocId) // I assumed your LocId is an int, switch to string if it's a string .List<int>(); Of course all of this only works if you have the right associations set up in your Mapping configuration (XML or Fluent NHibernate) which is where you should define the two join conditions. * *Many-To-One (Object Reference): http://nhibernate.info/doc/nhibernate-reference/mapping.html#mapping-declaration-manytoone *Many-To-Many or One-To-Many (Collection Reference): http://nhibernate.info/doc/nhibernate-reference/collections.html#collections-ofvalues
Q: NHibernate join multiple tables i have searched the web and couldnt find a satisfying answer. I am attempting to write a QueryOver/CreateCriteria query to get a field from 1 table after joining 3 tables. The SQL query itself is simple, however i wasnt able to convert that into the above format. The query: select LOC_ID from VISITOR_VISIT vv join VISIT v on vv.VISIT_ID = v.VISIT_ID join VISITOR_LAY_ENTRY_POINTS vlep on vlep.VLEP_ID = v.VEP_ID where vv.VIS_ID = PARAMETER A: // Join aliases for ease of getting access to all parts of the query VisitorVisit visitorVisitAlias = null; Visit visitAlias = null; VisitorLayEntryPoints = visitorLayEntryPointsAlias = null; IList<int> locationIds = session.QueryOver<VisitorVisit>() .JoinAlias(() => visitorVisitAlias.VisitId, () => visitAlias) .JoinAlias(() => visitAlias.VepId, () => visitorLayEntryPointsAlias) // Depends on where your LocId is .Select(() => visitorVisit.LocId) // I assumed your LocId is an int, switch to string if it's a string .List<int>(); Of course all of this only works if you have the right associations set up in your Mapping configuration (XML or Fluent NHibernate) which is where you should define the two join conditions. * *Many-To-One (Object Reference): http://nhibernate.info/doc/nhibernate-reference/mapping.html#mapping-declaration-manytoone *Many-To-Many or One-To-Many (Collection Reference): http://nhibernate.info/doc/nhibernate-reference/collections.html#collections-ofvalues
stackoverflow
{ "language": "en", "length": 191, "provenance": "stackexchange_0000F.jsonl.gz:846428", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484897" }
9791f2311390662da57e9b83968300bd448f4c29
Stackoverflow Stackexchange Q: WordPress admin_enqueue_scripts not working I have this code below and it seems not working: function load_custom_wp_admin_style() { wp_register_style( 'custom_wp_admin_css', get_stylesheet_directory_uri() . '/admin-style.css', false, '1.0.0' ); wp_enqueue_style( 'custom_wp_admin_css' ); } add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' ); But when I replace it with wp_enqueue_scripts instead of admin_enqueue_scripts then it will load the file. I'm not sure what's the issue. A: admin_enqueue_scripts() only fires in your back-end admin area (/wp-admin/) - https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts wp_enqueue_scripts() is used to properly enqueue scripts in front-end (https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts) So if your want load stuff in front-end wp_enqueue_scripts() is the way to go. Cheers
Q: WordPress admin_enqueue_scripts not working I have this code below and it seems not working: function load_custom_wp_admin_style() { wp_register_style( 'custom_wp_admin_css', get_stylesheet_directory_uri() . '/admin-style.css', false, '1.0.0' ); wp_enqueue_style( 'custom_wp_admin_css' ); } add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' ); But when I replace it with wp_enqueue_scripts instead of admin_enqueue_scripts then it will load the file. I'm not sure what's the issue. A: admin_enqueue_scripts() only fires in your back-end admin area (/wp-admin/) - https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts wp_enqueue_scripts() is used to properly enqueue scripts in front-end (https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts) So if your want load stuff in front-end wp_enqueue_scripts() is the way to go. Cheers A: add_action( 'admin_enqueue_scripts', 'your_function_name' ); this is use for the backend side work. add_action( 'wp_enqueue_scripts', 'your_function_name' ); this is use for front-end side work.
stackoverflow
{ "language": "en", "length": 117, "provenance": "stackexchange_0000F.jsonl.gz:846451", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484975" }
6a19727cd03cf9d95769b892936ef036b3f47016
Stackoverflow Stackexchange Q: private variable declaration in TypeScript constructor to induce DI To introduce Dependency Injection in Angular 2 using TypeScript, we use the code as below: constructor(private _service : SampleService){} I would like to know the importance of private keyword in the declaration of variable here. Will it impact if we don't declare the service a private? Thanks A: constructor(private _service : SampleService){} is the recommended way to inject a service that you wish to use in the component. If you do not use private, you will have to write more lines of code to access the injected service outside the constructor like below: class CompClass { private _service: SampleService; constructor(service : SampleService) { this._service = service; } doSomething() : void { this._service.makeServiceCall(); } }
Q: private variable declaration in TypeScript constructor to induce DI To introduce Dependency Injection in Angular 2 using TypeScript, we use the code as below: constructor(private _service : SampleService){} I would like to know the importance of private keyword in the declaration of variable here. Will it impact if we don't declare the service a private? Thanks A: constructor(private _service : SampleService){} is the recommended way to inject a service that you wish to use in the component. If you do not use private, you will have to write more lines of code to access the injected service outside the constructor like below: class CompClass { private _service: SampleService; constructor(service : SampleService) { this._service = service; } doSomething() : void { this._service.makeServiceCall(); } }
stackoverflow
{ "language": "en", "length": 124, "provenance": "stackexchange_0000F.jsonl.gz:846456", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484987" }
cdf4a7a7cff4d59316b91ca385efe62e78a295d1
Stackoverflow Stackexchange Q: Turn off right panel magnifier (VScode) How do you turn off the right panel that shows the full code? The app updated and added that right panel that shows the full length of the code. There's no option to turn it out. A: settings.json >> "editor.minimap.enabled": false
Q: Turn off right panel magnifier (VScode) How do you turn off the right panel that shows the full code? The app updated and added that right panel that shows the full length of the code. There's no option to turn it out. A: settings.json >> "editor.minimap.enabled": false A: Alternatively, you can click View > Toggle Minimap
stackoverflow
{ "language": "en", "length": 57, "provenance": "stackexchange_0000F.jsonl.gz:846458", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44484993" }
01543693e59da3ebab1910caa01fcc31f3dda186
Stackoverflow Stackexchange Q: Lambda capture an array element failed The following C++ code makes the compiler GCC(6.3.0) and Clang (3.8.0) mad. for (auto v : vectors2d) for_each (begin(ret), end(ret), [v[3]] (int &n) { n+= v[3];}); While the following is fine for (auto v : vectors2d) { auto val = v[3]; for_each (begin(ret), end(ret), [val] (int &n) { n+= val;}); } I know in C++ 14 I can do something like for (auto v : vectors2d) for_each (begin(ret), end(ret), [val=v[3]] (int &n) { n+= val;}); The error in GCC is expected identifier before '[' token Clang says expected ',' or ']' in lambda capture list My question is: Why it is illegal for [v[3]] to appear in a capture list? A: My question is why it is illegal for [v[3]] in capture list? As described in 5.1.2/1 [expr.prim.lambda] in N4141, the items in a capture list shall be either a simple-capture or an init-capture. The former is any of * *identifier *& identifier *this, the latter either identifier initializer or & identifier initializer. v[3] fits none of the above and is thus correctly rejected by the compiler.
Q: Lambda capture an array element failed The following C++ code makes the compiler GCC(6.3.0) and Clang (3.8.0) mad. for (auto v : vectors2d) for_each (begin(ret), end(ret), [v[3]] (int &n) { n+= v[3];}); While the following is fine for (auto v : vectors2d) { auto val = v[3]; for_each (begin(ret), end(ret), [val] (int &n) { n+= val;}); } I know in C++ 14 I can do something like for (auto v : vectors2d) for_each (begin(ret), end(ret), [val=v[3]] (int &n) { n+= val;}); The error in GCC is expected identifier before '[' token Clang says expected ',' or ']' in lambda capture list My question is: Why it is illegal for [v[3]] to appear in a capture list? A: My question is why it is illegal for [v[3]] in capture list? As described in 5.1.2/1 [expr.prim.lambda] in N4141, the items in a capture list shall be either a simple-capture or an init-capture. The former is any of * *identifier *& identifier *this, the latter either identifier initializer or & identifier initializer. v[3] fits none of the above and is thus correctly rejected by the compiler. A: v[3] is not a variable - it's a complex expression which unfolds to *(v + 3) (if operator[] is not overloaded). So, capturing v[3] is very similar in its spirit to capturing of x * x + y * y - and that makes much less sense. E.g. the compiler would have to accept x * x + y * y inside the lambda, but sometimes reject y * y + x * x because overloaded operators do not have to be commutative. Basically, you ask compiler: "if I use an expression equivalent to what I captured, it's ok, but if I mix variables the other way around, you should give me compiler error". Suppose v[3] was legal. Then all of the following lambdas should be compiled correctly: [v[3]]() { return v[3]; } [v[3]]() { return v[2 * 2 - 1]; } [v[3]](int x) { assert(x == 3); return v[x]; } So if we want "invalid capture" to be a compiler error, the compiler should be able to somehow "prove" that we're not going to access any element in v other than v[3]. This is harder than the halting problem, so it's impossible. We could, of course, make some less strict limitations: e.g. allow only v[3], but not v[2 * 2 - 1] or create some algorithm for detection of such cases that work "good enough", but sometimes provide false negatives. I don't think it's worth the effort - you can always "cache" the expression inside a variable and capture that by value.
stackoverflow
{ "language": "en", "length": 438, "provenance": "stackexchange_0000F.jsonl.gz:846469", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485030" }
96d5f26d220c852a746be3d0b6f7250ff4c1fb34
Stackoverflow Stackexchange Q: Is struct packing deterministic? For example, say I have two equivalent structs a and b in different projects: typedef struct _a { int a; double b; char c; } a; typedef struct _b { int d; double e; char f; } b; Assuming I haven't used any directives like #pragma pack and these structs are compiled on the same compiler for the same architecture with the same optimization settings, will they have identical padding between variables? A: will they have identical padding between variables? In practice, they mostly like to have the same memory layout. In theory, since the standard doesn't say much on how padding should be employed on objects, you can't really assume anything on the padding between the elements. Also, I can't see even why would you want to know/assume something about the padding between the members of a struct. simply write standard, compliant C code and you'll be fine.
Q: Is struct packing deterministic? For example, say I have two equivalent structs a and b in different projects: typedef struct _a { int a; double b; char c; } a; typedef struct _b { int d; double e; char f; } b; Assuming I haven't used any directives like #pragma pack and these structs are compiled on the same compiler for the same architecture with the same optimization settings, will they have identical padding between variables? A: will they have identical padding between variables? In practice, they mostly like to have the same memory layout. In theory, since the standard doesn't say much on how padding should be employed on objects, you can't really assume anything on the padding between the elements. Also, I can't see even why would you want to know/assume something about the padding between the members of a struct. simply write standard, compliant C code and you'll be fine. A: The compiler is deterministic; if it weren't, separate compilation would be impossible. Two different translation units with the same struct declaration will work together; that is guaranteed by §6.2.7/1: Compatible types and composite types. Moreover, two different compilers on the same platform should interoperate, although this is not guaranteed by the standard. (It's a quality of implementation issue.) To allow inter-operability, compiler writers agree on a platform ABI (Application Binary Interface) which will include a precise specification of how composite types are represented. In this way, it is possible for a program compiled with one compiler to use library modules compiled with a different compiler. But you are not just interested in determinism; you also want the layout of two different types to be the same. According to the standard, two struct types are compatible if their members (taken in order) are compatible, and if their tags and member names are the same. Since your example structs have different tags and names, they are not compatible even though their member types are, so you cannot use one where the other is required. It may seem odd that the standard allows tags and member names to affect compatibility. The standard requires that the members of a struct be laid out in declaration order, so names cannot change the order of members within the struct. Why, then, could they affect padding? I don't know of any compiler where they do, but the standard's flexibility is based on the principle that the requirements should be the minimum necessary to guarantee correct execution. Aliasing differently tagged structs is not permitted within a translation unit, so there is no need to condone it between different translation units. And so the standard does not allow it. (It would be legitimate for an implementation to insert information about the type in a struct's padding bytes, even if it needed to deterministically add padding to provide space for such information. The only restriction is that padding cannot be placed before the first member of a struct.) A platform ABI is likely to specify the layout of a composite type without reference to its tag or member names. On a particular platform, with a platform ABI which has such a specification and a compiler documented to conform to the platform ABI, you could get away with the aliasing, although it would not be technically correct, and obviously the preconditions make it non-portable. A: You cannot approach deterministically the layout of a structure or union in C language on different systems. While many times it could seem that the layout generated by different compilers is the same, you must consider the cases a convergence dictated by practical and functional convenience of compiler design in the ambit of choice freedom left to the programmer by the standard, and thus not effective. The C11 standard ISO/IEC 9899:2011, almost unchanged from previous standards, clearly stated in paragraph 6.7.2.1 Structure and union specifiers: Each non-bit-field member of a structure or union object is aligned in an implementation defined manner appropriate to its type. Even worst the case of bitfields where a large autonomy is left to the programmer: An implementation may allocate any addressable storage unit large enough to hold a bitfield. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified. Just count how many times the terms 'implementation-defined' and 'unspecified' appear in the text. Agreed that to check compiler version, machine and target architecture each run before to use structure or union generated on a different system is unaffordable you should have got a decent answer to your question. Now let's say that yes, there is a way-around. Be clear that it is not definitely the solution, but is a common approach that you can found around when data structures exchange is shared between different systems: pack structure elements on value 1 (standard char size). The use of packing and an accurate structure definition can lead to a sufficiently reliable declaration that can be used on different systems. The packing forces the compiler to remove implementation defined alignments, reducing the eventual incompatibilities due to standard. Moreover avoiding to use bitfields you can remove residual implementation dependent inconsistencies. Last, the access efficiency, due to missing alignment can be recreated by manually adding some dummy declaration inbetween elements, crafted in such a way to force back each field on correct alignment. As a residual case you have to consider a padding at structure end that some compilers add, but because there is no useful data associated you can ignore it (unless for dynamic space allocation, but again you can deal with it). A: ISO C says that two struct types in different translation units are compatible if they have the same tag and members. More precisely, here is the exact text from the C99 standard: 6.2.7 Compatible type and composite type Two types have compatible type if their types are the same. Additional rules for determining whether two types are compatible are described in 6.7.2 for type specifiers, in 6.7.3 for type qualifiers, and in 6.7.5 for declarators. Moreover, two structure, union, or enumerated types declared in separate translation units are compatible if their tags and members satisfy the following requirements: If one is declared with a tag, the other shall be declared with the same tag. If both are complete types, then the following additional requirements apply: there shall be a one-to-one correspondence between their members such that each pair of corresponding members are declared with compatible types, and such that if one member of a corresponding pair is declared with a name, the other member is declared with the same name. For two structures, corresponding members shall be declared in the same order. For two structures or unions, corresponding bit-fields shall have the same widths. For two enumerations, corresponding members shall have the same values. It seems very strange if we interpret it from the point of view of, "what, the tag or member names could affect padding?" But basically the rules are simply as strict as they can possibly be while allowing the common case: multiple translation units sharing the exact text of a struct declaration via a header file. If programs follow looser rules, they aren't wrong; they are just not relying on requirements for behavior from the standard, but from elsewhere. In your example, you are running afoul of the language rules, by having only structural equivalence, but not equivalent tag and member names. In practice, this is not actually enforced; struct types with different tags and member names in different translation units are de facto physically compatible anyway. All sorts of technology depends on this, such as bindings from non-C languages to C libraries. If both your projects are in C (or C++), it would probably be worth the effort to try to put the definition into a common header. It's also a good idea to put in some defense against versioning issues, such as a size field: // Widely shared definition between projects affecting interop! // Do not change any of the members. // Add new ones only at the end! typedef struct a { size_t size; // of whole structure int a; double b; char c; } a; The idea is that whoever constructs an instance of a must initialize the size field to sizeof (a). Then when the object is passed to another software component (perhaps from the other project), it can check the size against its sizeof (a). If the size field is smaller, then it knows that the software which constructed a is using an old declaration with fewer members. Therefore, the nonexistent members must not be accessed. A: Any particular compiler ought to be deterministic, but between any two compilers, or even the same compiler with different compilation options, or even between different versions of the same compiler, all bets are off. You're much better off if you don't depend on the details of the structure, or if you do, you should embed code to check at runtime that the structure is actually as you depend. A good example of this is the recent change from 32 to 64 bit architectures, where even if you didn't change the size of integers used in a structure, the default packing of partial integers changed; where previously 3 32bit integers in a row would pack perfectly, now they pack into two 64 bit slots. You can't possibly anticipate what changes may occur in the future; if you depend on details that are not guaranteed by the language, such as structure packing, you ought to verify your assumptions at runtime. A: The C standard itself says nothing about it, so in line of principle you just cannot be sure. But: most probably your compiler adheres to some particular ABI, otherwise communicating with other libraries and with the operating system would be a nightmare. In this last case, the ABI will usually prescribe exactly how packing works. For example: * *on x86_64 Linux/BSD, the SystemV AMD64 ABI is the reference. Here (§3.1) for every primitive processor data type it is detailed the correspondence with the C type, its size and its alignment requirement, and it's explained how to use this data to make up the memory layout of bitfields, structs and unions; everything (besides the actual content of the padding) is specified and deterministic. The same holds for many other architectures, see these links. *ARM recommends its EABI for its processors, and it's generally followed by both Linux and Windows; the aggregates alignment is specified in "Procedure Call Standard for the ARM Architecture Documentation", §4.3. *on Windows there's no cross-vendor standard, but VC++ essentially dictates the ABI, to which virtually any compiler adhere; it can be found here for x86_64, here for ARM (but for the part of interest of this question it just refers to the ARM EABI). A: Any sane compiler will produce identical memory layout for the two structs. Compilers are usually written as perfectly deterministic programs. Non-determinism would need to be added explicitly and deliberately, and I for one fail to see the benefit of doing so. However, that does not allow you to cast a struct _a* to a struct _b* and access its data via both. Afaik, this would still be a violation of strict aliasing rules even if the memory layout is identical, as it would allow the compiler to reorder accesses via the struct _a* with accesses via the struct _b*, which would result in unpredictable, undefined behavior. A: Yes. You should always assume deterministic behaviour from your compiler. [EDIT] From the comments below, it is obvious there are many Java programmers reading the question above. Let's be clear: C structs do not generate any name, hash, or the likes in object files, libraries, or dlls. The C function signatures do not refer to them either. Which means, the member names can be changed at whim - really! - provided the type and order of the member variables is the same. In C, the two structures in the example are equivalent, since packing does not change. which means that the following abuse is perfectly valid in C, and there's certainly much worse abuse to be found in some of the most widely-used libraries. [EDIT2] No one should ever dare to do any of the following in C++ /* the 3 structures below are 100% binary compatible */ typedef struct _a { int a; double b; char c; } typedef struct _b { int d; double e; char f; } typedef struct SOME_STRUCT { int my_i; double my_f; char my_c[1]; } struct _a a = { 1, 2.5, 'z' }; struct _b b; /* the following is valid, copy b -> a */ *(SOME_STRUCT*)&a = *(SOME_STRUCT*)b; assert((SOME_STRUCT*)&a)->my_c[0] == b.f); assert(a.c == b.f); /* more generally these identities are always true. */ assert(sizeof(a) == sizeof(b)); assert(memcmp(&a, &b, sizeof(a)) == 0); assert(pure_function_requiring_a(&a) == pure_function_requiring_a((_a*)&b)); assert(pure_function_requiring_b((b*)&a) == pure_function_requiring_b(&b)); function_requiring_a_SOME_STRUCT_pointer(&a); /* may generate a warning, but not all compiler will */ /* etc... the name space abuse is limited to the programmer's imagination */
stackoverflow
{ "language": "en", "length": 2229, "provenance": "stackexchange_0000F.jsonl.gz:846520", "question_score": "43", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485168" }
2318c3049794cbf44a40537bc0dc042aa4eab9b9
Stackoverflow Stackexchange Q: Dexie: How to reference one dexie db across multiple browsers? Scenario: * *User opens a Dexie webapp in Firefox. *User writes some Dexie data and closes Firefox. *User opens same webapp in Chrome. *User is able to see the Dexie data that had been added previously in Firefox. Can Dexie do this? If Dexie always creates one database per browser, then one workaround might be to read all the relevant Dexie databases on the device and then sync them. I will research that separately in the meantime. Below is just the beginning of my webapp to show the basics of how I'm currently building the Dexie database. Everything works fine. The only issue is that I'd like the app to always read the same database regardless of which browser I'm in. var db = new Dexie("NameOfDexieDB"); db.version(1).stores({ table1: '++id, field1'}); db.open().catch (function (e) { console.log ("Oh oh: " + e.stack); }); A: IndexedDB is local to a single browser. If you want the same data in multiple browsers, you need to sync it with a server.
Q: Dexie: How to reference one dexie db across multiple browsers? Scenario: * *User opens a Dexie webapp in Firefox. *User writes some Dexie data and closes Firefox. *User opens same webapp in Chrome. *User is able to see the Dexie data that had been added previously in Firefox. Can Dexie do this? If Dexie always creates one database per browser, then one workaround might be to read all the relevant Dexie databases on the device and then sync them. I will research that separately in the meantime. Below is just the beginning of my webapp to show the basics of how I'm currently building the Dexie database. Everything works fine. The only issue is that I'd like the app to always read the same database regardless of which browser I'm in. var db = new Dexie("NameOfDexieDB"); db.version(1).stores({ table1: '++id, field1'}); db.open().catch (function (e) { console.log ("Oh oh: " + e.stack); }); A: IndexedDB is local to a single browser. If you want the same data in multiple browsers, you need to sync it with a server.
stackoverflow
{ "language": "en", "length": 177, "provenance": "stackexchange_0000F.jsonl.gz:846530", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485196" }
579d1effa5bb4a1e56187f8863511da78457d809
Stackoverflow Stackexchange Q: Using Firebase in React Native shows a timer warning I am using Firebase with React Native. Firebase shows me a timer warning as shown in the screenshot. I read the following note in the React Native troubleshooting guide. React Native implements a polyfill for WebSockets. These polyfills are initialized as part of the react-native module that you include in your application through import React from 'react'. If you load another module that requires WebSockets, such as Firebase, be sure to load/require it after react-native: import React from 'react'; import Firebase from 'firebase'; I tried import React before Firebase. But, I still keep getting these timer warnings. The application does work fine. I keep getting multiple warnings at regular intervals. Any help would be well appreciated. I am using the latest React Native and the warning comes in the Android emulator. A: To sort this out all need to do is increase the value of the variable MAX_TIMER_DURATION_MS. Here are the steps: * *Go to node_modules/react-native/Libraries/Core/Timer/JSTimers.js *Look for the variable MAX_TIMER_DURATION_MS *Change 60 * 1000 to 10000 * 1000 , needed for firebase *Save the changes and re-build your app.
Q: Using Firebase in React Native shows a timer warning I am using Firebase with React Native. Firebase shows me a timer warning as shown in the screenshot. I read the following note in the React Native troubleshooting guide. React Native implements a polyfill for WebSockets. These polyfills are initialized as part of the react-native module that you include in your application through import React from 'react'. If you load another module that requires WebSockets, such as Firebase, be sure to load/require it after react-native: import React from 'react'; import Firebase from 'firebase'; I tried import React before Firebase. But, I still keep getting these timer warnings. The application does work fine. I keep getting multiple warnings at regular intervals. Any help would be well appreciated. I am using the latest React Native and the warning comes in the Android emulator. A: To sort this out all need to do is increase the value of the variable MAX_TIMER_DURATION_MS. Here are the steps: * *Go to node_modules/react-native/Libraries/Core/Timer/JSTimers.js *Look for the variable MAX_TIMER_DURATION_MS *Change 60 * 1000 to 10000 * 1000 , needed for firebase *Save the changes and re-build your app. A: You could also switch to the native SDK's via a wrapper, it's generally much more performant as it's done natively so there's no timer warnings plus you get access to more than just the auth and database modules. One such wrapper is react-native-firebase and it currently supports 10+ firebase modules: Disclaimer: author of the above. A: It's worked for me to changed to both variable's values. const FRAME_DURATION = 100000 / 60; const MAX_TIMER_DURATION_MS = 60 * 100000; A: Its worked for me also. Go to node_modules/react-native/Libraries/Core/Timer/JSTimers.js Look for the variable MAX_TIMER_DURATION_MS Change 60 * 1000 to 10000 * 1000 , needed for firebase Save the changes and re-build your app. A: It's worked for me to changed values. const FRAME_DURATION = 100000 / 60; const MAX_TIMER_DURATION_MS = 60 * 100000;
stackoverflow
{ "language": "en", "length": 322, "provenance": "stackexchange_0000F.jsonl.gz:846538", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485213" }
7a4d7689cfeca7628d38214ea5e1aaa73c14b4aa
Stackoverflow Stackexchange Q: Getting concurrently scripts to complete I am trying to create a script to run an end-to-end testing suite. I am currently using concurrently and the angular cli, like so: "e2e": "concurrently \"ng e2e --proxy-config proxy.conf.json\" \"cross-env NODE_ENV=development node server\"", It runs fine, but my issue is that obviously whilst the ng e2e command completes, my backend server does not. Is there any way to get the whole command to finish when the tests are complete? A: Found it! Concurrently has already thought of this and helpfully implemented the following switches --kill-others --success first. --kill-others means "if one command completes, kill the other and --success first means "if the first command is successful return a success code for the whole concurrently command.
Q: Getting concurrently scripts to complete I am trying to create a script to run an end-to-end testing suite. I am currently using concurrently and the angular cli, like so: "e2e": "concurrently \"ng e2e --proxy-config proxy.conf.json\" \"cross-env NODE_ENV=development node server\"", It runs fine, but my issue is that obviously whilst the ng e2e command completes, my backend server does not. Is there any way to get the whole command to finish when the tests are complete? A: Found it! Concurrently has already thought of this and helpfully implemented the following switches --kill-others --success first. --kill-others means "if one command completes, kill the other and --success first means "if the first command is successful return a success code for the whole concurrently command.
stackoverflow
{ "language": "en", "length": 122, "provenance": "stackexchange_0000F.jsonl.gz:846569", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485306" }
559e9b9fc91f51571621a01ac75a3cde2e8eabfc
Stackoverflow Stackexchange Q: how to print whole HTML page as A4 I have taken a template from w3-schools, did some research, and tried this by looking into this question: @page { size: 7in 9.25in; margin: 27mm 16mm 27mm 16mm; } I inserted this print code <script> $(document).ready(function() { window.print(); }); </script> And got this result: But this is not I want. I do not want the extra whitespaces around the divs. It should be printed as an A4 page, like this: What should I do to achieve this? PS: Before unleashing frustration, I am a pure backend developer. My partner, who is a front-end dev, is sick for days. Sorry and thank you :) A: Try tweaking those margin values in the CSS snippet you used. Start from: @page { size: 7in 9.25in; margin: 0mm 0mm 0mm 0mm; } … and increase those "0mm" values until you're happy, i.e. 1mm, 2mm, etc. Those 4 values (all currently 0mm in my example) represent the top margin, right margin, bottom margin and left margin of the printed page, in order. So if you only want to increase the margin from the bottom of the page, you'd change the third 0mm in that line.
Q: how to print whole HTML page as A4 I have taken a template from w3-schools, did some research, and tried this by looking into this question: @page { size: 7in 9.25in; margin: 27mm 16mm 27mm 16mm; } I inserted this print code <script> $(document).ready(function() { window.print(); }); </script> And got this result: But this is not I want. I do not want the extra whitespaces around the divs. It should be printed as an A4 page, like this: What should I do to achieve this? PS: Before unleashing frustration, I am a pure backend developer. My partner, who is a front-end dev, is sick for days. Sorry and thank you :) A: Try tweaking those margin values in the CSS snippet you used. Start from: @page { size: 7in 9.25in; margin: 0mm 0mm 0mm 0mm; } … and increase those "0mm" values until you're happy, i.e. 1mm, 2mm, etc. Those 4 values (all currently 0mm in my example) represent the top margin, right margin, bottom margin and left margin of the printed page, in order. So if you only want to increase the margin from the bottom of the page, you'd change the third 0mm in that line.
stackoverflow
{ "language": "en", "length": 199, "provenance": "stackexchange_0000F.jsonl.gz:846600", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485409" }
d34147da15ee48f0745106efa107e4a17c594f9b
Stackoverflow Stackexchange Q: Using a relative path in executable with symbolic link I'm trying to figure out how to use my application with a link in ubuntu. I've compiled the code and it contains relative paths to certain files. When I create a link to the executable in a different directory, I can't use these paths. Is there a way (in my code or in the creation of the link) to make it work with the relative paths? Thanks A: Is it realpath you're after? Something like this (source for test in below example): #include <iostream> #include <cstdlib> int main(int argc, char *argv[]) { char *path = realpath(argv[0], NULL); std::cout << path << '\n'; free(path); return 0; } Example execution: $ ln -s tmp/test $ ./test /home/mlil/tmp/test $
Q: Using a relative path in executable with symbolic link I'm trying to figure out how to use my application with a link in ubuntu. I've compiled the code and it contains relative paths to certain files. When I create a link to the executable in a different directory, I can't use these paths. Is there a way (in my code or in the creation of the link) to make it work with the relative paths? Thanks A: Is it realpath you're after? Something like this (source for test in below example): #include <iostream> #include <cstdlib> int main(int argc, char *argv[]) { char *path = realpath(argv[0], NULL); std::cout << path << '\n'; free(path); return 0; } Example execution: $ ln -s tmp/test $ ./test /home/mlil/tmp/test $ A: In linux: ln -sr <source relative path> <destination relative path> You can verify the symbolic link created in the desination by navigating to that directory and typing the command: ls -l The accepted answer is the one that should be used if it is an executable, which is what your question is about. If outside an executable, this is a quick an easy solution.
stackoverflow
{ "language": "en", "length": 191, "provenance": "stackexchange_0000F.jsonl.gz:846604", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485421" }
12d10093db69326a4c31adef46f2b253c5fa54c9
Stackoverflow Stackexchange Q: Error:null value in entry: aaptFriendlyManifestOutputFile=null I keep getting error when building my project in Android Studio Error:null value in entry: aaptFriendlyManifestOutputFile=null How do I fix this A: delete the folder on this path : ...\.gradle\3.3\taskArtifacts and build project again, this folder build by gradle again. Now everything works.
Q: Error:null value in entry: aaptFriendlyManifestOutputFile=null I keep getting error when building my project in Android Studio Error:null value in entry: aaptFriendlyManifestOutputFile=null How do I fix this A: delete the folder on this path : ...\.gradle\3.3\taskArtifacts and build project again, this folder build by gradle again. Now everything works. A: You dont need to delete whole .gradle folder and in new android studio you might not find the taskArtifacts file so delete taskHistory file only and rebuild the project. A: Deleting the .gradle folder in the project root directory solved the problem. Just rebuild the project afterwards.
stackoverflow
{ "language": "en", "length": 97, "provenance": "stackexchange_0000F.jsonl.gz:846625", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485479" }
a19cbfbcf6080ded0c850ee970533e1778637c34
Stackoverflow Stackexchange Q: Hiding an SVG element in HTML without disabling clip paths defined inside? With reference to the question clip-path not working in SVG sprite, it seems we can't use style="display:none" to hide an SVG element that defines a clip path that will be used elsewhere. However, the suggested alternative for hiding it given (using width="0" height="0") is not working for me (at least in Chrome, the SVG element still gets allocated space in the page layout, which causes a vertical scroll bar to appear, as I have a div with height="100%" above it). What other was are available for hiding an SVG that won't stop it being used for clipping? A: In the end, I used position:absolute to take the item out of the usual HTML document flow. I don't understand why a zero-sized element would cause scrollbars to appear, but that certainly seemed to be what was happening.
Q: Hiding an SVG element in HTML without disabling clip paths defined inside? With reference to the question clip-path not working in SVG sprite, it seems we can't use style="display:none" to hide an SVG element that defines a clip path that will be used elsewhere. However, the suggested alternative for hiding it given (using width="0" height="0") is not working for me (at least in Chrome, the SVG element still gets allocated space in the page layout, which causes a vertical scroll bar to appear, as I have a div with height="100%" above it). What other was are available for hiding an SVG that won't stop it being used for clipping? A: In the end, I used position:absolute to take the item out of the usual HTML document flow. I don't understand why a zero-sized element would cause scrollbars to appear, but that certainly seemed to be what was happening.
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:846630", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485500" }
aa9db0c16a0efc7c2c43f7cd11355cb0238a5a8b
Stackoverflow Stackexchange Q: Apache POI release 3.16 no longer working on Android? after switching from Apache POI release 3.15 to 3.16 (https://poi.apache.org/), my app crashes with this exception: UncaughtException: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Color; at org.apache.poi.hssf.util.HSSFColor$HSSFColorPredefined.<init>(HSSFColor.java:113) at org.apache.poi.hssf.util.HSSFColor$HSSFColorPredefined.<clinit>(HSSFColor.java:55) at org.apache.poi.hssf.util.HSSFColor$BLUE.<clinit>(HSSFColor.java:549) I realize that this is because java.awt.* is not available on Android, but wonder why I didn't encounter this issue using the 3.15 release? My code has not changed. Is there a solution to be able to use the 3.16 version on Android?
Q: Apache POI release 3.16 no longer working on Android? after switching from Apache POI release 3.15 to 3.16 (https://poi.apache.org/), my app crashes with this exception: UncaughtException: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Color; at org.apache.poi.hssf.util.HSSFColor$HSSFColorPredefined.<init>(HSSFColor.java:113) at org.apache.poi.hssf.util.HSSFColor$HSSFColorPredefined.<clinit>(HSSFColor.java:55) at org.apache.poi.hssf.util.HSSFColor$BLUE.<clinit>(HSSFColor.java:549) I realize that this is because java.awt.* is not available on Android, but wonder why I didn't encounter this issue using the 3.15 release? My code has not changed. Is there a solution to be able to use the 3.16 version on Android?
stackoverflow
{ "language": "en", "length": 81, "provenance": "stackexchange_0000F.jsonl.gz:846634", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485522" }
4149a5b5c6fec0235ed9dfb5685cd4d0c445f1ba
Stackoverflow Stackexchange Q: Web scraping image inside canvas I am web scraping a page where with various numbers appears also images of small price charts. If I click on this images inside the browser I can save that chart as a .png image. When I look at the source code that element looks like this when inspected: <div class="performance_2d_sparkline graph ng-isolate-scope ng-scope" x-data-percent-change-day="ticker.pct_chge_1D" x-sparkline="watchlistData.sparklineData[ticker.ticker]"> <span class="inlinesparkline ng-binding"> <canvas width="100" height="40" style="display: inline-block; width: 100px; height: 40px; vertical-align: top;"> </canvas> </span> </div> Is there any way I can save through web scraping the same images that I can save manually through the browser? A: If you are using Selenium for your web scraping, you can get the canvas element and save it to the image file using the following code snippet: # get the base64 representation of the canvas image (the part substring(21) is for removing the padding "data:image/png;base64") base64_image = driver.execute_script("return document.querySelector('.inlinesparkline canvas').toDataURL('image/png').substring(21);") # decode the base64 image output_image = base64.b64decode(base64_image) # save to the output image with open("image.png", 'wb') as f: f.write(output_image)
Q: Web scraping image inside canvas I am web scraping a page where with various numbers appears also images of small price charts. If I click on this images inside the browser I can save that chart as a .png image. When I look at the source code that element looks like this when inspected: <div class="performance_2d_sparkline graph ng-isolate-scope ng-scope" x-data-percent-change-day="ticker.pct_chge_1D" x-sparkline="watchlistData.sparklineData[ticker.ticker]"> <span class="inlinesparkline ng-binding"> <canvas width="100" height="40" style="display: inline-block; width: 100px; height: 40px; vertical-align: top;"> </canvas> </span> </div> Is there any way I can save through web scraping the same images that I can save manually through the browser? A: If you are using Selenium for your web scraping, you can get the canvas element and save it to the image file using the following code snippet: # get the base64 representation of the canvas image (the part substring(21) is for removing the padding "data:image/png;base64") base64_image = driver.execute_script("return document.querySelector('.inlinesparkline canvas').toDataURL('image/png').substring(21);") # decode the base64 image output_image = base64.b64decode(base64_image) # save to the output image with open("image.png", 'wb') as f: f.write(output_image)
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:846669", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485616" }
79040fa376e674b15e1121d1b3d6e12cd61503f3
Stackoverflow Stackexchange Q: Room Persistence: Error:Entities and Pojos must have a usable public constructor I'm converting a project to Kotlin and I'm trying to make my model (which is also my entity) a data class I intend to use Moshi to convert the JSON responses from the API @Entity(tableName = "movies") data class MovieKt( @PrimaryKey var id : Int, var title: String, var overview: String, var poster_path: String, var backdrop_path: String, var release_date: String, var vote_average: Double, var isFavorite: Int ) I can't build the app cause of the following error Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type). Cannot find setter for field. The examples I found are not far from this Ideas on how to solve it? A: I also had this issue, but i realized the problem was that i added the @Embedded annotation to a property that already had a type converter, so anyone having the same problem should check the property declarations for your model class carefully and make sure the @Embedded annotation is not on a property that has a type converter associated with it.
Q: Room Persistence: Error:Entities and Pojos must have a usable public constructor I'm converting a project to Kotlin and I'm trying to make my model (which is also my entity) a data class I intend to use Moshi to convert the JSON responses from the API @Entity(tableName = "movies") data class MovieKt( @PrimaryKey var id : Int, var title: String, var overview: String, var poster_path: String, var backdrop_path: String, var release_date: String, var vote_average: Double, var isFavorite: Int ) I can't build the app cause of the following error Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type). Cannot find setter for field. The examples I found are not far from this Ideas on how to solve it? A: I also had this issue, but i realized the problem was that i added the @Embedded annotation to a property that already had a type converter, so anyone having the same problem should check the property declarations for your model class carefully and make sure the @Embedded annotation is not on a property that has a type converter associated with it. A: I spent an hour trying to figure this out with no success. This is what I found. I forgot to add the return type in one of my Queries this resulted with the POJO error @Query("SELECT userNote FROM CardObject WHERE identifier = :identifier") suspend fun getUserNote(identifier: String) No POJO error @Query("SELECT userNote FROM CardObject WHERE identifier = :identifier") suspend fun getUserNote(identifier: String): String A: It's not a problem in your case, but for others, this error can occur if you have @Ignore params in your primary constructor, i.e. Room expects to have either: * *parameterless constructor or *constructor with all fields not marked with @Ignore for example: @Entity(tableName = "movies") data class MovieKt( @PrimaryKey var id : Int, var title: String, @Ignore var overview: String) will not work. This will: @Entity(tableName = "movies") data class MovieKt( @PrimaryKey var id : Int, var title: String) A: I think that a good option for resolve it is: @Entity(tableName = "movies") data class MovieKt( @PrimaryKey var id : Int = 0, var title: String = "", var overview: String = "", var poster_path: String = "", var backdrop_path: String = "", var release_date: String = "", var vote_average: Double = 0.0, var isFavorite: Int = 0 ) A: Had a similar issue before. First I've updated/added apply plugin: 'kotlin-kapt' to gradle. Next, I've used it instead of annotationProcessor in gradle: kapt "android.arch.persistence.room:compiler:1.0.0-alpha4" Tha last thing was to create an immutable data class: @Entity(tableName = "movies") data class MovieKt( @PrimaryKey val id : Int, val title: String, val overview: String, val poster_path: String, val backdrop_path: String, val release_date: String, val vote_average: Double, val isFavorite: Int ) UPDATE: This solution works when you have classes for the model and classes for Database in the same Android Module. If you have model classes in Android Library module and the rest of the code in your main module, Room will NOT recognize them. A: I had the same issue. You can move the @Ignore fields to class body. For example : @Entity(tableName = "movies") data class MovieKt( @PrimaryKey var id : Int, var title: String ){ //here @Ignore var overview: String } A: For me, I was using 'lat' & 'long' as a variable name in the data(Entity) class for kotlin so renaming to latitude & longitude it worked. Not working: @Entity(tableName = "table_User") data class User(@PrimaryKey var userId : Int, @ColumnInfo(name = "first_name") var firstName: String , @ColumnInfo(name = "last_name") var lastName: String , @ColumnInfo(name = "password") var password: String , @ColumnInfo(name = "dob") var dob: Long , @ColumnInfo(name = "address") var address: String , @ColumnInfo(name = "lat") var latitude: Double , @ColumnInfo(name = "long") var longitude: Double) { } Working: @Entity(tableName = "table_User") data class User(@PrimaryKey var userId : Int, @ColumnInfo(name = "first_name") var firstName: String , @ColumnInfo(name = "last_name") var lastName: String , @ColumnInfo(name = "password") var password: String , @ColumnInfo(name = "dob") var dob: Long , @ColumnInfo(name = "address") var address: String , @ColumnInfo(name = "latitude") var latitude: Double , @ColumnInfo(name = "longitude") var longitude: Double) { } A: you need to specify a secondary constructor like so: @Entity(tableName = "movies") data class MovieKt( @PrimaryKey var id : Int, var title: String, var overview: String, var poster_path: String, var backdrop_path: String, var release_date: String, var vote_average: Double, var isFavorite: Int ) { constructor() : this(0, "", "", "", "", "", 0.0, 0) } A: To expand on the answers provided by @evanchooly and @daneejela, you need a secondary constructor to be able to use @Ignore parameters in your primary constructor. This is so Room still has a constructor that it can use when instantiating your object. Per your example, if we ignore one of the fields: @Entity(tableName = "movies") data class MovieKt( @PrimaryKey var id : Int, var title: String, var overview: String, var poster_path: String, var backdrop_path: String, @Ignore var release_date: String, @Ignore var vote_average: Double, @Ignore var isFavorite: Int ) { constructor(id: Int, title: String, overview: String, poster_path: String, backdrop_path: String) : this(id, title, overview, poster_path, backdrop_path, "", 0.0, 0) } A: I had this problem with an entity (all fields were properly-initialized vars like a lot of the answers here are suggesting) that included a list of related, non-primitive items like the OP in this SO question had. For example: @Entity(tableName = "fruits") data class CachedFruitEntity( @PrimaryKey var id: Long = 0L, @Embedded(prefix = "buyer_") var buyerEntity: CachedBuyerEntity? = null @TypeConverters(VendorsConverter::class) var vendorEntities: List<CachedVendorEntity?> = listOf())) That is, it has an embedded field, and it took me a while to realize that what I actually needed was a type converter for the vendor entity list instead (the compiler wasn't throwing the usual Error:(58, 31) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it. So my solution was very similar to this answer This google architecture components github thread has more info on this misleading error, but not sure if the issue has been fixed yet. A: Like it's said in the Room docs, you are required to make an empty public constructor. At the same time, if you want to declare other custom constructors, you must add @Ignore annotation. @Entity public class CartItem { @PrimaryKey public int product_id; public int qty; public CartItem() { } @Ignore public CartItem(int product_id, int count) { this.product_id = product_id; this.qty = count; } } A: What worked for me: @Entity(tableName = "movies") data class MovieKt( @PrimaryKey var id : Int? = 0, var title: String? = "", var overview: String? = "", var poster_path: String? = "", var backdrop_path: String? = "", var release_date: String? = "", var vote_average: Double? = 0.0, var isFavorite: Int? = 0 ) A: Kotlin allows long as a parameter name, but this won't work when room generates java code. A: Today I was having this problem. I used @Ignore, that is why I got the error. To solve this I created a secondary constructor. So my code looks something like this: @Entity(tableName = "profile") data class Profile( @field:SerializedName("id") @PrimaryKey @ColumnInfo(name = "id") var id:Long, @field:SerializedName("foo") @ColumnInfo(name = "foo") var foo:String?, @field:SerializedName("bar") @Ignore var Bar:String? ){ constructor(id:Long, foo:String) : this(id, foo, null) } This worked for me. A: For me all I had to do was to add a constructor to the data class with empty params sent to it like so: @Entity(tableName = "posts") data class JobPost( @Ignore @SerializedName("companyLogo") var companyLogo: String, @Ignore @SerializedName("companyName") var companyName: String, @Ignore @SerializedName("isAggregated") var isAggregated: String, @PrimaryKey(autoGenerate = false) @SerializedName("jobID") var jobID: String, @Ignore @SerializedName("jobTitle") var jobTitle: String, @Ignore @SerializedName("postedOn") var postedOn: String, @Ignore @SerializedName("region") var region: String ) { constructor() : this("","","","","","","") } A: It turned out to be a bug on the library https://github.com/googlesamples/android-architecture-components/issues/49 A: https://issuetracker.google.com/issues/62851733 i found this is @Relation's projection bug! not Kotlin language problem. based google GithubBrowserSample java also happend error, but different error message. below is my kotlin code: data class UserWithCommunities( @Embedded var user: User = User(0, null), @Relation(parentColumn = "id", entityColumn = "users_id", entity = CommunityUsers::class, projection = arrayOf("communities_id")) // delete this line. var communityIds: List<Int> = emptyList() ) right: data class UserWithCommunities( @Embedded var user: User = User(0, null), @Relation(parentColumn = "id", entityColumn = "users_id", entity = CommunityUsers::class) var communityList: List<CommunityUsers> = emptyList() ) A: Same bug, much stranger solution: Do not return cursor using reactivex Maybe<Cursor> on your Dao. Flowable, Single, and Observable did not work either. Simply bite the bullet and make the reactive call outside the Dao request. Before: @Dao interface MyDao{ @Query("SELECT * FROM mydao") fun getCursorAll(): Flowable<Cursor> } After: @Dao interface MyDao{ @Query("SELECT * FROM mydao") fun getCursorAll(): Cursor } Meta: Android Studio 3.2 Build #AI-181.5540.7.32.5014246, built on September 17, 2018 JRE: 1.8.0_152-release-1136-b06 x86_64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o macOS 10.12.6 A: Just add the below annotation to any constructor that causes the errors and add a new blank constructor. @Ignore A: With 2.1.0-alpha6, it turned out to be an invalid return type in Dao. Fixing the return type as expected fixed it. A: Kotlin plugin doesn't pick up annotationProcessor dependencies, So use the latest version of Kotlin annotation processor - put this line at top of your module's level build.gradle file apply plugin: 'kotlin-kapt' like apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' // add this line android { compileSdkVersion 28 defaultConfig { ........ } } Don't forget to change the compileSdkVersion accordingly. A: I had the same problem and the reason was because the type of data I was getting by query in dao , was not equal to the type of data I was returning. The type of id in my database was String and I changed the dao from: @Query("SELECT id FROM content_table") fun getIds(): Flow<List<Int>> To : @Query("SELECT id FROM content_table") fun getIds(): Flow<List<String>> A: For this issue, I had the same problem. Replace the Room Dependencies with that of the latest one present in the official docs A: As stated in Room Database Entity: Each entity must either have a no-arg constructor or a constructor whose parameters match fields (based on type and name). So adding an empty constructor and annotating your parameterized constructor with @Ignore will solve your problem. An example: public class POJO { long id; String firstName; @Ignore String lastName; public POJO() { } @Ignore public POJO(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } // getters and setters // ... } A: make sure room database column name and field name in constructor are same A: In my case I had the @Ignore Tags and 'kotlin-kapt' plugin but still this started to happen after updating to kotlin to version 1.5.0. I ended up updating my room library from version 2.2.5 to 2.3.0 and the problem was fixed. A: another problem with @Entity data class SomeEnity( @PrimaryKey(autoGenerate = true) val id: Long = 0, val filed: SomeClass ) **inline** class SomeClass consider to remove inline class A: If u use Java. Then my solution was to only ADD @Nonull in the constructor constructor(@Nonull String, A: I've been having this error for the longest time. And so I want to give tips to those who are facing the same problem, it may help you. * *Add all these dependencies or choose the one you will be using : https://developer.android.com/jetpack/androidx/releases/lifecycle *Make sure while creating your Class (in my case Public Class Message) it implements Serializable (example) *Avoid naming your attr with capital in front, it will be hard for the DAO_impl to detect. If you want to then make sure the getter and setter is also capitalized. A: In my case I was using datatype name long as a field name @Entity(tableName = "MyLocations") data class MyLocationModel( @PrimaryKey(autoGenerate = true) val id: Int = 0, var name: String, val stored: Boolean, val lat: Double, val long: Double ) just changed long to lon worked for me @Entity(tableName = "MyLocations") data class MyLocationModel( @PrimaryKey(autoGenerate = true) val id: Int = 0, var name: String, val stored: Boolean, val lat: Double, val lon: Double ) A: For a variation on FutureShocked answer that implements autoGenerate: @Entity(tableName = "movies") data class MovieKt( var title: String, var overview: String, var poster_path: String, var backdrop_path: String, @Ignore var release_date: String, @Ignore var vote_average: Double, @Ignore var isFavorite: Int ) { @PrimaryKey(autoGenerate = true) var id : Int = 0 constructor(title: String, overview: String, poster_path: String, backdrop_path: String) { this(id, title, overview, poster_path, backdrop_path, "", 0.0, 0) } } A: Don't use to dataclass,use normal class instead. This method will solve problem A: In my case I wasn't returning type in one of the Dao query hope it helps others Thanks
stackoverflow
{ "language": "en", "length": 2131, "provenance": "stackexchange_0000F.jsonl.gz:846674", "question_score": "105", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485631" }
d1f82455b033ab4621fd9ceab3f63fa1467f9dd7
Stackoverflow Stackexchange Q: ShareThis icons resizing Please I need to know is there any way I can resize ShareThis sharing buttons on my website? The problem is that it is very small when rendered on a mobile device. I need to make it larger. Is it possible? or it is fixed and can not be changed since we are retrieving it from the server? A: This might be a late reply. I work at ShareThis, and I believe this is definitely solvable. We have our new SOP (Social Optimization Platform) for customizing your buttons at https://platform.sharethis.com. And you can install and customize your buttons there. And if you are using reactjs, we recently released our reactjs plugin at https://www.npmjs.com/package/sharethis-reactjs, and you can customize your buttons through the configuration. Find more details in the documentation, and if you have more questions, I'm glad to help.
Q: ShareThis icons resizing Please I need to know is there any way I can resize ShareThis sharing buttons on my website? The problem is that it is very small when rendered on a mobile device. I need to make it larger. Is it possible? or it is fixed and can not be changed since we are retrieving it from the server? A: This might be a late reply. I work at ShareThis, and I believe this is definitely solvable. We have our new SOP (Social Optimization Platform) for customizing your buttons at https://platform.sharethis.com. And you can install and customize your buttons there. And if you are using reactjs, we recently released our reactjs plugin at https://www.npmjs.com/package/sharethis-reactjs, and you can customize your buttons through the configuration. Find more details in the documentation, and if you have more questions, I'm glad to help.
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:846681", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485650" }
15ffb0e35efcc16dbdba58e5f81806f604f4cd10
Stackoverflow Stackexchange Q: Two buttons sharing a row in react-native I have two buttons that look like this This is the code render = () => ( <Image source={require('../../images/login.jpg')} style={[AppStyles.containerCentered, AppStyles.container, styles.background]} > <Image source={require('../../images/logo.png')} style={[styles.logo]} /> <Spacer size={200} /> <View style={[AppStyles.row, AppStyles.paddingHorizontal]}> <View style={[AppStyles.flex1]}> <Button title={'Login'} icon={{ name: 'lock' }} onPress={Actions.login} /> </View> </View> <Spacer size={10} /> <View style={[AppStyles.row, AppStyles.paddingHorizontal]}> <View style={[AppStyles.flex1]}> <Button title={'Sign up'} backgroundColor={'#FB6567'} icon={{ name: 'face' }} onPress={Actions.signUp} /> </View> </View> </Image> ) I want the buttons to occupy one row and possibly share 40% - 40% of the space with the rest of the 20% going to the padding. How can i have them occupy one row?. A: You'd need to define a container with flexDirection set to row and use justifyContent depending on where you want your padding: render() { return ( <View style={styles.container}> <View style={styles.button} /> <View style={styles.button} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', justifyContent: 'space-between' }, button: { backgroundColor: 'green', width: '40%', height: 40 } }); Change space-between to space-around if you want the padding to be distributed to the sides too. (Demo)
Q: Two buttons sharing a row in react-native I have two buttons that look like this This is the code render = () => ( <Image source={require('../../images/login.jpg')} style={[AppStyles.containerCentered, AppStyles.container, styles.background]} > <Image source={require('../../images/logo.png')} style={[styles.logo]} /> <Spacer size={200} /> <View style={[AppStyles.row, AppStyles.paddingHorizontal]}> <View style={[AppStyles.flex1]}> <Button title={'Login'} icon={{ name: 'lock' }} onPress={Actions.login} /> </View> </View> <Spacer size={10} /> <View style={[AppStyles.row, AppStyles.paddingHorizontal]}> <View style={[AppStyles.flex1]}> <Button title={'Sign up'} backgroundColor={'#FB6567'} icon={{ name: 'face' }} onPress={Actions.signUp} /> </View> </View> </Image> ) I want the buttons to occupy one row and possibly share 40% - 40% of the space with the rest of the 20% going to the padding. How can i have them occupy one row?. A: You'd need to define a container with flexDirection set to row and use justifyContent depending on where you want your padding: render() { return ( <View style={styles.container}> <View style={styles.button} /> <View style={styles.button} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', justifyContent: 'space-between' }, button: { backgroundColor: 'green', width: '40%', height: 40 } }); Change space-between to space-around if you want the padding to be distributed to the sides too. (Demo)
stackoverflow
{ "language": "en", "length": 187, "provenance": "stackexchange_0000F.jsonl.gz:846682", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485653" }
92a01a012f7a5ef309a4898f334c4bd49a1608c8
Stackoverflow Stackexchange Q: Android crash related to android.app.LoadedApk.makeApplication(LoadedApk.java:563) An app gets quite a few crashes with the following stack trace java.lang.RuntimeException: at android.app.LoadedApk.makeApplication(LoadedApk.java:563) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4530) at android.app.ActivityThread.access$1500(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5258) at java.lang.reflect.Method.invoke(Native Method:0) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:735) Caused by: java.lang.IllegalStateException: at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:409) at android.app.LoadedApk.makeApplication(LoadedApk.java:555) The stack trace does not have any trace of the app's code. Considering the large user base, it is relatively rare (about 1 per 10K active devices per day). I cannot figure out any clues from the above information. Could anyone shed some light on this to help prevent this crash? Edit (2017-06-14): The following screenshot of Google Play Console shows that the top 6 crash clusters do not have app code in their stack traces: java.lang.IllegalArgumentException in android.view.WindowManagerGlobal.findViewLocked java.lang.IllegalArgumentException in android.view.WindowManagerGlobal.findViewLocked java.lang.IllegalArgumentException in android.view.WindowManagerGlobal.findViewLocked in tgkill in tgkill java.lang.IllegalStateException in android.app.LoadedApk.initializeJavaContextClassLoader
Q: Android crash related to android.app.LoadedApk.makeApplication(LoadedApk.java:563) An app gets quite a few crashes with the following stack trace java.lang.RuntimeException: at android.app.LoadedApk.makeApplication(LoadedApk.java:563) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4530) at android.app.ActivityThread.access$1500(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5258) at java.lang.reflect.Method.invoke(Native Method:0) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:735) Caused by: java.lang.IllegalStateException: at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:409) at android.app.LoadedApk.makeApplication(LoadedApk.java:555) The stack trace does not have any trace of the app's code. Considering the large user base, it is relatively rare (about 1 per 10K active devices per day). I cannot figure out any clues from the above information. Could anyone shed some light on this to help prevent this crash? Edit (2017-06-14): The following screenshot of Google Play Console shows that the top 6 crash clusters do not have app code in their stack traces: java.lang.IllegalArgumentException in android.view.WindowManagerGlobal.findViewLocked java.lang.IllegalArgumentException in android.view.WindowManagerGlobal.findViewLocked java.lang.IllegalArgumentException in android.view.WindowManagerGlobal.findViewLocked in tgkill in tgkill java.lang.IllegalStateException in android.app.LoadedApk.initializeJavaContextClassLoader
stackoverflow
{ "language": "en", "length": 141, "provenance": "stackexchange_0000F.jsonl.gz:846730", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485814" }
9e28b448ede53e8daa98bd611e61d5d29eeac97b
Stackoverflow Stackexchange Q: PostgreSQL: UPDATE row if exists I need update row in the table only if row exists. UPDATE table1 SET ctime = now() WHERE id = 112233; Or with select before IF EXISTS (SELECT 1 FROM table1 WHERE id = 112233) THEN UPDATE table1 SET ctime = now() WHERE id = 112233; END IF; Which query better to reduce write operations? For performance purpose, do I need to do SELECT before UPDATE to check row exists? A: This query: UPDATE table1 SET ctime = now() WHERE id = 112233; Does exactly what you want. It updates all rows that match the WHERE condition -- over zero rows. If you are concerned about performance, create an index on table1(id). If id is a primary key, then it already has an index.
Q: PostgreSQL: UPDATE row if exists I need update row in the table only if row exists. UPDATE table1 SET ctime = now() WHERE id = 112233; Or with select before IF EXISTS (SELECT 1 FROM table1 WHERE id = 112233) THEN UPDATE table1 SET ctime = now() WHERE id = 112233; END IF; Which query better to reduce write operations? For performance purpose, do I need to do SELECT before UPDATE to check row exists? A: This query: UPDATE table1 SET ctime = now() WHERE id = 112233; Does exactly what you want. It updates all rows that match the WHERE condition -- over zero rows. If you are concerned about performance, create an index on table1(id). If id is a primary key, then it already has an index.
stackoverflow
{ "language": "en", "length": 130, "provenance": "stackexchange_0000F.jsonl.gz:846753", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44485885" }
9413d9f03c26dc1a86ac564f53465835c2621b0d
Stackoverflow Stackexchange Q: React-Native picker - change font size I want to change the font size of the picker plus format the picker items. I've followed the instructions in the following link, re-run react-native run-android, but nothing changes. How to style the standard react-native android picker? A: It can be styled via native android. See this and this. Add the following code to /res/values/styles.xml ... <style name="SpinnerItem" parent="Theme.AppCompat.Light.NoActionBar">> <item name="android:fontFamily">sans-serif-light</item> <item name="android:textSize">18dp</item> </style> <style name="SpinnerDropDownItem" parent="Theme.AppCompat.Light.NoActionBar">> <item name="android:textColor">#ffffff</item> <item name="android:textSize">18dp</item> <item name="android:fontFamily">sans-serif-light</item> <item name="android:gravity">center</item> <item name="android:background">@drawable/mydivider</item> </style> Create a file at res/drawable/mydivider.xml and add the following code <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#29A1C9" /> <corners android:radius="0.5dp" /> <stroke android:color="#FFFFFF" android:width="0.1dp" /> </shape>
Q: React-Native picker - change font size I want to change the font size of the picker plus format the picker items. I've followed the instructions in the following link, re-run react-native run-android, but nothing changes. How to style the standard react-native android picker? A: It can be styled via native android. See this and this. Add the following code to /res/values/styles.xml ... <style name="SpinnerItem" parent="Theme.AppCompat.Light.NoActionBar">> <item name="android:fontFamily">sans-serif-light</item> <item name="android:textSize">18dp</item> </style> <style name="SpinnerDropDownItem" parent="Theme.AppCompat.Light.NoActionBar">> <item name="android:textColor">#ffffff</item> <item name="android:textSize">18dp</item> <item name="android:fontFamily">sans-serif-light</item> <item name="android:gravity">center</item> <item name="android:background">@drawable/mydivider</item> </style> Create a file at res/drawable/mydivider.xml and add the following code <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#29A1C9" /> <corners android:radius="0.5dp" /> <stroke android:color="#FFFFFF" android:width="0.1dp" /> </shape>
stackoverflow
{ "language": "en", "length": 109, "provenance": "stackexchange_0000F.jsonl.gz:846794", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486033" }
abf5f9527c0cbda037be1c9fd9d3ce25307bdcbd
Stackoverflow Stackexchange Q: In pandas, how to query for a list? Let's say I have a DataFrame that has lists as its values: df = pd.DataFrame({'languages': [['en'], ['fr']], 'author': ['Dickens, Charles', 'Austen, Jane']}) I can query it for strings easily: df[df['author'] == 'Dickens, Charles'] which correctly returns the subset of df that matches that criteria. But when I have cell contents that are lists, such as languages whose values are things like ['en'], I can't seem to search for it: df[df['languages'] == ['en']] I get: ValueError: Arrays were different lengths: 2 vs 1 How can I query for contents that are a list? A: What you might do is use apply method to loop through the languages column and then compare the items: df[df.languages.apply(lambda x: x == ['en'])] # author languages #0 Dickens, Charles [en]
Q: In pandas, how to query for a list? Let's say I have a DataFrame that has lists as its values: df = pd.DataFrame({'languages': [['en'], ['fr']], 'author': ['Dickens, Charles', 'Austen, Jane']}) I can query it for strings easily: df[df['author'] == 'Dickens, Charles'] which correctly returns the subset of df that matches that criteria. But when I have cell contents that are lists, such as languages whose values are things like ['en'], I can't seem to search for it: df[df['languages'] == ['en']] I get: ValueError: Arrays were different lengths: 2 vs 1 How can I query for contents that are a list? A: What you might do is use apply method to loop through the languages column and then compare the items: df[df.languages.apply(lambda x: x == ['en'])] # author languages #0 Dickens, Charles [en] A: We can use some trickery to get this to run faster. Note that this avoids the use of apply. # create a numpy array of lists... one list to be exact c = np.empty(1, object) c[0] = ['en'] df[df.languages.values == c] author languages 0 Dickens, Charles [en] A: I typically use an isin() filter and pass a list as an argument. lst = ['A', 'B'] df[df['column'].isin(lst)]
stackoverflow
{ "language": "en", "length": 200, "provenance": "stackexchange_0000F.jsonl.gz:846829", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486137" }
fdafbe234c3f911bd204ea50d756e49814e9a800
Stackoverflow Stackexchange Q: Angular 2 limit parallel http calls I've got an Angular 2 app, which fetches a varying number of ids from a server, and then, for each id makes another REST call in a forkJoin. However, the amount of ids can go up to a few hundreds, which might be problematic when suddenly making several hundred REST calls in parallel. Is there a way of limiting the number of parallel calls when using RxJs and the forkJoin operator? A: Onw way would be to use bufferCount: Rx.Observable.from([1,2,3,4,5,6,7,8]) .bufferCount(3) .concatMap(items => { console.log('ConcatMap', items); let tasks = items.map(item => Rx.Observable.timer(Math.random() * 1000).do(() => console.log(item, 'ready'))); return Rx.Observable.forkJoin(...tasks); }) .subscribe() <script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.js"></script>
Q: Angular 2 limit parallel http calls I've got an Angular 2 app, which fetches a varying number of ids from a server, and then, for each id makes another REST call in a forkJoin. However, the amount of ids can go up to a few hundreds, which might be problematic when suddenly making several hundred REST calls in parallel. Is there a way of limiting the number of parallel calls when using RxJs and the forkJoin operator? A: Onw way would be to use bufferCount: Rx.Observable.from([1,2,3,4,5,6,7,8]) .bufferCount(3) .concatMap(items => { console.log('ConcatMap', items); let tasks = items.map(item => Rx.Observable.timer(Math.random() * 1000).do(() => console.log(item, 'ready'))); return Rx.Observable.forkJoin(...tasks); }) .subscribe() <script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.js"></script> A: I have done a function, hope it helps someone! (with RxJS 6 and lodash) const { timer, forkJoin, of } = rxjs; const { tap, map, mapTo, first, switchMapTo, concatMap } = rxjs.operators; forkJoinLimit = (limit, sources) => { if (sources.length < limit) { return forkJoin(sources); } return _.reduce( _.chunk(sources, limit), (acc, subSource) => { acc = acc.pipe( concatMap(val => forkJoin(subSource).pipe( map(val2 => (val)? _.concat(val, val2): val2), ))); return acc; }, of(null)); }; generateObservable = val => of(null).pipe( tap(() => console.log("Starting " + val)), switchMapTo( timer(Math.floor(Math.random() * 1000) + 1).pipe( first(), mapTo(val), tap(() => console.log("Ending " + val))), )); console.clear(); const serie = []; const size = 10; const limit = 3; for (let i = 0; i < 10; i++) { serie.push(generateObservable(i)); } forkJoinLimit(limit, serie).subscribe(x => console.log("-- End --", x)); <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.2.0/rxjs.umd.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
stackoverflow
{ "language": "en", "length": 246, "provenance": "stackexchange_0000F.jsonl.gz:846835", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486150" }
9f9c7ddcdc0a696d0e827c9078fbee4d24ba79e7
Stackoverflow Stackexchange Q: Is there an event connected to the choice of a datalist ? I have a (dynamic) list of choices in an <input> field: <input list="choices"> <datalist id="choices"> <option>one</option> <option>two</option> </datalist> Is there an event fired right after the choice of the <option> is made? (which I would like to catch/use in Vue.js if this matters). This would be when the left button of the mouse is clicked in the scenario below: A: Try this. it will check if the value exist in the input box and alert is triggered when you select an option as you have requested <input list="choices" id="searchbox"> <datalist id="choices"> <option id="one">one</option> <option>two</option> </datalist> $("#searchbox").bind('input', function () { if(checkExists( $('#searchbox').val() ) === true){ alert('item selected') } }); function checkExists(inputValue) { console.log(inputValue); var x = document.getElementById("choices"); var i; var flag; for (i = 0; i < x.options.length; i++) { if(inputValue == x.options[i].value){ flag = true; } } return flag; }
Q: Is there an event connected to the choice of a datalist ? I have a (dynamic) list of choices in an <input> field: <input list="choices"> <datalist id="choices"> <option>one</option> <option>two</option> </datalist> Is there an event fired right after the choice of the <option> is made? (which I would like to catch/use in Vue.js if this matters). This would be when the left button of the mouse is clicked in the scenario below: A: Try this. it will check if the value exist in the input box and alert is triggered when you select an option as you have requested <input list="choices" id="searchbox"> <datalist id="choices"> <option id="one">one</option> <option>two</option> </datalist> $("#searchbox").bind('input', function () { if(checkExists( $('#searchbox').val() ) === true){ alert('item selected') } }); function checkExists(inputValue) { console.log(inputValue); var x = document.getElementById("choices"); var i; var flag; for (i = 0; i < x.options.length; i++) { if(inputValue == x.options[i].value){ flag = true; } } return flag; } A: It looks like options in datalist do not tigger any event, so you need to code your own solution. I was able to do something similar to fire events with options in datalist, using @input in the element For example in your code you can try a solution starting with this <input list="choices" @input="checkInput" > <datalist id="choices"> <option>one</option> <option>two</option> </datalist> In the method used with @input you can check the changes in the input value. checkInput(e){ var inputValue = e.target.value; //Your code }, For example you can check if the input value, after click in one option of your datalyst, is a valid option, and after that conditions meets you can launch another method or whatever you want.
stackoverflow
{ "language": "en", "length": 272, "provenance": "stackexchange_0000F.jsonl.gz:846849", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486181" }
f42fd35abef49b4099469717c42674d5ae340ab8
Stackoverflow Stackexchange Q: Android: Convert image object to bitmap does not work I am trying to convert image object to bitmap, but it return null. image = reader.acquireLatestImage(); ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.capacity()]; Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null); The image itself is jpeg image, I can save it to the disk fine, the reason I want to convert to bitmap is because I want to do final rotation before saving it to the disk. Digging in the Class BitmapFactory I see this line. bm = nativeDecodeByteArray(data, offset, length, opts); This line return null. Further Digging with the debugger private static native Bitmap nativeDecodeByteArray(byte[] data, int offset, int length, Options opts); This suppose to return Bitmap object but it return null. Any tricks.. or ideas? Thanks A: You haven't copied bytes.You checked capacity but not copied bytes. ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null);
Q: Android: Convert image object to bitmap does not work I am trying to convert image object to bitmap, but it return null. image = reader.acquireLatestImage(); ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.capacity()]; Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null); The image itself is jpeg image, I can save it to the disk fine, the reason I want to convert to bitmap is because I want to do final rotation before saving it to the disk. Digging in the Class BitmapFactory I see this line. bm = nativeDecodeByteArray(data, offset, length, opts); This line return null. Further Digging with the debugger private static native Bitmap nativeDecodeByteArray(byte[] data, int offset, int length, Options opts); This suppose to return Bitmap object but it return null. Any tricks.. or ideas? Thanks A: You haven't copied bytes.You checked capacity but not copied bytes. ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null); A: I think you're trying to decode an empty array, you just create it but never copy the image data to it. You can try: ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = buffer.array(); Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null); As you say it doesn't work, then we need to copy the buffer manually ... try this :) byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null);
stackoverflow
{ "language": "en", "length": 216, "provenance": "stackexchange_0000F.jsonl.gz:846851", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486188" }
0006dc00f1f9d7a0385d0a48c91de11ebd1cb089
Stackoverflow Stackexchange Q: How to correctly find the stream characteristics in Java-8? While doing stream operations, during the intermediate/pipeline operations the streams would be created with different characteristics(e.g: SORTED/SIZED/DISTINCT/ORDERED) - Mastering Lambdas(Ch 6) Stream.of(8,3,5,6,7,4) // ORDERED, SIZED .filter(i->i%2==0) // ORDERED .sorted() // ORDERED, SORTED .distinct() // DISTINCT, ORDERED, SORTED .map(i->i+1) // ORDERED .unordered(); // none How do we find out the different characteristics of the stream as mentioned in the above snippet? A: At each stage you can call: int c = stream.spliterator().characteristics(); And then test the result against the constants defined in the Spliterator class. For example to see if the stream is ordered: boolean isOrdered = (c & Spliterator.ORDERED) == Spliterator.ORDERED; Alternatively you can use: boolean isOrdered = stream.spliterator().hasCharacteristics(Spliterator.ORDERED);
Q: How to correctly find the stream characteristics in Java-8? While doing stream operations, during the intermediate/pipeline operations the streams would be created with different characteristics(e.g: SORTED/SIZED/DISTINCT/ORDERED) - Mastering Lambdas(Ch 6) Stream.of(8,3,5,6,7,4) // ORDERED, SIZED .filter(i->i%2==0) // ORDERED .sorted() // ORDERED, SORTED .distinct() // DISTINCT, ORDERED, SORTED .map(i->i+1) // ORDERED .unordered(); // none How do we find out the different characteristics of the stream as mentioned in the above snippet? A: At each stage you can call: int c = stream.spliterator().characteristics(); And then test the result against the constants defined in the Spliterator class. For example to see if the stream is ordered: boolean isOrdered = (c & Spliterator.ORDERED) == Spliterator.ORDERED; Alternatively you can use: boolean isOrdered = stream.spliterator().hasCharacteristics(Spliterator.ORDERED); A: I would like to slightly extend what assylias said (which is absolutely correct). First, these characteristics are implemented as plain int, it's binary representation. First it's all zeroes, but when you add a certain characteristic it's bit is set to one via the OR operation, removed via the AND operation. You can see where a certain Spliterator property sets its one simply by doing this for example: System.out.println(Integer.toBinaryString(Spliterator.SIZED)); // 1000000 It's setting the 7-th bit into one from the right. So when you check: Spliterator<Integer> spliterator = Stream.of(8, 3, 5, 6, 7, 4).spliterator(); System.out.println((spliterator.characteristics() & Spliterator.SIZED) == Spliterator.SIZED); You are actually checking if this particular bit is set. Second There are 4 stream characteristics that are set as the result of your first stream creation(and not two). Either the book is a bit outdated or you have not showed us the entire example: Spliterator<Integer> spliterator = Stream.of(8, 3, 5, 6, 7, 4).spliterator(); System.out.println(Integer.bitCount(spliterator.characteristics())); // 4 System.out.println(Integer.toBinaryString(spliterator.characteristics()));// 100010001010000 These set bits (that are equal to one) correspond to SIZED, ORDERED, IMMUTABLE, SUBSIZED. The others that you have shown are obviously slightly off too - you can check those yourself. Third These characteristics are extremely important in stream processing. A few examples: long howMany = Stream.of(1, 2, 3).map(x -> { System.out.println("mapping"); return x * 2; }).count(); System.out.println(howMany); // 3 In java-9 you will not see the mapping printed, because you have not changed the stream (you have not cleared the SIZED characteristic); thus no need to even evaluate the mapping at all. Stream<Integer> unlimited = Stream.iterate(0, x -> x + 1); System.out.println(unlimited.spliterator().hasCharacteristics(Spliterator.SIZED)); Stream<Integer> limited = unlimited.limit(3); System.out.println(limited.spliterator().hasCharacteristics(Spliterator.SIZED)); You would think that the output should be false true - we are adding a limit after all, but no; the result is false false: no such optimization is done, even if there is not much preventing it.
stackoverflow
{ "language": "en", "length": 423, "provenance": "stackexchange_0000F.jsonl.gz:846870", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486238" }
8d6d02c61dfd45fdafe6ab97d9e7357f063efa83
Stackoverflow Stackexchange Q: What's the shortcut to close vscode's message box? Is there a shortcut to close the message box shown in the screenshot? A: Updated, as of Jan 2020: { "key": "shift+escape", "command": "notifications.clearAll" }
Q: What's the shortcut to close vscode's message box? Is there a shortcut to close the message box shown in the screenshot? A: Updated, as of Jan 2020: { "key": "shift+escape", "command": "notifications.clearAll" } A: esc should dismiss all visible messages. You can also configure a custom keybinding for the leaveEditorMessage command (or workbench.action.closeMessages on older VS Code versions). Here's the default keybinding: { "key": "escape", "command": "leaveEditorMessage", "when": "messageVisible" }
stackoverflow
{ "language": "en", "length": 71, "provenance": "stackexchange_0000F.jsonl.gz:846905", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486330" }
83aac1fcd5c2516c5b1a3aa945157c90f95ef314
Stackoverflow Stackexchange Q: ffmpeg how to allow a file extension New ffmpeg version check for file extension due to security issue in ffmpeg.org that use #EXT-X-KEY:METHOD=AES-128 since the key usually doesn't use file extension or use *.key extension so example ffmpeg -i "C:\streamingtest.m3u8" -c copy "test.ts" inside the m3u8 I have : #EXT-X-KEY:METHOD=AES-128,URI="C:/keytest.key" And ffmpeg will spew an error [hls,applehttp @ 0000000000dc6460] Filename extension of 'C:/keytest.key' is not a common multimedia extension, blocked for security reasons. If you wish to override this adjust allowed_extensions, you can set it to 'ALL' to allow all Unable to open key file c:/keytest.key But it doesn't explain how to use the ALL options in allowed_extensions So how do i allow key extension in ffmpeg or allow all extension Thanks A: It's a private option of the HLS demuxer, so ffmpeg -allowed_extensions ALL -i "C:\streamingtest.m3u8" -c copy "test.ts"
Q: ffmpeg how to allow a file extension New ffmpeg version check for file extension due to security issue in ffmpeg.org that use #EXT-X-KEY:METHOD=AES-128 since the key usually doesn't use file extension or use *.key extension so example ffmpeg -i "C:\streamingtest.m3u8" -c copy "test.ts" inside the m3u8 I have : #EXT-X-KEY:METHOD=AES-128,URI="C:/keytest.key" And ffmpeg will spew an error [hls,applehttp @ 0000000000dc6460] Filename extension of 'C:/keytest.key' is not a common multimedia extension, blocked for security reasons. If you wish to override this adjust allowed_extensions, you can set it to 'ALL' to allow all Unable to open key file c:/keytest.key But it doesn't explain how to use the ALL options in allowed_extensions So how do i allow key extension in ffmpeg or allow all extension Thanks A: It's a private option of the HLS demuxer, so ffmpeg -allowed_extensions ALL -i "C:\streamingtest.m3u8" -c copy "test.ts" A: I think this is directive for the player -allowed_extensions try the following: ffplay -allowed_extensions ALL index.m3u8 it is working form me with the key stored in the local folder
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:846926", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486404" }
d5c7e39745f38caf4f983cab359e02d994c0763a
Stackoverflow Stackexchange Q: Produce a table spanning multiple pages using kable() I would like to produce a table that spans over multiple pages using kable(). I know this is possible using xtable() with the "longtable" option, but I need kable() for other features. Any ideas? ```{r cars, echo=TRUE, results='asis', warning=FALSE, message=FALSE} library(knitr) library(kableExtra) # OUTPUT 1, fits on one page output = rbind(mtcars[, 1:5]) kable(output, booktabs = T, format="latex", caption = "Small Output") # OUTPUT 2, will not fit on one page output = rbind(mtcars[, 1:5], mtcars[, 1:5]) kable(output, booktabs = T, format="latex", caption = "Large Output") ``` Update: I am dumb! "longtable=TRUE," is an option. The problem is that this changes the order of my output and kinda messes things up. A: You can try to use the kableExtra package. If you specify hold_position in kable_styling, you should be able to ping the table to the place you want. Also, in the current dev version, I introduced a new feature called repeat_header for longtable to repeat the header row on every page. You can check it out. kable(output, "latex", booktabs = TRUE, longtable = TRUE, caption = "Test") %>% kable_styling(latex_options = c("hold_position", "repeat_header"))
Q: Produce a table spanning multiple pages using kable() I would like to produce a table that spans over multiple pages using kable(). I know this is possible using xtable() with the "longtable" option, but I need kable() for other features. Any ideas? ```{r cars, echo=TRUE, results='asis', warning=FALSE, message=FALSE} library(knitr) library(kableExtra) # OUTPUT 1, fits on one page output = rbind(mtcars[, 1:5]) kable(output, booktabs = T, format="latex", caption = "Small Output") # OUTPUT 2, will not fit on one page output = rbind(mtcars[, 1:5], mtcars[, 1:5]) kable(output, booktabs = T, format="latex", caption = "Large Output") ``` Update: I am dumb! "longtable=TRUE," is an option. The problem is that this changes the order of my output and kinda messes things up. A: You can try to use the kableExtra package. If you specify hold_position in kable_styling, you should be able to ping the table to the place you want. Also, in the current dev version, I introduced a new feature called repeat_header for longtable to repeat the header row on every page. You can check it out. kable(output, "latex", booktabs = TRUE, longtable = TRUE, caption = "Test") %>% kable_styling(latex_options = c("hold_position", "repeat_header"))
stackoverflow
{ "language": "en", "length": 192, "provenance": "stackexchange_0000F.jsonl.gz:846948", "question_score": "25", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486493" }
0191fb74c8ac425ffccf7fcdec423199097e3549
Stackoverflow Stackexchange Q: Firebase Serve Error I am new to firebase and am trying to make a simple app that utilizes user authentication. At this point in the project I am trying to run firebase on a local server using CLI commands. I have set up firebase init and firebase deploy. When I type firebase serve on my project folder i get the response, "an unexpected error has occurred". Below i am attaching the contents of my firebase-debug.log file. Any help would be appreciated. Thanks command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase",... [debug] [2017-06-11T17:09:09.607Z] > authorizing via signed-in user TypeError: Cannot read property 'public' of undefined A: I faced this issue today, I ran it with --debug and found out that I've installed npm/node as sudo user, running following: firebase serve was giving me this error: Error: An unexpected error has occurred. When I ran it with sudo, I was able to deploy hosting and functions locally: sudo firebase serve --debug --only hosting,functions
Q: Firebase Serve Error I am new to firebase and am trying to make a simple app that utilizes user authentication. At this point in the project I am trying to run firebase on a local server using CLI commands. I have set up firebase init and firebase deploy. When I type firebase serve on my project folder i get the response, "an unexpected error has occurred". Below i am attaching the contents of my firebase-debug.log file. Any help would be appreciated. Thanks command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase",... [debug] [2017-06-11T17:09:09.607Z] > authorizing via signed-in user TypeError: Cannot read property 'public' of undefined A: I faced this issue today, I ran it with --debug and found out that I've installed npm/node as sudo user, running following: firebase serve was giving me this error: Error: An unexpected error has occurred. When I ran it with sudo, I was able to deploy hosting and functions locally: sudo firebase serve --debug --only hosting,functions A: 1) create a folder called "public" and put your files inside. 2) edit the firebase.json and just write this: { "hosting": { "public": "public" } } A: Look in your firebase.json file, which you should have in the directory where you're running firebase serve. It should look something like this: { "hosting": { "public": "app", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ] } } If it doesn't have that "hosting" key, then you'll get that Cannot read property 'public' of undefined error because firebase serve tries to access .hosting.public. A: This appears to be a bug - that ideally should be resolved with Firebase Init. I have logged a support ticket with Firebase, and would encourage others to do so as well. A: I think you may have skipped an initialization step by accident (I did the same thing on my first run-through) Try this (from your same project directory): 1) firebase init 2) When prompted for which services you'll need make sure that Database AND Hosting options have their markers highlighted green (tab to Hosting with the spacebar). It's easy to select just database and let it run its configuration and assume it configures all of the bulleted options below it if you do not watch closely because the stdout info isn't very clear. Now hit Enter 3) Accept the default database settings as you probably did before, and when asked "What do you want to use as your public directory? (public)", hit Enter. At this point you should be good to go spin up a local firebase web server... 4) try 'firebase serve', hit Enter, and you should get a verification that hosting files are being served from /public Hope this helps. Good luck. A: As for me the error is (--debug attr) Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/firebase-tools/node_modules/@google-cloud/functions-emulator/logs' So the solution will be to run with sudo
stackoverflow
{ "language": "en", "length": 468, "provenance": "stackexchange_0000F.jsonl.gz:846978", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486589" }
ac94f1f570cc4cb7557d2b8eaf93e6ef99cac664
Stackoverflow Stackexchange Q: Send a message from an iframe on the main page I have seen from this documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage , the way to pass a data correctly to an iframe. But now I want to send an answer: //from main page myIframe.contentWindow.postMessage('send me a response', '*'); //from iframe of main page window.addEventListener("message", receiveMessage, false); function receiveMessage(event){ alert(event.data);//the value of message //now i need to send an answer 'this is a response' } } How do I send an answer to the main page from the iframe? I need really of this answer. Edit: Ok i found the solution ty at all. A: You have access to the parent window on the global window.parent. I believe it is as easy as using this object's method at this point to postMessage. So something like: var parent = window.parent; parent.postMessage("some message"); A full example can be found here. The gist is the window.parent.postMessage() function takes the following arguments: otherWindow.postMessage(message, targetOrigin, [transfer]);
Q: Send a message from an iframe on the main page I have seen from this documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage , the way to pass a data correctly to an iframe. But now I want to send an answer: //from main page myIframe.contentWindow.postMessage('send me a response', '*'); //from iframe of main page window.addEventListener("message", receiveMessage, false); function receiveMessage(event){ alert(event.data);//the value of message //now i need to send an answer 'this is a response' } } How do I send an answer to the main page from the iframe? I need really of this answer. Edit: Ok i found the solution ty at all. A: You have access to the parent window on the global window.parent. I believe it is as easy as using this object's method at this point to postMessage. So something like: var parent = window.parent; parent.postMessage("some message"); A full example can be found here. The gist is the window.parent.postMessage() function takes the following arguments: otherWindow.postMessage(message, targetOrigin, [transfer]); A: I would consider using easyXDM EasyXDM WebSite
stackoverflow
{ "language": "en", "length": 165, "provenance": "stackexchange_0000F.jsonl.gz:846979", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486590" }
59449f8ec1ba696b4e4d465e6585ec3cc83946dc
Stackoverflow Stackexchange Q: Pandas, read in file without a separator between columns I want to read in a file that looks like this: 1.49998061E-01 2.49996769E-01 3.99994830E-01 5.99992245E-01 9.99987075E-01 1.49998061E+00 2.49996769E+00 5.99992245E+00 9.99987075E+00 1.99997415E+01 4.99993537E+01 9.99987075E+01 .00000000E+00-2.70636350E+03-6.37027451E+03 -1.97521328E+04-4.64928272E+04-1.09435407E+05-3.39323088E+05-7.98702345E+05 -1.87999269E+06-5.82921376E+06-1.37207895E+07-2.26385807E+07-4.25429547E+07 -7.60167523E+07-1.25422049E+08-2.35690283E+08-3.88862033E+08-7.30701955E+08 -1.30546599E+09-2.15348023E+09-4.04455001E+09-4.54896210E+09-5.32533888E+09 So, each column is denoted by a 15 character sequence, but there's no official separator. Does pandas have a way of doing this? A: Let's look at using pd.read_fwf: df = pd.read_fwf(csv_file,widths=[15]*5,header=None)
Q: Pandas, read in file without a separator between columns I want to read in a file that looks like this: 1.49998061E-01 2.49996769E-01 3.99994830E-01 5.99992245E-01 9.99987075E-01 1.49998061E+00 2.49996769E+00 5.99992245E+00 9.99987075E+00 1.99997415E+01 4.99993537E+01 9.99987075E+01 .00000000E+00-2.70636350E+03-6.37027451E+03 -1.97521328E+04-4.64928272E+04-1.09435407E+05-3.39323088E+05-7.98702345E+05 -1.87999269E+06-5.82921376E+06-1.37207895E+07-2.26385807E+07-4.25429547E+07 -7.60167523E+07-1.25422049E+08-2.35690283E+08-3.88862033E+08-7.30701955E+08 -1.30546599E+09-2.15348023E+09-4.04455001E+09-4.54896210E+09-5.32533888E+09 So, each column is denoted by a 15 character sequence, but there's no official separator. Does pandas have a way of doing this? A: Let's look at using pd.read_fwf: df = pd.read_fwf(csv_file,widths=[15]*5,header=None) A: Yes! its called pd.read_fwf from io import StringIO import pandas as pd txt = """ 1.49998061E-01 2.49996769E-01 3.99994830E-01 5.99992245E-01 9.99987075E-01 1.49998061E+00 2.49996769E+00 5.99992245E+00 9.99987075E+00 1.99997415E+01 4.99993537E+01 9.99987075E+01 .00000000E+00-2.70636350E+03-6.37027451E+03 -1.97521328E+04-4.64928272E+04-1.09435407E+05-3.39323088E+05-7.98702345E+05 -1.87999269E+06-5.82921376E+06-1.37207895E+07-2.26385807E+07-4.25429547E+07 -7.60167523E+07-1.25422049E+08-2.35690283E+08-3.88862033E+08-7.30701955E+08 -1.30546599E+09-2.15348023E+09-4.04455001E+09-4.54896210E+09-5.32533888E+09""" pd.read_fwf(StringIO(txt), widths=[15] * 5, header=None) 0 1 2 3 4 0 1.499981e-01 2.499968e-01 3.999948e-01 5.999922e-01 9.999871e-01 1 1.499981e+00 2.499968e+00 5.999922e+00 9.999871e+00 1.999974e+01 2 4.999935e+01 9.999871e+01 0.000000e+00 -2.706363e+03 -6.370275e+03 3 -1.975213e+04 -4.649283e+04 -1.094354e+05 -3.393231e+05 -7.987023e+05 4 -1.879993e+06 -5.829214e+06 -1.372079e+07 -2.263858e+07 -4.254295e+07 5 -7.601675e+07 -1.254220e+08 -2.356903e+08 -3.888620e+08 -7.307020e+08 6 -1.305466e+09 -2.153480e+09 -4.044550e+09 -4.548962e+09 -5.325339e+09 A: Let's do like that: for example: housing.data dataset = pd.read_csv('c:/1/housing.data', engine = 'python', sep='\s+', header=None)
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:846982", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486597" }
2f853950d8aab8afea3b82d262bbbc631c532857
Stackoverflow Stackexchange Q: Laravel Validate Array of Inputs I have a form: <input type="text" name="name[1]"> <input type="text" name="name[2]"> <input type="text" name="name[3]"> <input type="submit" value="Submit"> I've created form validation file with rules: class formRequest extends FormRequest { .... public function rules() { return ['name.*' => 'unique:names']; } public function messages() { return ['name.unique' => 'Name is already in DB!']; } After submitting the form with value (e.g. 'John') in input (e.g. name[1]), which already exists in the DB, I get: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name.1' in 'where clause' (SQL: select count(*) as aggregate from `names` where `name`.`1` = John) So it's treating name.* as for creating another field name, instead of looping through the array. My Laravel Framework is version 5.4.19. According to the docs, the name.* should work to iterate through an array during validation. What I am doing wrong? A: by default if you didn't provide a column name for the unique rule, Laravel will add the input name, and in your case the input name is a number. to fix this issue change the rule to the following instead: return ['name.*' => 'unique:names,name'];
Q: Laravel Validate Array of Inputs I have a form: <input type="text" name="name[1]"> <input type="text" name="name[2]"> <input type="text" name="name[3]"> <input type="submit" value="Submit"> I've created form validation file with rules: class formRequest extends FormRequest { .... public function rules() { return ['name.*' => 'unique:names']; } public function messages() { return ['name.unique' => 'Name is already in DB!']; } After submitting the form with value (e.g. 'John') in input (e.g. name[1]), which already exists in the DB, I get: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name.1' in 'where clause' (SQL: select count(*) as aggregate from `names` where `name`.`1` = John) So it's treating name.* as for creating another field name, instead of looping through the array. My Laravel Framework is version 5.4.19. According to the docs, the name.* should work to iterate through an array during validation. What I am doing wrong? A: by default if you didn't provide a column name for the unique rule, Laravel will add the input name, and in your case the input name is a number. to fix this issue change the rule to the following instead: return ['name.*' => 'unique:names,name'];
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:847014", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486684" }
c75948a52d5c897b46aba4660ed5195f30829048
Stackoverflow Stackexchange Q: Deployment Server Ignores .htaccess File My .htaccess file on root looks like this: RewriteEngine on RewriteBase / options +FollowSymLinks RewriteRule ^en/users/profile/?$ [F,NC] RewriteRule ^en/users/profile/?([0-9]+)?/?$ en/user/index.php?id=$1 RewriteRule ^en/users/profile/([0-9]+)/photo/? en/user/index.php?pageID=photoEdit&id=$1 RewriteCond %{HTTP_REFERER} !^http://example\.ge/?.*$ [NC] RewriteCond %{HTTP_REFERER} !^http://example\.dev/?.*$ [NC] RewriteCond %{HTTP_REFERER} !^http://localhost/?.*$ [NC] RewriteRule \.(gif|jpe?g|png|bmp)$ - [F,NC] It can reroute perfectly on local host but it is ignored on deployment server! This is the phpinfo(); of the server! this is the etc folder: A: You probably don't have .htaccess files enabled on the server. Have a look at the AllowOverride directive. You can add something like this to the <Directory> block for your <VirtualHost>'s document root: AllowOverride all
Q: Deployment Server Ignores .htaccess File My .htaccess file on root looks like this: RewriteEngine on RewriteBase / options +FollowSymLinks RewriteRule ^en/users/profile/?$ [F,NC] RewriteRule ^en/users/profile/?([0-9]+)?/?$ en/user/index.php?id=$1 RewriteRule ^en/users/profile/([0-9]+)/photo/? en/user/index.php?pageID=photoEdit&id=$1 RewriteCond %{HTTP_REFERER} !^http://example\.ge/?.*$ [NC] RewriteCond %{HTTP_REFERER} !^http://example\.dev/?.*$ [NC] RewriteCond %{HTTP_REFERER} !^http://localhost/?.*$ [NC] RewriteRule \.(gif|jpe?g|png|bmp)$ - [F,NC] It can reroute perfectly on local host but it is ignored on deployment server! This is the phpinfo(); of the server! this is the etc folder: A: You probably don't have .htaccess files enabled on the server. Have a look at the AllowOverride directive. You can add something like this to the <Directory> block for your <VirtualHost>'s document root: AllowOverride all A: RewriteRule ^en/users/profile/?$ [F,NC] Not the cause of why your .htaccess file is being ignored (the other answers have already given solutions for that, with regards to checking the AllowOverride directive in the server config), but you are missing a valid substitution in the above directive. A request for /en/users/profile/ will not be forbidden and will likely just result in an error/404. It would need to be something like: RewriteRule ^en/users/profile/?$ - [F,NC] (Just a single hyphen for the substitution.) RewriteCond %{HTTP_REFERER} !^http://example\.ge/?.*$ [NC] RewriteCond %{HTTP_REFERER} !^http://example\.dev/?.*$ [NC] RewriteCond %{HTTP_REFERER} !^http://localhost/?.*$ [NC] RewriteRule \.(gif|jpe?g|png|bmp)$ - [F,NC] You should also move your "hotlink protection" directives (above) to before your routing directives. Otherwise, it's possible (depending on the URL format) that the URL is routed before the hotlink protection is able to block the request. A: Edit your virtual host: 1. Login to your server. 2. cd /etc/apache2/sites-available/ 3. You can edit your default or web1 or ... virtual-host-.conf-file. Type nano web1.conf (...) and edit your file. <VirtualHost *:80> ServerName yoururl.com ServerAdmin webmaster@localhost DocumentRoot /var/www/web1/htdocs/ <Directory /var/www/web1/htdocs/> Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny allow from all </Directory> ErrorLog /var/log/apache2/error.log LogLevel warn CustomLog /var/log/apache2/access.log combined ServerSignature On </VirtualHost> 4. Stop your Apache2 and restart it - /etc/init.d/apache2 stop and /etc/init.d/apache2 start. 5. Upload your .htaccess into your root directory and test it. If you using Cloudflare, then there is a option in the settings "Always use HTTPS" in the SSL settings. You can also use Forwarding URL action: http://yoururl.fqdn/* redirected with a 301 response code to https://www.yoururl.fqdn/$1
stackoverflow
{ "language": "en", "length": 362, "provenance": "stackexchange_0000F.jsonl.gz:847057", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486825" }
1c1424a211b84fd47e1f16097bde67eb5b6db852
Stackoverflow Stackexchange Q: ElementRef of ng-bootstrap modal I want to Reference html element which is inside ng-bootstrap modal from component of angular 2 <ng-template #liveView id="liveView" let-c="close" let-d="dismiss"> <div class="modal-header"> <h4 class="modal-title">Live View</h4> <button type="button" class="close" aria-label="Close" (click)="d('Cross click')"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <canvas #liveViewCanvas style="border: 1px solid black;" width="270" height="480"></canvas> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-xs" (click)="closeLiveViewModal()"> <span class="fa fa-trash"></span> Close </button> </div> </ng-template> How to Reference #liveViewCanvas within angular 2 component? I am getting "ERROR TypeError: Cannot read property 'nativeElement' of undefined" when referencing through @viewchild A: Maybe something this. const modalRef = this.modalService.open(HoldingModalsProductCreateComponent,{backdrop: 'static'}); modalRef._windowCmptRef.hostView.rootNodes[0];
Q: ElementRef of ng-bootstrap modal I want to Reference html element which is inside ng-bootstrap modal from component of angular 2 <ng-template #liveView id="liveView" let-c="close" let-d="dismiss"> <div class="modal-header"> <h4 class="modal-title">Live View</h4> <button type="button" class="close" aria-label="Close" (click)="d('Cross click')"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <canvas #liveViewCanvas style="border: 1px solid black;" width="270" height="480"></canvas> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-xs" (click)="closeLiveViewModal()"> <span class="fa fa-trash"></span> Close </button> </div> </ng-template> How to Reference #liveViewCanvas within angular 2 component? I am getting "ERROR TypeError: Cannot read property 'nativeElement' of undefined" when referencing through @viewchild A: Maybe something this. const modalRef = this.modalService.open(HoldingModalsProductCreateComponent,{backdrop: 'static'}); modalRef._windowCmptRef.hostView.rootNodes[0]; A: Like NgIf directive, you can only use a reference when is in the DOM. If you want to manipulate the template, just create a component with the template and logic of the modal, and launch it. export class NgbdModalComponent { constructor(private modalService: NgbModal) {} open() { const modalRef = this.modalService.open(NgbdModalContent); modalRef.componentInstance.name = 'World'; } } A: Just use DevTools to get the element you want. But it might stop working if the layout of modal would change in the next release: this.notificationModalRef = this.modalService.open(notificationComponentRef.instance.notificationContent, { centered: true, size: 'xl', scrollable: true }); this.dragDrop.createDrag((this.notificationModalRef as any)._windowCmptRef.instance._dialogEl); // you get the idea
stackoverflow
{ "language": "en", "length": 201, "provenance": "stackexchange_0000F.jsonl.gz:847101", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486952" }
53b46e43a199f266282eec2722d6fae2cc6a85d6
Stackoverflow Stackexchange Q: How could i transfer duplicate items in other ArrayList? I have an array list ArrayList<String> list=new ArrayList<String>(); list.add("Apple"); list.add("Ball"); list.add("Ball"); list.add("Cat"); list.add("Cat"); list.add("dog"); and I want to transfer duplicate strings to other ArrayList. I mean 2nd array list should only contain Ball and Cat not Apple and dog. Any kind of help is appreciated. A: You can do this: List<String> duplicates = new ArrayList<String>(); for(String str: list) { if(Collections.frequency(list, str) > 1) { duplicates.add(str); } } duplicates will contain your duplicates
Q: How could i transfer duplicate items in other ArrayList? I have an array list ArrayList<String> list=new ArrayList<String>(); list.add("Apple"); list.add("Ball"); list.add("Ball"); list.add("Cat"); list.add("Cat"); list.add("dog"); and I want to transfer duplicate strings to other ArrayList. I mean 2nd array list should only contain Ball and Cat not Apple and dog. Any kind of help is appreciated. A: You can do this: List<String> duplicates = new ArrayList<String>(); for(String str: list) { if(Collections.frequency(list, str) > 1) { duplicates.add(str); } } duplicates will contain your duplicates A: You can use a Set as a way to help determine the duplicated elements then simply return an ArrayList of those elements. public static ArrayList<String> retainDuplicates(ArrayList<String> inputList){ Set<String> tempSet = new HashSet<>(); ArrayList<String> duplicateList = new ArrayList<>(); for (String elem : inputList) { if(!tempSet.add(elem)) duplicateList.add(elem); } return duplicateList.stream().distinct().collect(Collectors.toCollection(ArrayList::new)); } call the method like so: ArrayList<String> resultList = retainDuplicates(list); note that I've used distinct() to remove any elements that occur more than once within the duplicateList. However, if you want to keep the duplicates regardless of theirs occurrences within the duplicateList then just perform return duplicateList; rather than return duplicateList.stream().distinct().collect(Collectors.toCollection(ArrayList::new));. A: Try this: // Custom list to ensure that one duplicate gets added to a list at most as // opposed to n-1 instances (only two instances of a value in this list would // be deceiving). List<String> list = new ArrayList<>(); list.add("Apple"); list.add("Ball"); list.add("Ball"); list.add("Ball"); list.add("Ball"); list.add("Cat"); list.add("Cat"); list.add("Cat"); list.add("dog"); list.add("dog"); Set<String> set = new HashSet<>(); Set<String> setOfDuplicates = new HashSet<>(); for (String s : list) { if (!set.add(s)) { // Remember that sets do not accept duplicates setOfDuplicates.add(s); } } List<String> listOfDuplicates = new ArrayList<>(setOfDuplicates); A: since you said your duplicates will all be next to each other, you can itterate through the list in pairs, and if the pair's elements match, there is a duplicate here would be the general pseudo code for it int first = 0 int second = 1 for (arraySize) if (array[first] == array[second]) //there is a match here newArray.add(array[first]) first += 1 second += 1 Note that this does not check the bounds of the array, which should be easy to implement yourself now as for the second list not having duplicate items, you can simply store a variable with the last transfered item, and if the new found duplicate is the same, dont transfer it again A: ArrayList<String> list=new ArrayList<String>(); list.add("Apple"); list.add("Ball"); list.add("Ball"); list.add("Cat"); list.add("Cat"); list.add("dog"); List<String> duplicateList= new ArrayList<String>(); for(String str: list) { if(Collections.frequency(list, str) > 1) { duplicateList.add(str); } } System.out.println(duplicateList.toString()); //Here you will get duplicate String from the original list.
stackoverflow
{ "language": "en", "length": 424, "provenance": "stackexchange_0000F.jsonl.gz:847108", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486968" }
55418f31cdd0ff2d0f8c37918e41933a395832cc
Stackoverflow Stackexchange Q: Could it be argued that Ada subtypes are equivalent to dependent types? I've been trying to wrap my head around Ada, and I've been reading a bit about dependent types in Agda and Idris. Could it be argued that subtypes in Ada are equivalent to dependent types? A: In computer science and logic, a dependent type is a type whose definition depends on a value. A "pair of integers" is a type. A "pair of integers where the second is greater than the first" is a dependent type because of the dependence on the value. So then you can use subtypes to implement them-- -- The "pair of integers" from the example. Type Pair is record A, B : Integer; end record; -- The "where the second is greater than the first" constraint. Subtype Constrained_Pair is Pair with Dynamic_Predicate => Constrained_Pair.B > Constrained_Pair.A;
Q: Could it be argued that Ada subtypes are equivalent to dependent types? I've been trying to wrap my head around Ada, and I've been reading a bit about dependent types in Agda and Idris. Could it be argued that subtypes in Ada are equivalent to dependent types? A: In computer science and logic, a dependent type is a type whose definition depends on a value. A "pair of integers" is a type. A "pair of integers where the second is greater than the first" is a dependent type because of the dependence on the value. So then you can use subtypes to implement them-- -- The "pair of integers" from the example. Type Pair is record A, B : Integer; end record; -- The "where the second is greater than the first" constraint. Subtype Constrained_Pair is Pair with Dynamic_Predicate => Constrained_Pair.B > Constrained_Pair.A; A: No, not as I read the formal definition of dependent types you referenced. A: Consider the following example: type A_T is range 1 .. 50; subtype B_T is A_T; Sub_type B_T is in fact the "same" as the type A_T, since it does not pose any restrictions on it. It is rather a renaming of type A_T for convenience, for example. Thus, you cannot say that Ada sub-types are dependent types.
stackoverflow
{ "language": "en", "length": 216, "provenance": "stackexchange_0000F.jsonl.gz:847110", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486970" }
c7668974626a174d76d86cd0fb5155c7e8dd3ebb
Stackoverflow Stackexchange Q: Keyboard pushes the screen up ionic 2 I'm developing an ionic 2 app. The html code of my login page is the following one: <ion-header> <ion-navbar color="royal"> <ion-title> Inicio de sesión </ion-title> </ion-navbar> </ion-header> <ion-content class="fondo"> <img src="assets/markerBoy.png" class="logo"/> <ion-card center> <ion-card-header> Credenciales </ion-card-header> <ion-card-content> <form> <ion-list> <ion-item> <ion-label floating> Usuario: </ion-label> <ion-input type="text" [(ngModel)]="user" name="user"> </ion-input> </ion-item> <ion-item> <ion-label floating> Contraseña: </ion-label> <ion-input type="password" [(ngModel)]="password" name="password"> </ion-input> </ion-item> </ion-list> <div padding> <button ion-button block (click)="iniciarSesionValidar()" color="royal"> Entrar </button> </div> </form> </ion-card-content> </ion-card> </ion-content> I don't know why but when I run the app in an android device at first the screen looks right but when I click in the username input, the keyboard appears and pushes up the screen. I'll show you two images, one when nothing is selected and another when I click in the username input. Normal Screen Input clicked Any idea? A: This solution works well for android, this is what I was looking for! just one thing, just make a change in android manifest file. add the tag attribute: android:windowSoftInputMode="adjustPan" inside <activity XXXattributeXX> eg: <activity android:windowSoftInputMode="adjustPan" />
Q: Keyboard pushes the screen up ionic 2 I'm developing an ionic 2 app. The html code of my login page is the following one: <ion-header> <ion-navbar color="royal"> <ion-title> Inicio de sesión </ion-title> </ion-navbar> </ion-header> <ion-content class="fondo"> <img src="assets/markerBoy.png" class="logo"/> <ion-card center> <ion-card-header> Credenciales </ion-card-header> <ion-card-content> <form> <ion-list> <ion-item> <ion-label floating> Usuario: </ion-label> <ion-input type="text" [(ngModel)]="user" name="user"> </ion-input> </ion-item> <ion-item> <ion-label floating> Contraseña: </ion-label> <ion-input type="password" [(ngModel)]="password" name="password"> </ion-input> </ion-item> </ion-list> <div padding> <button ion-button block (click)="iniciarSesionValidar()" color="royal"> Entrar </button> </div> </form> </ion-card-content> </ion-card> </ion-content> I don't know why but when I run the app in an android device at first the screen looks right but when I click in the username input, the keyboard appears and pushes up the screen. I'll show you two images, one when nothing is selected and another when I click in the username input. Normal Screen Input clicked Any idea? A: This solution works well for android, this is what I was looking for! just one thing, just make a change in android manifest file. add the tag attribute: android:windowSoftInputMode="adjustPan" inside <activity XXXattributeXX> eg: <activity android:windowSoftInputMode="adjustPan" /> A: I've had success doing the following: 1.) Throwing content you dont want to scroll within a ion-fixed container: <ion-content class="fondo"> <div ion-fixed> <img src="assets/markerBoy.png" class="logo" /> <ion-card center> <ion-card-header> Credenciales </ion-card-header> <ion-card-content> <form> <ion-list> <ion-item> <ion-label floating> Usuario: </ion-label> <ion-input type="text" [(ngModel)]="user" name="user"> </ion-input> </ion-item> <ion-item> <ion-label floating> Contraseña: </ion-label> <ion-input type="password" [(ngModel)]="password" name="password"> </ion-input> </ion-item> </ion-list> <div padding> <button ion-button block (click)="iniciarSesionValidar()" color="royal"> Entrar </button> </div> </form> </ion-card-content> </ion-card> </div> </ion-content> 2.) I've also read the changing from ion-input to the standard input element fixes some keyboard issues. A: Ive been dealing with this issue but with Ionic 4. I fixed it by setting the CSS property of the position to relative. For me specifically, I had a button that kept on getting moved when I wanted it at the bottom. Based on what you specify about the position it will always be relative to those that. Its kind of funny that the properties fixed and absolute have to do with currently available space. https://www.w3schools.com/css/css_positioning.asp
stackoverflow
{ "language": "en", "length": 350, "provenance": "stackexchange_0000F.jsonl.gz:847115", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44486991" }
99592db82fa129aaccf2b178a60a68740642349b
Stackoverflow Stackexchange Q: React Native on Android Studio Emulator I am not sure if I am doing this right. I have gone to the React Native website and now it looks like they are attempting to force you to use Expo which I do not want to use at this point. I was not able to find any information on running an Android simulator. I have installed Android Studio, I then start the emulator, run react-native run-android, and I get the following error. Can anyone point me in the right direction so I can test my code for Android? A: The work around for this was to use a different version of the mobile emulator. I was trying to use Nexus. I deleted the Nexus and installed a Galaxy and everything worked. The discussion regarding this issue can be read in the included link: https://github.com/facebook/react-native/issues/2720
Q: React Native on Android Studio Emulator I am not sure if I am doing this right. I have gone to the React Native website and now it looks like they are attempting to force you to use Expo which I do not want to use at this point. I was not able to find any information on running an Android simulator. I have installed Android Studio, I then start the emulator, run react-native run-android, and I get the following error. Can anyone point me in the right direction so I can test my code for Android? A: The work around for this was to use a different version of the mobile emulator. I was trying to use Nexus. I deleted the Nexus and installed a Galaxy and everything worked. The discussion regarding this issue can be read in the included link: https://github.com/facebook/react-native/issues/2720 A: React Native does not force you to use Expo. Did you follow the directions for Android Setup? Also Genymotion is much easier to set up than stock Google emulators.
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:847157", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487110" }
647001e7b6e58f6b105c4312b7802347eab9bee6
Stackoverflow Stackexchange Q: How can I remove white space between words in an array using Javascript? In the below array, how can I remove whitespace between words within each string? I want to convert "FLAT RATE" to "FLATRATE" and "FREE SHIPPING" to "FREESHIPPING". I had to work out with array. I saw the solutions for simple string's case. A: You can use array.map function to loop in array and use regex to remove all space: var array = ['FLAT RATE', 'FREE SHIPPING']; var nospace_array = array.map(function(item){ return item.replace(/\s+/g,''); }) console.log(nospace_array)
Q: How can I remove white space between words in an array using Javascript? In the below array, how can I remove whitespace between words within each string? I want to convert "FLAT RATE" to "FLATRATE" and "FREE SHIPPING" to "FREESHIPPING". I had to work out with array. I saw the solutions for simple string's case. A: You can use array.map function to loop in array and use regex to remove all space: var array = ['FLAT RATE', 'FREE SHIPPING']; var nospace_array = array.map(function(item){ return item.replace(/\s+/g,''); }) console.log(nospace_array) A: a string can be split and joined this way: s.split(" ").join(""); That removes spaces. A: ['FLAT RATE', 'FREE SHIPPING'].toString().replace(/ /g,"").split(",") I admit : not the best answer, since it relies on the array strings not to contain a comma. .map is indeed the way to go, but since that was already given, and since I like chaining, I gave another (quick and dirty) solution A: You really don't need jQuery for that. var ListOfWords = ["Some Words Here", "More Words Here"]; for(var i=0; i < ListOfWords.length; i++){ ListOfWords[i] = ListOfWords[i].replace(/\s+/gmi, ""); } console.log(ListOfWords); A: You can use the replace function to achieve this. var shipping = ["FLAT RATE", "FREE SHIPPING"]; var without_whitespace = shipping.map(function(str) { replaced = str.replace(' ', ''); return replaced; });
stackoverflow
{ "language": "en", "length": 212, "provenance": "stackexchange_0000F.jsonl.gz:847160", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487123" }
d9a1c12faf14bad7c9fd6070bda166c3b131b102
Stackoverflow Stackexchange Q: Understanding Closure concept in deep Hey check this code here, function getspinner(){ var count = 0; function increment(){ return ++count; } function decrement(){ return --count; } return { up:increment, down:decrement } } If I call it like var spinner = getspinner(); spinner.up(); // value increments by 1 each time spinner.down(); // value decrements by 1 each time But when I call it Like getspinner().up(); // i'l get 1 each time getspinner().down(); // i'l get -1 each time I would like to know the difference. why the lifetime of count is not increased in case of getspinner().up() or getspinner().down();
Q: Understanding Closure concept in deep Hey check this code here, function getspinner(){ var count = 0; function increment(){ return ++count; } function decrement(){ return --count; } return { up:increment, down:decrement } } If I call it like var spinner = getspinner(); spinner.up(); // value increments by 1 each time spinner.down(); // value decrements by 1 each time But when I call it Like getspinner().up(); // i'l get 1 each time getspinner().down(); // i'l get -1 each time I would like to know the difference. why the lifetime of count is not increased in case of getspinner().up() or getspinner().down();
stackoverflow
{ "language": "en", "length": 99, "provenance": "stackexchange_0000F.jsonl.gz:847166", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487139" }
262fab33ba67abb1bf5f4a321cffbcf338d9f34f
Stackoverflow Stackexchange Q: Make uiCollectionView scrollable when not full I want my CollectionView to still be able to scroll a bit up and down when there’s only a few cells (to get that bounce effect). In a previous question it was suggested that using self.collectionview?.alwaysBounceVerticle = true would work (this was marked as the correct answer) but this doesn’t work anymore. I’m using swift 3 A: After looking tying some stuff in the interface builder it turns out that you have to check the box for “Bounces” and “Bounces Vertically”
Q: Make uiCollectionView scrollable when not full I want my CollectionView to still be able to scroll a bit up and down when there’s only a few cells (to get that bounce effect). In a previous question it was suggested that using self.collectionview?.alwaysBounceVerticle = true would work (this was marked as the correct answer) but this doesn’t work anymore. I’m using swift 3 A: After looking tying some stuff in the interface builder it turns out that you have to check the box for “Bounces” and “Bounces Vertically” A: You can configure it using Storyboard. Just select your collection view and in attribute inspector check * Bounces* and Bounce Vertically. A: // swift self.collectionview?.alwaysBounceVertical = true self.collectionview?.bounces = true
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:847229", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487333" }
f1138b025fea0882dd51a53bb32569a64742bc35
Stackoverflow Stackexchange Q: Regular expression to reject all non-English characters except some characters with accents This works great to disallow all non-English letters: /[^\x00-\x7F]+/ But I would like to allow these characters: âäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ How do I add those to the regex so that they are allowed? A: If the pattern like /[^\x00-\x7F]+/ works for you, it matches all the letters you now want to avoid matching. Since the [^...] is a negated character class, the easiest way to exclude a char/set of chars is to just add them to the class: /[^\x00-\x7FâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ]+/ See the regex demo. If you use an empty string as the replacement pattern, you will remove every 1+ chars that are not ASCII (\x00-\x7F) and that are not equal to the letters added to the negated character class.
Q: Regular expression to reject all non-English characters except some characters with accents This works great to disallow all non-English letters: /[^\x00-\x7F]+/ But I would like to allow these characters: âäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ How do I add those to the regex so that they are allowed? A: If the pattern like /[^\x00-\x7F]+/ works for you, it matches all the letters you now want to avoid matching. Since the [^...] is a negated character class, the easiest way to exclude a char/set of chars is to just add them to the class: /[^\x00-\x7FâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ]+/ See the regex demo. If you use an empty string as the replacement pattern, you will remove every 1+ chars that are not ASCII (\x00-\x7F) and that are not equal to the letters added to the negated character class. A: Though it looks long one but a simple character class would do the job. Regex: [a-zA-ZâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ]
stackoverflow
{ "language": "en", "length": 146, "provenance": "stackexchange_0000F.jsonl.gz:847242", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487377" }
7e58a31d691067d2e9d727220c70ef6f498ab2c9
Stackoverflow Stackexchange Q: Returning boolean value in an rxjs function fails Am new to the rxjs and i would like to return an observable of either true or false this is what i have tried checkLoggedin():Observable<boolean> { //check from server if user is loggdin if(this._tokenService.getToken()){ //this returns synchronous true or false this._httpservice.checkifloggedin() .subscribe((res)=>{ return res.data //this comes in as true or false value }, err=>{ return false } ) }else{ return false //this fails with an error of //type false is not assignable to observable<boolean> } } How do i change the above else part to work with the boolean observable so that in the other components i can only do this._authservice.checkLoggedin() .subscribe.....//here get the value whether true or false A: this should work checkLoggedin():Observable<boolean> { if(this._tokenService.getToken()){ return this._httpservice.checkifloggedin().map(res=>res.data ) ; } else { return Observable.of(false); } }
Q: Returning boolean value in an rxjs function fails Am new to the rxjs and i would like to return an observable of either true or false this is what i have tried checkLoggedin():Observable<boolean> { //check from server if user is loggdin if(this._tokenService.getToken()){ //this returns synchronous true or false this._httpservice.checkifloggedin() .subscribe((res)=>{ return res.data //this comes in as true or false value }, err=>{ return false } ) }else{ return false //this fails with an error of //type false is not assignable to observable<boolean> } } How do i change the above else part to work with the boolean observable so that in the other components i can only do this._authservice.checkLoggedin() .subscribe.....//here get the value whether true or false A: this should work checkLoggedin():Observable<boolean> { if(this._tokenService.getToken()){ return this._httpservice.checkifloggedin().map(res=>res.data ) ; } else { return Observable.of(false); } } A: Use return Observable.of(false) instead of return false.
stackoverflow
{ "language": "en", "length": 144, "provenance": "stackexchange_0000F.jsonl.gz:847261", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487442" }
7b24008e1915f8b28f42677ad162c05cdcd376f2
Stackoverflow Stackexchange Q: How can I disable the blinking cursor in SciTE? I just installed the SciTE text editor as it was recommended for AutoHotkey syntax highlighting. However, I can't handle the blinking cursor, and SciTE does not obey the cursor settings on my Windows system, which are set to 'no blink'. Nor does it allow me to change the settings that I can find. I've looked online and through the 'Options' and all the entries on the menu bar, but I found no references. How can I disable it/prevent the cursor from blinking? Thanks for any help and suggestions. A: In your installation directory, exist a file named SciTEGlobal.properties. Open it and as suggested by wOxxOm find the line caret.period and change it's value to 0
Q: How can I disable the blinking cursor in SciTE? I just installed the SciTE text editor as it was recommended for AutoHotkey syntax highlighting. However, I can't handle the blinking cursor, and SciTE does not obey the cursor settings on my Windows system, which are set to 'no blink'. Nor does it allow me to change the settings that I can find. I've looked online and through the 'Options' and all the entries on the menu bar, but I found no references. How can I disable it/prevent the cursor from blinking? Thanks for any help and suggestions. A: In your installation directory, exist a file named SciTEGlobal.properties. Open it and as suggested by wOxxOm find the line caret.period and change it's value to 0
stackoverflow
{ "language": "en", "length": 125, "provenance": "stackexchange_0000F.jsonl.gz:847272", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487477" }
99ce9cfeab739d23ae689eb10237447c4670ba0f
Stackoverflow Stackexchange Q: Are android studio modules and eclipse projects the same thing? If yes, can modules be ran stand-alone as in eclipse projects ? Also, bonus points. If I save a variable in MainActivity.java can I pass it to a different java class in a a different module? If yes, how?
Q: Are android studio modules and eclipse projects the same thing? If yes, can modules be ran stand-alone as in eclipse projects ? Also, bonus points. If I save a variable in MainActivity.java can I pass it to a different java class in a a different module? If yes, how?
stackoverflow
{ "language": "en", "length": 50, "provenance": "stackexchange_0000F.jsonl.gz:847307", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487559" }
54e4c8abf344bf86418d828d9b905abfce43b082
Stackoverflow Stackexchange Q: Django shell mode in docker I am learning how to develop Django application in docker with this official tutorial: https://docs.docker.com/compose/django/ I have successfully run through the tutorial, and docker-compose run web django-admin.py startproject composeexample . creates the image docker-compose up runs the application The question is: I often use python manage.py shell to run Django in shell mode, but I do not know how to achieve that with docker. A: I use this command (when run with compose) docker-compose run <service_name> python manage.py shell where <service name> is the name of the docker service(in docker-compose.yml). So, In your case the command will be docker-compose run web python manage.py shell https://docs.docker.com/compose/reference/run/ When run with Dockerfile docker exec -it <container_id> python manage.py shell
Q: Django shell mode in docker I am learning how to develop Django application in docker with this official tutorial: https://docs.docker.com/compose/django/ I have successfully run through the tutorial, and docker-compose run web django-admin.py startproject composeexample . creates the image docker-compose up runs the application The question is: I often use python manage.py shell to run Django in shell mode, but I do not know how to achieve that with docker. A: I use this command (when run with compose) docker-compose run <service_name> python manage.py shell where <service name> is the name of the docker service(in docker-compose.yml). So, In your case the command will be docker-compose run web python manage.py shell https://docs.docker.com/compose/reference/run/ When run with Dockerfile docker exec -it <container_id> python manage.py shell A: You can use docker exec in the container to run commands like below. docker exec -it container_id python manage.py shell A: If you're using docker-compose you shouldn't always run additional containers when it's not needed to, as each run will start new container and you'll lose a lot of disk space. So you can end up with running multiple containers when you totally won't have to. Basically it's better to: * *Start your services once with docker-compose up -d *Execute (instead of running) your commands: docker-compose exec web ./manage.py shell or, if you don't want to start all services (because, for example - you want to run only one command in Django), then you should pass --rm flag to docker-compose run command, so the container will be removed just after passed command will be finished. docker-compose run --rm web ./manage.py shell In this case when you'll escape shell, the container created with run command will be destroyed, so you'll save much space on your disk. A: * *Run docker exec -it --user desired_user your_container bash Running this command has similar effect then runing ssh to remote server - after you run this command you will be inside container's bash terminal. You will be able to run all Django's manage.py commands. *Inside your container just run python manage.py shell A: If you're using Docker Compose (using command docker compose up) to spin up your applications, after you run that command then you can run the interactive shell in the container by using the following command: docker compose exec <container id or name of your Django app> python3 <path to your manage.py file, for example, src/manage.py> shell Keep in mind the above is using Python version 3+ with python3.
stackoverflow
{ "language": "en", "length": 410, "provenance": "stackexchange_0000F.jsonl.gz:847311", "question_score": "25", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487590" }
118cba908b23f56da73b8aad50a4f013b4d1920c
Stackoverflow Stackexchange Q: Laravel order of middleware (Middleware Priority). Multi-tenant using Postgres In web.php I've switched Postgres schemas in middleware as the subdomain type of HTTP request is made. This way: Route::group( [ 'domain' => '{tenant}.' . config('app.url'), 'middleware' => 'select-schema' ], function () { $this->get('/', 'HomeController@index')->middleware('auth'); } ); In select-schema middleware, I do something like this. This works correctly. (don't worry) DB::select('SET search_path TO ' . {tenant}); My main problem is that: I've different migrations for public schema and for any individual tenant. In individual tenant I have users table. As soon I'm logged in it pop up this error. SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "users" does not exist The main issue is $this->get('/', 'HomeController@index')->middleware('auth'); The model works well but middleware auth execute first before select-schema How do I order? select-schema then auth A: I've found the solution, For this, there's something called $middlewarePriority in App\Kernel. Adding this help me solve the problem. /** * Responsible for prioritizing the middleware * * @var array */ protected $middlewarePriority = [ \App\Http\Middleware\SwitchSchema::class, ]; I've got solution from this link. https://github.com/laravel/framework/issues/19565
Q: Laravel order of middleware (Middleware Priority). Multi-tenant using Postgres In web.php I've switched Postgres schemas in middleware as the subdomain type of HTTP request is made. This way: Route::group( [ 'domain' => '{tenant}.' . config('app.url'), 'middleware' => 'select-schema' ], function () { $this->get('/', 'HomeController@index')->middleware('auth'); } ); In select-schema middleware, I do something like this. This works correctly. (don't worry) DB::select('SET search_path TO ' . {tenant}); My main problem is that: I've different migrations for public schema and for any individual tenant. In individual tenant I have users table. As soon I'm logged in it pop up this error. SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "users" does not exist The main issue is $this->get('/', 'HomeController@index')->middleware('auth'); The model works well but middleware auth execute first before select-schema How do I order? select-schema then auth A: I've found the solution, For this, there's something called $middlewarePriority in App\Kernel. Adding this help me solve the problem. /** * Responsible for prioritizing the middleware * * @var array */ protected $middlewarePriority = [ \App\Http\Middleware\SwitchSchema::class, ]; I've got solution from this link. https://github.com/laravel/framework/issues/19565 A: Have you tried wrapping your routes in the tenant group with another group? See if this works: Route::group([ 'domain' => '{tenant}.' . config('app.url'), 'middleware' => 'select-schema' ],function () { Route::group(['middleware' => 'auth'], function () { Route::get('/', 'HomeController@index'); }); } );
stackoverflow
{ "language": "en", "length": 219, "provenance": "stackexchange_0000F.jsonl.gz:847368", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487764" }
449de978ce8cdf9a2980ad61c9ff83ba9e68d567
Stackoverflow Stackexchange Q: Rx.Subject.create(observer, observable) confusion In the API documentation it says Arguments * *observer (Observer): The observer used to send messages to the subject. *observable (Observable): The observable used to subscribe to messages sent from the subject. But isn't the concept backwards in that the observer is supposed to be receiving/handling messages emitted from the subject, and the observable is what the subject would be subscribed to? The API doc and the getting started with subjects doc don't seem consistent. A: Your question is already answered here: Subjects created with Subject.create can't unsubscribe Subject.create is a static method that just connects the Observable with an observer. No instance of Subject is involved. What you're describing looks more like multicasting so maybe have a look at multicast() operator or its derivatives. Also see: * *RxJs Subject.subscribe method not working as expected *Subject vs AnonymousSubject
Q: Rx.Subject.create(observer, observable) confusion In the API documentation it says Arguments * *observer (Observer): The observer used to send messages to the subject. *observable (Observable): The observable used to subscribe to messages sent from the subject. But isn't the concept backwards in that the observer is supposed to be receiving/handling messages emitted from the subject, and the observable is what the subject would be subscribed to? The API doc and the getting started with subjects doc don't seem consistent. A: Your question is already answered here: Subjects created with Subject.create can't unsubscribe Subject.create is a static method that just connects the Observable with an observer. No instance of Subject is involved. What you're describing looks more like multicasting so maybe have a look at multicast() operator or its derivatives. Also see: * *RxJs Subject.subscribe method not working as expected *Subject vs AnonymousSubject
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:847440", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44487988" }
7212e64b88390d070c2c3cac4acef871810d9e8c
Stackoverflow Stackexchange Q: JS: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience I'm receiving the error in my project trying an Ajax request [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. function getReviews() { var toReturn = $.ajax({ url: 'API/reviews.json', async: false }).responseJSON; return toReturn; } I would like to know if there is a different way to write this to not have that error A: Synchronous XMLHttpRequest is very bad because they are blocking entire app while it's waiting for a response from the server so you never should be using them. To make your request asynchronous remove async option and specify callback instead: function getReviews(cb) { $.ajax({ url: 'API/reviews.json' }).done(cb); } getReviews(function(data) { // Access your data here }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Q: JS: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience I'm receiving the error in my project trying an Ajax request [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. function getReviews() { var toReturn = $.ajax({ url: 'API/reviews.json', async: false }).responseJSON; return toReturn; } I would like to know if there is a different way to write this to not have that error A: Synchronous XMLHttpRequest is very bad because they are blocking entire app while it's waiting for a response from the server so you never should be using them. To make your request asynchronous remove async option and specify callback instead: function getReviews(cb) { $.ajax({ url: 'API/reviews.json' }).done(cb); } getReviews(function(data) { // Access your data here }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
stackoverflow
{ "language": "en", "length": 143, "provenance": "stackexchange_0000F.jsonl.gz:847446", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488002" }
02c7af2d4e64d56670b14820920a035411eebec4
Stackoverflow Stackexchange Q: How to check if a file exists So my problem is basically is that I can't figure out a condition to give an error message if can't find the file given as argument. if ARGV.empty? puts "Give me a file!" elseif [condition] puts "Can't find the file" else file = File.open(ARGV[0]) What I exactly need is the condition for the elseif. A: Try File.exist?, e.g. 2.3.0 :003 > File.exist? 'foo' => false
Q: How to check if a file exists So my problem is basically is that I can't figure out a condition to give an error message if can't find the file given as argument. if ARGV.empty? puts "Give me a file!" elseif [condition] puts "Can't find the file" else file = File.open(ARGV[0]) What I exactly need is the condition for the elseif. A: Try File.exist?, e.g. 2.3.0 :003 > File.exist? 'foo' => false
stackoverflow
{ "language": "en", "length": 73, "provenance": "stackexchange_0000F.jsonl.gz:847452", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488031" }
42d365e2aae6c66e46cdaa9f4faeb3e44013699e
Stackoverflow Stackexchange Q: Is Regexp.new(user_input) in ruby secure? Is it secure to create Regexp object from user-provided query directly, or do I need to do some validations on it first? Documentation doesn't say much one way or the other. A: Doesn't sound pretty good, if you allow to create any regex can be insecure (maybe cause DOS),since regexp can be cpu intensive. I would avoid to my client to create their own regexp freely. https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS
Q: Is Regexp.new(user_input) in ruby secure? Is it secure to create Regexp object from user-provided query directly, or do I need to do some validations on it first? Documentation doesn't say much one way or the other. A: Doesn't sound pretty good, if you allow to create any regex can be insecure (maybe cause DOS),since regexp can be cpu intensive. I would avoid to my client to create their own regexp freely. https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS
stackoverflow
{ "language": "en", "length": 73, "provenance": "stackexchange_0000F.jsonl.gz:847461", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488056" }
941df5a079530cdb311c33c6a664cc21c4c6e726
Stackoverflow Stackexchange Q: Concurrent http requests I am running the following method on multiple threads: private JSONObject jsonFromUrl(String requestUrl) { try { URLConnection connection = new URL(requestUrl).openConnection(); connection.setRequestProperty("Accept-Charset", charset); InputStream response = connection.getInputStream(); JSONParser jsonParser = new JSONParser(); return (JSONObject)jsonParser.parse( new InputStreamReader(response,charset)); } catch (Exception e) { Logger.error("Exception while sending request: " + requestUrl + " error: " + e); e.printStackTrace(); return new JSONObject(); } } Are the HTTP requests being processed in parallel? Does making the requests in this way blocks the other threads from sending a request until the first response arrives? A: The method can be invoked from different threads. No shared variable are present there so no concurrency issue. However you could optimize the process, by having a pool of connections (sockets connections) to reuse connections and for faster responses. Having no way to control the sockets, you could end up by having slow time response. Of course we are discussing about open socket connections and the possibility of the sever to keep the socket opened (Keep-Alive header)
Q: Concurrent http requests I am running the following method on multiple threads: private JSONObject jsonFromUrl(String requestUrl) { try { URLConnection connection = new URL(requestUrl).openConnection(); connection.setRequestProperty("Accept-Charset", charset); InputStream response = connection.getInputStream(); JSONParser jsonParser = new JSONParser(); return (JSONObject)jsonParser.parse( new InputStreamReader(response,charset)); } catch (Exception e) { Logger.error("Exception while sending request: " + requestUrl + " error: " + e); e.printStackTrace(); return new JSONObject(); } } Are the HTTP requests being processed in parallel? Does making the requests in this way blocks the other threads from sending a request until the first response arrives? A: The method can be invoked from different threads. No shared variable are present there so no concurrency issue. However you could optimize the process, by having a pool of connections (sockets connections) to reuse connections and for faster responses. Having no way to control the sockets, you could end up by having slow time response. Of course we are discussing about open socket connections and the possibility of the sever to keep the socket opened (Keep-Alive header)
stackoverflow
{ "language": "en", "length": 170, "provenance": "stackexchange_0000F.jsonl.gz:847481", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488110" }
c1a7dbf2612ac3e67050c134fc4b5bd75349b2b7
Stackoverflow Stackexchange Q: Change column variable string from "1" to "01" I have a column in a dataframe that is a charachter type. The variables are a mix of 1, 01, 2, 01, 3, 03, 4, 04 etc. How would I select all without a leading '0' and format so they are all 01, 02, 03, 04 etc A: We need to first convert it to numeric and use sprintf df1$col1 <- sprintf("%02d", as.numeric(df1$col1)) df1$col1 #[1] "01" "01" "02" "01" "03" "03" "04" "04" If it is a factor column, first convert to character before heading to numeric df1$col1 <- sprintf("%02d", as.numeric(as.character(df1$col1))) If there are LETTERS included df1$col1 <- c(1, '01', 2, '01', 3, 'A', 4, '04') i1 <- grepl("^[0-9]$", df1$col1) df1$col1[i1] <- paste0("0", df1$col1[i1]) df1$col1 #[1] "01" "01" "02" "01" "03" "A" "04" "04" data df1 <- data.frame(col1 = c(1, '01', 2, '01', 3, '03', 4, '04'), stringsAsFactors=FALSE)
Q: Change column variable string from "1" to "01" I have a column in a dataframe that is a charachter type. The variables are a mix of 1, 01, 2, 01, 3, 03, 4, 04 etc. How would I select all without a leading '0' and format so they are all 01, 02, 03, 04 etc A: We need to first convert it to numeric and use sprintf df1$col1 <- sprintf("%02d", as.numeric(df1$col1)) df1$col1 #[1] "01" "01" "02" "01" "03" "03" "04" "04" If it is a factor column, first convert to character before heading to numeric df1$col1 <- sprintf("%02d", as.numeric(as.character(df1$col1))) If there are LETTERS included df1$col1 <- c(1, '01', 2, '01', 3, 'A', 4, '04') i1 <- grepl("^[0-9]$", df1$col1) df1$col1[i1] <- paste0("0", df1$col1[i1]) df1$col1 #[1] "01" "01" "02" "01" "03" "A" "04" "04" data df1 <- data.frame(col1 = c(1, '01', 2, '01', 3, '03', 4, '04'), stringsAsFactors=FALSE) A: vec<-c("01","1","2","03","05","3","4","A","B","XX") >vec [1] "01" "1" "2" "03" "05" "3" "4" "A" "B" "XX" Then: ifelse(nchar(vec)!=2,paste0("0",vec),vec) [1] "01" "01" "02" "03" "05" "03" "04" "0A" "0B" "XX" EDIT (check only numeric ones. Leave characters unchanged) ifelse((nchar(vec)!=2 &!is.na(as.numeric(vec))) ,paste0("0",vec),vec) [1] "01" "01" "02" "03" "05" "03" "04" "A" "B" "XX" A: This regex solution inserts a 0 when col1 is a digit: df1 <- data.frame( col1 = c(1, '01', 2, '01', 3, '03', 4, '04','A','XX'), stringsAsFactors = FALSE) df1$col1 <- gsub("(\\d)+", "0\\1", df1$col1) df1$col1 # [1] "01" "01" "02" "01" "03" "03" "04" "04" "A" "XX"
stackoverflow
{ "language": "en", "length": 242, "provenance": "stackexchange_0000F.jsonl.gz:847538", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488300" }
6f84218d78c82985389f1d51d85831cc7a8b54b5
Stackoverflow Stackexchange Q: Krakenex API multiple pairs query I am trying to use the Krakenex python library to query the order book for multiple currency pairs at once. When I do it for a single currency is works, like this: con = krakenex.API() con.load_key('kraken.key') con.query_public('Depth', {'pair':'GNOETH'}) However, if I do: con = krakenex.API() con.load_key('kraken.key') con.query_public('Depth', {'pair':['GNOETH', 'GNOEUR']}) I get {'error': ['EQuery:Unknown asset pair']}. I assume that the syntax is incorrect but can't figure out the correct one. This is the first time that I use an API and the example provided are not covering enough info yet. A: Unfortunately you can not query the Depth of multiple asset pairs with a single request. I had the same question to Kraken's support: their reason not allowing it, is high computational cost. On contrary, querying e.g. AssetPairs endpoint in the same manner works.
Q: Krakenex API multiple pairs query I am trying to use the Krakenex python library to query the order book for multiple currency pairs at once. When I do it for a single currency is works, like this: con = krakenex.API() con.load_key('kraken.key') con.query_public('Depth', {'pair':'GNOETH'}) However, if I do: con = krakenex.API() con.load_key('kraken.key') con.query_public('Depth', {'pair':['GNOETH', 'GNOEUR']}) I get {'error': ['EQuery:Unknown asset pair']}. I assume that the syntax is incorrect but can't figure out the correct one. This is the first time that I use an API and the example provided are not covering enough info yet. A: Unfortunately you can not query the Depth of multiple asset pairs with a single request. I had the same question to Kraken's support: their reason not allowing it, is high computational cost. On contrary, querying e.g. AssetPairs endpoint in the same manner works. A: Spent a lot of time trying different combos, finally figured it out. try con.query_public('Depth', {'pair':'GNOETH, GNOEUR'})
stackoverflow
{ "language": "en", "length": 156, "provenance": "stackexchange_0000F.jsonl.gz:847548", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488326" }
67fdf1aa0ea9498c07321835327c95e4e0438a8c
Stackoverflow Stackexchange Q: Windows 10 conda is not recognized as an internal or external command Tried to conda install -c conda-forge requests-futures=0.9.7 but failed with conda is not recognized as an internal or external command, C:\Users\user_name\Anaconda3\Scripts has been set for Path in environment variables under both user and System variables. I installed Python 3.5 as well and it is on Path, I am using Win10 X64. How to fix the issue? A: When you install anaconda on windows now, it doesn't automatically add Python or Conda to your path. If you don’t know where your conda and/or python is, you type the following commands into your anaconda prompt Next, you can add Python and Conda to your path by using the setx command in your command prompt. Next close that command prompt and open a new one. Congrats you can now use conda and python Source: https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444
Q: Windows 10 conda is not recognized as an internal or external command Tried to conda install -c conda-forge requests-futures=0.9.7 but failed with conda is not recognized as an internal or external command, C:\Users\user_name\Anaconda3\Scripts has been set for Path in environment variables under both user and System variables. I installed Python 3.5 as well and it is on Path, I am using Win10 X64. How to fix the issue? A: When you install anaconda on windows now, it doesn't automatically add Python or Conda to your path. If you don’t know where your conda and/or python is, you type the following commands into your anaconda prompt Next, you can add Python and Conda to your path by using the setx command in your command prompt. Next close that command prompt and open a new one. Congrats you can now use conda and python Source: https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444 A: There is a similar question asked here before, check this may be it will help you. To make sure that conda package is installed correctly, check if conda package files , i.e conda conda-env conda-env-script conda-script conda-server conda-server-script etc are present in Anaconda3\Scripts folder. A: I had a similar problem when using cmd. From your Command prompt 'C:\Users\zkdur\anaconda3\Scripts Now try conda init --help conda init --verbose after that restart your command prompt and conda will be working. A: After installing Anaconda on windows 10, you can use Anaconda prompt from start menu to activate a conda enabled terminal window. A: Just Check Both the options while installing Anaconda. (https://i.stack.imgur.com/WogNs.jpg)
stackoverflow
{ "language": "en", "length": 255, "provenance": "stackexchange_0000F.jsonl.gz:847557", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488349" }
05d76a2c5cd445c34ddcd828efcffb871aa7e86d
Stackoverflow Stackexchange Q: How can I get list of all data set codes of Quandl API? I want list of all dataset codes for each company,Ex. for Facebook dataset code is FB,for MICROSOFT it is MSFT.How can I get such list of all available codes for data sets ?? A: You can get the list of all the available datasets in a database provided you have the database name. GET https://www.quandl.com/api/v3/datasets?database_code=<database-name>&api_key=<api-key> Replace the value <database-name> and <api-key> in the above URL. This will return a list of dataset object. Each object will have a dataset_code field having the required value. Make sure you register on the quandl website for getting the access key. You do not have to pay or give credit card details for registration. For JSON response you can use the below. Also you can mention the current page and page size as below - https://www.quandl.com/api/v3/datasets.json?database_code=${databaseCode}&api_key=${apiKey}&current_page=${currentPage}&per_page=${perPage}
Q: How can I get list of all data set codes of Quandl API? I want list of all dataset codes for each company,Ex. for Facebook dataset code is FB,for MICROSOFT it is MSFT.How can I get such list of all available codes for data sets ?? A: You can get the list of all the available datasets in a database provided you have the database name. GET https://www.quandl.com/api/v3/datasets?database_code=<database-name>&api_key=<api-key> Replace the value <database-name> and <api-key> in the above URL. This will return a list of dataset object. Each object will have a dataset_code field having the required value. Make sure you register on the quandl website for getting the access key. You do not have to pay or give credit card details for registration. For JSON response you can use the below. Also you can mention the current page and page size as below - https://www.quandl.com/api/v3/datasets.json?database_code=${databaseCode}&api_key=${apiKey}&current_page=${currentPage}&per_page=${perPage}
stackoverflow
{ "language": "en", "length": 146, "provenance": "stackexchange_0000F.jsonl.gz:847589", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488454" }
41c0d9203f1e779b997f5e6c6ffb4b2e02f7476e
Stackoverflow Stackexchange Q: How do I get Celery to return a json object instead of bytea? This is my first time working with Celery in Python 3. To get my feet wet, I'm returning a string "this was a hello task" as a result from a worker and storing this is a Postgres database. When I access the result from my database it's in the form of a memoryview in Python and the database itself has a the result column of celery_taskmeta as the datatype bytea (this is also what Celery sends to the database as well). This is my celery config: import os broker_url = os.environ.get('RABBITMQ_BIGWIG_TX_URL') worker_concurrency = 3 result_backend = 'db+postgres://...' task_serializer = 'json' result_serializer = 'json' accept_content = ['json'] Why am I not getting a json result stored in my database? Also, I cannot decode the bytea to json or utf-8 text, i get this error: here's what it looks like in bytes: b'\x80\x04\x95\x1b\x00\x00\x00\x00\x00\x00\x00\x8c\x17"this was a hello task"\x94.' command: json.loads(t.tobytes()) result: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte A: you need to convert byte data to unicode t.decode("utf-8")
Q: How do I get Celery to return a json object instead of bytea? This is my first time working with Celery in Python 3. To get my feet wet, I'm returning a string "this was a hello task" as a result from a worker and storing this is a Postgres database. When I access the result from my database it's in the form of a memoryview in Python and the database itself has a the result column of celery_taskmeta as the datatype bytea (this is also what Celery sends to the database as well). This is my celery config: import os broker_url = os.environ.get('RABBITMQ_BIGWIG_TX_URL') worker_concurrency = 3 result_backend = 'db+postgres://...' task_serializer = 'json' result_serializer = 'json' accept_content = ['json'] Why am I not getting a json result stored in my database? Also, I cannot decode the bytea to json or utf-8 text, i get this error: here's what it looks like in bytes: b'\x80\x04\x95\x1b\x00\x00\x00\x00\x00\x00\x00\x8c\x17"this was a hello task"\x94.' command: json.loads(t.tobytes()) result: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte A: you need to convert byte data to unicode t.decode("utf-8") A: You'll need to load it with pickle. import pickle pickle.loads(t, encoding='utf-8') Struggling with this myself, trying to get Celery to store results in the DB JSON-serialized instead of pickled.
stackoverflow
{ "language": "en", "length": 215, "provenance": "stackexchange_0000F.jsonl.gz:847598", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488489" }
623f91432f3eddeacfc2affd8b329c2ef52ea2da
Stackoverflow Stackexchange Q: How does one take the transpose of an R data.table? Why doesn't t() work? I have the following R data.table library(data.table) mtcars = as.data.table(mtcars) dt = colSums(mtcars) > dt mpg cyl disp hp drat wt qsec vs 642.900 198.000 7383.100 4694.000 115.090 102.952 571.160 14.000 am gear carb 13.000 118.000 90.000 I would like to reshape the data.table dt as follows: > transpose column1 column2 mpg 642.900 cyl 198.000 disp 7373.100 hp 4694.000 drat 115.090 wt 102.952 qsec 571.160 vs 14.000 am 13.000 gear 118.000 carb 90.000 The function t() doesn't appear to work as expected. transpose = t(dt) I suspect there's a quick way to do this with melt() and dcast(), but I'm not sure how one defines each column, i.e. column1 and column2 A: I found this to work: df = as.data.table(t(as.matrix(dt))) And it even preserves the names
Q: How does one take the transpose of an R data.table? Why doesn't t() work? I have the following R data.table library(data.table) mtcars = as.data.table(mtcars) dt = colSums(mtcars) > dt mpg cyl disp hp drat wt qsec vs 642.900 198.000 7383.100 4694.000 115.090 102.952 571.160 14.000 am gear carb 13.000 118.000 90.000 I would like to reshape the data.table dt as follows: > transpose column1 column2 mpg 642.900 cyl 198.000 disp 7373.100 hp 4694.000 drat 115.090 wt 102.952 qsec 571.160 vs 14.000 am 13.000 gear 118.000 carb 90.000 The function t() doesn't appear to work as expected. transpose = t(dt) I suspect there's a quick way to do this with melt() and dcast(), but I'm not sure how one defines each column, i.e. column1 and column2 A: I found this to work: df = as.data.table(t(as.matrix(dt))) And it even preserves the names A: A dplyr solution: library(dplyr) library(data.table) mtcars <- data.table(mtcars) # make data.table class(mtcars) # check that it is a data.table mtcars %>% # take the data.table summarise_all(funs(sum)) %>% # get the sum of each column gather(variable, sum) # gather all columns gather, spread, and summarise is how I do all of my transposing. "Variable" and "sum" become the new column names: variable sum 1 mpg 642.900 2 cyl 198.000 3 disp 7383.100 4 hp 4694.000 5 drat 115.090 6 wt 102.952 7 qsec 571.160 8 vs 14.000 9 am 13.000 10 gear 118.000 11 carb 90.000
stackoverflow
{ "language": "en", "length": 237, "provenance": "stackexchange_0000F.jsonl.gz:847599", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488496" }
353d033096c983d0b7b5e2832f77ec019a2728da
Stackoverflow Stackexchange Q: C#: SerializableAttribute could not be found I am trying to use the [Serializable] attribute in a C# class library project (latest .NET version), but it is not recognised. As far as I could search, Serializable it something that belongs in System.Runtime.Serialization System, but I have used it and it still doesn't work. I am using it in other projects (Unity), but it doesn't work here. Any ideas? using System; using System.Runtime; using System.Xml.Serialization; using System.Runtime.Serialization; using System.Collections.Generic; namespace Model{ [Serializable] public struct GameSettings{ public int Players; } } Thank you in advance Edit: format Edit2: screenshot of the error A: This attribute lives in System, not in System.Runtime.Serialization: namespace System { /// <summary>Indicates that a class can be serialized. This class cannot be inherited.</summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)] [ComVisible(true)] public sealed class SerializableAttribute : Attribute { //... } } Are you sure you have referenced mscorlib.dll? This question might be interessting for you.
Q: C#: SerializableAttribute could not be found I am trying to use the [Serializable] attribute in a C# class library project (latest .NET version), but it is not recognised. As far as I could search, Serializable it something that belongs in System.Runtime.Serialization System, but I have used it and it still doesn't work. I am using it in other projects (Unity), but it doesn't work here. Any ideas? using System; using System.Runtime; using System.Xml.Serialization; using System.Runtime.Serialization; using System.Collections.Generic; namespace Model{ [Serializable] public struct GameSettings{ public int Players; } } Thank you in advance Edit: format Edit2: screenshot of the error A: This attribute lives in System, not in System.Runtime.Serialization: namespace System { /// <summary>Indicates that a class can be serialized. This class cannot be inherited.</summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)] [ComVisible(true)] public sealed class SerializableAttribute : Attribute { //... } } Are you sure you have referenced mscorlib.dll? This question might be interessting for you. A: https://apisof.net/catalog/System.SerializableAttribute shows that [Serializable] is defined in the System.Runtime.Serialization.Formatters package for .NET Core 1.0 and 1.1 and .NET Standard 1.6. It then moved to System.Runtime for .NET Core 2.0 and the netstandard monolith for .NET Standard 2.0. If you just care about being able to compile shared code, you could try adding the package reference. But What is the equivalent of [Serializable] in .NET Core ? (Conversion Projects) has already answered that the binary serializer isn't in .NET Core 1.x (unsure about its 2.0 status... but since 2.0 is in preview you could always try it out).
stackoverflow
{ "language": "en", "length": 258, "provenance": "stackexchange_0000F.jsonl.gz:847637", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488609" }
66d7d691801f2bc06a485b23002d7c75c2824bb6
Stackoverflow Stackexchange Q: Kotlin kapt and android architecture components build fail I'am using Kotlin, kapt and Android Architecture components. When I build project everything seems fine but after trying to run app on device/emulator Gradle's :assemble task throw these errors: Warning:warning: Supported source version 'RELEASE_7' from annotation processor 'android.arch.persistence.room.RoomProcessor' less than -source '1.8' Warning:warning: Supported source version 'RELEASE_7' from annotation processor 'android.arch.lifecycle.LifecycleProcessor' less than -source '1.8' Warning:warning: The following options were not recognized by any processor: '[kapt.kotlin.generated]' And build fails. Can someone help me with it? UPDATE * *module build.gradle HERE *project build.gradle HERE A: I had the same problem with version 1.0.0-alpha3, but with version 1.0.0-alpha1 everything works fine.
Q: Kotlin kapt and android architecture components build fail I'am using Kotlin, kapt and Android Architecture components. When I build project everything seems fine but after trying to run app on device/emulator Gradle's :assemble task throw these errors: Warning:warning: Supported source version 'RELEASE_7' from annotation processor 'android.arch.persistence.room.RoomProcessor' less than -source '1.8' Warning:warning: Supported source version 'RELEASE_7' from annotation processor 'android.arch.lifecycle.LifecycleProcessor' less than -source '1.8' Warning:warning: The following options were not recognized by any processor: '[kapt.kotlin.generated]' And build fails. Can someone help me with it? UPDATE * *module build.gradle HERE *project build.gradle HERE A: I had the same problem with version 1.0.0-alpha3, but with version 1.0.0-alpha1 everything works fine.
stackoverflow
{ "language": "en", "length": 108, "provenance": "stackexchange_0000F.jsonl.gz:847642", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488620" }
46deaaa580c409c5e79a2405f8eb54bd6059ae5f
Stackoverflow Stackexchange Q: In React do ref's reference the virtual DOM, or the actual DOM? I'm assuming the virtual DOM, and that React takes care of it with diff'ing. But I had a recruiter say that ref's affect the actual DOM, I can't see how this can be. I assume that they were just mistaken. A: Refs should reference the actual DOM. One usage of Refs is integrating with third-party DOM libraries, so you can directly modify the DOM using Refs. If Refs reference the virtual DOM, I don't think the demand can be meet. You modify a virtual DOM, but you can't make sure the modification would be synchronized to the actual DOM. Besides, if you want to modify actual DOM when using react, you should always modify the state of components instead of modifying the DOM by Refs.
Q: In React do ref's reference the virtual DOM, or the actual DOM? I'm assuming the virtual DOM, and that React takes care of it with diff'ing. But I had a recruiter say that ref's affect the actual DOM, I can't see how this can be. I assume that they were just mistaken. A: Refs should reference the actual DOM. One usage of Refs is integrating with third-party DOM libraries, so you can directly modify the DOM using Refs. If Refs reference the virtual DOM, I don't think the demand can be meet. You modify a virtual DOM, but you can't make sure the modification would be synchronized to the actual DOM. Besides, if you want to modify actual DOM when using react, you should always modify the state of components instead of modifying the DOM by Refs.
stackoverflow
{ "language": "en", "length": 138, "provenance": "stackexchange_0000F.jsonl.gz:847699", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488816" }
ec2317f009ea6f0d9283bf11a9f9774d8b1aa4cd
Stackoverflow Stackexchange Q: How to get first value from this sql query Im trying to get by subquery clientId of customer with most orders but only one expression can be specified in the select list when the subquery is not introduced with EXISTS. SELECT a.ClientName FROM Clients as a INNER JOIN Orders as b ON a.Id=b.ClientId WHERE b.ClientId IN(SELECT b.ClientId,COUNT( b.ClientId) as MAKS FROM Orders as b GROUP BY b.ClientId ORDER BY MAKS DESC) Do we have some tools to handle this and how can i optimize this query? Thanks in advance. A: You don't really need the inner join because you are asking for an ID that is the same in both tables, SELECT ClientName FROM Clients WHERE Id = (SELECT TOP 1 ClientId FROM Orders GROUP BY ClientId ORDER BY COUNT(ClientId) DESC)
Q: How to get first value from this sql query Im trying to get by subquery clientId of customer with most orders but only one expression can be specified in the select list when the subquery is not introduced with EXISTS. SELECT a.ClientName FROM Clients as a INNER JOIN Orders as b ON a.Id=b.ClientId WHERE b.ClientId IN(SELECT b.ClientId,COUNT( b.ClientId) as MAKS FROM Orders as b GROUP BY b.ClientId ORDER BY MAKS DESC) Do we have some tools to handle this and how can i optimize this query? Thanks in advance. A: You don't really need the inner join because you are asking for an ID that is the same in both tables, SELECT ClientName FROM Clients WHERE Id = (SELECT TOP 1 ClientId FROM Orders GROUP BY ClientId ORDER BY COUNT(ClientId) DESC) A: Using Top 1, Count and Group By SQL Server SELECT Top 1 a.ClientName , count(b.orders_id) TotalOrders FROM Clients as a INNER JOIN Orders as b ON a.Id=b.ClientId GROUP BY a.client_name order by TotalOrders desc MySQL SELECT a.ClientName , count(b.orders_id) TotalOrders FROM Clients as a INNER JOIN Orders as b ON a.Id=b.ClientId GROUP BY a.client_name order by TotalOrders desc LIMIT 1
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:847703", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488829" }
caff4883a1b949a3c2f0715c967c02a648b4ecb9
Stackoverflow Stackexchange Q: No FileSystem for scheme: wasb error in Hadoop 2.7 I am trying to establish the connection between hadoop and Azure storage. I have added the property in core-site.xml mentioned here: Link, still getting the error No FileSystem for scheme: wasb Any help is appreciated! A: Please try to add the required Java library hadoop-azure into your Hadoop lib path. You can download from here. Hope it helps. Any concern, please feel free to let me know.
Q: No FileSystem for scheme: wasb error in Hadoop 2.7 I am trying to establish the connection between hadoop and Azure storage. I have added the property in core-site.xml mentioned here: Link, still getting the error No FileSystem for scheme: wasb Any help is appreciated! A: Please try to add the required Java library hadoop-azure into your Hadoop lib path. You can download from here. Hope it helps. Any concern, please feel free to let me know.
stackoverflow
{ "language": "en", "length": 77, "provenance": "stackexchange_0000F.jsonl.gz:847723", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488872" }
da03dd82588636dda2c7a48fbcc910c92c9f167f
Stackoverflow Stackexchange Q: Angular2: How to get a reference to a component using Javascript in the browser console In an Angular2 app, how do I access a component's controller from the browser console, using Javascript? I am trying to invoke a method from a service used by my component. EDIT: My intent is to invoke it from within Protractor tests. From what I've read here, I should be able to get a reference to the instance of my component class by using ng.probe($0).componentInstance, but I am getting null.
Q: Angular2: How to get a reference to a component using Javascript in the browser console In an Angular2 app, how do I access a component's controller from the browser console, using Javascript? I am trying to invoke a method from a service used by my component. EDIT: My intent is to invoke it from within Protractor tests. From what I've read here, I should be able to get a reference to the instance of my component class by using ng.probe($0).componentInstance, but I am getting null.
stackoverflow
{ "language": "en", "length": 86, "provenance": "stackexchange_0000F.jsonl.gz:847761", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44488984" }
5f49f4b20f2ded65cc056756485dc671b13a818b
Stackoverflow Stackexchange Q: Angular - Form Array push specific index addStop() { const control = <FormArray>this.editForm.controls['stops']; control.push(this.initStop()); } I have this code to add a "stop" at the bottom of the form array. But I want to add the new "stop" not to the last position, but one position before the last stop. This doesn't work for example (not at all, I know that the numbers are wrong. Splice function doesn't exist at ) control.splice(2, 0, this.initStop()); A: Use FormArray#insert: control.insert(<index>, this.initStop());
Q: Angular - Form Array push specific index addStop() { const control = <FormArray>this.editForm.controls['stops']; control.push(this.initStop()); } I have this code to add a "stop" at the bottom of the form array. But I want to add the new "stop" not to the last position, but one position before the last stop. This doesn't work for example (not at all, I know that the numbers are wrong. Splice function doesn't exist at ) control.splice(2, 0, this.initStop()); A: Use FormArray#insert: control.insert(<index>, this.initStop());
stackoverflow
{ "language": "en", "length": 80, "provenance": "stackexchange_0000F.jsonl.gz:847775", "question_score": "20", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489034" }
d7a3e02347fda0b5dee4bb42cdfe517e0569862a
Stackoverflow Stackexchange Q: How can I add a new form control to the nested form group? I have this form group: this.form = fb.group({ 'teacher': [''], 'schools': fb.array([ fb.group({ 'school_name': [''], 'school_description': [''], }) }) }); The question is: How can I add a new form control (named school_city) to a specific *group" of FormArray programatically through a function? A: To add some control to every group inside FormArray, you can do the following: someFunc() { const formArr = this.form.get('schools') as FormArray; for (const group of formArr.controls) { group.addControl('school_city', this.fb.control('')); } } PLUNKER Edit#1: As the OP now explains that he wants to add the control to a specific group: You have to pass the index of the group that you want to add the control: someFunc(idx: number) { const group = this.form.get(`schools.${idx}`) as FormGroup; group.addControl('school_city', this.fb.control('')); }
Q: How can I add a new form control to the nested form group? I have this form group: this.form = fb.group({ 'teacher': [''], 'schools': fb.array([ fb.group({ 'school_name': [''], 'school_description': [''], }) }) }); The question is: How can I add a new form control (named school_city) to a specific *group" of FormArray programatically through a function? A: To add some control to every group inside FormArray, you can do the following: someFunc() { const formArr = this.form.get('schools') as FormArray; for (const group of formArr.controls) { group.addControl('school_city', this.fb.control('')); } } PLUNKER Edit#1: As the OP now explains that he wants to add the control to a specific group: You have to pass the index of the group that you want to add the control: someFunc(idx: number) { const group = this.form.get(`schools.${idx}`) as FormGroup; group.addControl('school_city', this.fb.control('')); }
stackoverflow
{ "language": "en", "length": 136, "provenance": "stackexchange_0000F.jsonl.gz:847787", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489078" }
bda6fba953a851f587af10c3826e2fb55267aee7
Stackoverflow Stackexchange Q: How to create named reference-type tuples? The following line creates a named ValueTuple: var tuple = (a:1, b:2, c:3, d:4, e:5, f:6); Value types can not be passed around efficiently. Does C#7 offer a way to create named tuples of the Tuple type? A: If you mean if there's a way to attach other names to the properties of System.Tuple<...> instances, no there isn't. Depending on why you want it, you might get around it by converting System.Tuple<...> instances to System.ValueTuple<...> instances using the ToValueTuple overloads in TupleExtensions and back using the ToTuple overloads. If you don't really need the tuples, you can deconstruct them into discrete variables using the Deconstruct overloads or the var (v1, .., vn) = tuple deconstruction syntax.
Q: How to create named reference-type tuples? The following line creates a named ValueTuple: var tuple = (a:1, b:2, c:3, d:4, e:5, f:6); Value types can not be passed around efficiently. Does C#7 offer a way to create named tuples of the Tuple type? A: If you mean if there's a way to attach other names to the properties of System.Tuple<...> instances, no there isn't. Depending on why you want it, you might get around it by converting System.Tuple<...> instances to System.ValueTuple<...> instances using the ToValueTuple overloads in TupleExtensions and back using the ToTuple overloads. If you don't really need the tuples, you can deconstruct them into discrete variables using the Deconstruct overloads or the var (v1, .., vn) = tuple deconstruction syntax. A: Not sure what the problem is; everything works as expected for me for passing the new ValueTuple<T> with out, ref, and the new ref locals. I'm using .NET 4.7 and have my C#7 compiler set to "latest" in the .csproj settings "Advanced..." button. Demonstration functions (and data): static (int, int) g = (1, 2); static void SetValues(int a, int b, ref (int, int) tt) => tt = (a, b); static void SetValuesOut(int a, int b, out (int, int) tt) => tt = (a, b); static ref (int, int) GetKnownTuple() => ref g; static ref (int, int) SelectRef( int ix, ref (int, int) x, ref (int, int) y, ref (int, int) z) { if (ix == 0) return ref x; if (ix == 1) return ref y; return ref z; } Usage Examples: static void demo_usages() { /// use 'ref return' to initialize a new 'ref local' tuple 'aa' ref (int, int) aa = ref GetKnownTuple(); /// or use the same function without 'ref' to create a local COPY 'bb' var bb = GetKnownTuple(); /// use 'ref' parameter to modify values of local copy 'bb' ('aa/g' are not altered) SetValues(3, 4, ref bb); /// deconstruction of 'ref local' tuple; reads values from referent 'g' (1, 2) (int x, int y) = aa; /// 'ref local' reference to a local tuple copy ref (int, int) dd = ref bb; /// use 'out' parameter to construct a new (non-'ref') local tuple 'cc' SetValuesOut(y, x, out (int, int) cc); /// ...or use 'out' with 'ref local' to wholly replace existing referent ('g' here) SetValuesOut(5, 6, out aa); /// 'ref return' function can also be used as assignment l-value... GetKnownTuple() = (7, 8); /// ('aa/g' are altered; locals 'bb' and 'cc' remain unchanged) /// ...or assign a referent via 'ref local' variable (changes 'g' again) aa = (9, 10); /// conditional assignment via 'ref return' (changes 'g' again) SelectRef(0, ref aa, ref bb, ref cc) = (11, 12); } It should be clear that much more is possible, but all cannot be shown here since the OP's question does not get into too many specific further requirements.
stackoverflow
{ "language": "en", "length": 476, "provenance": "stackexchange_0000F.jsonl.gz:847794", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489110" }
ea01324b231402035e589f5e9917c7a411a6f5ee
Stackoverflow Stackexchange Q: Magic Python not working I am newbie in python, and I am working on a project that need to detect the type of the file so I used magic library, However the code is not working and it is raising exception. The test code is: import magic magic.from_file("./example.db") The Traceback : Traceback (most recent call last): - File "C:\Users\mariam\Desktop\pythonscripto\test.py", line 4, in <module> magic.from_file("./example.db") - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 122, in from_file m = _get_magic_type(mime) - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 111, in _get_magic_type i = _instances[mime] = Magic(mime=mime) - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 60, in \__init__ magic_load(self.cookie, magic_file) - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 250, in magic_load return _magic_load(cookie, coerce_filename(filename)) - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 181, in errorcheck_negative_one raise MagicException(err) magic.MagicException: None Any help? A: I solved this problem, only make sure that your Python version is 64 bit, as well as dependencies files, you should include the following files in the same folder: * *regex2.dll *zlib1.dll *magic (no extension) *magic.mgc *libgnurx-0.dll *magic.py
Q: Magic Python not working I am newbie in python, and I am working on a project that need to detect the type of the file so I used magic library, However the code is not working and it is raising exception. The test code is: import magic magic.from_file("./example.db") The Traceback : Traceback (most recent call last): - File "C:\Users\mariam\Desktop\pythonscripto\test.py", line 4, in <module> magic.from_file("./example.db") - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 122, in from_file m = _get_magic_type(mime) - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 111, in _get_magic_type i = _instances[mime] = Magic(mime=mime) - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 60, in \__init__ magic_load(self.cookie, magic_file) - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 250, in magic_load return _magic_load(cookie, coerce_filename(filename)) - File "C:\Users\mariam\Desktop\pythonscripto\magic.py", line 181, in errorcheck_negative_one raise MagicException(err) magic.MagicException: None Any help? A: I solved this problem, only make sure that your Python version is 64 bit, as well as dependencies files, you should include the following files in the same folder: * *regex2.dll *zlib1.dll *magic (no extension) *magic.mgc *libgnurx-0.dll *magic.py
stackoverflow
{ "language": "en", "length": 158, "provenance": "stackexchange_0000F.jsonl.gz:847796", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489116" }
2fabe737ab247e39884cc09b64e22868c68d55c8
Stackoverflow Stackexchange Q: Python passing parameters with ctypes, invalid parameter I am new in python and recently using python to program CCD camera to taking pictures. I want to call a function in a .so file using ctypes. The prototype of the function is: INT is_ImageFile (HIDS hCam, UINT nCommand, void* pParam, UINT cbSizeOfParam) HIDS is uint type. An example given officially with c code is : is_ImageFile(m_hCam, IS_IMAGE_FILE_CMD_SAVE, (void*)&ImageFileParams, sizeof(ImageFileParams)); where ImageFileParams is a struct type: typedef struct{ wchar_t* pwchFileName; UINT nFileType; UINT nQuality; char** ppcImageMem; UINT* pnImageID; BYTE reserved[32];}IMAGE_FILE_PARAMS; In my .py file, I tried to define the struct in this way: class IMAGE_FILE_PARAMS(Structure): _fields_=[("pwchFileNmae",c_wchar_p),("nFileType",c_uint),("nQuality",c_uint),("ppcImageMem",POINTER(c_char_p)),("pnImageID",POINTER(c_char_p)),("reserved",c_byte*32)] and define some of the members in this way: ImageFileParams.pwchFileName = c_wchar_p("/home/user/aa.jpg") ImageFileParams.nQuality=c_uint(80) ImageFileParams.nFileType=c_uint(1) then call the function: is_ImageFile(hCam, IS_IMAGE_FILE_CMD_SAVE, cast(pointer(ImageFileParams),c_void_p),c_uint(sizeof(ImageFileParams))) But I always get an error indicating invalid parameter. What's the problem? A: I believe you are getting the invalid parameter error because of the last parameter: c_uint(sizeof(ImageFileParams)) I checked the docs, and some example codes on their IDS website and I think you need to call it like this (assuming you import their ueye library: is_ImageFile(hCam, ueye.IS_IMAGE_FILE_CMD_SAVE, ImageFileParams,ueye.sizeof(ImageFileParams))
Q: Python passing parameters with ctypes, invalid parameter I am new in python and recently using python to program CCD camera to taking pictures. I want to call a function in a .so file using ctypes. The prototype of the function is: INT is_ImageFile (HIDS hCam, UINT nCommand, void* pParam, UINT cbSizeOfParam) HIDS is uint type. An example given officially with c code is : is_ImageFile(m_hCam, IS_IMAGE_FILE_CMD_SAVE, (void*)&ImageFileParams, sizeof(ImageFileParams)); where ImageFileParams is a struct type: typedef struct{ wchar_t* pwchFileName; UINT nFileType; UINT nQuality; char** ppcImageMem; UINT* pnImageID; BYTE reserved[32];}IMAGE_FILE_PARAMS; In my .py file, I tried to define the struct in this way: class IMAGE_FILE_PARAMS(Structure): _fields_=[("pwchFileNmae",c_wchar_p),("nFileType",c_uint),("nQuality",c_uint),("ppcImageMem",POINTER(c_char_p)),("pnImageID",POINTER(c_char_p)),("reserved",c_byte*32)] and define some of the members in this way: ImageFileParams.pwchFileName = c_wchar_p("/home/user/aa.jpg") ImageFileParams.nQuality=c_uint(80) ImageFileParams.nFileType=c_uint(1) then call the function: is_ImageFile(hCam, IS_IMAGE_FILE_CMD_SAVE, cast(pointer(ImageFileParams),c_void_p),c_uint(sizeof(ImageFileParams))) But I always get an error indicating invalid parameter. What's the problem? A: I believe you are getting the invalid parameter error because of the last parameter: c_uint(sizeof(ImageFileParams)) I checked the docs, and some example codes on their IDS website and I think you need to call it like this (assuming you import their ueye library: is_ImageFile(hCam, ueye.IS_IMAGE_FILE_CMD_SAVE, ImageFileParams,ueye.sizeof(ImageFileParams))
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:847797", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489118" }
890fd0545ee5a81911853d2cd346a783a11feb6f
Stackoverflow Stackexchange Q: fatal error: curl/curl.h: No such file or directory I downloaded the libcurl library from https://curl.haxx.se/libcurl/ and i'm trying to include and compile it but I get this error fatal error: curl/curl.h: No such file or directory even that I put the curl folder in the same directory the command that I used to compile x86_64-w64-mingw32-gcc try.c -o a.exe -lws2_32 -lcurl So I searched and I found these answers curl.h no such file or directory , Ubuntu - #include <curl/curl.h> no such file or directory so I did sudo apt-get install libcurl4-openssl-dev but still not working what to do? A: I solved it I just copied the curl directory that I downloaded to /usr/x86_64-w64-mingw32/include/ and when you compile you need to do -lcurl/curl Thanks for your help
Q: fatal error: curl/curl.h: No such file or directory I downloaded the libcurl library from https://curl.haxx.se/libcurl/ and i'm trying to include and compile it but I get this error fatal error: curl/curl.h: No such file or directory even that I put the curl folder in the same directory the command that I used to compile x86_64-w64-mingw32-gcc try.c -o a.exe -lws2_32 -lcurl So I searched and I found these answers curl.h no such file or directory , Ubuntu - #include <curl/curl.h> no such file or directory so I did sudo apt-get install libcurl4-openssl-dev but still not working what to do? A: I solved it I just copied the curl directory that I downloaded to /usr/x86_64-w64-mingw32/include/ and when you compile you need to do -lcurl/curl Thanks for your help
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:847813", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489166" }
f8f532b722ea10ede041a859ce18db2656298694
Stackoverflow Stackexchange Q: update RecyclerView with Android LiveData There are many examples how to push new list to adapter on LiveData change. I'm trying to update one row (e.g number of comments for post) in the huge list. It would be stupid to reset whole list to change only one field. I am able to add observer onBindViewHolder, but I can't understand when should I remove observer @Override public void onBindViewHolder(ViewHolder vh, int position) { Post post = getPost(position); vh.itemView.setTag(post); post.getLiveName().observeForever(vh.nameObserver); ... } A: Use Transformations.switchMap() to swap the underlying Post object. Then there is no need to remove and re-add observers when the cell is recycled. @Override public void onBindViewHolder(PostViewHolder vh, int position) { Post post = getPost(position); vh.bind(post); } Then in your ViewHolder class public class PostViewHolder extends RecyclerView.ViewHolder { private final MutableLiveData<Post> post = new MutableLiveData<>(); public PostViewHolder(View itemView) { super(itemView); LiveData<String> name = Transformations.switchMap(post, new Function<Post, LiveData<String>>() { @Override public LiveData<String> apply(Post input) { return input.getLiveName(); } }); name.observeForever(new Observer<String>() { @Override public void onChanged(@Nullable String name) { // use name } }); } public void bind(Post post) { post.setValue(post); } }
Q: update RecyclerView with Android LiveData There are many examples how to push new list to adapter on LiveData change. I'm trying to update one row (e.g number of comments for post) in the huge list. It would be stupid to reset whole list to change only one field. I am able to add observer onBindViewHolder, but I can't understand when should I remove observer @Override public void onBindViewHolder(ViewHolder vh, int position) { Post post = getPost(position); vh.itemView.setTag(post); post.getLiveName().observeForever(vh.nameObserver); ... } A: Use Transformations.switchMap() to swap the underlying Post object. Then there is no need to remove and re-add observers when the cell is recycled. @Override public void onBindViewHolder(PostViewHolder vh, int position) { Post post = getPost(position); vh.bind(post); } Then in your ViewHolder class public class PostViewHolder extends RecyclerView.ViewHolder { private final MutableLiveData<Post> post = new MutableLiveData<>(); public PostViewHolder(View itemView) { super(itemView); LiveData<String> name = Transformations.switchMap(post, new Function<Post, LiveData<String>>() { @Override public LiveData<String> apply(Post input) { return input.getLiveName(); } }); name.observeForever(new Observer<String>() { @Override public void onChanged(@Nullable String name) { // use name } }); } public void bind(Post post) { post.setValue(post); } } A: Like @Lyla said, you should observe the whole list as LiveData in Fragment or Activity, when receive changes, you should set the whole list to the adapter by DiffUtil. Fake code: PostViewModel { LiveData<List<Post>> posts; // posts comes from DAO or Webservice } MyFragment extends LifecycleFragment { PostAdapter postAdapter; ... void onActivityCreated() { ... postViewModel.posts.observer(this, (postList) -> { postAdapter.setPosts(postList); } } } PostAdapter { void setPosts(List<Post> postList) { DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {...} ... } } A: Using DiffUtil might help with updating one row in a huge list. You can then have LiveData wrap the list of comments instead of a single comment or attribute of a comment. Here's an example of using DiffUtil within a RecyclerView adapter and the list LiveData observation code in the fragment. A: I think you should use LiveAdapter for RecyclerView Adapter instead of creating an extra class for the adapter. It has DiffUtil implementation as well, so only single item will be updated. and without calling notifyDatasetChange. // Kotlin sample LiveAdapter( data = liveListOfItems, lifecycleOwner = this@MainActivity, variable = BR.item ) .map<Header, ItemHeaderBinding>(R.layout.item_header) { onBind{ } onClick{ } areContentsTheSame { old: Header, new: Header -> return@areContentsTheSame old.text == new.text } areItemSame { old: Header, new: Header -> return@areContentsTheSame old.text == new.text } } .map<Point, ItemPointBinding>(R.layout.item_point) { onBind{ } onClick{ } areContentsTheSame { old: Point, new: Point -> return@areContentsTheSame old.id == new.id } areItemSame { old: Header, new: Header -> return@areContentsTheSame old.text == new.text } } .into(recyclerview) A: add context to your adapterClass construstor : AdpaterClass(context: Context) then smart cast the context to AppCompactActivity livedata.observe(context as AppCompatActivity, Observer {it -> //perform action on it(livedata.value) }) when calling the adapter from anywhere activity, fragment pass the context into the adpater
stackoverflow
{ "language": "en", "length": 471, "provenance": "stackexchange_0000F.jsonl.gz:847837", "question_score": "36", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489235" }
6596c9008751ac1f97f1bfc748583419a5a0040a
Stackoverflow Stackexchange Q: undefined is not an object(ecaluating 'ReactInternals.ReactCurrentOwner') I want to run my react-native project, but an error occurred. Please give me advise. Environment $ npm list --depth=0 [email protected] /Dev/lrn/rn/nav ├── [email protected] ├── [email protected] ├── [email protected] ├── UNMET PEER DEPENDENCY [email protected] ├── [email protected] ├── [email protected] └── [email protected] Project Directory $ls __tests__ index.android.js node_modules yarn.lock android index.ios.js package-lock.json app.json ios package.json What I Do $ rm -rf node_modules $ npm cache clean --force $ npm install $ react-native run-ios Error Red Screen iPhone Simulator I think environment was wrong, but what I do cannot correct it. Thank you for seeing and any advice is welcome. thank you. A: I ran into the same problem, after doing some reading on their Github Issues yarn add [email protected] or npm i [email protected] --save did the trick for me.
Q: undefined is not an object(ecaluating 'ReactInternals.ReactCurrentOwner') I want to run my react-native project, but an error occurred. Please give me advise. Environment $ npm list --depth=0 [email protected] /Dev/lrn/rn/nav ├── [email protected] ├── [email protected] ├── [email protected] ├── UNMET PEER DEPENDENCY [email protected] ├── [email protected] ├── [email protected] └── [email protected] Project Directory $ls __tests__ index.android.js node_modules yarn.lock android index.ios.js package-lock.json app.json ios package.json What I Do $ rm -rf node_modules $ npm cache clean --force $ npm install $ react-native run-ios Error Red Screen iPhone Simulator I think environment was wrong, but what I do cannot correct it. Thank you for seeing and any advice is welcome. thank you. A: I ran into the same problem, after doing some reading on their Github Issues yarn add [email protected] or npm i [email protected] --save did the trick for me.
stackoverflow
{ "language": "en", "length": 133, "provenance": "stackexchange_0000F.jsonl.gz:847863", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489330" }
68daba5033755bdd3917fab1279dd2ae621b0ae3
Stackoverflow Stackexchange Q: Powershell Try Catch and retry? I have this script #Change hostname [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') Write-Host "Change hostname " -NoNewLine $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname') Write-Host "- DONE" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host " hostname = $ComputerName " Rename-Computer -NewName $ComputerName when the computer name gets spaces, it fails cause a hostname cant have spaces. Can i block the form to have any spaces or does anyone knows how to get back to the inputbox when a error has been created for a re-try A: do { $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:','Change hostname') } while ($ComputerName -match "\s") using a do{}while() loop and checking the Input doesn't have any whitespace should resolve your issue, this will re-prompt until a valid hostname is input, if you want to check for any errors at all: do{ $Failed = $false Try{ $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname') Write-Host "- DONE" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host " hostname = $ComputerName " Rename-Computer -NewName $ComputerName -ErrorAction Stop } catch { $Failed = $true } } while ($Failed)
Q: Powershell Try Catch and retry? I have this script #Change hostname [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') Write-Host "Change hostname " -NoNewLine $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname') Write-Host "- DONE" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host " hostname = $ComputerName " Rename-Computer -NewName $ComputerName when the computer name gets spaces, it fails cause a hostname cant have spaces. Can i block the form to have any spaces or does anyone knows how to get back to the inputbox when a error has been created for a re-try A: do { $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:','Change hostname') } while ($ComputerName -match "\s") using a do{}while() loop and checking the Input doesn't have any whitespace should resolve your issue, this will re-prompt until a valid hostname is input, if you want to check for any errors at all: do{ $Failed = $false Try{ $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname') Write-Host "- DONE" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host " hostname = $ComputerName " Rename-Computer -NewName $ComputerName -ErrorAction Stop } catch { $Failed = $true } } while ($Failed) A: Very satisfied with the end result, much thanks #Change hostname Write-Host "Change hostname " -NoNewLine do{ $Failed = $false Try{ $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname') Rename-Computer -NewName $ComputerName -ErrorAction Stop Write-Host "- DONE -" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host "Hostname = $ComputerName" -ForegroundColor DarkGreen -BackgroundColor yellow } catch { $Failed = $true } } while ($Failed) #Change workgroupname Write-Host "Change Workgroup " -NoNewLine do{ $Failed = $false Try{ $WorkGroup = [Microsoft.VisualBasic.Interaction]::InputBox("Insert the Workgroupname:", 'Change WorkGroupName', 'werkgroep') Add-Computer -WorkGroupName $WorkGroup -ErrorAction Stop Write-Host "- DONE -" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host "Workgroup = $WorkGroup" -ForegroundColor DarkGreen -BackgroundColor yellow } catch { $Failed = $true } } while ($Failed)
stackoverflow
{ "language": "en", "length": 291, "provenance": "stackexchange_0000F.jsonl.gz:847893", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489404" }
e4783547247a01a9ea76949c78100bfdf6b95c65
Stackoverflow Stackexchange Q: Union of 2 sets does not contain all items How come when I change the order of the two sets in the unions below, I get different results? set1 = {1, 2, 3} set2 = {True, False} print(set1 | set2) # {False, 1, 2, 3} print(set2 | set1) #{False, True, 2, 3} A: If you look at https://docs.python.org/3/library/stdtypes.html#boolean-values section 4.12.10. Boolean Values: Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively.
Q: Union of 2 sets does not contain all items How come when I change the order of the two sets in the unions below, I get different results? set1 = {1, 2, 3} set2 = {True, False} print(set1 | set2) # {False, 1, 2, 3} print(set2 | set1) #{False, True, 2, 3} A: If you look at https://docs.python.org/3/library/stdtypes.html#boolean-values section 4.12.10. Boolean Values: Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. A: The comparison operator (==, !=) is defined for boolean True and False to match 1 and 0. That's why, in the set union, when it checks whether True is in the new set already, it gets a truthy answer: >>> True in {1} True >>> 1 in {True} True A: In Python, False and 0 are considered equivalent, as are True and 1. Because True and 1 are considered the same value, only one of them can be present in a set a the same time. Which one depends on the order they are added to the set in. In the first line, set1 is used as the first set, so we get 1 in the resulting set. In the second set, True is in the first set, so True is included in the result. A: Why the union() doesn't contain all items The 1 and True are equivalent and considered to be duplicates. Likewise the 0 and False are equivalent as well: >>> 1 == True True >>> 0 == False True Which equivalent value is used When multiple equivalent values are encountered, sets keep the first one seen: >>> {0, False} {0} >>> {False, 0} {False} Ways to make the values be distinct To get them to be treated as distinct, just store them in a (value, type) pair: >>> set1 = {(1, int), (2, int), (3, int)} >>> set2 = {(True, bool), (False, bool)} >>> set1 | set2 {(3, <class 'int'>), (1, <class 'int'>), (2, <class 'int'>), (True, <class 'bool'>), (False, <class 'bool'>)} >>> set1 & set2 set() Another way to make the values distinct is to store them as strings: >>> set1 = {'1', '2', '3'} >>> set2 = {'True', 'False'} >>> set1 | set2 {'2', '3', 'False', 'True', '1'} >>> set1 & set2 set() Hope this clears up the mystery and shows the way forward :-) Rescued from the comments: This is the standard technique for breaking cross-type equivalence (i.e. 0.0 == 0, True == 1, and Decimal(8.5) == 8.5). The technique is used in Python 2.7's regular expression module to force unicode regexes to be cached distinctly from otherwise equivalent str regexes. The technique is also used in Python 3 for functools.lru_cache() when the typed parameter is true. If the OP needs something other than the default equivalence relation, then some new relation needs to be defined. Depending the use case, that could be case-insensitivity for strings, normalization for unicode, visual appearance (things that look different are considered different), identity (no two distinct objects are considered equal), a value/type pair, or some other function that defines an equivalence relation. Given the OPs specific example, it would seem that he/she expected either distinction by type or visual distinction.
stackoverflow
{ "language": "en", "length": 567, "provenance": "stackexchange_0000F.jsonl.gz:847967", "question_score": "95", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489658" }
94a9d8fdf3f6d0603bb3801aa6187e1d30213d9f
Stackoverflow Stackexchange Q: What is the equivalent of git squash in perforce (p4) In git, I find the squash or fixup very useful while rebasing local commits. Consider the below scenario. * *Commit "Feature", "Partial Bug Fix", "Complete Bug fix" are three separate local commits. *While doing git rebase --interactive, I squash those commits into one commit "Complete Feature" I am looking for something similar in perforce (or p4v interface). I am aware of shelving/unshelving. Any possible workarounds? A: Use p4 unsubmit to unsubmit the changes, then p4 resubmit -i to resubmit them in interactive mode (which I believe allows you to squash/etc). Since unsubmit converts the submitted changes into normal shelved changes you can operate on them with other commands as well.
Q: What is the equivalent of git squash in perforce (p4) In git, I find the squash or fixup very useful while rebasing local commits. Consider the below scenario. * *Commit "Feature", "Partial Bug Fix", "Complete Bug fix" are three separate local commits. *While doing git rebase --interactive, I squash those commits into one commit "Complete Feature" I am looking for something similar in perforce (or p4v interface). I am aware of shelving/unshelving. Any possible workarounds? A: Use p4 unsubmit to unsubmit the changes, then p4 resubmit -i to resubmit them in interactive mode (which I believe allows you to squash/etc). Since unsubmit converts the submitted changes into normal shelved changes you can operate on them with other commands as well.
stackoverflow
{ "language": "en", "length": 121, "provenance": "stackexchange_0000F.jsonl.gz:847978", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489691" }
723e19ce4004379628df65689dc65fbc9b80da8d
Stackoverflow Stackexchange Q: Passing arrays in C: square brackets vs. pointer I'm wanting to pass an array into a function. From what I can see, there are 2 ways of doing this: 1. void f (int array[]) { // Taking an array with square brackets } 2. void f (int *array) { // Taking a pointer } Each one is called by: int array[] = {0, 1, 2, 3, 4, 5}; f (array); Is there any actual difference between these 2 approaches? A: There is no difference apart from the syntax. For historical reasons, even though int array[] looks like it should pass an array, it actually passes a pointer (meaning it's the same as int *array). If I were you, I would prefer int *array just because it does what it looks like it does - that is, it's less likely to confuse you.
Q: Passing arrays in C: square brackets vs. pointer I'm wanting to pass an array into a function. From what I can see, there are 2 ways of doing this: 1. void f (int array[]) { // Taking an array with square brackets } 2. void f (int *array) { // Taking a pointer } Each one is called by: int array[] = {0, 1, 2, 3, 4, 5}; f (array); Is there any actual difference between these 2 approaches? A: There is no difference apart from the syntax. For historical reasons, even though int array[] looks like it should pass an array, it actually passes a pointer (meaning it's the same as int *array). If I were you, I would prefer int *array just because it does what it looks like it does - that is, it's less likely to confuse you. A: In your specific example there is no difference. In more general case one difference between these two approaches stems from the fact that in case of [] syntax the language performs "usual" checks for correctness of array declaration. For example, when the [] syntax is used, the array element type must be complete. There's no such requirement for pointer syntax struct S; void foo(struct S *a); // OK void bar(struct S a[]); // ERROR A specific side-effect of this rule is that you cannot declare void * parameters as void [] parameters. And if you specify array size, it has to be positive (even though it is ignored afterwards). A: They are identical, by definition. The calling code always passes an array argument as a pointer, even if it looks like the caller is passing an array. The array-like parameter declaration might make it look more like the call, but the pointer parameter declaration more accurately reflects what's actually going on. See also this entry in the C FAQ list. As Dennis Ritchie explains in "The Development of the C Language", the pointer declaration is actually a "living fossil", a relic from a very early version of C where arrays and pointers worked quite differently. A: They are the same when passing an array into a function, however, they are NOT the same in general. Consider the following code snippet: #include <stdio.h> #include <stdlib.h> #include <string.h> char *mod_string(char *str) { puts(str); str[0] = 'h'; puts(str); return str; } int main() { char hello_world[] = "Hello world"; mod_string(hello_world); } If you run this, you will get Hello world hello world However, if you change the first line of the program to char *hello_world = "Hello world"; When you run the program the output will be Hello world Segmentation fault (core dumped) I'll leave it to the C experts to properly explain this, but I just wanted to point out that the notation differences are NOT syntactic sugar.
stackoverflow
{ "language": "en", "length": 470, "provenance": "stackexchange_0000F.jsonl.gz:847998", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489773" }
ddae8f04369ad37bd5d9c749f03d5a8dea1f0b0e
Stackoverflow Stackexchange Q: How can I square each item of an integer array in Kotlin I am trying learn Kotlin. I have an array: [1,2,3,4,5] How can I print the squares of each of the numbers in the array? For example in Python I could just do: array = [1,2,3,4,5] print(" ".join (str(n*n) for n in array)) But I am not sure how to do this in Kotlin A: In Kotlin you use joinToString: val array = arrayOf(1, 2, 3, 4, 5) println(array.joinToString(separator = " ") { n -> "${n * n}" }) You can also use joinTo to join directly to a buffer (e.g. System.out) and avoid the intermediate String: array.joinTo(System.out, separator = " ") { n -> "${n * n}" }
Q: How can I square each item of an integer array in Kotlin I am trying learn Kotlin. I have an array: [1,2,3,4,5] How can I print the squares of each of the numbers in the array? For example in Python I could just do: array = [1,2,3,4,5] print(" ".join (str(n*n) for n in array)) But I am not sure how to do this in Kotlin A: In Kotlin you use joinToString: val array = arrayOf(1, 2, 3, 4, 5) println(array.joinToString(separator = " ") { n -> "${n * n}" }) You can also use joinTo to join directly to a buffer (e.g. System.out) and avoid the intermediate String: array.joinTo(System.out, separator = " ") { n -> "${n * n}" } A: You could use map: val array = arrayOf(1, 2, 3, 4, 5) println(array.map { n: Int -> n * n }) Output: [1, 4, 9, 16, 25]
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:848016", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489815" }
bfe241f37c56b9d4f5ce43bd6d77c8476dbd97a8
Stackoverflow Stackexchange Q: Examples of Topological sorts in Massive graphs I am interested in finding some real world massive data sets (>=1M) which needed to be topologically sorted. Perhaps something relating to bioinformatics? A: Did you have a look at the Stanford Large Network Dataset Collection? There are plenty of real world datasets, huge ones too, many of them directed.
Q: Examples of Topological sorts in Massive graphs I am interested in finding some real world massive data sets (>=1M) which needed to be topologically sorted. Perhaps something relating to bioinformatics? A: Did you have a look at the Stanford Large Network Dataset Collection? There are plenty of real world datasets, huge ones too, many of them directed. A: There are 650k commits in the Linux git history; performing a topological sort on the separate commits would have the plausible purpose of rediscovering the branches (merged or no). You could extend this well past a million objects by including the other Git object types (tags, trees, and blobs): then the topological sort would reconstruct the directory hierarchies as well as the commit history.
stackoverflow
{ "language": "en", "length": 123, "provenance": "stackexchange_0000F.jsonl.gz:848018", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489821" }
3210287739397073dd743b9fc4142a0b71ce1eff
Stackoverflow Stackexchange Q: Fail Gradle build when JUnit test is marked ignored I have a Java project in which I'm running gradle test. I would like execution of this task to fail if any test is ignored using the @Ignore annotation. I can currently see when tests are ignored using the following test task configuration in my build.gradle file: test { testLogging { events = ["passed", "failed", "skipped"] } } With this configuration, an ignored test results in a log statement like: TestClass > testName SKIPPED rather than: TestClass > testName PASSED or TestClass > testName FAILED How can I achieve my goal of actually causing execution of this task to fail? A: Haven't tested this yet but this might work: test { afterTest { descriptor, result -> if (result.resultType == TestResult.ResultType.SKIPPED) { throw new GradleException("Do not ignore test cases") } } } References: * *Test.afterTest *TestResult.ResultType
Q: Fail Gradle build when JUnit test is marked ignored I have a Java project in which I'm running gradle test. I would like execution of this task to fail if any test is ignored using the @Ignore annotation. I can currently see when tests are ignored using the following test task configuration in my build.gradle file: test { testLogging { events = ["passed", "failed", "skipped"] } } With this configuration, an ignored test results in a log statement like: TestClass > testName SKIPPED rather than: TestClass > testName PASSED or TestClass > testName FAILED How can I achieve my goal of actually causing execution of this task to fail? A: Haven't tested this yet but this might work: test { afterTest { descriptor, result -> if (result.resultType == TestResult.ResultType.SKIPPED) { throw new GradleException("Do not ignore test cases") } } } References: * *Test.afterTest *TestResult.ResultType
stackoverflow
{ "language": "en", "length": 145, "provenance": "stackexchange_0000F.jsonl.gz:848037", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44489890" }
ca7c200770f76c331520d71007d60835cddc1ae9
Stackoverflow Stackexchange Q: Can the Angular CLI auto include moduleId in new components? Quick question cause I may be blind or stupid. But is there a flag in the CLI so that I can have every component I generate add moduleId: module.id to my @Component decorator? Updates: Just to clear things up a little bit, I'm trying to use ngu-sw-manifest command from a package called ng-pwa-tools. More Updates: I'm aware that some people have said that the CLI recommends not to use moduleId anymore, but I'm basing this need off of what a member of the Angular team has said. A: As is explained elsewhere, moduleId is not needed in angular-cli apps. The reason for this is that, under the hood, webpack automatically adds moduleId to the final bundle; hence, it is no surprise that there are no command line options having to do with moduleId.
Q: Can the Angular CLI auto include moduleId in new components? Quick question cause I may be blind or stupid. But is there a flag in the CLI so that I can have every component I generate add moduleId: module.id to my @Component decorator? Updates: Just to clear things up a little bit, I'm trying to use ngu-sw-manifest command from a package called ng-pwa-tools. More Updates: I'm aware that some people have said that the CLI recommends not to use moduleId anymore, but I'm basing this need off of what a member of the Angular team has said. A: As is explained elsewhere, moduleId is not needed in angular-cli apps. The reason for this is that, under the hood, webpack automatically adds moduleId to the final bundle; hence, it is no surprise that there are no command line options having to do with moduleId.
stackoverflow
{ "language": "en", "length": 144, "provenance": "stackexchange_0000F.jsonl.gz:848082", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44490046" }
4e07842f519a44992fa7eb3653a521172cb8cc03
Stackoverflow Stackexchange Q: How to cross compile Python packages with PIP? Is it possible to cross-compile Python packages using PIP? I'm trying to install several Python packages containing significant portions of C/C++ (scipy/numpy/matplotlib/pynacl) on a Raspberry Pi. Installing these packages on an x86 machine takes under a minute, but because the Pi is so underpowered, and there are no pre-compiled binary packages for ARM, it takes the Pi a couple hours to compile and install everything. Is there anyway to compile and install these packages into a special virtualenv on an x86 machine, but targeting the ARM platform, and then rsync the virtualenv onto the Pi? Both the Pi and x86 are running Ubuntu 16. A: Take a look at proot. It is made for such things as you describe: https://proot-me.github.io/
Q: How to cross compile Python packages with PIP? Is it possible to cross-compile Python packages using PIP? I'm trying to install several Python packages containing significant portions of C/C++ (scipy/numpy/matplotlib/pynacl) on a Raspberry Pi. Installing these packages on an x86 machine takes under a minute, but because the Pi is so underpowered, and there are no pre-compiled binary packages for ARM, it takes the Pi a couple hours to compile and install everything. Is there anyway to compile and install these packages into a special virtualenv on an x86 machine, but targeting the ARM platform, and then rsync the virtualenv onto the Pi? Both the Pi and x86 are running Ubuntu 16. A: Take a look at proot. It is made for such things as you describe: https://proot-me.github.io/
stackoverflow
{ "language": "en", "length": 129, "provenance": "stackexchange_0000F.jsonl.gz:848131", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44490197" }
04725ed59f3308a13f30038ebb8a370b447d3c58
Stackoverflow Stackexchange Q: How to install pymssql module in Python 3.6? I have been through a couple of documentations involving FreeTDS, Wheel, git and github but nothing was working on my Windows 10 PC with Python 3.6 but I need to install it. I'm working on a project and I'm most comfortable with mssql which is already installed in my pc. A: this seems to work from export PYMSSQL_BUILD_WITH_BUNDLED_FREETDS=1 pip install pymssql
Q: How to install pymssql module in Python 3.6? I have been through a couple of documentations involving FreeTDS, Wheel, git and github but nothing was working on my Windows 10 PC with Python 3.6 but I need to install it. I'm working on a project and I'm most comfortable with mssql which is already installed in my pc. A: this seems to work from export PYMSSQL_BUILD_WITH_BUNDLED_FREETDS=1 pip install pymssql A: Remember to install FreeTDS first. Ubuntu/Debian: sudo apt-get install freetds-dev Mac OS X with Homebrew: brew install freetds Finally: pip install pymssql A: As the site pymssql_documentation page states that the module is deprecated, we can use pip install "pymssql<3.0". It works on python 3.0 and above. I think they should change it in the main copy area as well. as of 12/17/2019 it is still showing pip install pymssql, which has been updated on Nov 16 2019. A: Just use the newest build of pymssql from gitub: pip3 install git+https://github.com/pymssql/pymssql Also works for python2 pip install git+https://github.com/pymssql/pymssql UPDATE: For macOS Big Sur Apple M1 chip processor: * *You will need to install Rosetta2 emulator for the new ARM silicon (M1 chip). I just installed Rosetta2 via terminal using: /usr/sbin/softwareupdate --install-rosetta --agree-to-license * *Homebrew for ARM M1 chip: arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" * *Homebrew for M1 ARM command to install packages: arch -x86_64 brew install <package>. It is necessary to install FreeTDS before installing the pymssql. arch -x86_64 brew install freetds Finally: pip install pymssql output: Collecting pymssql Using cached pymssql-2.1.5.tar.gz (167 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing wheel metadata ... done Building wheels for collected packages: pymssql Building wheel for pymssql (PEP 517) ... done Created wheel for pymssql: filename=pymssql-2.1.5-cp39-cp39-macosx_10_9_x86_64.whl size=287029 . . . Successfully built pymssql Installing collected packages: pymssql Successfully installed pymssql-2.1.5
stackoverflow
{ "language": "en", "length": 312, "provenance": "stackexchange_0000F.jsonl.gz:848159", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44490286" }
6b5c8973fee9d60bd1bc2f15fea7fb7b2c090104
Stackoverflow Stackexchange Q: ActionController::InvalidAuthenticityToken in Rails 5 I'm getting ActionController::InvalidAuthenticityToken in rails 5. It was working correctly for a while, and then just gave up working. # Application Controller class ApplicationController < ActionController::Base protect_from_forgery with: :exception end I'm using the rails form helper, and passing in a form object # price_history/new.html.erb <%= form_for @price_history_form, url: 'price_history' do |f| %> ... <% end %> I can see the authenticity token being generated in the html, and passed into the controller.. class PriceHistoriesController < ApplicationController I'm at a loss as to why this is happening. Any thoughts? A: An easy fix without the need of disabling Turbolinks with the Rails native UJS implementation: $(document).on('turbolinks:load', function() { Rails.refreshCSRFTokens(); });
Q: ActionController::InvalidAuthenticityToken in Rails 5 I'm getting ActionController::InvalidAuthenticityToken in rails 5. It was working correctly for a while, and then just gave up working. # Application Controller class ApplicationController < ActionController::Base protect_from_forgery with: :exception end I'm using the rails form helper, and passing in a form object # price_history/new.html.erb <%= form_for @price_history_form, url: 'price_history' do |f| %> ... <% end %> I can see the authenticity token being generated in the html, and passed into the controller.. class PriceHistoriesController < ApplicationController I'm at a loss as to why this is happening. Any thoughts? A: An easy fix without the need of disabling Turbolinks with the Rails native UJS implementation: $(document).on('turbolinks:load', function() { Rails.refreshCSRFTokens(); }); A: For anyone else who might find this.. There were two problems. Turbo links adding 'data-no-turbolink' => true and then the url: needed to start with a / A: Not sure about internals of the problem, but this js fixed it for me (rails 5.1 with turbolinks enabled): $(document).on("turbolinks:load",function() { $.rails.refreshCSRFTokens(); }) It updates head csrf token so it matches form csrf token. Idea from here: https://github.com/rails/jquery-ujs/issues/456 A: Try disabling Turbolinks. What version of Rails are you running? For help disabling turbolinks, refer here: How to disable turbolinks in Rails 5? A: The issue is with the :url option. According to this Rails issue, it will raise that error when you use it: https://github.com/rails/rails/issues/24257 Apparently there are 2 solutions to this problem: 1) Disable Turbolinks in your form ('data-no-turbolink' => true) 2) Remove render stream: true from the controller action rendering the link or form
stackoverflow
{ "language": "en", "length": 259, "provenance": "stackexchange_0000F.jsonl.gz:848162", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44490299" }
c8a85bcb7025fc7b113cff9e5482e52ef6c647be
Stackoverflow Stackexchange Q: How to rename file name contains backslash in bash? I got a tar file, after extracting, there are many files naming like a b\c d\e\f g\h I want to correct their name into files in sub-directories like a b/c d/e/f g/h I face a problem when a variable contains backslash, it will change the original file name. I want to write a script to rename them. A: Renaming a file with backslashes is simple: mv 'a\b' 'newname' (just quote it), but you'll need more than that. You need to: * *find all files with a backslash (e.g. a\b\c) *split path from filename (e.g. a\b from c) *create a complete path (e.g. a/b, dir b under dir a) *move the old file under a new name, under a created path (e.g. rename a\b\c to file named c in dir a/b) Something like this: #!/bin/bash find . -name '*\\*' | while read f; do base="${f%\\*}" file="${f##*\\}" path="${base//\\//}" mkdir -p "$path" mv "$f" "$path/$file" done (Edit: correct handling of filenames with spaces)
Q: How to rename file name contains backslash in bash? I got a tar file, after extracting, there are many files naming like a b\c d\e\f g\h I want to correct their name into files in sub-directories like a b/c d/e/f g/h I face a problem when a variable contains backslash, it will change the original file name. I want to write a script to rename them. A: Renaming a file with backslashes is simple: mv 'a\b' 'newname' (just quote it), but you'll need more than that. You need to: * *find all files with a backslash (e.g. a\b\c) *split path from filename (e.g. a\b from c) *create a complete path (e.g. a/b, dir b under dir a) *move the old file under a new name, under a created path (e.g. rename a\b\c to file named c in dir a/b) Something like this: #!/bin/bash find . -name '*\\*' | while read f; do base="${f%\\*}" file="${f##*\\}" path="${base//\\//}" mkdir -p "$path" mv "$f" "$path/$file" done (Edit: correct handling of filenames with spaces) A: Parameter expansion is the way to go. You have everything you need in bash, no need to use external tools like find. $ touch a\\b c\\d\\e $ ls -l total 0 -rw-r--r-- 1 ghoti staff 0 11 Jun 23:13 a\b -rw-r--r-- 1 ghoti staff 0 11 Jun 23:13 c\d\e $ for file in *\\*; do > target="${file//\\//}"; mkdir -p "${target%/*}"; mv -v "$file" "$target"; done a\b -> a/b c\d\e -> c/d/e The for loop breaks out as follows: * *for file in *\\*; do - select all files whose names contain backslashes *target="${file//\\//}"; - swap backslashes for forward slashes *mkdir -p "${target%/*}"; - create the target directory by stripping the filename from $target *mv -v "$file" "$target"; - move the file to its new home *done - end the loop. The only tricky bit here I think is the second line: ${file//\\//} is an expression of ${var//pattern/replacement}, where the pattern is an escaped backslash (\\) and the replacement is a single forward slash. Have a look at man bash and search for "Parameter Expansion" to learn more about this. Alternately, if you really want to use find, you can still take advantage of bash's Parameter Expansion: find . -name '*\\*' -type f \ -exec bash -c 't="${0//\\//}"; mkdir -p "${t%/*}"; mv -v "$0" "$t"' {} \; This uses find to identify each file and process it with an -exec option that basically does the same thing as the for loop above. One significant difference here is that find will traverse subdirectories (limited by the -maxdepth option), so ... be careful.
stackoverflow
{ "language": "en", "length": 431, "provenance": "stackexchange_0000F.jsonl.gz:848207", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44490413" }
963bb51b03516d3df4f09ab59d33bc07c2febd58
Stackoverflow Stackexchange Q: Receiving 401 "Bad Credentials" when hitting github API endpoint I'm trying to build a CLI that uses the GitHub api. I instantly run into a road block. Although I've read the introductory docs up and down, I don't see what is wrong in the following code. var userData = require('../userData'); var request = require('request'); module.exports = { hitEndpoint: function() { var username = "<redacted_user_name>", password = "<redacted_password>", auth = "Basic " + new Buffer(username + ":" + password).toString("base64"); var options = { method: 'get', url: " https://api.github.com/<redacted_user_name>", headers: { "Authorization": auth, "User-Agent": "<redacted_whatever_doesnt_matter>" } } request(options, function (error, response, body) { console.log('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the HTML for the Google homepage. }); }, } prints: error: null statusCode: 404 body: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"} A: To get your own profile you'll want to hit the authenticated user endpoint, you shouldn't replace this with your own username, GitHub will know who you are based on your authentication string: https://api.github.com/user To get another user's profile you'll want to hit the users endpoint: https://api.github.com/users/:username
Q: Receiving 401 "Bad Credentials" when hitting github API endpoint I'm trying to build a CLI that uses the GitHub api. I instantly run into a road block. Although I've read the introductory docs up and down, I don't see what is wrong in the following code. var userData = require('../userData'); var request = require('request'); module.exports = { hitEndpoint: function() { var username = "<redacted_user_name>", password = "<redacted_password>", auth = "Basic " + new Buffer(username + ":" + password).toString("base64"); var options = { method: 'get', url: " https://api.github.com/<redacted_user_name>", headers: { "Authorization": auth, "User-Agent": "<redacted_whatever_doesnt_matter>" } } request(options, function (error, response, body) { console.log('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the HTML for the Google homepage. }); }, } prints: error: null statusCode: 404 body: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"} A: To get your own profile you'll want to hit the authenticated user endpoint, you shouldn't replace this with your own username, GitHub will know who you are based on your authentication string: https://api.github.com/user To get another user's profile you'll want to hit the users endpoint: https://api.github.com/users/:username
stackoverflow
{ "language": "en", "length": 194, "provenance": "stackexchange_0000F.jsonl.gz:848210", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44490426" }
38524f2f6c60ec0f4fcb1f19f16ccb85cf01bb99
Stackoverflow Stackexchange Q: Delphi Tokyo FMX - TDateEdit not changing displayed month I am running Delphi 10.2 Tokyo with the April hotfix applied on Windows 10 (I do not have Creator's update installed). I am noticing a weird behavior with the TDateEdit control: Here's what the date drop down looks like when first opened (showing current date): However, when I change the month or year by either using the left/right arrow or by clicking on the month/year and picking a new value, the month does not get redrawn and continues to show the month of June: I do not have any event handlers on the date edit. I am not sure what may be causing this. Any ideas what may be causing this behavior - or what I could do to fix it? UPDATE 20170613: As this seems to be a bug, I have opened a ticket with Embarcadero: https://quality.embarcadero.com/browse/RSP-18348 UPDATE 20170816: A workaround has been posted to https://quality.embarcadero.com/browse/RSP-18348 by Matt Davis that seems to work for now (until Embarcadero issues a proper fix).
Q: Delphi Tokyo FMX - TDateEdit not changing displayed month I am running Delphi 10.2 Tokyo with the April hotfix applied on Windows 10 (I do not have Creator's update installed). I am noticing a weird behavior with the TDateEdit control: Here's what the date drop down looks like when first opened (showing current date): However, when I change the month or year by either using the left/right arrow or by clicking on the month/year and picking a new value, the month does not get redrawn and continues to show the month of June: I do not have any event handlers on the date edit. I am not sure what may be causing this. Any ideas what may be causing this behavior - or what I could do to fix it? UPDATE 20170613: As this seems to be a bug, I have opened a ticket with Embarcadero: https://quality.embarcadero.com/browse/RSP-18348 UPDATE 20170816: A workaround has been posted to https://quality.embarcadero.com/browse/RSP-18348 by Matt Davis that seems to work for now (until Embarcadero issues a proper fix).
stackoverflow
{ "language": "en", "length": 172, "provenance": "stackexchange_0000F.jsonl.gz:848250", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44490548" }
a390233871f3a1aeabf62351efe00906edbc8c80
Stackoverflow Stackexchange Q: Highlight error syntax in Visual Studio Code C++ extensions Is it possible to have the Visual Studio Code C++ extensions to check syntax error? For example, the below error syntax would be highlighted. std::vectorr vec; A: Yes. The Microsoft C/C++ extension checks for and indicates syntax errors, among other things. Example: The red squiggly line is always there, while the popup appears on mouse hover. I recommend going through the Getting Started with C++ tutorial for VSCode to make sure you've got everything configured right.
Q: Highlight error syntax in Visual Studio Code C++ extensions Is it possible to have the Visual Studio Code C++ extensions to check syntax error? For example, the below error syntax would be highlighted. std::vectorr vec; A: Yes. The Microsoft C/C++ extension checks for and indicates syntax errors, among other things. Example: The red squiggly line is always there, while the popup appears on mouse hover. I recommend going through the Getting Started with C++ tutorial for VSCode to make sure you've got everything configured right.
stackoverflow
{ "language": "en", "length": 86, "provenance": "stackexchange_0000F.jsonl.gz:848266", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44490584" }
b04a3d578d97096e3490e2d132e2344b6fb1cfaa
Stackoverflow Stackexchange Q: Codeigniter Datamapper ORM php 7 static issue When I upgraded my server to php7 codeigniter and in particular datamapper ORM gives me this error... Message: Accessing static property DataMapper::$config as non static Filename: libraries/datamapper.php Line Number: 6474 the function in question is... protected function _dmz_assign_libraries() { static $CI; if ($CI || $CI =& get_instance()) { // make sure these exists to not trip __get() $this->load = NULL; $this->config = NULL; $this->lang = NULL; // access to the loader $this->load =& $CI->load; // to the config $this->config =& $CI->config; // and the language class $this->lang =& $CI->lang; } } A: I have the same problem. To fix it, try to add new protected static method protected static function get_config_object() { $CI =& get_instance(); return $CI->config; } then delete or comment the lines 6474 and 6481 (in _dmz_assign_libraries, where values are assigned to $this->config), and finally replace all calls $this->config with self::get_config_object() It should run correctly now.
Q: Codeigniter Datamapper ORM php 7 static issue When I upgraded my server to php7 codeigniter and in particular datamapper ORM gives me this error... Message: Accessing static property DataMapper::$config as non static Filename: libraries/datamapper.php Line Number: 6474 the function in question is... protected function _dmz_assign_libraries() { static $CI; if ($CI || $CI =& get_instance()) { // make sure these exists to not trip __get() $this->load = NULL; $this->config = NULL; $this->lang = NULL; // access to the loader $this->load =& $CI->load; // to the config $this->config =& $CI->config; // and the language class $this->lang =& $CI->lang; } } A: I have the same problem. To fix it, try to add new protected static method protected static function get_config_object() { $CI =& get_instance(); return $CI->config; } then delete or comment the lines 6474 and 6481 (in _dmz_assign_libraries, where values are assigned to $this->config), and finally replace all calls $this->config with self::get_config_object() It should run correctly now. A: Try to suppress error with @, eg: @$this->config =& $CI->config; A: I faced the same problem. FIX: Replace the actual datamapper.php library version with the latest one. As mentioned in the official library website Latest library version (1.8.3-dev) - source: https://github.com/saekort/datamapper/blob/master/application/libraries/datamapper.php
stackoverflow
{ "language": "en", "length": 198, "provenance": "stackexchange_0000F.jsonl.gz:848280", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44490616" }