content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
30
130
Q: PHP Fatal error:Uncaught Error: Failed opening required 'new-project/vendor/autoload.php' (include_path='.;C:\php\pear') in E:\new-project\artisan:18 I want to create new laravel project by composer. I use composer create-project laravel/laravel new-project command for create new project. then, my project is created following this picture. I start Laravel's local development server using the Laravel's Artisan CLI serve command (first cd new-project and then php artisan serve command). But I got the following error. Why is there no vendor folder in this project?!!! How do I fix this error? (I used PHP 8.1.10) A: You need to issue composer install to install packages which creates the vendor/ folder A: If composer install doesn't work then try composer install --ignore-platform-reqs.
PHP Fatal error:Uncaught Error: Failed opening required 'new-project/vendor/autoload.php' (include_path='.;C:\php\pear') in E:\new-project\artisan:18
I want to create new laravel project by composer. I use composer create-project laravel/laravel new-project command for create new project. then, my project is created following this picture. I start Laravel's local development server using the Laravel's Artisan CLI serve command (first cd new-project and then php artisan serve command). But I got the following error. Why is there no vendor folder in this project?!!! How do I fix this error? (I used PHP 8.1.10)
[ "You need to issue composer install to install packages which creates the vendor/ folder\n", "If composer install doesn't work then try composer install --ignore-platform-reqs.\n" ]
[ 4, 0 ]
[]
[]
[ "autoload", "composer_php", "laravel", "laravel_artisan", "php" ]
stackoverflow_0073916730_autoload_composer_php_laravel_laravel_artisan_php.txt
Q: The letters won't appear in VScode (Ubuntu 20.04, M1 pro(arm64)) enter image description here I can't see the letter of the VScode like the image. VScode has been installed in Debian arm64. How can I fix the problem. A: I am having the same issue running Ubuntu 20.04 in UTM 4.0.9 on the M1 apple silicon. Starting visual studio code from the command line like this soled it. code --disable-gpu There is a discussion in github about this issue: https://github.com/microsoft/vscode/issues/161681
The letters won't appear in VScode (Ubuntu 20.04, M1 pro(arm64))
enter image description here I can't see the letter of the VScode like the image. VScode has been installed in Debian arm64. How can I fix the problem.
[ "I am having the same issue running Ubuntu 20.04 in UTM 4.0.9 on the M1 apple silicon. Starting visual studio code from the command line like this soled it.\ncode --disable-gpu\n\nThere is a discussion in github about this issue: https://github.com/microsoft/vscode/issues/161681\n" ]
[ 0 ]
[]
[]
[ "visual_studio_code" ]
stackoverflow_0073760824_visual_studio_code.txt
Q: How to use SharedPreferences to store form data in an Android app that uses Kotlin, Compose and Navigator? I am quite new to Android Studio, and for a study project, I am creating an app that uses Kotlin, Compose and Navigator. I want to store data from a form as key-value pairs in SharedPreferences, but although I have found an example how to do it in Compose, this was not using navigator, and I haven’t been able to figure out where to initialize the variables with the navigator structure, can someone help me with that? In the example, these variables are initiated at the start of MainActivity.kt: class MainActivity : ComponentActivity() { lateinit var sharedPreferences: SharedPreferences var PREFS_KEY = "prefs" var EMAIL_KEY = "email" var PWD_KEY = "pwd" var e = "" var p = "" and then within setContent, shared preferences is initialized: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) In my case with the navigator structure, I have tried placing the variables either in the MainActivity file, as well as within the navigator fragment where I want to store the values. If I place it in the MainActivity, the sharedPreference variable is not known in the navigator fragment, and when I place it in the main function of the navigator fragment, the line: sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) gives me the error: Unresolved reference: getSharedPreferences (I have included import android.content.SharedPreferences in both files) A: To use SharedPreferences to store form data in an Android app that uses Kotlin, Compose and Navigator, you need to create a SharedPreferences object in your MainActivity.kt file. Then use the object to store your form data using the putString() and getString() methods. Then, in your navigator fragment, you can access your SharedPreferences object using the getSharedPreferences() method. Then you can use the getString() and putString() methods to access and store the data. See the example: In MainActivity.kt: val sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) In NavigatorFragment.kt: val sharedPreferences = activity?.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) // To store data sharedPreferences?.edit { putString("name", name) } // To retrieve data val name = sharedPreferences?.getString("name", "")
How to use SharedPreferences to store form data in an Android app that uses Kotlin, Compose and Navigator?
I am quite new to Android Studio, and for a study project, I am creating an app that uses Kotlin, Compose and Navigator. I want to store data from a form as key-value pairs in SharedPreferences, but although I have found an example how to do it in Compose, this was not using navigator, and I haven’t been able to figure out where to initialize the variables with the navigator structure, can someone help me with that? In the example, these variables are initiated at the start of MainActivity.kt: class MainActivity : ComponentActivity() { lateinit var sharedPreferences: SharedPreferences var PREFS_KEY = "prefs" var EMAIL_KEY = "email" var PWD_KEY = "pwd" var e = "" var p = "" and then within setContent, shared preferences is initialized: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) In my case with the navigator structure, I have tried placing the variables either in the MainActivity file, as well as within the navigator fragment where I want to store the values. If I place it in the MainActivity, the sharedPreference variable is not known in the navigator fragment, and when I place it in the main function of the navigator fragment, the line: sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) gives me the error: Unresolved reference: getSharedPreferences (I have included import android.content.SharedPreferences in both files)
[ "To use SharedPreferences to store form data in an Android app that uses Kotlin, Compose and Navigator, you need to create a SharedPreferences object in your MainActivity.kt file. Then use the object to store your form data using the putString() and getString() methods. Then, in your navigator fragment, you can access your SharedPreferences object using the getSharedPreferences() method. Then you can use the getString() and putString() methods to access and store the data.\nSee the example:\nIn MainActivity.kt:\nval sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)\n\nIn NavigatorFragment.kt:\nval sharedPreferences = activity?.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)\n\n// To store data\nsharedPreferences?.edit { putString(\"name\", name) }\n\n// To retrieve data\nval name = sharedPreferences?.getString(\"name\", \"\")\n\n" ]
[ 0 ]
[]
[]
[ "android_jetpack_compose", "jetpack_compose_navigation", "kotlin", "sharedpreferences" ]
stackoverflow_0074667685_android_jetpack_compose_jetpack_compose_navigation_kotlin_sharedpreferences.txt
Q: ionic Failed to load webpage with error: Could not connect to the server I'm having an issue with Ionic projects after updating to Xcode 6 and iOS 8. When trying to run projects I get the following error in Xcode: Failed to load webpage with error: Could not connect to the server. The full log is: 2014-10-11 14:08:29.468 test[23293:109668] Apache Cordova native platform version 3.6.3 is starting. 2014-10-11 14:08:29.469 test[23293:109668] Multi-tasking -> Device: YES, App: YES 2014-10-11 14:08:29.495 test[23293:109668] Unlimited access to network resources 2014-10-11 14:08:29.866 test[23293:109668] [CDVTimer][keyboard] 0.079989ms 2014-10-11 14:08:29.866 test[23293:109668] [CDVTimer][TotalPluginStartup] 0.284970ms 2014-10-11 14:08:30.721 test[23293:109668] Resetting plugins due to page load. 2014-10-11 14:08:30.764 test[23293:109668] Failed to load webpage with error: Could not connect to the server. Even when trying to update Ionic and Cordova and starting a new project this error keeps popping up. I couldn't find any threads with this particular error and I'm not sure if this is an iOS 8 compatibility issue or something is messed up with my setup. Thanks! EDIT: A bit more info on what's in the index.html and app.js index.html: <!DOCTYPE html> <html ng-app="app" ng-controller="AppCtrl"> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <!-- compiled CSS --> <link rel="stylesheet" type="text/css" href="assets/app-0.0.1.css" /> <!-- compiled JavaScript --> <script type="text/javascript" src="src/app/app.js"></script> <!-- cordova script (this will be a 404 during development) --> <script src="cordova.js"></script> </head> <body > <ion-nav-view></ion-nav-view> <!-- Load deferred scripts --> <!-- Google Maps --> <script src='http://maps.googleapis.com/maps/api/js?sensor=true&callback=googleMapsLoaded' defer async></script> </body> </html> and app.js (before compilation with the rest of the files using ngbp): angular.module( 'app', [ 'ionic', // Common requirements 'templates-app', 'templates-common', // Common Components 'app.auth', // All page modules 'app.businesses', 'app.business', 'app.search', 'app.branch', 'app.profile', 'app.feed', // Other dependencies 'ui.router' ]) .config(['$stateProvider', '$urlRouterProvider', function myAppConfig ($stateProvider, $urlRouterProvider) { $stateProvider .state('app', { url: "/app", abstract: true, templateUrl: "menu/menu.tpl.html", controller: 'AppCtrl' }); $urlRouterProvider.otherwise( 'app/feed' ); }]) .run(['$ionicPlatform', 'appAuthService', '$sessionStorage', function($ionicPlatform, appAuthService, $sessionStorage) { // Initialize ionic styles $ionicPlatform.ready(function() { if(window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); StatusBar.styleLightContent(); } }); // Initialize app authentication service appAuthService.init(); // Initialize a session cache validation object $sessionStorage.updated = {}; }]) .controller( 'AppCtrl', ['$scope', '$location', function AppCtrl ($scope, $location) { }]) ; A: I had the same problem. I opened the ios project in the platform folder via Xcode, but I forgot that the codebase in the Xcode folder was not up to date and therefore broken. To get the new code in your Xcode project use the command: ionic cordova prepare ios If your problem is rooted in the same as mine this should help. A: This error may also occur if you open the project using Xcode after used the live debugging with the emulator ionic cordova emulate ios --livereload -lc To solve the issue, close Xcode and build the project again using ionic cordova build ios Then build and run using Xcode. A: I encountered this issue when I tried to run my Ionic 4 app on an iOS device. What solved it for me, was running the dev server on all network interfaces using the --address option, for example: ionic cordova run ios --address=0.0.0.0 --debug --consolelogs -l A: I had this same issue using XCode9.3 and ionic3. Turns out that the issue was caused by missing configurations in "config.xml" needed for WKWebview to function properly. I added the following snippet to my config.xml, before deleting the "platforms/ios" folder and running "ionic cordova build ios --prod" again. <allow-navigation href="http://localhost:8080/*" /> <feature name="CDVWKWebViewEngine"> <param name="ios-package" value="CDVWKWebViewEngine" /> </feature> <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" /> See link here for a more detailed explanation from the ionic team. A: I have run the server and simulator and again am trying to update the app on the device. Then I had the same problem I stoped my simulator and re builded the app and opened the project.xcodeproj file with Xcode and run it on the device.This worked for me A: I had the same issue, reinstalling the cordova-plugin-ionic-webview worked for me. cordova plugin rm cordova-plugin-ionic-webview cordova plugin add cordova-plugin-ionic-webview A: In our case (under IONIC 5) the entry "server": { "url": "http://192.168.0.6:8100" } in the file "capacitor.config.json" had to be deleted. Afterwards the app ran smoothly on mobile devices. A: I found a solution, i hope it helps: https://github.com/glebmachine/cordova-plugin-ionic/commit/7c095a45a13f7349e93f14a3057153775109f635 To install from my fork: cordova plugin add https://github.com/glebmachine/cordova-plugin-ionic.git#v4 A: This error may also be caused if the test device is not connected properly to the WiFi network. Both your development machine (i.e., Laptop) and the test device (i.e., mobile device/phone) must be connected to the same WiFi network. For testing on actual device with live reload run the following command: ionic cordova run ios -l --external
ionic Failed to load webpage with error: Could not connect to the server
I'm having an issue with Ionic projects after updating to Xcode 6 and iOS 8. When trying to run projects I get the following error in Xcode: Failed to load webpage with error: Could not connect to the server. The full log is: 2014-10-11 14:08:29.468 test[23293:109668] Apache Cordova native platform version 3.6.3 is starting. 2014-10-11 14:08:29.469 test[23293:109668] Multi-tasking -> Device: YES, App: YES 2014-10-11 14:08:29.495 test[23293:109668] Unlimited access to network resources 2014-10-11 14:08:29.866 test[23293:109668] [CDVTimer][keyboard] 0.079989ms 2014-10-11 14:08:29.866 test[23293:109668] [CDVTimer][TotalPluginStartup] 0.284970ms 2014-10-11 14:08:30.721 test[23293:109668] Resetting plugins due to page load. 2014-10-11 14:08:30.764 test[23293:109668] Failed to load webpage with error: Could not connect to the server. Even when trying to update Ionic and Cordova and starting a new project this error keeps popping up. I couldn't find any threads with this particular error and I'm not sure if this is an iOS 8 compatibility issue or something is messed up with my setup. Thanks! EDIT: A bit more info on what's in the index.html and app.js index.html: <!DOCTYPE html> <html ng-app="app" ng-controller="AppCtrl"> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <!-- compiled CSS --> <link rel="stylesheet" type="text/css" href="assets/app-0.0.1.css" /> <!-- compiled JavaScript --> <script type="text/javascript" src="src/app/app.js"></script> <!-- cordova script (this will be a 404 during development) --> <script src="cordova.js"></script> </head> <body > <ion-nav-view></ion-nav-view> <!-- Load deferred scripts --> <!-- Google Maps --> <script src='http://maps.googleapis.com/maps/api/js?sensor=true&callback=googleMapsLoaded' defer async></script> </body> </html> and app.js (before compilation with the rest of the files using ngbp): angular.module( 'app', [ 'ionic', // Common requirements 'templates-app', 'templates-common', // Common Components 'app.auth', // All page modules 'app.businesses', 'app.business', 'app.search', 'app.branch', 'app.profile', 'app.feed', // Other dependencies 'ui.router' ]) .config(['$stateProvider', '$urlRouterProvider', function myAppConfig ($stateProvider, $urlRouterProvider) { $stateProvider .state('app', { url: "/app", abstract: true, templateUrl: "menu/menu.tpl.html", controller: 'AppCtrl' }); $urlRouterProvider.otherwise( 'app/feed' ); }]) .run(['$ionicPlatform', 'appAuthService', '$sessionStorage', function($ionicPlatform, appAuthService, $sessionStorage) { // Initialize ionic styles $ionicPlatform.ready(function() { if(window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); StatusBar.styleLightContent(); } }); // Initialize app authentication service appAuthService.init(); // Initialize a session cache validation object $sessionStorage.updated = {}; }]) .controller( 'AppCtrl', ['$scope', '$location', function AppCtrl ($scope, $location) { }]) ;
[ "I had the same problem.\nI opened the ios project in the platform folder via Xcode, but I forgot that the codebase in the Xcode folder was not up to date and therefore broken.\nTo get the new code in your Xcode project use the command:\nionic cordova prepare ios\n\nIf your problem is rooted in the same as mine this should help.\n", "This error may also occur if you open the project using Xcode after used the live debugging with the emulator \n\nionic cordova emulate ios --livereload -lc\n\nTo solve the issue, close Xcode and build the project again using\nionic cordova build ios\n\nThen build and run using Xcode.\n", "I encountered this issue when I tried to run my Ionic 4 app on an iOS device.\nWhat solved it for me, was running the dev server on all network interfaces using the --address option, for example:\nionic cordova run ios --address=0.0.0.0 --debug --consolelogs -l\n", "I had this same issue using XCode9.3 and ionic3. Turns out that the issue was caused by missing configurations in \"config.xml\" needed for WKWebview to function properly. I added the following snippet to my config.xml, before deleting the \"platforms/ios\" folder and running \"ionic cordova build ios --prod\" again.\n\n\n <allow-navigation href=\"http://localhost:8080/*\" />\r\n <feature name=\"CDVWKWebViewEngine\">\r\n <param name=\"ios-package\" value=\"CDVWKWebViewEngine\" />\r\n </feature>\r\n <preference name=\"CordovaWebViewEngine\" value=\"CDVWKWebViewEngine\" />\n\n\n\nSee link here for a more detailed explanation from the ionic team. \n", "I have run the server and simulator and again am trying to update the app on the device.\nThen I had the same problem\nI stoped my simulator and re builded the app and opened the project.xcodeproj file with Xcode and run it on the device.This worked for me\n", "I had the same issue, reinstalling the cordova-plugin-ionic-webview worked for me.\ncordova plugin rm cordova-plugin-ionic-webview\ncordova plugin add cordova-plugin-ionic-webview\n\n", "In our case (under IONIC 5) the entry\n\"server\": {\n \"url\": \"http://192.168.0.6:8100\"\n }\n\nin the file \"capacitor.config.json\" had to be deleted.\nAfterwards the app ran smoothly on mobile devices.\n", "I found a solution, i hope it helps:\nhttps://github.com/glebmachine/cordova-plugin-ionic/commit/7c095a45a13f7349e93f14a3057153775109f635\nTo install from my fork: \n\ncordova plugin add https://github.com/glebmachine/cordova-plugin-ionic.git#v4\n\n", "This error may also be caused if the test device is not connected properly to the WiFi network. Both your development machine (i.e., Laptop) and the test device (i.e., mobile device/phone) must be connected to the same WiFi network.\nFor testing on actual device with live reload run the following command:\nionic cordova run ios -l --external\n\n" ]
[ 98, 24, 17, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "cordova", "ionic_framework", "ios8", "xcode" ]
stackoverflow_0026314005_cordova_ionic_framework_ios8_xcode.txt
Q: Springboot with both aspectj and Spring AOP I am trying to get a springboot (2.6.2) project to work with both AspectJ and Spring AOP. I have the following sample classes: @Entity public class Item { @Id @Getter private String uuid = UUID.randomUUID().toString(); private String name; @Verify.Access public String getName() { return name; } } public @interface Verify { @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface Access {} } @Aspect @Slf4j public class MyAspect { @Before("@annotation(Verify.Access)") public void beforeAnnotation(JoinPoint joinPoint) { log.error("BEFORE ANNOTATION"); } } @Aspect @Service public class OtherAspect { @Autowired private MyUtility myUtility; @Around("@annotation(SystemCall)") public Object run(@NonNull final ProceedingJoinPoint join) throws Throwable { return myUtility.getInfo(); } } @Service @Data public class MyUtility { Object info; } My pom.xml file has the following plugins defined: <plugin> <groupId>com.nickwongdev</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.12.6</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <proc>none</proc> <complianceLevel>${java.version}</complianceLevel> <showWeaveInfo>true</showWeaveInfo> <forceAjcCompile>true</forceAjcCompile> <sources/> <weaveDirectories> <weaveDirectory>${project.build.directory}/classes</weaveDirectory> </weaveDirectories> </configuration> <executions> <execution> <goals> <goal>compile</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>${aspectj.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.projectlombok</groupId> <artifactId>lombok-maven-plugin</artifactId> <version>1.18.20.0</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>delombok</goal> </goals> </execution> </executions> <configuration> <addOutputDirectory>false</addOutputDirectory> <sourceDirectory>src/main/java</sourceDirectory> <encoding>UTF-8</encoding> </configuration> </plugin> I have also defined a src/main/resources/org/aspectj/aop.xml: <!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> <aspectj> <weaver> <include within="mypackage..*" /> <include within="org.springframework.boot..*" /> </weaver> <aspects> <aspect name="mypackage.MyAspect" /> </aspects> </aspectj> It seems to compile okay and I see the info messages that the join points are being advised. However, in the OtherAspect the autowired MyUtility is not getting set. From what I could find I would expect Spring to recognize OtherAspect as a Component and Autowire in MyUtility but instead I get a NullPointerException. Any thoughts? Thanks! A: OK, I had a little bit of time and prepared the MCVE which actually would have been your job to provide. I made the following assumptions: You need native AspectJ, because you want to weave a target class which is not a Spring bean. You want to use compile-time, not load-time weaaving. Therefore, you would use AspectJ Maven Plugin. You want to use Spring dependency injection for wiring Spring beans into native AspectJ aspects, as described in the Spring manual, i.e. using an aspectOf factory method for the native aspect in Spring. You absolutely insist on combining Lombok and native AspectJ, even though they are incompatible out of the box. I.e., you need a workaround in Maven, either binary weaving (e.g. if Lombok is only used for your non-aspect classes) or a "delombok" build step (e.g. if your aspects also use Lombok, which unfortunately they do, using the @Slf4j Lombok annotation in MyAspect. What I changed in your setup: I removed the dependency on Spring Data JPA to make things easier, because I was too lazy to set up a dummy in-memory database. It is not relevant for the solution here. I.e., I also commented out the @Entity and @Id annotations in class Item. You already configured a "delombok" build step, which I wanted to stick with, because it seems to be your preference. Hence, your sample code only compiles with AspectJ Maven when using ${project.build.directory}/generated-sources/delombok as the source directory. Your idea to use a <weaveDirectory> does not work, because the aspect with the Lombok annotation does not compile that way, as it refers to the Lombok-generated static log field. I removed the @Service annotation from the native AspectJ aspect, because that would lead to problems when wiring the application. Instead, I added a @Bean factory method to OtherAspect, so we can use @Autowired MyUtility myUtility there. In the same aspect, I also switched from @annotation(SystemCall) (due to missing code in your example) to @annotation(Verify.Access) in order to have something to test against. I removed the superfluous aop.xml file. I added a little Spring Boot driver application. I switched from the no longer maintained com.nickwongdev AspectJ Maven plugin to the current dev.aspectj plugin which has more features and supports Java 17+, too. The whole application looks like this: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>SO_AJ_SpringAutowireBeanNativeAspect_74661663</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <aspectj.version>1.9.9.1</aspectj.version> </properties> <build> <plugins> <plugin> <groupId>dev.aspectj</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.13.1</version> <configuration> <complianceLevel>${maven.compiler.target}</complianceLevel> <proc>none</proc> <showWeaveInfo>true</showWeaveInfo> <forceAjcCompile>true</forceAjcCompile> <sources> <source> <basedir>${project.build.directory}/generated-sources/delombok</basedir> </source> </sources> <!-- <weaveDirectories> <weaveDirectory>${project.build.directory}/classes</weaveDirectory> </weaveDirectories> --> </configuration> <executions> <execution> <goals> <goal>compile</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>${aspectj.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.projectlombok</groupId> <artifactId>lombok-maven-plugin</artifactId> <version>1.18.20.0</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>delombok</goal> </goals> </execution> </executions> <configuration> <addOutputDirectory>false</addOutputDirectory> <sourceDirectory>src/main/java</sourceDirectory> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.6.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.6.2</version> <scope>compile</scope> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.6.2</version> <scope>compile</scope> </dependency> --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> </dependencies> </project> package org.example; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; public @interface Verify { @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @interface Access {} } package org.example; import lombok.Data; import org.springframework.stereotype.Service; @Service @Data public class MyUtility { Object info; } package org.example; import lombok.Getter; //import javax.persistence.Entity; //import javax.persistence.Id; import java.util.UUID; //@Entity public class Item { // @Id @Getter private String uuid = UUID.randomUUID().toString(); private String name; public Item(String name) { this.name = name; } @Verify.Access public String getName() { return name; } } package org.example; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect @Slf4j public class MyAspect { @Before("@annotation(Verify.Access)") public void beforeAnnotation(JoinPoint joinPoint) { log.error("BEFORE ANNOTATION"); } } package org.example; import lombok.NonNull; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.beans.factory.annotation.Autowired; @Aspect public class OtherAspect { @Autowired private MyUtility myUtility; // @Around("@annotation(SystemCall)") @Around("@annotation(Verify.Access)") public Object run(@NonNull final ProceedingJoinPoint join) throws Throwable { return myUtility.getInfo(); // return join.proceed(); } } package org.example; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.Aspects; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @SpringBootApplication @Configuration @Slf4j public class Main { @Bean public OtherAspect otherAspect() { return Aspects.aspectOf(OtherAspect.class); } public static void main(String[] args) { try (ConfigurableApplicationContext appContext = SpringApplication.run(Main.class, args)) { doStuff(appContext); } } private static void doStuff(ConfigurableApplicationContext appContext) { MyUtility myUtility = appContext.getBean(MyUtility.class); myUtility.setInfo("my info"); Item item = new Item("my name"); log.info(item.getName()); } } If you run the Spring Boot application, you will see the following on the console (timestamps removed): ERROR 20680 --- [ main] org.example.MyAspect : BEFORE ANNOTATION INFO 20680 --- [ main] org.example.Main : my info As you can see, both aspects kick in, the first one logging an ERROR and the other one changing the return value from "my name" to "my info". The advantage of the "delombok" variant is that within the same Maven module, you can weave aspects into the Lolbok-generated source code. The disadvantage is, that in your IDE you might not be able to compile the project imported from Maven because of the very unusual custom configuration. In IntelliJ IDEA, I had to delegate the build to Maven, but still the source code editor shows squiggly lines. As an alternative, you could create one module with Lombok compilation (no "delombok") and a second module using binary weaving in order to weave aspects into the Lombok-enhanced class files, as described here. It would all be much easier without Lombok, though. The third alternative is compilation with Lombok and native AspectJ load-time weaving configured for Spring Boot instead of compile-time or binary weaving during build time. I cannot explain and show every variant in detail here, it is a long answer already.
Springboot with both aspectj and Spring AOP
I am trying to get a springboot (2.6.2) project to work with both AspectJ and Spring AOP. I have the following sample classes: @Entity public class Item { @Id @Getter private String uuid = UUID.randomUUID().toString(); private String name; @Verify.Access public String getName() { return name; } } public @interface Verify { @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface Access {} } @Aspect @Slf4j public class MyAspect { @Before("@annotation(Verify.Access)") public void beforeAnnotation(JoinPoint joinPoint) { log.error("BEFORE ANNOTATION"); } } @Aspect @Service public class OtherAspect { @Autowired private MyUtility myUtility; @Around("@annotation(SystemCall)") public Object run(@NonNull final ProceedingJoinPoint join) throws Throwable { return myUtility.getInfo(); } } @Service @Data public class MyUtility { Object info; } My pom.xml file has the following plugins defined: <plugin> <groupId>com.nickwongdev</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.12.6</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <proc>none</proc> <complianceLevel>${java.version}</complianceLevel> <showWeaveInfo>true</showWeaveInfo> <forceAjcCompile>true</forceAjcCompile> <sources/> <weaveDirectories> <weaveDirectory>${project.build.directory}/classes</weaveDirectory> </weaveDirectories> </configuration> <executions> <execution> <goals> <goal>compile</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>${aspectj.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.projectlombok</groupId> <artifactId>lombok-maven-plugin</artifactId> <version>1.18.20.0</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>delombok</goal> </goals> </execution> </executions> <configuration> <addOutputDirectory>false</addOutputDirectory> <sourceDirectory>src/main/java</sourceDirectory> <encoding>UTF-8</encoding> </configuration> </plugin> I have also defined a src/main/resources/org/aspectj/aop.xml: <!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> <aspectj> <weaver> <include within="mypackage..*" /> <include within="org.springframework.boot..*" /> </weaver> <aspects> <aspect name="mypackage.MyAspect" /> </aspects> </aspectj> It seems to compile okay and I see the info messages that the join points are being advised. However, in the OtherAspect the autowired MyUtility is not getting set. From what I could find I would expect Spring to recognize OtherAspect as a Component and Autowire in MyUtility but instead I get a NullPointerException. Any thoughts? Thanks!
[ "OK, I had a little bit of time and prepared the MCVE which actually would have been your job to provide. I made the following assumptions:\n\nYou need native AspectJ, because you want to weave a target class which is not a Spring bean.\nYou want to use compile-time, not load-time weaaving. Therefore, you would use AspectJ Maven Plugin.\nYou want to use Spring dependency injection for wiring Spring beans into native AspectJ aspects, as described in the Spring manual, i.e. using an aspectOf factory method for the native aspect in Spring.\nYou absolutely insist on combining Lombok and native AspectJ, even though they are incompatible out of the box. I.e., you need a workaround in Maven, either binary weaving (e.g. if Lombok is only used for your non-aspect classes) or a \"delombok\" build step (e.g. if your aspects also use Lombok, which unfortunately they do, using the @Slf4j Lombok annotation in MyAspect.\n\nWhat I changed in your setup:\n\nI removed the dependency on Spring Data JPA to make things easier, because I was too lazy to set up a dummy in-memory database. It is not relevant for the solution here. I.e., I also commented out the @Entity and @Id annotations in class Item.\nYou already configured a \"delombok\" build step, which I wanted to stick with, because it seems to be your preference. Hence, your sample code only compiles with AspectJ Maven when using ${project.build.directory}/generated-sources/delombok as the source directory. Your idea to use a <weaveDirectory> does not work, because the aspect with the Lombok annotation does not compile that way, as it refers to the Lombok-generated static log field.\nI removed the @Service annotation from the native AspectJ aspect, because that would lead to problems when wiring the application. Instead, I added a @Bean factory method to OtherAspect, so we can use @Autowired MyUtility myUtility there. In the same aspect, I also switched from @annotation(SystemCall) (due to missing code in your example) to @annotation(Verify.Access) in order to have something to test against.\nI removed the superfluous aop.xml file.\nI added a little Spring Boot driver application.\nI switched from the no longer maintained com.nickwongdev AspectJ Maven plugin to the current dev.aspectj plugin which has more features and supports Java 17+, too.\n\nThe whole application looks like this:\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>org.example</groupId>\n <artifactId>SO_AJ_SpringAutowireBeanNativeAspect_74661663</artifactId>\n <version>1.0-SNAPSHOT</version>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <maven.compiler.source>17</maven.compiler.source>\n <maven.compiler.target>17</maven.compiler.target>\n <aspectj.version>1.9.9.1</aspectj.version>\n </properties>\n\n <build>\n <plugins>\n <plugin>\n <groupId>dev.aspectj</groupId>\n <artifactId>aspectj-maven-plugin</artifactId>\n <version>1.13.1</version>\n <configuration>\n <complianceLevel>${maven.compiler.target}</complianceLevel>\n <proc>none</proc>\n <showWeaveInfo>true</showWeaveInfo>\n <forceAjcCompile>true</forceAjcCompile>\n <sources>\n <source>\n <basedir>${project.build.directory}/generated-sources/delombok</basedir>\n </source>\n </sources>\n <!--\n <weaveDirectories>\n <weaveDirectory>${project.build.directory}/classes</weaveDirectory>\n </weaveDirectories>\n -->\n </configuration>\n <executions>\n <execution>\n <goals>\n <goal>compile</goal>\n </goals>\n </execution>\n </executions>\n <dependencies>\n <dependency>\n <groupId>org.aspectj</groupId>\n <artifactId>aspectjtools</artifactId>\n <version>${aspectj.version}</version>\n </dependency>\n </dependencies>\n </plugin>\n <plugin>\n <groupId>org.projectlombok</groupId>\n <artifactId>lombok-maven-plugin</artifactId>\n <version>1.18.20.0</version>\n <executions>\n <execution>\n <phase>generate-sources</phase>\n <goals>\n <goal>delombok</goal>\n </goals>\n </execution>\n </executions>\n <configuration>\n <addOutputDirectory>false</addOutputDirectory>\n <sourceDirectory>src/main/java</sourceDirectory>\n <encoding>UTF-8</encoding>\n </configuration>\n </plugin>\n </plugins>\n </build>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-aop</artifactId>\n <version>2.6.2</version>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n <version>2.6.2</version>\n <scope>compile</scope>\n </dependency>\n <!--\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-data-jpa</artifactId>\n <version>2.6.2</version>\n <scope>compile</scope>\n </dependency>\n -->\n <dependency>\n <groupId>org.projectlombok</groupId>\n <artifactId>lombok</artifactId>\n <version>1.18.24</version>\n </dependency>\n </dependencies>\n\n</project>\n\npackage org.example;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\npublic @interface Verify {\n @Target({ ElementType.METHOD })\n @Retention(RetentionPolicy.RUNTIME)\n @interface Access {}\n}\n\npackage org.example;\n\nimport lombok.Data;\nimport org.springframework.stereotype.Service;\n\n@Service\n@Data\npublic class MyUtility {\n Object info;\n}\n\npackage org.example;\n\nimport lombok.Getter;\n\n//import javax.persistence.Entity;\n//import javax.persistence.Id;\nimport java.util.UUID;\n\n//@Entity\npublic class Item {\n// @Id\n @Getter\n private String uuid = UUID.randomUUID().toString();\n\n private String name;\n\n public Item(String name) {\n this.name = name;\n }\n\n @Verify.Access\n public String getName() {\n return name;\n }\n}\n\npackage org.example;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.aspectj.lang.JoinPoint;\nimport org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.Before;\n\n@Aspect\n@Slf4j\npublic class MyAspect {\n @Before(\"@annotation(Verify.Access)\")\n public void beforeAnnotation(JoinPoint joinPoint) {\n log.error(\"BEFORE ANNOTATION\");\n }\n}\n\npackage org.example;\n\nimport lombok.NonNull;\nimport org.aspectj.lang.ProceedingJoinPoint;\nimport org.aspectj.lang.annotation.Around;\nimport org.aspectj.lang.annotation.Aspect;\nimport org.springframework.beans.factory.annotation.Autowired;\n\n@Aspect\npublic class OtherAspect {\n @Autowired\n private MyUtility myUtility;\n\n// @Around(\"@annotation(SystemCall)\")\n @Around(\"@annotation(Verify.Access)\")\n public Object run(@NonNull final ProceedingJoinPoint join) throws Throwable {\n return myUtility.getInfo();\n// return join.proceed();\n }\n}\n\npackage org.example;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.aspectj.lang.Aspects;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ConfigurableApplicationContext;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@SpringBootApplication\n@Configuration\n@Slf4j\npublic class Main {\n @Bean\n public OtherAspect otherAspect() {\n return Aspects.aspectOf(OtherAspect.class);\n }\n\n public static void main(String[] args) {\n try (ConfigurableApplicationContext appContext = SpringApplication.run(Main.class, args)) {\n doStuff(appContext);\n }\n }\n\n private static void doStuff(ConfigurableApplicationContext appContext) {\n MyUtility myUtility = appContext.getBean(MyUtility.class);\n myUtility.setInfo(\"my info\");\n Item item = new Item(\"my name\");\n log.info(item.getName());\n }\n}\n\nIf you run the Spring Boot application, you will see the following on the console (timestamps removed):\nERROR 20680 --- [ main] org.example.MyAspect : BEFORE ANNOTATION\n INFO 20680 --- [ main] org.example.Main : my info\n\nAs you can see, both aspects kick in, the first one logging an ERROR and the other one changing the return value from \"my name\" to \"my info\".\nThe advantage of the \"delombok\" variant is that within the same Maven module, you can weave aspects into the Lolbok-generated source code. The disadvantage is, that in your IDE you might not be able to compile the project imported from Maven because of the very unusual custom configuration. In IntelliJ IDEA, I had to delegate the build to Maven, but still the source code editor shows squiggly lines.\nAs an alternative, you could create one module with Lombok compilation (no \"delombok\") and a second module using binary weaving in order to weave aspects into the Lombok-enhanced class files, as described here. It would all be much easier without Lombok, though. The third alternative is compilation with Lombok and native AspectJ load-time weaving configured for Spring Boot instead of compile-time or binary weaving during build time. I cannot explain and show every variant in detail here, it is a long answer already.\n" ]
[ 0 ]
[]
[]
[ "aspectj", "spring_aop", "spring_boot" ]
stackoverflow_0074661663_aspectj_spring_aop_spring_boot.txt
Q: Dynamically add attributes to instance and use attribute like @Property with get and set Im learning Python here so please spare me for silly questions. I Encounter an issue with adding attribute to a class instance I have a dictionary of people with name,age and strength, i.e { "Mary": {"age":25, "strength": 80}, "John": {"age": 40, "strength": 70}, ... } and a class that will get in list of people as constructor input and add them as its own attribute, and when that attribute is called, it will return the age i.e: group = Person({dictionary of person}) # call person name as attribute, get back age first_person = group.Mary # return 25 here group.John # return 40 here However, each attribute will also need to maintain its behavior as a dict/object group.Mary["strength"] # return 80 here I tried __get()__ but it seems to work only on class variables which is not this case since I need to create multiple group instances of class Person and they don't share variables. Also tried setattr() but it will keep each attribute as a dict and therefore cannot directly call like group.Maryto get age May I know is there any way in Python to implement this requirement? A: I don't think this is possible. The expression group.Mary["strength"] essentially consists of 2 steps: retrieving the attribute named "Mary" from the object group, and; calling the method __getitem__ on the retrieved attribute with argument "strength". However, note that in your example you require Step 1 (group.Mary) to return 25, which is an integer. Unfortunately, integers can't also be a mapping (objects that implement __getitem__). A: Added to class a method to create dynamically the properties but, for example, it can also be refactor as global function. Each attribute is private and its access is ruled by the descriptors. Notice the private attributes created dynamically required a bit more of care, see this for details and references. class Person: @classmethod def property_factory(cls, name): # dynamical descriptors, -> private name mangling! p = property(fget=lambda self: getattr(self, f'_{cls.__name__}__{name}'), fset=lambda self, v: setattr(self, f'_{cls.__name__}__{name}', v)) setattr(cls, name, p) def __init__(self, **p): # dynamically add properties for name in p.keys(): self.property_factory(name) # initialization descriptors for name, d in p.items(): setattr(self, name, d) data = {"Mary": {"age":25, "strength": 80}, "John": {"age": 40, "strength": 70}} p = Person(**data) # check property print(type(p).Mary) #<property object at 0x7f5e5d469e00> print(type(p.Mary)) #<class 'dict'> # descriptors in action p.Mary['age'] += 666 p.John['strength'] -= 666 print(p.John) #{'age': 40, 'strength': -596} print(p.Mary) #{'age': 691, 'strength': 80}
Dynamically add attributes to instance and use attribute like @Property with get and set
Im learning Python here so please spare me for silly questions. I Encounter an issue with adding attribute to a class instance I have a dictionary of people with name,age and strength, i.e { "Mary": {"age":25, "strength": 80}, "John": {"age": 40, "strength": 70}, ... } and a class that will get in list of people as constructor input and add them as its own attribute, and when that attribute is called, it will return the age i.e: group = Person({dictionary of person}) # call person name as attribute, get back age first_person = group.Mary # return 25 here group.John # return 40 here However, each attribute will also need to maintain its behavior as a dict/object group.Mary["strength"] # return 80 here I tried __get()__ but it seems to work only on class variables which is not this case since I need to create multiple group instances of class Person and they don't share variables. Also tried setattr() but it will keep each attribute as a dict and therefore cannot directly call like group.Maryto get age May I know is there any way in Python to implement this requirement?
[ "I don't think this is possible. The expression group.Mary[\"strength\"] essentially consists of 2 steps:\n\nretrieving the attribute named \"Mary\" from the object group, and;\ncalling the method __getitem__ on the retrieved attribute with argument \"strength\".\n\nHowever, note that in your example you require Step 1 (group.Mary) to return 25, which is an integer. Unfortunately, integers can't also be a mapping (objects that implement __getitem__).\n", "Added to class a method to create dynamically the properties but, for example, it can also be refactor as global function.\nEach attribute is private and its access is ruled by the descriptors. Notice the private attributes created dynamically required a bit more of care, see this for details and references.\nclass Person:\n @classmethod\n def property_factory(cls, name):\n # dynamical descriptors, -> private name mangling!\n p = property(fget=lambda self: getattr(self, f'_{cls.__name__}__{name}'), \n fset=lambda self, v: setattr(self, f'_{cls.__name__}__{name}', v))\n \n setattr(cls, name, p)\n\n def __init__(self, **p):\n # dynamically add properties\n for name in p.keys():\n self.property_factory(name)\n\n # initialization descriptors\n for name, d in p.items():\n setattr(self, name, d)\n\n\ndata = {\"Mary\": {\"age\":25, \"strength\": 80}, \"John\": {\"age\": 40, \"strength\": 70}}\n\np = Person(**data)\n\n# check property\nprint(type(p).Mary)\n#<property object at 0x7f5e5d469e00>\nprint(type(p.Mary))\n#<class 'dict'>\n\n# descriptors in action\np.Mary['age'] += 666\np.John['strength'] -= 666\nprint(p.John)\n#{'age': 40, 'strength': -596}\nprint(p.Mary)\n#{'age': 691, 'strength': 80}\n\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074665577_python.txt
Q: SQL to exclude two column values in a join table I have following two tables Table 1 PKey number amount date CN-897687 YHVY 299.99 11/21/22 3:32 PM CN-646465 JWVF 271.05 10/21/22 4:34 AM CN-475678 C96H 61.99 7/1/22 11:05 AM CN-858673 QCVM 324.08 3/1/22 9:51 AM CN-347468 RW44 165.02 5/9/22 8:49 AM CN-079836 3XTY 371.34 11/27/22 8:48 PM Table 2 PKey state open_amt date CN-897687 issued -299.99 11/21/22 3:32 PM CN-897687 issued -0.99 11/29/22 11:31 AM CN-475678 issued -61.99 7/1/22 11:05 AM CN-858673 issued -324.08 3/1/22 9:51 AM CN-858673 cleared 0.00 11/17/22 12:32 AM CN-858673 issued -173.75 5/1/22 12:17 AM CN-347468 issued -165.02 5/9/22 8:49 AM CN-079836 issued -371.34 11/27/22 8:48 PM CN-079836 issued -21.84 12/1/22 10:53 AM CN-646465 issued -271.05 10/21/22 4:34 AM CN-646465 issued -22.95 11/4/22 9:42 AM CN-646465 issued -9.60 12/1/22 12:20 AM CN-646465 cleared 0.00 12/2/22 12:34 AM I am using a SQL query to get the output as follows PKey number amount date state open_amt CN-897687 YHVY 299.99 11/21/22 3:32 PM issued -0.99 CN-646465 JWVF 271.05 10/21/22 4:34 AM cleared 0.00 CN-475678 C96H 61.99 7/1/22 11:05 AM issued -61.99 CN-858673 QCVM 324.08 3/1/22 9:51 AM cleared 0.00 CN-347468 RW44 165.02 5/9/22 8:49 AM issued -165.02 CN-079836 3XTY 371.34 11/27/22 8:48 PM issued -21.84 I want the output as follows PKey number amount date state open_amt CN-897687 YHVY 299.99 11/21/22 3:32 PM issued -0.99 CN-475678 C96H 61.99 7/1/22 11:05 AM issued -61.99 CN-347468 RW44 165.02 5/9/22 8:49 AM issued -165.02 CN-079836 3XTY 371.34 11/27/22 8:48 PM issued -21.84 SELECT DISTINCT t1.Pkey t1.number, t1.date, t1.amount, t2.open_amt, t2.state FROM (SELECT * FROM table 1 WHERE PKey IN ('CN-897687', 'CN-646465', 'CN-475678', 'CN-858673', 'CN-347468', 'CN-079836')) t1 LEFT JOIN (SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY Pkey ORDER BY date DESC) rn FROM table 2) WHERE rn = 1 -- AND open_amt <> 0 -- AND state <> 'cleared' ) t2 ON t1.Pkey = t2.Pkey Tried to put the filter for state <> 'cleared' and open_amt <> 0 with different combinations, but not getting the required output
SQL to exclude two column values in a join table
I have following two tables Table 1 PKey number amount date CN-897687 YHVY 299.99 11/21/22 3:32 PM CN-646465 JWVF 271.05 10/21/22 4:34 AM CN-475678 C96H 61.99 7/1/22 11:05 AM CN-858673 QCVM 324.08 3/1/22 9:51 AM CN-347468 RW44 165.02 5/9/22 8:49 AM CN-079836 3XTY 371.34 11/27/22 8:48 PM Table 2 PKey state open_amt date CN-897687 issued -299.99 11/21/22 3:32 PM CN-897687 issued -0.99 11/29/22 11:31 AM CN-475678 issued -61.99 7/1/22 11:05 AM CN-858673 issued -324.08 3/1/22 9:51 AM CN-858673 cleared 0.00 11/17/22 12:32 AM CN-858673 issued -173.75 5/1/22 12:17 AM CN-347468 issued -165.02 5/9/22 8:49 AM CN-079836 issued -371.34 11/27/22 8:48 PM CN-079836 issued -21.84 12/1/22 10:53 AM CN-646465 issued -271.05 10/21/22 4:34 AM CN-646465 issued -22.95 11/4/22 9:42 AM CN-646465 issued -9.60 12/1/22 12:20 AM CN-646465 cleared 0.00 12/2/22 12:34 AM I am using a SQL query to get the output as follows PKey number amount date state open_amt CN-897687 YHVY 299.99 11/21/22 3:32 PM issued -0.99 CN-646465 JWVF 271.05 10/21/22 4:34 AM cleared 0.00 CN-475678 C96H 61.99 7/1/22 11:05 AM issued -61.99 CN-858673 QCVM 324.08 3/1/22 9:51 AM cleared 0.00 CN-347468 RW44 165.02 5/9/22 8:49 AM issued -165.02 CN-079836 3XTY 371.34 11/27/22 8:48 PM issued -21.84 I want the output as follows PKey number amount date state open_amt CN-897687 YHVY 299.99 11/21/22 3:32 PM issued -0.99 CN-475678 C96H 61.99 7/1/22 11:05 AM issued -61.99 CN-347468 RW44 165.02 5/9/22 8:49 AM issued -165.02 CN-079836 3XTY 371.34 11/27/22 8:48 PM issued -21.84 SELECT DISTINCT t1.Pkey t1.number, t1.date, t1.amount, t2.open_amt, t2.state FROM (SELECT * FROM table 1 WHERE PKey IN ('CN-897687', 'CN-646465', 'CN-475678', 'CN-858673', 'CN-347468', 'CN-079836')) t1 LEFT JOIN (SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY Pkey ORDER BY date DESC) rn FROM table 2) WHERE rn = 1 -- AND open_amt <> 0 -- AND state <> 'cleared' ) t2 ON t1.Pkey = t2.Pkey Tried to put the filter for state <> 'cleared' and open_amt <> 0 with different combinations, but not getting the required output
[]
[]
[ "just add filter condition inside sub query.\nselect *, row_number () over (partition by Pkey order by date desc) rn\n from table 2 where open_amt >0\n and trim(lower(state)) <> 'cleared'\n\nBTW : i didn't execute your query.\n" ]
[ -1 ]
[ "sql", "sql_server" ]
stackoverflow_0074667735_sql_sql_server.txt
Q: Loading older sklearn models with new sklearn package I have upgraded my python version from 3.6.5 to 3.10.6 and scikit-learn version from 0.20.3 to 1.1.3. I am getting the following error when I am trying to load my older models built on older sklearn version using the new sklearn version: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/deepakahire/codebase/venv_3_10_6/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 658, in load obj = _unpickle(fobj, filename, mmap_mode) File "/home/deepakahire/codebase/venv_3_10_6/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 577, in _unpickle obj = unpickler.load() File "/home/deepakahire/.pyenv/versions/3.10.6/lib/python3.10/pickle.py", line 1213, in load dispatch[key[0]](self) File "/home/deepakahire/.pyenv/versions/3.10.6/lib/python3.10/pickle.py", line 1529, in load_global klass = self.find_class(module, name) File "/home/deepakahire/.pyenv/versions/3.10.6/lib/python3.10/pickle.py", line 1580, in find_class __import__(module, level=0) ModuleNotFoundError: No module named 'sklearn.linear_model.logistic' I am using joblib's load functionality to load the model. I did not upgrade the joblib package. A: This is the problem which I faced during a production release. Complete details and the solution to this issue are discussed at - https://www.kaggle.com/code/adeepak7/load-old-sklearn-models-with-new-sklearn-package
Loading older sklearn models with new sklearn package
I have upgraded my python version from 3.6.5 to 3.10.6 and scikit-learn version from 0.20.3 to 1.1.3. I am getting the following error when I am trying to load my older models built on older sklearn version using the new sklearn version: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/deepakahire/codebase/venv_3_10_6/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 658, in load obj = _unpickle(fobj, filename, mmap_mode) File "/home/deepakahire/codebase/venv_3_10_6/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 577, in _unpickle obj = unpickler.load() File "/home/deepakahire/.pyenv/versions/3.10.6/lib/python3.10/pickle.py", line 1213, in load dispatch[key[0]](self) File "/home/deepakahire/.pyenv/versions/3.10.6/lib/python3.10/pickle.py", line 1529, in load_global klass = self.find_class(module, name) File "/home/deepakahire/.pyenv/versions/3.10.6/lib/python3.10/pickle.py", line 1580, in find_class __import__(module, level=0) ModuleNotFoundError: No module named 'sklearn.linear_model.logistic' I am using joblib's load functionality to load the model. I did not upgrade the joblib package.
[ "This is the problem which I faced during a production release.\nComplete details and the solution to this issue are discussed at -\nhttps://www.kaggle.com/code/adeepak7/load-old-sklearn-models-with-new-sklearn-package\n" ]
[ 0 ]
[]
[]
[ "model_management", "python", "python_3.x", "scikit_learn" ]
stackoverflow_0074667759_model_management_python_python_3.x_scikit_learn.txt
Q: Return a list of weekdays, starting with given weekday My task is to define a function weekdays(weekday) that returns a list of weekdays, starting with the given weekday. It should work like this: >>> weekdays('Wednesday') ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday'] So far I've come up with this one: def weekdays(weekday): days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') result = "" for day in days: if day == weekday: result += day return result But this prints the input day only: >>> weekdays("Sunday") 'Sunday' What am I doing wrong? A: The reason your code is only returning one day name is because weekday will never match more than one string in the days tuple and therefore won't add any of the days of the week that follow it (nor wrap around to those before it). Even if it did somehow, it would still return them all as one long string because you're initializing result to an empty string, not an empty list. Here's a solution that uses the datetime module to create a list of all the weekday names starting with "Monday" in the current locale's language. This list is then used to create another list of names in the desired order which is returned. It does the ordering by finding the index of designated day in the original list and then splicing together two slices of it relative to that index to form the result. As an optimization it also caches the locale's day names so if it's ever called again with the same current locale (a likely scenario), it won't need to recreate this private list. import datetime import locale def weekdays(weekday): current_locale = locale.getlocale() if current_locale not in weekdays._days_cache: # Add day names from a reference date, Monday 2001-Jan-1 to cache. weekdays._days_cache[current_locale] = [ datetime.date(2001, 1, i).strftime('%A') for i in range(1, 8)] days = weekdays._days_cache[current_locale] index = days.index(weekday) return days[index:] + days[:index] weekdays._days_cache = {} # initialize cache print(weekdays('Wednesday')) # ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday'] Besides not needing to hard-code days names in the function, another advantage to using the datetime module is that code utilizing it will automatically work in other languages. This can be illustrated by changing the locale and then calling the function with a day name in the corresponding language. For example, although France is not my default locale, I can set it to be the current one for testing purposes as shown below. Note: According to this Capitalization of day names article, the names of the days of the week are not capitalized in French like they are in my default English locale, but that is taken into account automatically, too, which means the weekday name passed to it must be in the language of the current locale and is also case-sensitive. Of course you could modify the function to ignore the lettercase of the input argument, if desired. # set or change locale locale.setlocale(locale.LC_ALL, 'french_france') print(weekdays('mercredi')) # use French equivalent of 'Wednesday' # ['mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche', 'lundi', 'mardi'] A: A far quicker approach would be to keep in mind, that the weekdays cycle. As such, we just need to get the first day we want to include the list, and add the remaining 6 elements to the end. Or in other words, we get the weekday list starting from the starting day, append another full week, and return only the first 7 elements (for the full week). days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') def weekdays ( weekday ): index = days.index( weekday ) return list( days[index:] + days )[:7] >>> weekdays( 'Wednesday' ) ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday'] A: def weekdays(day): days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] i=days.index(day) # get the index of the selected day d1=days[i:] #get the list from an including this index d1.extend(days[:i]) # append the list form the beginning to this index return d1 And if you want to test that it works: def test_weekdays(): days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for day in days: print weekdays(day) A: Hmm, you are currently only searching for the given weekday and set as result :) You can use the slice ability in python list to do this: result = days[days.index(weekday):] + days[:days.index(weekdays)] A: Here's more what you want: def weekdays(weekday): days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] index = days.index(weekday) return (days + days)[index:index+7] A: You don't need to hardcode array of weekdays. It's already available in calendar module. import calendar as cal def weekdays(weekday): start = [d for d in cal.day_name].index(weekday) return [cal.day_name[(i+start) % 7] for i in range(7)] A: Your result variable is a string and not a list object. Also, it only gets updated one time which is when it is equal to the passed weekday argument. Here's an implementation: import calendar def weekdays(weekday): days = [day for day in calendar.day_name] for day in days: days.insert(0, days.pop()) # add last day as new first day of list if days[0] == weekday: # if new first day same as weekday then all done break return days Example output: >>> weekdays("Wednesday") ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday'] >>> weekdays("Friday") ['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'] >>> weekdays("Tuesday") ['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday'] A: Every time you run the for loop, the day variable changes. So day is equal to your input only once. Using "Sunday" as input, it first checked if Monday = Sunday, then if Tuesday = Sunday, then if Wednesday = Sunday, until it finally found that Sunday = Sunday and returned Sunday. A: Another approach using the standard library: days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] def weekdays(weekday): n = days.index(weekday) return list(itertools.islice(itertools.cycle(days), n, n + 7)) Itertools is a bit much in this case. Since you know at most one extra cycle is needed, you could do that manually: days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] days += days def weekdays(weekday): n = days.index(weekday) return days[n:n+7] Both give the expected output: >>> weekdays("Wednesday") ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday'] >>> weekdays("Sunday") ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] >>> weekdays("Monday") ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] A: The code below will gnereate a list based on X days you want a head , of you want to generate list of days going back change the [ minus to plus ] import datetime numdays = 7 base = datetime.date.today() date_list = [base + datetime.timedelta(days=x) for x in range(numdays)] date_list_with_dayname = ["%s, %s" % ((base + datetime.timedelta(days=x)).strftime("%A"), base + datetime.timedelta(days=x)) for x in range(numdays)] A: You can use Python standard calendar module with very convenient list-like deque object. This way, we just have to rotate the list of the days to the one we want. import calendar from collections import deque def get_weekdays(first: str = 'Monday') -> deque[str]: weekdays = deque(calendar.day_name) weekdays.rotate(-weekdays.index(first)) return weekdays get_weekdays('Wednesday') that outputs: deque(['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']) A: okay, My simple approach would be : result = days[days.index(weekday):] + days[:days.index(weekdays)] hope This will be helpfull
Return a list of weekdays, starting with given weekday
My task is to define a function weekdays(weekday) that returns a list of weekdays, starting with the given weekday. It should work like this: >>> weekdays('Wednesday') ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday'] So far I've come up with this one: def weekdays(weekday): days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') result = "" for day in days: if day == weekday: result += day return result But this prints the input day only: >>> weekdays("Sunday") 'Sunday' What am I doing wrong?
[ "The reason your code is only returning one day name is because weekday will never match more than one string in the days tuple and therefore won't add any of the days of the week that follow it (nor wrap around to those before it). Even if it did somehow, it would still return them all as one long string because you're initializing result to an empty string, not an empty list.\nHere's a solution that uses the datetime module to create a list of all the weekday names starting with \"Monday\" in the current locale's language. This list is then used to create another list of names in the desired order which is returned. It does the ordering by finding the index of designated day in the original list and then splicing together two slices of it relative to that index to form the result. As an optimization it also caches the locale's day names so if it's ever called again with the same current locale (a likely scenario), it won't need to recreate this private list.\nimport datetime\nimport locale\n\ndef weekdays(weekday):\n current_locale = locale.getlocale()\n if current_locale not in weekdays._days_cache:\n # Add day names from a reference date, Monday 2001-Jan-1 to cache.\n weekdays._days_cache[current_locale] = [\n datetime.date(2001, 1, i).strftime('%A') for i in range(1, 8)]\n days = weekdays._days_cache[current_locale]\n index = days.index(weekday)\n return days[index:] + days[:index]\n\nweekdays._days_cache = {} # initialize cache\n\nprint(weekdays('Wednesday'))\n# ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']\n\nBesides not needing to hard-code days names in the function, another advantage to using the datetime module is that code utilizing it will automatically work in other languages. This can be illustrated by changing the locale and then calling the function with a day name in the corresponding language.\nFor example, although France is not my default locale, I can set it to be the current one for testing purposes as shown below. Note: According to this Capitalization of day names article, the names of the days of the week are not capitalized in French like they are in my default English locale, but that is taken into account automatically, too, which means the weekday name passed to it must be in the language of the current locale and is also case-sensitive. Of course you could modify the function to ignore the lettercase of the input argument, if desired.\n# set or change locale\nlocale.setlocale(locale.LC_ALL, 'french_france')\n\nprint(weekdays('mercredi')) # use French equivalent of 'Wednesday'\n# ['mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche', 'lundi', 'mardi']\n\n", "A far quicker approach would be to keep in mind, that the weekdays cycle. As such, we just need to get the first day we want to include the list, and add the remaining 6 elements to the end. Or in other words, we get the weekday list starting from the starting day, append another full week, and return only the first 7 elements (for the full week).\ndays = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')\ndef weekdays ( weekday ):\n index = days.index( weekday )\n return list( days[index:] + days )[:7]\n\n>>> weekdays( 'Wednesday' )\n['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']\n\n", "def weekdays(day):\n days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n i=days.index(day) # get the index of the selected day\n d1=days[i:] #get the list from an including this index\n d1.extend(days[:i]) # append the list form the beginning to this index\n return d1\n\nAnd if you want to test that it works: \ndef test_weekdays():\n days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n for day in days:\n print weekdays(day)\n\n", "Hmm, you are currently only searching for the given weekday and set as result :)\nYou can use the slice ability in python list to do this:\nresult = days[days.index(weekday):] + days[:days.index(weekdays)]\n\n", "Here's more what you want:\ndef weekdays(weekday):\n days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n index = days.index(weekday)\n return (days + days)[index:index+7]\n\n", "You don't need to hardcode array of weekdays. It's already available in calendar module.\nimport calendar as cal\n\ndef weekdays(weekday):\n start = [d for d in cal.day_name].index(weekday)\n return [cal.day_name[(i+start) % 7] for i in range(7)]\n\n", "Your result variable is a string and not a list object. Also, it only gets updated one time which is when it is equal to the passed weekday argument.\nHere's an implementation:\nimport calendar\n\ndef weekdays(weekday):\n days = [day for day in calendar.day_name]\n for day in days:\n days.insert(0, days.pop()) # add last day as new first day of list \n if days[0] == weekday: # if new first day same as weekday then all done\n break \n return days\n\nExample output:\n>>> weekdays(\"Wednesday\")\n['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']\n>>> weekdays(\"Friday\")\n['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']\n>>> weekdays(\"Tuesday\")\n['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday']\n\n", "Every time you run the for loop, the day variable changes. So day is equal to your input only once. Using \"Sunday\" as input, it first checked if Monday = Sunday, then if Tuesday = Sunday, then if Wednesday = Sunday, until it finally found that Sunday = Sunday and returned Sunday.\n", "Another approach using the standard library:\ndays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',\n 'Sunday']\ndef weekdays(weekday):\n n = days.index(weekday)\n return list(itertools.islice(itertools.cycle(days), n, n + 7))\n\nItertools is a bit much in this case. Since you know at most one extra cycle is needed, you could do that manually:\ndays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',\n 'Sunday']\ndays += days\ndef weekdays(weekday):\n n = days.index(weekday)\n return days[n:n+7]\n\nBoth give the expected output:\n>>> weekdays(\"Wednesday\")\n['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']\n>>> weekdays(\"Sunday\")\n['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n>>> weekdays(\"Monday\")\n['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\n", "The code below will gnereate a list based on X days you want a head , of you want to generate list of days going back change the [ minus to plus ]\nimport datetime\nnumdays = 7\nbase = datetime.date.today()\ndate_list = [base + datetime.timedelta(days=x) for x in range(numdays)]\ndate_list_with_dayname = [\"%s, %s\" % ((base + datetime.timedelta(days=x)).strftime(\"%A\"), base + datetime.timedelta(days=x)) for x in range(numdays)]\n\n", "You can use Python standard calendar module with very convenient list-like deque object. This way, we just have to rotate the list of the days to the one we want.\nimport calendar\nfrom collections import deque\n\ndef get_weekdays(first: str = 'Monday') -> deque[str]:\n weekdays = deque(calendar.day_name)\n weekdays.rotate(-weekdays.index(first))\n return weekdays\n\nget_weekdays('Wednesday')\n\nthat outputs:\ndeque(['Wednesday',\n 'Thursday',\n 'Friday',\n 'Saturday',\n 'Sunday',\n 'Monday',\n 'Tuesday'])\n\n", "okay, My simple approach would be :\nresult = days[days.index(weekday):] + days[:days.index(weekdays)]\n\nhope This will be helpfull\n" ]
[ 15, 10, 7, 4, 4, 4, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "calendar", "python", "weekday" ]
stackoverflow_0004082772_calendar_python_weekday.txt
Q: Raw SQL Query working fine in MySQL Workbench, but causing SQLSTATE[22007] when executed through Laravel I'm trying to execute a RAW query using DB::select(DB::raw(..)) in Laravel, but it returns SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect time value FYI, columns are TIMESTAMP data type in MySQL db. That same query, executed in MySQL Workbench works fine. I'm assuming some default settings for Laravel-MySQL communication could be to blame, but I may be wrong. Thanks in advance! Tried Google-ing the issue, couldn't find much on the matter, except to change the config/database.php >> mysql >> strict mode to False, since default is True. I wouldn't want to change config files unless absolutely necessary. Which brings me to, what exactly does the MySQL Strict Mode refer to? A: The error message SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect time value indicates that you are trying to insert or update a value in a TIMESTAMP column that is not in a valid format. This can happen if the value you are trying to insert or update is not a valid date or time string, or if the value does not match the format expected by the TIMESTAMP column. In MySQL, the strict mode refers to a set of rules that the server applies when checking the validity of data. When strict mode is enabled, the server will reject invalid values for TIMESTAMP columns and return an error, such as the one you are seeing. When strict mode is disabled, the server will automatically convert invalid values to the default value for the column (usually 0000-00-00 00:00:00) and will not return an error. To fix the error you are seeing, you need to ensure that the value you are trying to insert or update in the TIMESTAMP column is a valid date or time string and that it matches the expected format for the column. You can do this by checking the value you are using and making sure it is in a valid format, such as YYYY-MM-DD HH:MM:SS. Alternatively, you can disable strict mode in your config/database.php file by setting the mysql.strict option to false. This will allow the server to automatically convert invalid values to the default value for the column and will prevent the error from occurring. However, it is generally recommended to keep strict mode enabled, as it helps ensure the integrity and consistency of your data. Here is an example of how you can disable strict mode in your config/database.php file: 'connections' => [ // Other connection settings... 'mysql' => [ // Other MySQL settings... 'strict' => false, ], ], You can modify this code as needed to fit your specific requirements. For example, you could set the strict option to false only for certain connections, or you could specify different values for the option depending on yours.
Raw SQL Query working fine in MySQL Workbench, but causing SQLSTATE[22007] when executed through Laravel
I'm trying to execute a RAW query using DB::select(DB::raw(..)) in Laravel, but it returns SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect time value FYI, columns are TIMESTAMP data type in MySQL db. That same query, executed in MySQL Workbench works fine. I'm assuming some default settings for Laravel-MySQL communication could be to blame, but I may be wrong. Thanks in advance! Tried Google-ing the issue, couldn't find much on the matter, except to change the config/database.php >> mysql >> strict mode to False, since default is True. I wouldn't want to change config files unless absolutely necessary. Which brings me to, what exactly does the MySQL Strict Mode refer to?
[ "The error message SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect time value indicates that you are trying to insert or update a value in a TIMESTAMP column that is not in a valid format. This can happen if the value you are trying to insert or update is not a valid date or time string, or if the value does not match the format expected by the TIMESTAMP column.\nIn MySQL, the strict mode refers to a set of rules that the server applies when checking the validity of data. When strict mode is enabled, the server will reject invalid values for TIMESTAMP columns and return an error, such as the one you are seeing. When strict mode is disabled, the server will automatically convert invalid values to the default value for the column (usually 0000-00-00 00:00:00) and will not return an error.\nTo fix the error you are seeing, you need to ensure that the value you are trying to insert or update in the TIMESTAMP column is a valid date or time string and that it matches the expected format for the column. You can do this by checking the value you are using and making sure it is in a valid format, such as YYYY-MM-DD HH:MM:SS.\nAlternatively, you can disable strict mode in your config/database.php file by setting the mysql.strict option to false. This will allow the server to automatically convert invalid values to the default value for the column and will prevent the error from occurring. However, it is generally recommended to keep strict mode enabled, as it helps ensure the integrity and consistency of your data.\nHere is an example of how you can disable strict mode in your config/database.php file:\n'connections' => [\n // Other connection settings...\n\n 'mysql' => [\n // Other MySQL settings...\n\n 'strict' => false,\n ],\n],\n\nYou can modify this code as needed to fit your specific requirements. For example, you could set the strict option to false only for certain connections, or you could specify different values for the option depending on yours.\n" ]
[ 0 ]
[]
[]
[ "laravel", "laravel_9", "mysql", "php", "sql" ]
stackoverflow_0074654380_laravel_laravel_9_mysql_php_sql.txt
Q: How can I convert hashmap to data class and save it as a list in kotlin? I am pulling data from website with api and I have a data class for this. my data class @Serializable data class ExchangeDto( val base_code: String, val conversion_rates: HashMap<String,Double>, val documentation: String, val result: String, val terms_of_use: String, val time_last_update_unix: Int, val time_last_update_utc: String, val time_next_update_unix: Int, val time_next_update_utc: String ) { fun toDomain() = Exchange( base_code = base_code, conversionRates = conversion_rates, result = result, ) } I get conversion rates as Hashmap but I want to save them as a list in my room database because it is difficult for me to process them as hashmaps. How can I do that Also, the sample data from the api is as follows { "result":"success", "documentation":"https://www.exchangerate-api.com/docs", "terms_of_use":"https://www.exchangerate-api.com/terms", "time_last_update_unix":1670025602, "time_last_update_utc":"Sat, 03 Dec 2022 00:00:02 +0000", "time_next_update_unix":1670112002, "time_next_update_utc":"Sun, 04 Dec 2022 00:00:02 +0000", "base_code":"USD", "conversion_rates":{ "USD":1, "AED":3.6725, "AFN":88.0980, "ALL":112.4117, "AMD":395.2364, "ANG":1.7900, "AOA":508.8502, "ARS":166.8477, "AUD":1.4705, "AWG":1.7900, "AZN":1.6974, "BAM":1.8602, "BBD":2.0000, "BDT":101.2527, "BGN":1.8596, "BHD":0.3760, "BIF":2048.3540, "BMD":1.0000, "BND":1.3507 } } A: You can use the Kotlin's standard library to convert a HashMap to a data class and save it as a list. You can use the map() function to iterate over the HashMap and create a new data class instance for each entry in the map, then add it to a list, like this: val listOfDataClasses = HashMap<String, String>().map { DataClass(it.key, it.value) }.toList()
How can I convert hashmap to data class and save it as a list in kotlin?
I am pulling data from website with api and I have a data class for this. my data class @Serializable data class ExchangeDto( val base_code: String, val conversion_rates: HashMap<String,Double>, val documentation: String, val result: String, val terms_of_use: String, val time_last_update_unix: Int, val time_last_update_utc: String, val time_next_update_unix: Int, val time_next_update_utc: String ) { fun toDomain() = Exchange( base_code = base_code, conversionRates = conversion_rates, result = result, ) } I get conversion rates as Hashmap but I want to save them as a list in my room database because it is difficult for me to process them as hashmaps. How can I do that Also, the sample data from the api is as follows { "result":"success", "documentation":"https://www.exchangerate-api.com/docs", "terms_of_use":"https://www.exchangerate-api.com/terms", "time_last_update_unix":1670025602, "time_last_update_utc":"Sat, 03 Dec 2022 00:00:02 +0000", "time_next_update_unix":1670112002, "time_next_update_utc":"Sun, 04 Dec 2022 00:00:02 +0000", "base_code":"USD", "conversion_rates":{ "USD":1, "AED":3.6725, "AFN":88.0980, "ALL":112.4117, "AMD":395.2364, "ANG":1.7900, "AOA":508.8502, "ARS":166.8477, "AUD":1.4705, "AWG":1.7900, "AZN":1.6974, "BAM":1.8602, "BBD":2.0000, "BDT":101.2527, "BGN":1.8596, "BHD":0.3760, "BIF":2048.3540, "BMD":1.0000, "BND":1.3507 } }
[ "You can use the Kotlin's standard library to convert a HashMap to a data class and save it as a list. You can use the map() function to iterate over the HashMap and create a new data class instance for each entry in the map, then add it to a list, like this:\nval listOfDataClasses = HashMap<String, String>().map {\n DataClass(it.key, it.value)\n}.toList()\n\n" ]
[ 0 ]
[]
[]
[ "android_room", "hashmap", "kotlin" ]
stackoverflow_0074667578_android_room_hashmap_kotlin.txt
Q: I want to convert array of intensities to an image I have the MNIST dataset. The CSV file contains 70,000 rows and 785 columns. The last column is the label. I want to convert the first columns of a row to the respective grayscale image with dimensions 28x28. Image of the data: A: So you just want to convert your data from csv to grayscale? from keras.preprocessing.image import ImageDataGenerator data_generator = ImageDataGenerator() data = data_generator.flow_from_dataframe(df, color_mode="grayscale") The df variable is your read csv. your data should return grayscale images using the code above.
I want to convert array of intensities to an image
I have the MNIST dataset. The CSV file contains 70,000 rows and 785 columns. The last column is the label. I want to convert the first columns of a row to the respective grayscale image with dimensions 28x28. Image of the data:
[ "So you just want to convert your data from csv to grayscale?\nfrom keras.preprocessing.image import ImageDataGenerator\ndata_generator = ImageDataGenerator()\ndata = data_generator.flow_from_dataframe(df, color_mode=\"grayscale\")\n\nThe df variable is your read csv. your data should return grayscale images using the code above.\n" ]
[ 0 ]
[]
[]
[ "csv", "mnist", "python" ]
stackoverflow_0074667006_csv_mnist_python.txt
Q: What´s the explenation for this in this piece of code, (related to strings in C)? Im new to coding and C, and cant found an explenation to this can someone explain me please: Piece of my code Why does those two last random characters pop up if I enter 8, but if I input 6 it doesn´t. It is related to null characters or something? Please I need an explenation. I tried almost everything, still figuring out, can´t found an explenation. A: In C, strings need to end with a special character called the NUL termination character. The value of that character is 0. If you pass a string to printf (%s), it expects the string to end with 0. Since you don't set the NUL termination, the printf function does not know when to stop reading characters from the string. This is called a buffer over read: you're reading past your allocated buffer (aster in that case). Make sure to terminate aster and it'll work. One way of achieving this would be to change char aster[n]; to char aster[n+1]; (allocate one character more for the NUL termination character) and then setting aster[n] = 0;. Consider n = 3 memory will look like this: (OUT OF BOUNDS means the memory afterwards doesn't belong to aster and is something else, we don't know what it is). aster[0] = ? aster[1] = ? aster[2] = ? aster[3] = ? <OUT OF BOUNDS> aster[4] = ? <OUT OF BOUNDS> aster[5] = ? <OUT OF BOUNDS> aster[6] = ... and so on After your code memory will look like this: aster[0] = * aster[1] = * aster[2] = * aster[3] = ? <OUT OF BOUNDS> aster[4] = ? <OUT OF BOUNDS> aster[5] = ? <OUT OF BOUNDS> aster[6] = ... and so on printf will look at each character. It should stop at aster[3] but it doesn't know that because there isn't a well-defined character at that place. This is why it might work sometimes, but other times it will not work. It's undefined behaviour. Changing the code to always set the NUL character it will look like this: aster[0] = * aster[1] = * aster[2] = 0 aster[3] = ? <OUT OF BOUNDS> aster[4] = ? <OUT OF BOUNDS> aster[5] = ? <OUT OF BOUNDS> aster[6] = ... and so on In that case printf will NEVER read past aster[2]. In any case, it's always a no-no to read or write past your memory buffers ;) Also you need to intialize your loop variable i to 0.
What´s the explenation for this in this piece of code, (related to strings in C)?
Im new to coding and C, and cant found an explenation to this can someone explain me please: Piece of my code Why does those two last random characters pop up if I enter 8, but if I input 6 it doesn´t. It is related to null characters or something? Please I need an explenation. I tried almost everything, still figuring out, can´t found an explenation.
[ "In C, strings need to end with a special character called the NUL termination character. The value of that character is 0.\nIf you pass a string to printf (%s), it expects the string to end with 0.\nSince you don't set the NUL termination, the printf function does not know when to stop reading characters from the string.\nThis is called a buffer over read: you're reading past your allocated buffer (aster in that case).\nMake sure to terminate aster and it'll work.\nOne way of achieving this would be to change char aster[n]; to char aster[n+1]; (allocate one character more for the NUL termination character) and then setting aster[n] = 0;.\nConsider n = 3 memory will look like this: (OUT OF BOUNDS means the memory afterwards doesn't belong to aster and is something else, we don't know what it is).\naster[0] = ?\naster[1] = ?\naster[2] = ?\naster[3] = ? <OUT OF BOUNDS>\naster[4] = ? <OUT OF BOUNDS>\naster[5] = ? <OUT OF BOUNDS>\naster[6] = ... and so on\n\nAfter your code memory will look like this:\naster[0] = *\naster[1] = *\naster[2] = *\naster[3] = ? <OUT OF BOUNDS>\naster[4] = ? <OUT OF BOUNDS>\naster[5] = ? <OUT OF BOUNDS>\naster[6] = ... and so on\n\nprintf will look at each character. It should stop at aster[3] but it doesn't know that because there isn't a well-defined character at that place. This is why it might work sometimes, but other times it will not work. It's undefined behaviour.\nChanging the code to always set the NUL character it will look like this:\naster[0] = *\naster[1] = *\naster[2] = 0\naster[3] = ? <OUT OF BOUNDS>\naster[4] = ? <OUT OF BOUNDS>\naster[5] = ? <OUT OF BOUNDS>\naster[6] = ... and so on\n\nIn that case printf will NEVER read past aster[2].\nIn any case, it's always a no-no to read or write past your memory buffers ;)\nAlso you need to intialize your loop variable i to 0.\n" ]
[ 2 ]
[]
[]
[ "c" ]
stackoverflow_0074667680_c.txt
Q: Various corotune filtering operations with return value I have situation where I have list of items. I want to to 3 changes on them. On my initial list, I want to do change1. I need to wait til this finishes and than after that happens, on my newList I want to do change2. Again I need to wait till operation2 finished and after that I want to do change3. Now I would get my finalList. I want to do calculations/changes with coroutines and return value after all this happens. I will write pseudocode to show you what I mean. However, my code does have errors and it does not compile. Please help: Class Operator() { val startingList: List<String> fun doListOperations(){ CoroutineScope(Dispatchers.IO).launch { async{doOperation1}.await async{doOperation2}.await async{doOperation3}.await } withContext(Dispatchers.Main){ return@withContext startingList } } fun doOperation1(){ //DOES SOME OPERATIONS ON startingList. Same applies on doOperation2 and doOperation3 } } tried the code above but need some good good example how to solve this A: I think this example will be useful for your problem: val initialList = listOf(1,2,3,4) suspend fun getFinalList(): List<Int> { val newList = initialList.map { change1(it) } // wait for change1 to finish val finalList = newList.map { change2(it) } // wait for change2 to finish return finalList.map { change3(it) } } suspend fun change1(item: Int): Int = item + 1 suspend fun change2(item: Int): Int = item + 2 suspend fun change3(item: Int): Int = item + 3 // usage GlobalScope.launch { val finalList = getFinalList() println(finalList) }
Various corotune filtering operations with return value
I have situation where I have list of items. I want to to 3 changes on them. On my initial list, I want to do change1. I need to wait til this finishes and than after that happens, on my newList I want to do change2. Again I need to wait till operation2 finished and after that I want to do change3. Now I would get my finalList. I want to do calculations/changes with coroutines and return value after all this happens. I will write pseudocode to show you what I mean. However, my code does have errors and it does not compile. Please help: Class Operator() { val startingList: List<String> fun doListOperations(){ CoroutineScope(Dispatchers.IO).launch { async{doOperation1}.await async{doOperation2}.await async{doOperation3}.await } withContext(Dispatchers.Main){ return@withContext startingList } } fun doOperation1(){ //DOES SOME OPERATIONS ON startingList. Same applies on doOperation2 and doOperation3 } } tried the code above but need some good good example how to solve this
[ "I think this example will be useful for your problem:\nval initialList = listOf(1,2,3,4)\n\nsuspend fun getFinalList(): List<Int> {\n val newList = initialList.map {\n change1(it)\n }\n // wait for change1 to finish\n val finalList = newList.map {\n change2(it)\n }\n // wait for change2 to finish\n return finalList.map {\n change3(it)\n }\n}\n\nsuspend fun change1(item: Int): Int = item + 1\nsuspend fun change2(item: Int): Int = item + 2\nsuspend fun change3(item: Int): Int = item + 3\n\n// usage\n\nGlobalScope.launch {\n val finalList = getFinalList()\n println(finalList)\n}\n\n" ]
[ 1 ]
[]
[]
[ "android", "kotlin", "kotlin_coroutines" ]
stackoverflow_0074666274_android_kotlin_kotlin_coroutines.txt
Q: How do you loop through api with list of parameters and store resulting calls in one dataframe I'm trying to loop a list of match ids (LMID5) as parameters for api calls. I think I have the looping the API calls correct as it prints the urls but I'm struggling to store the results every time in the same dataframe. The results of the API come through in JSON. Which I then normalise into a DF. When just using one parameter to call api this is how I code it and create a df. responsematchDetails = requests.get(url = matchDetails) dfLM = pd.json_normalize(responseleagueMatches.json()['data']) The issue is when trying to loop through a list of parameters and trying to store in one df. The below code is what I have wrote to try loop many calls to API using parameters from a list, but I'm struggling to store the data each time. for i in list(LMID5): url = 'https://api.football-data-api.com/match?key=&match_id=' + str(i) rm = requests.get(url) print(url) for match in pd.json_normalize(rm.json()["data"]): dfMatchDetails = dfMatchDetails.append({[match] }, ignore_index=True) A: Can you try this: dfMatchDetails=pd.DataFrame() for i in list(LMID5): url = 'https://api.football-data-api.com/match?key=&match_id=' + str(i) rm = requests.get(url) print(url) dfMatchDetails=pd.concat([dfMatchDetails,pd.json_normalize(rm.json()['data'])])
How do you loop through api with list of parameters and store resulting calls in one dataframe
I'm trying to loop a list of match ids (LMID5) as parameters for api calls. I think I have the looping the API calls correct as it prints the urls but I'm struggling to store the results every time in the same dataframe. The results of the API come through in JSON. Which I then normalise into a DF. When just using one parameter to call api this is how I code it and create a df. responsematchDetails = requests.get(url = matchDetails) dfLM = pd.json_normalize(responseleagueMatches.json()['data']) The issue is when trying to loop through a list of parameters and trying to store in one df. The below code is what I have wrote to try loop many calls to API using parameters from a list, but I'm struggling to store the data each time. for i in list(LMID5): url = 'https://api.football-data-api.com/match?key=&match_id=' + str(i) rm = requests.get(url) print(url) for match in pd.json_normalize(rm.json()["data"]): dfMatchDetails = dfMatchDetails.append({[match] }, ignore_index=True)
[ "Can you try this:\ndfMatchDetails=pd.DataFrame()\nfor i in list(LMID5):\n url = 'https://api.football-data-api.com/match?key=&match_id=' + str(i)\n rm = requests.get(url)\n print(url)\n dfMatchDetails=pd.concat([dfMatchDetails,pd.json_normalize(rm.json()['data'])])\n\n" ]
[ 1 ]
[]
[]
[ "api", "loops", "pandas", "python", "python_requests" ]
stackoverflow_0074667638_api_loops_pandas_python_python_requests.txt
Q: Is there solution to fix Loading failed for the I have this issue after the deployment of my ReactJS application. It works well on my localhost. The case: The problem only affect the routes with dynamic pages. First attempt of render, it shows ChunkFailedErr. I found React.lazy can cause this problem, so I changed the components not using React.lazy anymore. After go to the domain, it works well until I refresh the page Here is the image of the error after refreshing the page. this is the screenshot of console error Please kindly help me. App.js import { BrowserRouter, Route, Switch } from 'react-router-dom' import Login from './views/pages/login/Login' import Register from './views/pages/register/Register' import NotFound from './views/pages/page404/Page404' import InternalError from './views/pages/page500/Page500' import DefaultLayout from './layout/DefaultLayout' import './scss/style.scss' class App extends Component { render() { return ( <BrowserRouter> <Switch> <Route exact path="/login" name="Login Page" render={(props) => <Login {...props} />} /> <Route exact path="/register" name="Register Page" render={(props) => <Register {...props} />} /> <Route exact path="/404" name="Page 404" render={(props) => <NotFound {...props} />} /> <Route exact path="/500" name="Page 500" render={(props) => <InternalError {...props} />} /> <Route path="/" name="Home" render={(props) => <DefaultLayout {...props} />} /> </Switch> </BrowserRouter> ) } } export default App DefaultLayout.js import { AppContent, AppSidebar, AppHeader } from '../components/index' const DefaultLayout = () => { return ( <div> <AppSidebar /> <div className="wrapper d-flex flex-column min-vh-100 bg-light"> <AppHeader /> <div className="body flex-grow-1 px-3"> <AppContent /> </div> </div> </div> ) } export default DefaultLayout AppContent.js import { Redirect, Route, Switch } from 'react-router-dom' import { CContainer } from '@coreui/react' // routes config import routes from '../routes' const AppContent = () => { return ( <CContainer lg> <Switch> {routes.map((route, idx) => { return ( route.component && ( <Route key={idx} path={route.path} exact={route.exact} name={route.name} render={(props) => ( <> <route.component {...props} /> </> )} /> ) ) })} <Redirect from="/" to="/orders/list-order" /> </Switch> </CContainer> ) } export default React.memo(AppContent) routes.js import StatusOrder from './views/order-management/status-order/StatusOrder' import HistoryOrder from './views/order-management/history-order/HistoryOrder' import MonthlyRecap from './views/financing/MonthlyRecap' import RatingOverview from './views/rating-feedback/RatingOverview' const routes = [ { path: '/', exact: true, name: 'Home' }, { path: '/orders/list-order', name: 'List Order', component: ListOrder }, { path: '/orders/status-order', name: 'Status Order', component: StatusOrder }, { path: '/orders/history-order', name: 'History Order', component: HistoryOrder }, { path: '/financing/monthly-recap', name: 'Monthly Report', component: MonthlyRecap }, { path: '/feedback/rating-overview', name: 'Rating Overview', component: RatingOverview }, ] export default routes package.json { "name": "@coreui/coreui-free-react-admin-template", "version": "4.1.1", "description": "CoreUI Free React Admin Template", "homepage": ".", "bugs": { "url": "https://github.com/coreui/coreui-free-react-admin-template/issues" }, "repository": { "type": "git", "url": "[email protected]:coreui/coreui-free-react-admin-template.git" }, "license": "MIT", "author": "The CoreUI Team (https://github.com/orgs/coreui/people)", "scripts": { "build": "react-scripts build", "build:n17": "react-scripts --openssl-legacy-provider build", "changelog": "auto-changelog --starting-version 4.1.0 --commit-limit false --hide-credit", "eject": "react-scripts eject", "lint": "eslint \"src/**/*.js\"", "start": "react-scripts start", "start:n17": "react-scripts --openssl-legacy-provider start", "test": "react-scripts test", "test:cov": "npm test -- --coverage --watchAll=false", "test:debug": "react-scripts --inspect-brk test --runInBand" }, "config": { "coreui_library_short_version": "4.1" }, "dependencies": { "@coreui/chartjs": "^3.0.0", "@coreui/coreui": "^4.1.0", "@coreui/icons": "^2.1.0", "@coreui/icons-react": "^2.0.0", "@coreui/react": "^4.1.0", "@coreui/react-chartjs": "^2.0.0", "@coreui/utils": "^1.3.1", "@reduxjs/toolkit": "^1.8.1", "@wojtekmaj/enzyme-adapter-react-17": "^0.6.5", "chart.js": "^3.6.0", "classnames": "^2.3.1", "core-js": "^3.19.1", "enzyme": "^3.11.0", "prop-types": "^15.7.2", "react": "^17.0.2", "react-app-polyfill": "^2.0.0", "react-dom": "^17.0.2", "react-redux": "^7.2.8", "react-router-dom": "^5.3.2", "redux": "^4.1.2", "redux-thunk": "^2.4.1", "simplebar-react": "^2.3.6" }, "devDependencies": { "auto-changelog": "~2.3.0", "eslint": "^7.32.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-prettier": "^4.0.0", "prettier": "2.5.0", "react-scripts": "^4.0.3", "sass": "^1.43.5" }, "engines": { "node": ">=10", "npm": ">=6" } } A: Try replacing on package.js this "homepage": ".", for "homepage": "YOUR DOMAIN", then do npm run build and tell how it goes A: for me i used "/" instead of "." in the homepage property of package.json and this worked.i think because the homepage is the same as the url landing page and its the relative path.
Is there solution to fix Loading failed for the
I have this issue after the deployment of my ReactJS application. It works well on my localhost. The case: The problem only affect the routes with dynamic pages. First attempt of render, it shows ChunkFailedErr. I found React.lazy can cause this problem, so I changed the components not using React.lazy anymore. After go to the domain, it works well until I refresh the page Here is the image of the error after refreshing the page. this is the screenshot of console error Please kindly help me. App.js import { BrowserRouter, Route, Switch } from 'react-router-dom' import Login from './views/pages/login/Login' import Register from './views/pages/register/Register' import NotFound from './views/pages/page404/Page404' import InternalError from './views/pages/page500/Page500' import DefaultLayout from './layout/DefaultLayout' import './scss/style.scss' class App extends Component { render() { return ( <BrowserRouter> <Switch> <Route exact path="/login" name="Login Page" render={(props) => <Login {...props} />} /> <Route exact path="/register" name="Register Page" render={(props) => <Register {...props} />} /> <Route exact path="/404" name="Page 404" render={(props) => <NotFound {...props} />} /> <Route exact path="/500" name="Page 500" render={(props) => <InternalError {...props} />} /> <Route path="/" name="Home" render={(props) => <DefaultLayout {...props} />} /> </Switch> </BrowserRouter> ) } } export default App DefaultLayout.js import { AppContent, AppSidebar, AppHeader } from '../components/index' const DefaultLayout = () => { return ( <div> <AppSidebar /> <div className="wrapper d-flex flex-column min-vh-100 bg-light"> <AppHeader /> <div className="body flex-grow-1 px-3"> <AppContent /> </div> </div> </div> ) } export default DefaultLayout AppContent.js import { Redirect, Route, Switch } from 'react-router-dom' import { CContainer } from '@coreui/react' // routes config import routes from '../routes' const AppContent = () => { return ( <CContainer lg> <Switch> {routes.map((route, idx) => { return ( route.component && ( <Route key={idx} path={route.path} exact={route.exact} name={route.name} render={(props) => ( <> <route.component {...props} /> </> )} /> ) ) })} <Redirect from="/" to="/orders/list-order" /> </Switch> </CContainer> ) } export default React.memo(AppContent) routes.js import StatusOrder from './views/order-management/status-order/StatusOrder' import HistoryOrder from './views/order-management/history-order/HistoryOrder' import MonthlyRecap from './views/financing/MonthlyRecap' import RatingOverview from './views/rating-feedback/RatingOverview' const routes = [ { path: '/', exact: true, name: 'Home' }, { path: '/orders/list-order', name: 'List Order', component: ListOrder }, { path: '/orders/status-order', name: 'Status Order', component: StatusOrder }, { path: '/orders/history-order', name: 'History Order', component: HistoryOrder }, { path: '/financing/monthly-recap', name: 'Monthly Report', component: MonthlyRecap }, { path: '/feedback/rating-overview', name: 'Rating Overview', component: RatingOverview }, ] export default routes package.json { "name": "@coreui/coreui-free-react-admin-template", "version": "4.1.1", "description": "CoreUI Free React Admin Template", "homepage": ".", "bugs": { "url": "https://github.com/coreui/coreui-free-react-admin-template/issues" }, "repository": { "type": "git", "url": "[email protected]:coreui/coreui-free-react-admin-template.git" }, "license": "MIT", "author": "The CoreUI Team (https://github.com/orgs/coreui/people)", "scripts": { "build": "react-scripts build", "build:n17": "react-scripts --openssl-legacy-provider build", "changelog": "auto-changelog --starting-version 4.1.0 --commit-limit false --hide-credit", "eject": "react-scripts eject", "lint": "eslint \"src/**/*.js\"", "start": "react-scripts start", "start:n17": "react-scripts --openssl-legacy-provider start", "test": "react-scripts test", "test:cov": "npm test -- --coverage --watchAll=false", "test:debug": "react-scripts --inspect-brk test --runInBand" }, "config": { "coreui_library_short_version": "4.1" }, "dependencies": { "@coreui/chartjs": "^3.0.0", "@coreui/coreui": "^4.1.0", "@coreui/icons": "^2.1.0", "@coreui/icons-react": "^2.0.0", "@coreui/react": "^4.1.0", "@coreui/react-chartjs": "^2.0.0", "@coreui/utils": "^1.3.1", "@reduxjs/toolkit": "^1.8.1", "@wojtekmaj/enzyme-adapter-react-17": "^0.6.5", "chart.js": "^3.6.0", "classnames": "^2.3.1", "core-js": "^3.19.1", "enzyme": "^3.11.0", "prop-types": "^15.7.2", "react": "^17.0.2", "react-app-polyfill": "^2.0.0", "react-dom": "^17.0.2", "react-redux": "^7.2.8", "react-router-dom": "^5.3.2", "redux": "^4.1.2", "redux-thunk": "^2.4.1", "simplebar-react": "^2.3.6" }, "devDependencies": { "auto-changelog": "~2.3.0", "eslint": "^7.32.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-prettier": "^4.0.0", "prettier": "2.5.0", "react-scripts": "^4.0.3", "sass": "^1.43.5" }, "engines": { "node": ">=10", "npm": ">=6" } }
[ "Try replacing on package.js\nthis \"homepage\": \".\",\nfor \"homepage\": \"YOUR DOMAIN\",\nthen do npm run build\nand tell how it goes\n", "for me i used \"/\" instead of \".\" in the homepage property of package.json and this worked.i think because the homepage is the same as the url landing page and its the relative path.\n" ]
[ 0, 0 ]
[]
[]
[ "javascript", "reactjs" ]
stackoverflow_0072415322_javascript_reactjs.txt
Q: Copy all files with a certain extension from all subdirectories and preserving structure of subdirectories How can I copy specific files from all directories and subdirectories to a new directory while preserving the original subdirectorie structure? This answer: find . -name \*.xls -exec cp {} newDir \; solves to copy all xls files from all subdirectories in the same directory newDir. That is not what I want. If an xls file is in: /s1/s2/ then it sould be copied to newDir/s1/s2. copies all files from all folders and subfolders to a new folder, but the original file structure is lost. Everything is copied to a same new folder on top of each other. A: You can try: find . -type f -name '*.xls' -exec sh -c \ 'd="newDir/${1%/*}"; mkdir -p "$d" && cp "$1" "$d"' sh {} \; This applies the d="newDir/${1%/*}"; mkdir -p "$d" && cp "$1" "$d" shell script to all xls files, that is, first create the target directory and copy the file at destination. If you have a lot of files and performance issues you can try to optimize a bit with: find . -type f -name '*.xls' -exec sh -c \ 'for f in "$@"; do d="newDir/${f%/*}"; mkdir -p "$d" && cp "$f" "$d"; done' sh {} + This second version processes the files by batches and thus spawns less shells. A: This should do: # Ensure that newDir exists and is empty. Omit this step if you # don't want it. [[ -d newDir ]] && rm -r newDir && mkdir newDir # Copy the xls files. rsync -a --include='**/*.xls' --include='*/' --exclude='*' . newDir The trick here is the combination of include and exclude. By default, rsync copies everything below its source directory (. in your case). We change this by excluding everything, but also including the xls files. In your example, newDir is itself a subdirectory of your working directory and hence part of the directory tree searched for copying. I would rethink this decision. NOTE: This would not only also copy directories whrere the name ends in .xls, bur also recreated the whole directory structure of your source tree (even if there are no xls files in it), and populate it only with xls files. A: Thanks for the solutions. Meanwhile I found also: find . -name '*.xls' | cpio -pdm newDir
Copy all files with a certain extension from all subdirectories and preserving structure of subdirectories
How can I copy specific files from all directories and subdirectories to a new directory while preserving the original subdirectorie structure? This answer: find . -name \*.xls -exec cp {} newDir \; solves to copy all xls files from all subdirectories in the same directory newDir. That is not what I want. If an xls file is in: /s1/s2/ then it sould be copied to newDir/s1/s2. copies all files from all folders and subfolders to a new folder, but the original file structure is lost. Everything is copied to a same new folder on top of each other.
[ "You can try:\nfind . -type f -name '*.xls' -exec sh -c \\\n'd=\"newDir/${1%/*}\"; mkdir -p \"$d\" && cp \"$1\" \"$d\"' sh {} \\;\n\nThis applies the d=\"newDir/${1%/*}\"; mkdir -p \"$d\" && cp \"$1\" \"$d\" shell script to all xls files, that is, first create the target directory and copy the file at destination.\nIf you have a lot of files and performance issues you can try to optimize a bit with:\nfind . -type f -name '*.xls' -exec sh -c \\\n'for f in \"$@\"; do d=\"newDir/${f%/*}\"; mkdir -p \"$d\" && cp \"$f\" \"$d\"; done' sh {} +\n\nThis second version processes the files by batches and thus spawns less shells.\n", "This should do:\n# Ensure that newDir exists and is empty. Omit this step if you\n# don't want it.\n[[ -d newDir ]] && rm -r newDir && mkdir newDir\n\n# Copy the xls files.\nrsync -a --include='**/*.xls' --include='*/' --exclude='*' . newDir\n\nThe trick here is the combination of include and exclude. By default, rsync copies everything below its source directory (. in your case). We change this by excluding everything, but also including the xls files.\nIn your example, newDir is itself a subdirectory of your working directory and hence part of the directory tree searched for copying. I would rethink this decision.\nNOTE: This would not only also copy directories whrere the name ends in .xls, bur also recreated the whole directory structure of your source tree (even if there are no xls files in it), and populate it only with xls files.\n", "Thanks for the solutions.\nMeanwhile I found also:\nfind . -name '*.xls' | cpio -pdm newDir\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "bash", "cp", "unix" ]
stackoverflow_0074625117_bash_cp_unix.txt
Q: Do the views need to be in specific folders in order for an ASP.NET MVC project to work properly? For an ASP.NET MVC 5 project, is there some kind of priority ranking between views? And do they need to be in separate folders within the project? A: Although I am answering a year later but I should say "Yes there is!" to your first question. The locations are listed at a string list called ViewLocationFormats in the RazorViewEngin. You can even change the list by inheriting the RazorViewEngine, take a look at here or even changing the existing one So the answer to your second question is that they should be anywhere as long as the containing folder listed in the view locations of the used RazorViewEngine.
Do the views need to be in specific folders in order for an ASP.NET MVC project to work properly?
For an ASP.NET MVC 5 project, is there some kind of priority ranking between views? And do they need to be in separate folders within the project?
[ "Although I am answering a year later but I should say \"Yes there is!\" to your first question. The locations are listed at a string list called ViewLocationFormats in the RazorViewEngin. You can even change the list by inheriting the RazorViewEngine, take a look at here or even changing the existing one\nSo the answer to your second question is that they should be anywhere as long as the containing folder listed in the view locations of the used RazorViewEngine.\n" ]
[ 0 ]
[]
[]
[ "asp.net_mvc", "asp.net_mvc_views", "model_view_controller" ]
stackoverflow_0069313902_asp.net_mvc_asp.net_mvc_views_model_view_controller.txt
Q: solidity program compiler issue pragma solidity ^0.8.17; contract Greeter { string greeting; function Greeter(string _greeting) public{ greeting=_greeting; } function greet() constant returns (string){ return greeting; } } ERROR ParserError: Expected '{' but got 'constant' --> project:/contracts/greeter.sol:7:22: | 7 | function greet() constant returns (string){ i am compiling solidity program but there is issue when compiling A: In the new compiler versions (0.4.21 above) the constructor and constant keyword deleted. Now, you must use for: constructor: the following statement for: constructor([parameters]) { // your logic } constant: it depends on function accessibility that you give, in this case will be external. It allows to print the string that you initialized. You must change your original smart in this way: // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; contract Greeter { string greeting; constructor(string memory _greeting) { greeting = _greeting; } function greet() external view returns(string memory){ return greeting; } }
solidity program compiler issue
pragma solidity ^0.8.17; contract Greeter { string greeting; function Greeter(string _greeting) public{ greeting=_greeting; } function greet() constant returns (string){ return greeting; } } ERROR ParserError: Expected '{' but got 'constant' --> project:/contracts/greeter.sol:7:22: | 7 | function greet() constant returns (string){ i am compiling solidity program but there is issue when compiling
[ "In the new compiler versions (0.4.21 above) the constructor and constant keyword deleted. Now, you must use for:\n\nconstructor: the following statement for:\nconstructor([parameters]) { // your logic }\n\nconstant: it depends on function accessibility that you give, in this case will be external. It allows to print the string that you initialized.\n\n\nYou must change your original smart in this way:\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\ncontract Greeter {\n string greeting;\n\n constructor(string memory _greeting) {\n greeting = _greeting;\n }\n\n function greet() external view returns(string memory){\n return greeting;\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "solidity" ]
stackoverflow_0074665172_solidity.txt
Q: How can I avoid hardcoding URLs in a RESTful client/server web app with deep linking? I'm working on a SPA which is a client to a RESTful web service. Both the client and server are part of the same project, i.e. I can modify the code for both sides freely. I've been reading up on RESTful API design to try and make sure I'm doing everything the "right" way. One of my takeaways from reading is that a RESTful service should publish hyperlinks so clients can access more information, and that clients should have no hardcoded information about service URLs other than an entry point. Using hyperlinks allows the client to be more flexible in the event that the server makes URL changes. However I can't figure out how this architecture is supposed to work when users are allowed to link to a specific client state. For example: One of the views is a list of books available for purchase. The client sets the browser's location to /books/ to identify this page, and the backend data comes from an endpoint /api/books/, retrieved from an API entry point that publishes that URL. The service URL responds with a JSON document like this: [ {"title": "The Great Gatsby", "id": 24, "url": "http://localhost/api/books/24/"}, < and so on > ] The client uses this to generate readable links that, when clicked, go to a detailed view of a single book. The browser's location is updated to /books/the-great-gatsby/24/ so users can bookmark this view and link to it. How does the client handle when users click this link directly?? How would it know where to get the information for this book without having a hardcoded URL? The best I could come up with is the following sequence of requests: GET /api/ - view which services are available (to find there are books at all) OPTIONS /api/books/ - view a description of what operations are available on books (so e.g. it can make sure it can find books by ID) GET /api/books/?id=24 - See if it can find a book with an ID that matches the ID in the browser's location. GET /api/books/24/ - Actually retrieve the data Anything shorter would imply that the client has hardcoded knowledge of the API's URLs. However, from a web app point of view, this seems grossly inefficient. Is there some trick I'm missing? Is there a way for the client to "know" how to get more detail about book ID 24 without somehow having the /api/books/24/ endpoint hardcoded? A: if you request this resource /books/the-great-gatsby/24/ from the server, the server should respond with something specific to that URL. Currently, you are probably analyzing window.location which is a bit of a hack. If /books/the-great-gatsby/24/ is static content, then you have very little choice: You store the client's current state explicitly somewhere (i.e. /books?data=api/books/24 or implicitly /books/the-great-gatsby/24/ which then leads to the client having to know how to translate that to an API resource. The RESTful way is to use hypertext to indicate where any related resources (i.e. your data to render is) are which makes a tag an appropriate choice. i.e. ditch the static content, and render /books/the-great-gatsby/24/ with a <head><link href="api/books/24" ....></link></head> However, if you always retain control of your client side and don't plan to publish the API to third parties, you might be more productive ditching RESTful and just go RESTish. A: The Resource URL Locator pattern In this answer: user is (the human interacting with) the internet browser, client is the Single Page Application (SPA) and server is the REST API. Deep linking is a convenience of the client to the user; the client itself may still not have knowledge of the server's URLs, so the client must start at the root URL of the server. The client uses content negotiation to indicate which media type it needs. The first request of the client to the server when bootstrapping itself could be as follows: GET /?id=24 HTTP/1.1 Accept: application/vnd.company.book+json Optionally, the client uses the id querystring parameter as a hint to the server to select the specific resource it is looking for. When the server has determined which resource the client is looking for it can respond with a redirect to the canonical URL of the resource: HTTP/1.1 303 See Other Location: https://example.com/api/books/24 The client can now follow the redirect and get the resource it needs to bootstrap the application. A: @Evert's comment got me thinking. Isn't a deep link or a bookmark just a continuation of application state from a previous point in time? It doesn't really matter how much time has passed after the previous application state transition. You could say that the 'current' application state in HATEOAS is the last followed link. The current state must be stored somewhere and it might as well be stored in the application URL. Starting the application at a deep link indicates to the application that it should rebuild the application state by requesting the resource indicated by the application URL. If the resource is no longer available or has moved, the server should respond with a 404 Not Found or 301 Moved Permanently respectively. With this approach the server is still in control of the URLs. The application follows the hypermedia links in the server's responses and doesn't generate URLs itself.
How can I avoid hardcoding URLs in a RESTful client/server web app with deep linking?
I'm working on a SPA which is a client to a RESTful web service. Both the client and server are part of the same project, i.e. I can modify the code for both sides freely. I've been reading up on RESTful API design to try and make sure I'm doing everything the "right" way. One of my takeaways from reading is that a RESTful service should publish hyperlinks so clients can access more information, and that clients should have no hardcoded information about service URLs other than an entry point. Using hyperlinks allows the client to be more flexible in the event that the server makes URL changes. However I can't figure out how this architecture is supposed to work when users are allowed to link to a specific client state. For example: One of the views is a list of books available for purchase. The client sets the browser's location to /books/ to identify this page, and the backend data comes from an endpoint /api/books/, retrieved from an API entry point that publishes that URL. The service URL responds with a JSON document like this: [ {"title": "The Great Gatsby", "id": 24, "url": "http://localhost/api/books/24/"}, < and so on > ] The client uses this to generate readable links that, when clicked, go to a detailed view of a single book. The browser's location is updated to /books/the-great-gatsby/24/ so users can bookmark this view and link to it. How does the client handle when users click this link directly?? How would it know where to get the information for this book without having a hardcoded URL? The best I could come up with is the following sequence of requests: GET /api/ - view which services are available (to find there are books at all) OPTIONS /api/books/ - view a description of what operations are available on books (so e.g. it can make sure it can find books by ID) GET /api/books/?id=24 - See if it can find a book with an ID that matches the ID in the browser's location. GET /api/books/24/ - Actually retrieve the data Anything shorter would imply that the client has hardcoded knowledge of the API's URLs. However, from a web app point of view, this seems grossly inefficient. Is there some trick I'm missing? Is there a way for the client to "know" how to get more detail about book ID 24 without somehow having the /api/books/24/ endpoint hardcoded?
[ "if you request this resource /books/the-great-gatsby/24/ from the server, the server should respond with something specific to that URL. Currently, you are probably analyzing window.location which is a bit of a hack.\nIf /books/the-great-gatsby/24/ is static content, then you have very little choice: You store the client's current state explicitly somewhere (i.e. /books?data=api/books/24 or implicitly /books/the-great-gatsby/24/ which then leads to the client having to know how to translate that to an API resource.\nThe RESTful way is to use hypertext to indicate where any related resources (i.e. your data to render is) are which makes a tag an appropriate choice.\ni.e. ditch the static content, and render /books/the-great-gatsby/24/ with a <head><link href=\"api/books/24\" ....></link></head>\nHowever, if you always retain control of your client side and don't plan to publish the API to third parties, you might be more productive ditching RESTful and just go RESTish. \n", "The Resource URL Locator pattern\nIn this answer: user is (the human interacting with) the internet browser, client is the Single Page Application (SPA) and server is the REST API.\nDeep linking is a convenience of the client to the user; the client itself may still not have knowledge of the server's URLs, so the client must start at the root URL of the server. The client uses content negotiation to indicate which media type it needs. The first request of the client to the server when bootstrapping itself could be as follows:\nGET /?id=24 HTTP/1.1\nAccept: application/vnd.company.book+json\n\nOptionally, the client uses the id querystring parameter as a hint to the server to select the specific resource it is looking for.\nWhen the server has determined which resource the client is looking for it can respond with a redirect to the canonical URL of the resource:\nHTTP/1.1 303 See Other\nLocation: https://example.com/api/books/24\n\nThe client can now follow the redirect and get the resource it needs to bootstrap the application.\n", "@Evert's comment got me thinking. Isn't a deep link or a bookmark just a continuation of application state from a previous point in time? It doesn't really matter how much time has passed after the previous application state transition.\nYou could say that the 'current' application state in HATEOAS is the last followed link. The current state must be stored somewhere and it might as well be stored in the application URL.\nStarting the application at a deep link indicates to the application that it should rebuild the application state by requesting the resource indicated by the application URL. If the resource is no longer available or has moved, the server should respond with a 404 Not Found or 301 Moved Permanently respectively.\nWith this approach the server is still in control of the URLs. The application follows the hypermedia links in the server's responses and doesn't generate URLs itself.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "api_design", "deep_linking", "rest", "restful_url", "single_page_application" ]
stackoverflow_0044011528_api_design_deep_linking_rest_restful_url_single_page_application.txt
Q: How can I prevent proxying if index file exists NGINX? I have a NGINX server with proxy to apache. Wp-Rocket making all cache job, and store cache files to wp-content/cache/wp-rocket/mysite.com/ Each index file saved as index-https.html The idea is to prevent proxying if the index file already exists. Each time I refresh the page, I see GET requests in Apache logs. Can you please point me what I'm doing wrong? root /var/www/html; location ~ \.php$ { error_page 420 = @apache; return 420; } location / { index index.html index-https.html; error_page 420 = @apache; error_page 405 = @apache; if ($request_method = POST ) { return 420; } if ( $query_string ){ return 420; } if ( $http_cookie ~ "wordpress_logged_in" ){ return 420; } expires 365d; add_header Cache-Control "public, no-transform"; gzip_static on; try_files $uri wp-content/cache/wp-rocket/mysite.com/$uri/ @apache; } location @apache { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_hide_header Upgrade; } Tried to specify index files (index-https.html) but no luck also tried: try_files $uri wp-content/cache/wp-rocket/mysite.com/$uri/ @apache; try_files $uri /wp-content/cache/wp-rocket/mysite.com/$uri/ @apache; try_files $uri /wp-content/cache/wp-rocket/mysite.com/$uri @apache; try_files $uri /wp-content/cache/wp-rocket/mysite.com/$uri/index-https.html @apache; A: The URI /resumes/marina-7/ should point to the file /var/www/html/wp-content/cache/wp-rocket/mysite.com/resumes/marina-7/index-https.html The value of $uri is exactly /resumes/marina-7/, so take care you do not insert extra /s before or after the variable. Use: try_files $uri /wp-content/cache/wp-rocket/mysite.com${uri}index-https.html @apache; Notice that the term must begin with a / and that braces are used to delimit the variable name.
How can I prevent proxying if index file exists NGINX?
I have a NGINX server with proxy to apache. Wp-Rocket making all cache job, and store cache files to wp-content/cache/wp-rocket/mysite.com/ Each index file saved as index-https.html The idea is to prevent proxying if the index file already exists. Each time I refresh the page, I see GET requests in Apache logs. Can you please point me what I'm doing wrong? root /var/www/html; location ~ \.php$ { error_page 420 = @apache; return 420; } location / { index index.html index-https.html; error_page 420 = @apache; error_page 405 = @apache; if ($request_method = POST ) { return 420; } if ( $query_string ){ return 420; } if ( $http_cookie ~ "wordpress_logged_in" ){ return 420; } expires 365d; add_header Cache-Control "public, no-transform"; gzip_static on; try_files $uri wp-content/cache/wp-rocket/mysite.com/$uri/ @apache; } location @apache { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_hide_header Upgrade; } Tried to specify index files (index-https.html) but no luck also tried: try_files $uri wp-content/cache/wp-rocket/mysite.com/$uri/ @apache; try_files $uri /wp-content/cache/wp-rocket/mysite.com/$uri/ @apache; try_files $uri /wp-content/cache/wp-rocket/mysite.com/$uri @apache; try_files $uri /wp-content/cache/wp-rocket/mysite.com/$uri/index-https.html @apache;
[ "The URI /resumes/marina-7/ should point to the file /var/www/html/wp-content/cache/wp-rocket/mysite.com/resumes/marina-7/index-https.html\nThe value of $uri is exactly /resumes/marina-7/, so take care you do not insert extra /s before or after the variable.\nUse:\ntry_files $uri /wp-content/cache/wp-rocket/mysite.com${uri}index-https.html @apache;\n\nNotice that the term must begin with a / and that braces are used to delimit the variable name.\n" ]
[ 0 ]
[]
[]
[ "apache", "nginx", "proxy", "wordpress" ]
stackoverflow_0074659080_apache_nginx_proxy_wordpress.txt
Q: Why is the text inside the button not targeted? Im just curious why the linethrough worked on everything even the textbox placeholders but not with the text inside all the buttons, with css or not. `` function strike(){ document.getElementById("root").style.textDecoration= "line-through"; } function unstrike(){ document.getElementById("root").style.textDecoration= null; } function App() { return ( <div className="container"> <Form state={userIsRegistered} /> <button onClick={strike}>strike</button> <button onClick={unstrike}>unstrike</button> </div> ); } `` Even if i targeted the root. What should I do to include it when i click on the strike button? A: The text inside of a button does not inherit its outer elements properties. This applies to font also. Line through is a "unusual" property, so even if you check developer options (inspect element) the user agent stylesheet does not have a line-through property, but still the text appears without line through, the reason is: there is highest specification coming from browser UA that buttons will have only those properties, which are defined in the default user agent stylesheet. So, you need to set text decoration property to line through for button, separately A: document.getElementById("root") //-> it get the root element of React So if you set the style.textDecoration for this element, every things inside it changed. But the button with out a HTML Formatting Elements will not inherit this style. function App() { const strike = () => { document.getElementById("root").style.textDecoration = "line-through"; }; const unstrike = () => { document.getElementById("root").style.textDecoration = null; }; return ( <div className="container"> <Form state={userIsRegistered} /> <button onClick={strike}> <p>strike</p> </button> <button onClick={unstrike}> <p>unstrike</p> </button> </div> ); }
Why is the text inside the button not targeted?
Im just curious why the linethrough worked on everything even the textbox placeholders but not with the text inside all the buttons, with css or not. `` function strike(){ document.getElementById("root").style.textDecoration= "line-through"; } function unstrike(){ document.getElementById("root").style.textDecoration= null; } function App() { return ( <div className="container"> <Form state={userIsRegistered} /> <button onClick={strike}>strike</button> <button onClick={unstrike}>unstrike</button> </div> ); } `` Even if i targeted the root. What should I do to include it when i click on the strike button?
[ "The text inside of a button does not inherit its outer elements properties. This applies to font also.\nLine through is a \"unusual\" property, so even if you check developer options (inspect element) the user agent stylesheet does not have a line-through property, but still the text appears without line through, the reason is: there is highest specification coming from browser UA that buttons will have only those properties, which are defined in the default user agent stylesheet.\nSo, you need to set text decoration property to line through for button, separately\n", "document.getElementById(\"root\") //-> it get the root element of React\n\nSo if you set the style.textDecoration for this element, every things inside it changed. But the button with out a HTML Formatting Elements will not inherit this style.\nfunction App() {\n const strike = () => {\n document.getElementById(\"root\").style.textDecoration = \"line-through\";\n };\n const unstrike = () => {\n document.getElementById(\"root\").style.textDecoration = null;\n };\n return (\n <div className=\"container\">\n <Form state={userIsRegistered} />\n <button onClick={strike}>\n <p>strike</p>\n </button>\n <button onClick={unstrike}>\n <p>unstrike</p>\n </button>\n </div>\n );\n}\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "css", "html", "javascript", "reactjs" ]
stackoverflow_0074667749_css_html_javascript_reactjs.txt
Q: How can I change recyclerview item background color permanent and transact new Fragment? I want to change the color of recyclervView item that I clicked(so user can understand that already checked the detail of the item) and go detail fragment page. However this background color change must be permanent should I store it in livedata of recycler view items. I share my codes at the end I am new to android programming so please explain your solution for beginner and my english level is not good. Thanks for everything. class AdapterRecycler() : RecyclerView.Adapter<AdapterRecycler.ViewHolder>() class ViewHolder(view: View, listener: onItemClickListener) : RecyclerView.ViewHolder(view) { val name: TextView = view.findViewById(R.id.gameId) val score: TextView = view.findViewById(R.id.scoreId) val genre: TextView = view.findViewById(R.id.genres) val layout1: RelativeLayout = view.findViewById(R.id.rowlayout) init { // Define click listener for the ViewHolder's View. //val textView : TextView = view.findViewById(R.id.gameId) itemView.setOnClickListener { layout1.setBackgroundColor(Color.rgb(224,224,224)) listener.onItemClick(adapterPosition) } } } // Create new views (invoked by the layout manager) override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder { // Create a new view, which defines the UI of the list item val view = LayoutInflater.from(viewGroup.context) .inflate(R.layout.text_row_item, viewGroup, false) return ViewHolder(view, listenerItems) } class Games : Fragment() { ... override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ... adapter.setOnItemClickListener(object : AdapterRecycler.onItemClickListener { override fun onItemClick(position: Int) { // Fragment transaction to detail page requireActivity().supportFragmentManager.beginTransaction() .replace(R.id.fragmentContainerView2, Details()).commit() } }) } Should I store a boolean value in here to save item checked status? data class Game(val name : String, val score : Int, val genres : Array<String>) I tried solution at my codes and I get transaction but not the color changes of item layout. A: I think it will be good if you'll update your Game model, after it became checked. Something like this: data class Game(.., var isChecked: Boolean = false) And inside your AdapterRecycler.onItemClickListener realization call ViewModel function to update isChecked value: fun onItemChecked(position: Int) { val item = TODO("get item by position from your live data") item.isChecked = !item.isChecked } In addition, you should override your ViewHolder to setup a background rely on your isCheked value (it will be the same as must be after ViewHolder notify calls): class ViewHolder(view: View, listener: onItemClickListener) : RecyclerView.ViewHolder(view) { ... fun bind(item: Game) { val backColor = if (item.isChecked) Color.GREEN else Color.BLUE layout1.setBackgroundColor(Color.rgb(224,224,224)) } } Call bind function from your AdapterRecycler.onBindViewHolder this way: override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(getItem(position), callback) } Don't forget to notify your adapter. A: Guys thanks to your replies I reviewed my code and got solution. Here is my edit at the code: override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { ... val color = if (_data[position].isChecked) Color.rgb(224,224,224) else Color.WHITE viewHolder.layout1.setBackgroundColor(color) ... } That way I change the color of recyclerview item color since I change the fragments make the viewmodel at activity based and used it shared viewModel between fragments class MainActivity : AppCompatActivity() { private lateinit var viewModel: GamesViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) ... viewModel = ViewModelProvider(this)[GamesViewModel::class.java] ... } Then I added the boolean variable to my model. data class Game(val name : String, val score : Int, val genres : Array<String>, var isChecked : Boolean = false) Then I change the liveData's attribute of isChecked at the click listener. override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) adapter.setOnItemClickListener(object : AdapterRecycler.onItemClickListener { override fun onItemClick(position: Int) { viewModel= ViewModelProvider(requireActivity()).get(GamesViewModel::class.java) val item = viewModel.liveData.value!!.get(position) item.isChecked = true // toGo next fragment requireActivity().supportFragmentManager.beginTransaction() .replace(R.id.fragmentContainerView2, Details()).commit() } }) Voilà we got the perfect result thanks for helping me, have a great day.
How can I change recyclerview item background color permanent and transact new Fragment?
I want to change the color of recyclervView item that I clicked(so user can understand that already checked the detail of the item) and go detail fragment page. However this background color change must be permanent should I store it in livedata of recycler view items. I share my codes at the end I am new to android programming so please explain your solution for beginner and my english level is not good. Thanks for everything. class AdapterRecycler() : RecyclerView.Adapter<AdapterRecycler.ViewHolder>() class ViewHolder(view: View, listener: onItemClickListener) : RecyclerView.ViewHolder(view) { val name: TextView = view.findViewById(R.id.gameId) val score: TextView = view.findViewById(R.id.scoreId) val genre: TextView = view.findViewById(R.id.genres) val layout1: RelativeLayout = view.findViewById(R.id.rowlayout) init { // Define click listener for the ViewHolder's View. //val textView : TextView = view.findViewById(R.id.gameId) itemView.setOnClickListener { layout1.setBackgroundColor(Color.rgb(224,224,224)) listener.onItemClick(adapterPosition) } } } // Create new views (invoked by the layout manager) override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder { // Create a new view, which defines the UI of the list item val view = LayoutInflater.from(viewGroup.context) .inflate(R.layout.text_row_item, viewGroup, false) return ViewHolder(view, listenerItems) } class Games : Fragment() { ... override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ... adapter.setOnItemClickListener(object : AdapterRecycler.onItemClickListener { override fun onItemClick(position: Int) { // Fragment transaction to detail page requireActivity().supportFragmentManager.beginTransaction() .replace(R.id.fragmentContainerView2, Details()).commit() } }) } Should I store a boolean value in here to save item checked status? data class Game(val name : String, val score : Int, val genres : Array<String>) I tried solution at my codes and I get transaction but not the color changes of item layout.
[ "I think it will be good if you'll update your Game model, after it became checked. Something like this:\ndata class Game(.., var isChecked: Boolean = false)\n\nAnd inside your AdapterRecycler.onItemClickListener realization call ViewModel function to update isChecked value:\nfun onItemChecked(position: Int) {\n val item = TODO(\"get item by position from your live data\")\n item.isChecked = !item.isChecked\n}\n\nIn addition, you should override your ViewHolder to setup a background rely on your isCheked value (it will be the same as must be after ViewHolder notify calls):\nclass ViewHolder(view: View, listener: onItemClickListener) : RecyclerView.ViewHolder(view) {\n\n ...\n\n fun bind(item: Game) {\n val backColor = if (item.isChecked) Color.GREEN else Color.BLUE\n layout1.setBackgroundColor(Color.rgb(224,224,224))\n }\n\n}\n\nCall bind function from your AdapterRecycler.onBindViewHolder this way:\noverride fun onBindViewHolder(holder: ViewHolder, position: Int) {\n holder.bind(getItem(position), callback)\n}\n\nDon't forget to notify your adapter.\n", "Guys thanks to your replies I reviewed my code and got solution.\nHere is my edit at the code:\n override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {\n\n ...\n val color = if (_data[position].isChecked) Color.rgb(224,224,224) else Color.WHITE\n viewHolder.layout1.setBackgroundColor(color)\n ...\n }\n\nThat way I change the color of recyclerview item color since I change the fragments make the viewmodel at activity based and used it shared viewModel between fragments\nclass MainActivity : AppCompatActivity() {\n\n private lateinit var viewModel: GamesViewModel\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n \n...\n \n viewModel = ViewModelProvider(this)[GamesViewModel::class.java]\n\n...\n}\n\nThen I added the boolean variable to my model.\ndata class Game(val name : String, val score : Int, val genres : Array<String>, var isChecked : Boolean = false)\n\n\nThen I change the liveData's attribute of isChecked at the click listener.\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n super.onViewCreated(view, savedInstanceState)\n\n adapter.setOnItemClickListener(object : AdapterRecycler.onItemClickListener {\n\n override fun onItemClick(position: Int) {\n\n viewModel= ViewModelProvider(requireActivity()).get(GamesViewModel::class.java)\n val item = viewModel.liveData.value!!.get(position)\n item.isChecked = true\n // toGo next fragment\n requireActivity().supportFragmentManager.beginTransaction()\n .replace(R.id.fragmentContainerView2, Details()).commit()\n }\n\n })\n\nVoilà we got the perfect result thanks for helping me, have a great day.\n" ]
[ 0, 0 ]
[]
[]
[ "android_recyclerview", "kotlin", "mvvm" ]
stackoverflow_0074663497_android_recyclerview_kotlin_mvvm.txt
Q: How can i move from one element to another when pressing a button Hi all I am a newby and I am trying to create a function that when I press a button for example the 'b' key focus will move from one button on the page to the next. I am able to set the focus on the first button of the page but when I press the 'b' key again focus stays on the first button. let btn = document.querySelector("button"); document.body.addEventListener("keypress", (e) => { if (e.key == "b") { e.preventDefault(); document.querySelector("button").focus(); } }); <button>Button 1</button><br> <button>Button 2</button><br> <button>Button 3</button><br> <button>Button 4</button><br> <button>Button 5</button><br> A: A quick way to achieve that is by setting a data-* attribute, let's call it data-is-focused to the currently focused button where the value will be 1 and then we set that to 0 once the button loses focus and based on that attribute, the data-is-focused attribute, we can easily tell which button is currently selected and we can easily move focus to the next one. The idea is simple: we select all the buttons and cache them in the JavaScript code so we can easily access them when needed. Each button will have an index based on its appearance in the document tree (first button will have the index 0, second button will be at the index 1 and so on). initially, all the button do not have the data-is-focused attribute which will be considered as if that attribute is set to 0. once "b" is pressed we make some checks: get the currently focused button by finding the index of the button that has the data-is-focused attribute set to 1. if no button is focused then we manually set the index to 0 so we focus the first button. Otherwise, if we find the currently focused button, we increment the index. if we reach the last button, the index equals the number of buttons - 1 (remember, indexes start from 0) then we simply set 0 to the index of the button to be focused. To illustrate, here's a live demo, that handles returning back to the first button once we reach the last one (as described above): Update: allow using shift key to move backwards const btns = Array.from(document.querySelectorAll("button")), /** * guess the index of the buitton to be focused based on the index of the currently focused button and whether we want to walk forwards or backwards. */ guessNextButtonIndex = (focusedBtnIndex, inReverseOrder) => { return inReverseOrder ? (focusedBtnIndex <= 0 ? btns.length - 1 : focusedBtnIndex - 1) : (focusedBtnIndex === -1 || focusedBtnIndex === btns.length - 1 ? 0 : focusedBtnIndex + 1); }; document.body.addEventListener("keydown", e => { // because we accept shift key, when you press shift + "b" the output will be "B" (uppercased) so we need to transform that to lower case. if (e.key.toLowerCase() === "b") { // get the index of the currently focused button based on the data-is-focused attribute. If no button is focused, -1 is returned. const idx = btns.findIndex(btn => btn.dataset.isFocused == 1), btnToFocus = btns[guessNextButtonIndex(idx, e.shiftKey)]; // set the data-is-focused of the last focused button to "0" idx !== -1 && (btns[idx].dataset.isFocused = 0); // set the data-is-focused of the button to be focused to "1" btnToFocus.dataset.isFocused = 1; // focus the button to be focused btnToFocus.focus(); } }); <button>Button 1</button><br> <button>Button 2</button><br> <button>Button 3</button><br> <button>Button 4</button><br> <button>Button 5</button><br> A: Your code is half-way there! You need to select all the buttons by using querySelectorAll, because using querySelector it will only return the first matching element, and then keep track of which button you are focusing each time you call the function. So with the edits it would look like this: let buttons = document.querySelectorAll('button'); let currentButton = 0; document.body.addEventListener('keypress', e => { if (e.key == 'b') { e.preventDefault(); currentButton++; // move to the next button in the list if (currentButton >= buttons.length) { currentButton = 0; // loop back to the first button if we reach the end of the list } buttons[currentButton].focus(); } }); A: const boxes = document.querySelectorAll('button'); var boxesLength = boxes.length; for (var i = 0; i < boxesLength; i++) { boxes[i].addEventListener('click', function (i) { var findnextbtn; if ((boxesLength - 1) == i) { removeStyle(); findnextbtn = boxes[0]; } else { removeStyle(); findnextbtn = boxes[i + 1]; } findnextbtn.setAttribute('style', 'background-color: yellow;'); }.bind(null, i)); } function removeStyle() { boxes.forEach(box => { box.setAttribute('style', 'background-color: none;'); }); } <button>Button 1</button><br> <button>Button 2</button><br> <button>Button 3</button><br> <button>Button 4</button><br> <button>Button 5</button><br> A: To move the focus from one button to the next when you press the 'b' key, you can use the document.querySelectorAll() method to get a list of all the buttons on the page, and then use the Array.prototype.find() method to get the next button in the list. Here is an example of how you can do that: let btn = document.querySelector("button"); document.body.addEventListener("keypress", (e) => { if (e.key == "b") { e.preventDefault(); // Get a list of all buttons on the page const buttons = document.querySelectorAll("button"); // Find the next button in the list const nextButton = buttons.find((button) => button.tabIndex > btn.tabIndex); if (nextButton) { // Set focus on the next button nextButton.focus(); } } }); In this example, the buttons variable will contain a NodeList of all the elements on the page, and the nextButton variable will contain the next button in the list, if one exists. If a next button exists, we set focus on it using the HTMLElement.prototype.focus() method.
How can i move from one element to another when pressing a button
Hi all I am a newby and I am trying to create a function that when I press a button for example the 'b' key focus will move from one button on the page to the next. I am able to set the focus on the first button of the page but when I press the 'b' key again focus stays on the first button. let btn = document.querySelector("button"); document.body.addEventListener("keypress", (e) => { if (e.key == "b") { e.preventDefault(); document.querySelector("button").focus(); } }); <button>Button 1</button><br> <button>Button 2</button><br> <button>Button 3</button><br> <button>Button 4</button><br> <button>Button 5</button><br>
[ "A quick way to achieve that is by setting a data-* attribute, let's call it data-is-focused to the currently focused button where the value will be 1 and then we set that to 0 once the button loses focus and based on that attribute, the data-is-focused attribute, we can easily tell which button is currently selected and we can easily move focus to the next one.\nThe idea is simple:\n\nwe select all the buttons and cache them in the JavaScript code so we can easily access them when needed. Each button will have an index based on its appearance in the document tree (first button will have the index 0, second button will be at the index 1 and so on).\ninitially, all the button do not have the data-is-focused attribute which will be considered as if that attribute is set to 0.\nonce \"b\" is pressed we make some checks:\n\nget the currently focused button by finding the index of the button that has the data-is-focused attribute set to 1.\nif no button is focused then we manually set the index to 0 so we focus the first button.\nOtherwise, if we find the currently focused button, we increment the index.\nif we reach the last button, the index equals the number of buttons - 1 (remember, indexes start from 0) then we simply set 0 to the index of the button to be focused.\n\n\n\nTo illustrate, here's a live demo, that handles returning back to the first button once we reach the last one (as described above):\nUpdate: allow using shift key to move backwards\n\n\nconst btns = Array.from(document.querySelectorAll(\"button\")),\n /**\n * guess the index of the buitton to be focused based on the index of the currently focused button and whether we want to walk forwards or backwards.\n */\n guessNextButtonIndex = (focusedBtnIndex, inReverseOrder) => {\n return inReverseOrder\n ? (focusedBtnIndex <= 0 ? btns.length - 1 : focusedBtnIndex - 1) \n : (focusedBtnIndex === -1 || focusedBtnIndex === btns.length - 1 ? 0 : focusedBtnIndex + 1);\n };\n\ndocument.body.addEventListener(\"keydown\", e => {\n // because we accept shift key, when you press shift + \"b\" the output will be \"B\" (uppercased) so we need to transform that to lower case.\n if (e.key.toLowerCase() === \"b\") {\n // get the index of the currently focused button based on the data-is-focused attribute. If no button is focused, -1 is returned.\n const idx = btns.findIndex(btn => btn.dataset.isFocused == 1),\n btnToFocus = btns[guessNextButtonIndex(idx, e.shiftKey)];\n // set the data-is-focused of the last focused button to \"0\"\n idx !== -1 && (btns[idx].dataset.isFocused = 0);\n // set the data-is-focused of the button to be focused to \"1\"\n btnToFocus.dataset.isFocused = 1;\n // focus the button to be focused\n btnToFocus.focus();\n }\n});\n<button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>\n\n\n\n", "Your code is half-way there! You need to select all the buttons by using querySelectorAll, because using querySelector it will only return the first matching element, and then keep track of which button you are focusing each time you call the function. So with the edits it would look like this:\nlet buttons = document.querySelectorAll('button');\nlet currentButton = 0;\n\ndocument.body.addEventListener('keypress', e => {\n if (e.key == 'b') {\n e.preventDefault();\n currentButton++; // move to the next button in the list\n if (currentButton >= buttons.length) {\n currentButton = 0; // loop back to the first button if we reach the end of the list\n }\n buttons[currentButton].focus();\n }\n});\n\n", "\n\n const boxes = document.querySelectorAll('button');\n var boxesLength = boxes.length;\n for (var i = 0; i < boxesLength; i++) {\n boxes[i].addEventListener('click', function (i) {\n var findnextbtn;\n if ((boxesLength - 1) == i) {\n removeStyle();\n findnextbtn = boxes[0];\n } else {\n removeStyle();\n findnextbtn = boxes[i + 1];\n }\n findnextbtn.setAttribute('style', 'background-color: yellow;');\n }.bind(null, i));\n }\n function removeStyle() {\n boxes.forEach(box => {\n box.setAttribute('style', 'background-color: none;');\n });\n }\n<button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>\n\n\n\n", "To move the focus from one button to the next when you press the 'b' key, you can use the document.querySelectorAll() method to get a list of all the buttons on the page, and then use the Array.prototype.find() method to get the next button in the list.\nHere is an example of how you can do that:\nlet btn = document.querySelector(\"button\");\ndocument.body.addEventListener(\"keypress\", (e) => {\n if (e.key == \"b\") {\n e.preventDefault();\n // Get a list of all buttons on the page\n const buttons = document.querySelectorAll(\"button\");\n // Find the next button in the list\n const nextButton = buttons.find((button) => button.tabIndex > btn.tabIndex);\n if (nextButton) {\n // Set focus on the next button\n nextButton.focus();\n }\n }\n});\n\nIn this example, the buttons variable will contain a NodeList of all the elements on the page, and the nextButton variable will contain the next button in the list, if one exists. If a next button exists, we set focus on it using the HTMLElement.prototype.focus() method.\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074667001_javascript.txt
Q: Babel plugin transform-remove-strict-mode not working with @vue/cli-plugin-babel/preset? I created a Vue 2 project by Vue CLI and want to it work on IE 11. So I modified .browserlistrc and bable.config.js. defaults > 0.3% ie 11 module.exports = { presets: ["@vue/cli-plugin-babel/preset", ["@babel/preset-env", { modules: "auto" }]], plugins: [ [ "component", { libraryName: "element-ui", styleLibraryName: "theme-chalk", }, ], ], }; But IE throw an Error: SCRIPT5043: strict 模式下不允许访问函数或参数对象的“caller”属性, After google, I try to use babel-plugin-transform-remove-strict-mode to remove "use strict" and modified babel.config.js module.exports = { presets: ["@vue/cli-plugin-babel/preset", ["@babel/preset-env", { modules: "auto" }]], plugins: [ ["transform-remove-strict-mode"], // also tried "transform-remove-strict-mode" or ["transform-remove-strict-mode", {}] [ "component", { libraryName: "element-ui", styleLibraryName: "theme-chalk", }, ], ], }; At last, IE throw a same Error and the source code still has `"use strict" app.js A: It is possible that the transform-remove-strict-mode Babel plugin is not working with the @vue/cli-plugin-babel/preset because the plugin is not included in the preset. The @vue/cli-plugin-babel/preset is a pre-configured Babel preset that is used by the Vue CLI, and it includes a specific set of plugins and transformations that are applied to your code. If the transform-remove-strict-mode plugin is not included in the preset, then it will not be applied to your code, even if you have it installed and configured in your Babel configuration. To fix this, you can either add the transform-remove-strict-mode plugin to the list of plugins in the @vue/cli-plugin-babel/preset, or you can use a custom Babel preset that includes the transform-remove-strict-mode plugin. Here is an example of how you could add the transform-remove-strict-mode plugin to the @vue/cli-plugin-babel/preset: // In your babel.config.js file module.exports = { presets: [ [ '@vue/cli-plugin-babel/preset', { // Add the transform-remove-strict-mode plugin to the preset plugins: ['transform-remove-strict-mode'], }, ], ], }; Alternatively, you can create your own custom Babel preset that includes the transform-remove-strict-mode plugin, and use that preset instead of the @vue/cli-plugin-babel/preset: // In your babel.config.js file module.exports = { presets: [ // Use your custom preset instead of the @vue/cli-plugin-babel/preset ['my-custom-preset', { plugins: ['transform-remove-strict-mode'] }], ], }; I hope this helps! Let me know if you have any other questions.
Babel plugin transform-remove-strict-mode not working with @vue/cli-plugin-babel/preset?
I created a Vue 2 project by Vue CLI and want to it work on IE 11. So I modified .browserlistrc and bable.config.js. defaults > 0.3% ie 11 module.exports = { presets: ["@vue/cli-plugin-babel/preset", ["@babel/preset-env", { modules: "auto" }]], plugins: [ [ "component", { libraryName: "element-ui", styleLibraryName: "theme-chalk", }, ], ], }; But IE throw an Error: SCRIPT5043: strict 模式下不允许访问函数或参数对象的“caller”属性, After google, I try to use babel-plugin-transform-remove-strict-mode to remove "use strict" and modified babel.config.js module.exports = { presets: ["@vue/cli-plugin-babel/preset", ["@babel/preset-env", { modules: "auto" }]], plugins: [ ["transform-remove-strict-mode"], // also tried "transform-remove-strict-mode" or ["transform-remove-strict-mode", {}] [ "component", { libraryName: "element-ui", styleLibraryName: "theme-chalk", }, ], ], }; At last, IE throw a same Error and the source code still has `"use strict" app.js
[ "It is possible that the transform-remove-strict-mode Babel plugin is not working with the @vue/cli-plugin-babel/preset because the plugin is not included in the preset. The @vue/cli-plugin-babel/preset is a pre-configured Babel preset that is used by the Vue CLI, and it includes a specific set of plugins and transformations that are applied to your code.\nIf the transform-remove-strict-mode plugin is not included in the preset, then it will not be applied to your code, even if you have it installed and configured in your Babel configuration.\nTo fix this, you can either add the transform-remove-strict-mode plugin to the list of plugins in the @vue/cli-plugin-babel/preset, or you can use a custom Babel preset that includes the transform-remove-strict-mode plugin.\nHere is an example of how you could add the transform-remove-strict-mode plugin to the @vue/cli-plugin-babel/preset:\n // In your babel.config.js file\nmodule.exports = {\n presets: [\n [\n '@vue/cli-plugin-babel/preset',\n {\n // Add the transform-remove-strict-mode plugin to the preset\n plugins: ['transform-remove-strict-mode'],\n },\n ],\n ],\n};\n\nAlternatively, you can create your own custom Babel preset that includes the transform-remove-strict-mode plugin, and use that preset instead of the @vue/cli-plugin-babel/preset:\n// In your babel.config.js file\nmodule.exports = {\n presets: [\n // Use your custom preset instead of the @vue/cli-plugin-babel/preset\n ['my-custom-preset', { plugins: ['transform-remove-strict-mode'] }],\n ],\n};\n\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 0 ]
[]
[]
[ "babeljs", "internet_explorer", "vue_cli" ]
stackoverflow_0074667792_babeljs_internet_explorer_vue_cli.txt
Q: Adding categorical control variables to nlsLM regression I am trying to run an Nonlinear Least Squares regression to estimate three parameters while controlling for categorical variables. I am currently using the nlsLM function from the minpack.lm package for this. I have the following data set: df <- data.frame(Year=c(1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003), Color=c("blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown"), Y=c(6.9, 53.6, 3.9, 7.6, 17.3, 29.9, 35.1, 6.2, 6.9, 53.6, 3.6, 8.8, 10.6, 29.9, 23.2, 8.8, 5.8, 51.0, 5.8, 3.9, 9.9, 21.0, 35.8, 6.9, 3.9, 69.5, 5.4, 3.6, 13.2, 32.8, 27.3, 8.0, 6.2, 66.2, 3.2, 3.9, 10.6, 27.6, 23.9, 11.7, 8.8, 49.5, 4.3, 4.7, 7.3, 33.2, 18.8, 18.4, 8.8, 49.9, 2.5, 27.6, 11.4, 56.9, 16.9, 9.9, 3.6, 59.9, 0.6, 19.9, 16.2, 38.4, 19.9, 12.8, 7.3, 49.5, 2.5, 11.4, 11.4, 32.5, 25.8, 31.4, 4.7, 60.6, 5.4, 14.3, 16.5, 51.4, 26.5, 21.4, 6.5, 61.4, 5.1, 14.7, 12.1, 53.6, 22.1, 15.8, 6.5, 61.0, 3.9, 14.3, 12.1, 69.1, 28.4, 18.8, 6.5, 76.9, 1.7, 8.0, 9.1, 43.9, 21.0, 17.3, 3.6, 63.6, 2.8, 9.9, 5.1, 35.1, 20.6, 16.5), Value=c(45048.7, 218638.3, 39069.9, 10740.1, 62575.7, 76967.4, 226646.2, 36693.8, 40915.0, 247665.1, 43910.4, 11429.4, 60295.5, 76426.6, 244191.4, 36749.2, 35005.8, 228515.1, 42248.2, 10285.1, 60681.4, 72030.6, 229893.0, 36404.7, 43749.9, 268866.1, 38835.1, 11899.6, 58424.4, 82731.1, 255466.1, 31277.1, 55047.2, 305402.5, 39084.3, 13398.4, 65122.4, 79750.5, 281509.4, 35542.1, 47780.8, 327010.6, 44074.8, 14565.8, 70142.8, 104683.1, 315443.8, 46939.5, 41387.0, 327226.5, 44330.9, 16046.2, 67922.8, 122232.1, 323685.2, 44895.5, 36323.1, 346799.2, 43400.6, 16547.5, 77243.2, 111932.1, 331698.8, 47992.3, 34636.8, 357551.3, 41798.8, 17346.3, 87586.4, 99095.4, 366299.7, 53745.3, 39918.4, 357564.7, 43367.9, 17921.5, 96130.4, 101582.7, 399612.1, 40792.3, 45870.7, 360308.6, 46312.0, 20444.3, 101972.7, 96745.6, 439824.2, 49499.2, 48152.0, 346522.2, 54800.0, 20503.6, 98936.7, 105203.3, 436226.9, 40983.5, 53812.9, 351838.8, 55071.2, 20865.7, 99782.6, 112538.4, 474671.2, 43175.7, 53994.5, 333412.4, 54407.9, 19528.1, 95297.1, 101047.5, 470599.2, 33293.8), Amount=c(22357.1, 45323.2, 7060.7, 0.2, 103671.4, 100515.1, 122229.3, 1254.9, 78600.7, 48483.2, 6291.6, 1059.7, 28861.1, 179036.4, 40044.7, 12921.4, 19601.9, 6095.1, 4667.4, 2194.7, 22358.8, 161020.1, 40368.1, 4000.5, 139611.6, 45724.9, 1262.3, 86.4, 88898.4, 85844.9, 262167.2, 19233.5, 21174.3, 16797.2, 246.0, 4284.0, 124309.9, 109092.7, 80172.1, 5315.0, 17300.8, 58570.1, 4240.7, 29715.0, 67126.6, 42928.3, 132263.8, 12182.9, 77751.4, 117453.7, 443.9, 21868.6, 63683.6, 212790.1, 28990.6, 0.2, 39413.4, 134290.1, 4665.5, 0.2, 135307.1, 114914.2, 258602.7, 0.2, 3391.7, 74113.6, 3070.4, 17796.6, 6223.9, 188960.2, 260430.1, 0.2, 16379.0, 37389.8, 2587.3, 1149.9, 54814.3, 183559.8, 55877.1, 0.2, 5835.3, 39010.5, 8263.9, 13463.9, 40232.7, 152270.9, 314975.1, 119611.4, 5811.2, 102397.5, 6479.1, 890.6, 24356.6, 68414.0, 85800.6, 16564.8, 9218.9, 170079.5, 5181.0, 3378.0, 37603.9, 98078.2, 533192.3, 5753.8, 41286.3, 43227.9, 2494.7, 9025.1, 20819.6, 45227.4, 563984.9, 7129.6)) In the following function, I am estimating parameters z, k and g. Variables "Y", "Value" and "Amount" is given by my dataset. The following code works for me: library(minpack.lm) ### I set the following starting values for z, k and g: z <- 10 k <- 0.1 g <- 1 ### This is my nls function and formula: nlsfit <- nlsLM(formula = log(Y) ~ (k/z)*log(Value^z + g*Amount^z), data = df, control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), start = list(z = z, k = k, g = g)) However, I know that variables "color" and "Year" may have an impact on my regression and results, and thus I want to control for these. In a regular lm regression, I am able to add these categorical variables, but in the nlsLM function, I get an error. When adding Color as a control variable, I get: > nlsfit <- nlsLM(formula = log(Y) ~ (k/z)*log(Value^z + g*Amount^z) + Color, + data = df, + control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), + start = list(z = z, k = k, g = g)) Error in (k/z) * log(Value^z + g * Amount^z) + Color : non-numeric argument to binary operato And when adding factor(Year) as a control variable, I get: > nlsfit <- nlsLM(formula = log(Y) ~ (k/z)*log(Value^z + g*Amount^z) + factor(Year), + data = df, + control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), + start = list(z = z, k = k, g = g)) Error in numericDeriv(form[[3L]], names(ind), env) : Missing value or an infinity produced when evaluating the model I want to add both Color and Year in the (same) nls-function as categorical control variables. I know NLS might have some problems with categorical variables. I am appreciative for any help or suggestions for other types of solutions or work-arounds. A: We can avoid having to provide most of the starting values by switching to nls and using the plinear algorithm. It only requires initial values for those parameters that enter non-linearly. The starting values for the linear parameters, i.e. k and all the Color and Year starting values, can be omitted. Playing around with it a bit we notice that the g parameter has convergence problems so let us fix a sequence of g parameters and optimize on the rest taking the g which gives the least deviance (i.e. least residual sum of squares). In fm only the Color and k parameters are significant so refit without the Year parameters (fm2). g_seq <- seq(-1, 1, .01) mColor <- model.matrix(~ Color, df)[, -1] mYear <- model.matrix(~ Year, transform(df, Year = factor(Year)))[, -1] rss <- sapply(g_seq, function(g) try(deviance( nls(log(Y) ~ cbind(k = (1/z) * log(Value^z + g*Amount^z), mYear, mColor), df, start = list(z = 1), algorithm = "plinear")))) rss <- as.numeric(rss) g <- g_seq[which.min(rss)] g ## [1] 0.19 # fit with best g obtained above fm <- nls(log(Y) ~ cbind(k = (1/z) * log(Value^z + g*Amount^z), mYear, mColor), df, start = list(z = 1), algorithm = "plinear") # fit without mYear fm2 <- nls(log(Y) ~ cbind(k = (1/z) * log(Value^z + g*Amount^z), mColor), df, start = list(z = 1), algorithm = "plinear") summary(fm2) giving Formula: log(Y) ~ cbind(k = (1/z) * log(Value^z + g * Amount^z), mColor) Parameters: Estimate Std. Error t value Pr(>|t|) z 0.97166 5.47654 0.177 0.859525 .lin.k 0.16467 0.01472 11.185 < 2e-16 *** .lin.Colorbrown 0.81941 0.15972 5.130 1.37e-06 *** .lin.Colorgreen 1.98067 0.17444 11.354 < 2e-16 *** .lin.Colororange 0.60442 0.14776 4.091 8.55e-05 *** .lin.Colorpurple 0.53150 0.15857 3.352 0.001124 ** .lin.Colorred 1.70567 0.16161 10.554 < 2e-16 *** .lin.Colorwhite 1.07264 0.16924 6.338 6.24e-09 *** .lin.Coloryellow -0.60455 0.16543 -3.654 0.000408 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.4083 on 103 degrees of freedom Number of iterations to convergence: 7 Achieved convergence tolerance: 9.09e-06 A: How about this: df <- data.frame(Year=c(1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003), Color=c("blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown"), Y=c(6.9, 53.6, 3.9, 7.6, 17.3, 29.9, 35.1, 6.2, 6.9, 53.6, 3.6, 8.8, 10.6, 29.9, 23.2, 8.8, 5.8, 51.0, 5.8, 3.9, 9.9, 21.0, 35.8, 6.9, 3.9, 69.5, 5.4, 3.6, 13.2, 32.8, 27.3, 8.0, 6.2, 66.2, 3.2, 3.9, 10.6, 27.6, 23.9, 11.7, 8.8, 49.5, 4.3, 4.7, 7.3, 33.2, 18.8, 18.4, 8.8, 49.9, 2.5, 27.6, 11.4, 56.9, 16.9, 9.9, 3.6, 59.9, 0.6, 19.9, 16.2, 38.4, 19.9, 12.8, 7.3, 49.5, 2.5, 11.4, 11.4, 32.5, 25.8, 31.4, 4.7, 60.6, 5.4, 14.3, 16.5, 51.4, 26.5, 21.4, 6.5, 61.4, 5.1, 14.7, 12.1, 53.6, 22.1, 15.8, 6.5, 61.0, 3.9, 14.3, 12.1, 69.1, 28.4, 18.8, 6.5, 76.9, 1.7, 8.0, 9.1, 43.9, 21.0, 17.3, 3.6, 63.6, 2.8, 9.9, 5.1, 35.1, 20.6, 16.5), Value=c(45048.7, 218638.3, 39069.9, 10740.1, 62575.7, 76967.4, 226646.2, 36693.8, 40915.0, 247665.1, 43910.4, 11429.4, 60295.5, 76426.6, 244191.4, 36749.2, 35005.8, 228515.1, 42248.2, 10285.1, 60681.4, 72030.6, 229893.0, 36404.7, 43749.9, 268866.1, 38835.1, 11899.6, 58424.4, 82731.1, 255466.1, 31277.1, 55047.2, 305402.5, 39084.3, 13398.4, 65122.4, 79750.5, 281509.4, 35542.1, 47780.8, 327010.6, 44074.8, 14565.8, 70142.8, 104683.1, 315443.8, 46939.5, 41387.0, 327226.5, 44330.9, 16046.2, 67922.8, 122232.1, 323685.2, 44895.5, 36323.1, 346799.2, 43400.6, 16547.5, 77243.2, 111932.1, 331698.8, 47992.3, 34636.8, 357551.3, 41798.8, 17346.3, 87586.4, 99095.4, 366299.7, 53745.3, 39918.4, 357564.7, 43367.9, 17921.5, 96130.4, 101582.7, 399612.1, 40792.3, 45870.7, 360308.6, 46312.0, 20444.3, 101972.7, 96745.6, 439824.2, 49499.2, 48152.0, 346522.2, 54800.0, 20503.6, 98936.7, 105203.3, 436226.9, 40983.5, 53812.9, 351838.8, 55071.2, 20865.7, 99782.6, 112538.4, 474671.2, 43175.7, 53994.5, 333412.4, 54407.9, 19528.1, 95297.1, 101047.5, 470599.2, 33293.8), Amount=c(22357.1, 45323.2, 7060.7, 0.2, 103671.4, 100515.1, 122229.3, 1254.9, 78600.7, 48483.2, 6291.6, 1059.7, 28861.1, 179036.4, 40044.7, 12921.4, 19601.9, 6095.1, 4667.4, 2194.7, 22358.8, 161020.1, 40368.1, 4000.5, 139611.6, 45724.9, 1262.3, 86.4, 88898.4, 85844.9, 262167.2, 19233.5, 21174.3, 16797.2, 246.0, 4284.0, 124309.9, 109092.7, 80172.1, 5315.0, 17300.8, 58570.1, 4240.7, 29715.0, 67126.6, 42928.3, 132263.8, 12182.9, 77751.4, 117453.7, 443.9, 21868.6, 63683.6, 212790.1, 28990.6, 0.2, 39413.4, 134290.1, 4665.5, 0.2, 135307.1, 114914.2, 258602.7, 0.2, 3391.7, 74113.6, 3070.4, 17796.6, 6223.9, 188960.2, 260430.1, 0.2, 16379.0, 37389.8, 2587.3, 1149.9, 54814.3, 183559.8, 55877.1, 0.2, 5835.3, 39010.5, 8263.9, 13463.9, 40232.7, 152270.9, 314975.1, 119611.4, 5811.2, 102397.5, 6479.1, 890.6, 24356.6, 68414.0, 85800.6, 16564.8, 9218.9, 170079.5, 5181.0, 3378.0, 37603.9, 98078.2, 533192.3, 5753.8, 41286.3, 43227.9, 2494.7, 9025.1, 20819.6, 45227.4, 563984.9, 7129.6)) library(minpack.lm) ### I set the following starting values for z, k and g: z <- 10 k <- 0.1 g <- 1 df$Year <- as.factor(df$Year) df$Color <- as.factor(df$Color) X <- model.matrix(~Color + Year, data=df)[,-1] df <- cbind(df, X) form <- paste0("log(Y) ~ (k/z)*log(Value^z + g*Amount^z) + ", paste(paste0("b", 1:ncol(X)), "*", colnames(X), collapse=" + ")) nlsfit <- nlsLM(formula = form , data = df, control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), start = list(z = z, k = k, g = g, b1=0, b2=0, b3=0, b4=0, b5=0, b6=0, b7=0, b8=0, b9=0, b10=0, b11=0, b12=0, b13=0, b14=0, b15=0, b16=0, b17=0, b18=0, b19=0, b20=0)) pars <- nlsfit$m$getPars() pars #> z k g b1 b2 #> -2.176726e+00 1.697185e-01 -1.520116e-12 7.285176e-01 1.961322e+00 #> b3 b4 b5 b6 b7 #> 6.062530e-01 5.360258e-01 1.722828e+00 1.062541e+00 -6.178919e-01 #> b8 b9 b10 b11 b12 #> -6.618152e-02 -1.544231e-01 -1.186151e-01 -1.567786e-01 -1.044543e-01 #> b13 b14 b15 b16 b17 #> 6.997504e-02 -1.969730e-01 -4.729006e-02 2.103823e-01 1.488066e-01 #> b18 b19 b20 #> 1.950499e-01 -1.005054e-01 -2.060658e-01 b <- pars[4:23] xb <- X %*% b fit <- (pars[2]/pars[1])*log(df$Value^pars[1] + pars[3]*df$Amount^pars[1]) + xb plot(fit, log(df$Y)) Created on 2022-12-02 by the reprex package (v2.0.1) You get some warnings about NaNs being created throughout the optimization, but the final results don't produce any NaN values.
Adding categorical control variables to nlsLM regression
I am trying to run an Nonlinear Least Squares regression to estimate three parameters while controlling for categorical variables. I am currently using the nlsLM function from the minpack.lm package for this. I have the following data set: df <- data.frame(Year=c(1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003), Color=c("blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown", "blue", "green", "yellow", "orange", "purple", "red", "white", "brown"), Y=c(6.9, 53.6, 3.9, 7.6, 17.3, 29.9, 35.1, 6.2, 6.9, 53.6, 3.6, 8.8, 10.6, 29.9, 23.2, 8.8, 5.8, 51.0, 5.8, 3.9, 9.9, 21.0, 35.8, 6.9, 3.9, 69.5, 5.4, 3.6, 13.2, 32.8, 27.3, 8.0, 6.2, 66.2, 3.2, 3.9, 10.6, 27.6, 23.9, 11.7, 8.8, 49.5, 4.3, 4.7, 7.3, 33.2, 18.8, 18.4, 8.8, 49.9, 2.5, 27.6, 11.4, 56.9, 16.9, 9.9, 3.6, 59.9, 0.6, 19.9, 16.2, 38.4, 19.9, 12.8, 7.3, 49.5, 2.5, 11.4, 11.4, 32.5, 25.8, 31.4, 4.7, 60.6, 5.4, 14.3, 16.5, 51.4, 26.5, 21.4, 6.5, 61.4, 5.1, 14.7, 12.1, 53.6, 22.1, 15.8, 6.5, 61.0, 3.9, 14.3, 12.1, 69.1, 28.4, 18.8, 6.5, 76.9, 1.7, 8.0, 9.1, 43.9, 21.0, 17.3, 3.6, 63.6, 2.8, 9.9, 5.1, 35.1, 20.6, 16.5), Value=c(45048.7, 218638.3, 39069.9, 10740.1, 62575.7, 76967.4, 226646.2, 36693.8, 40915.0, 247665.1, 43910.4, 11429.4, 60295.5, 76426.6, 244191.4, 36749.2, 35005.8, 228515.1, 42248.2, 10285.1, 60681.4, 72030.6, 229893.0, 36404.7, 43749.9, 268866.1, 38835.1, 11899.6, 58424.4, 82731.1, 255466.1, 31277.1, 55047.2, 305402.5, 39084.3, 13398.4, 65122.4, 79750.5, 281509.4, 35542.1, 47780.8, 327010.6, 44074.8, 14565.8, 70142.8, 104683.1, 315443.8, 46939.5, 41387.0, 327226.5, 44330.9, 16046.2, 67922.8, 122232.1, 323685.2, 44895.5, 36323.1, 346799.2, 43400.6, 16547.5, 77243.2, 111932.1, 331698.8, 47992.3, 34636.8, 357551.3, 41798.8, 17346.3, 87586.4, 99095.4, 366299.7, 53745.3, 39918.4, 357564.7, 43367.9, 17921.5, 96130.4, 101582.7, 399612.1, 40792.3, 45870.7, 360308.6, 46312.0, 20444.3, 101972.7, 96745.6, 439824.2, 49499.2, 48152.0, 346522.2, 54800.0, 20503.6, 98936.7, 105203.3, 436226.9, 40983.5, 53812.9, 351838.8, 55071.2, 20865.7, 99782.6, 112538.4, 474671.2, 43175.7, 53994.5, 333412.4, 54407.9, 19528.1, 95297.1, 101047.5, 470599.2, 33293.8), Amount=c(22357.1, 45323.2, 7060.7, 0.2, 103671.4, 100515.1, 122229.3, 1254.9, 78600.7, 48483.2, 6291.6, 1059.7, 28861.1, 179036.4, 40044.7, 12921.4, 19601.9, 6095.1, 4667.4, 2194.7, 22358.8, 161020.1, 40368.1, 4000.5, 139611.6, 45724.9, 1262.3, 86.4, 88898.4, 85844.9, 262167.2, 19233.5, 21174.3, 16797.2, 246.0, 4284.0, 124309.9, 109092.7, 80172.1, 5315.0, 17300.8, 58570.1, 4240.7, 29715.0, 67126.6, 42928.3, 132263.8, 12182.9, 77751.4, 117453.7, 443.9, 21868.6, 63683.6, 212790.1, 28990.6, 0.2, 39413.4, 134290.1, 4665.5, 0.2, 135307.1, 114914.2, 258602.7, 0.2, 3391.7, 74113.6, 3070.4, 17796.6, 6223.9, 188960.2, 260430.1, 0.2, 16379.0, 37389.8, 2587.3, 1149.9, 54814.3, 183559.8, 55877.1, 0.2, 5835.3, 39010.5, 8263.9, 13463.9, 40232.7, 152270.9, 314975.1, 119611.4, 5811.2, 102397.5, 6479.1, 890.6, 24356.6, 68414.0, 85800.6, 16564.8, 9218.9, 170079.5, 5181.0, 3378.0, 37603.9, 98078.2, 533192.3, 5753.8, 41286.3, 43227.9, 2494.7, 9025.1, 20819.6, 45227.4, 563984.9, 7129.6)) In the following function, I am estimating parameters z, k and g. Variables "Y", "Value" and "Amount" is given by my dataset. The following code works for me: library(minpack.lm) ### I set the following starting values for z, k and g: z <- 10 k <- 0.1 g <- 1 ### This is my nls function and formula: nlsfit <- nlsLM(formula = log(Y) ~ (k/z)*log(Value^z + g*Amount^z), data = df, control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), start = list(z = z, k = k, g = g)) However, I know that variables "color" and "Year" may have an impact on my regression and results, and thus I want to control for these. In a regular lm regression, I am able to add these categorical variables, but in the nlsLM function, I get an error. When adding Color as a control variable, I get: > nlsfit <- nlsLM(formula = log(Y) ~ (k/z)*log(Value^z + g*Amount^z) + Color, + data = df, + control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), + start = list(z = z, k = k, g = g)) Error in (k/z) * log(Value^z + g * Amount^z) + Color : non-numeric argument to binary operato And when adding factor(Year) as a control variable, I get: > nlsfit <- nlsLM(formula = log(Y) ~ (k/z)*log(Value^z + g*Amount^z) + factor(Year), + data = df, + control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), + start = list(z = z, k = k, g = g)) Error in numericDeriv(form[[3L]], names(ind), env) : Missing value or an infinity produced when evaluating the model I want to add both Color and Year in the (same) nls-function as categorical control variables. I know NLS might have some problems with categorical variables. I am appreciative for any help or suggestions for other types of solutions or work-arounds.
[ "We can avoid having to provide most of the starting values by switching to nls and using the plinear algorithm. It only requires initial values for those parameters that enter non-linearly. The starting values for the linear parameters, i.e. k and all the Color and Year starting values, can be omitted.\nPlaying around with it a bit we notice that the g parameter has convergence problems so let us fix a sequence of g parameters and optimize on the rest taking the g which gives the least deviance (i.e. least residual sum of squares).\nIn fm only the Color and k parameters are significant so refit without the Year parameters (fm2).\ng_seq <- seq(-1, 1, .01)\nmColor <- model.matrix(~ Color, df)[, -1]\nmYear <- model.matrix(~ Year, transform(df, Year = factor(Year)))[, -1]\nrss <- sapply(g_seq, function(g) try(deviance(\n nls(log(Y) ~ cbind(k = (1/z) * log(Value^z + g*Amount^z), mYear, mColor),\n df, start = list(z = 1), algorithm = \"plinear\"))))\nrss <- as.numeric(rss)\ng <- g_seq[which.min(rss)]\ng\n## [1] 0.19\n\n# fit with best g obtained above\nfm <- nls(log(Y) ~ cbind(k = (1/z) * log(Value^z + g*Amount^z), mYear, mColor), df,\n start = list(z = 1), algorithm = \"plinear\")\n\n# fit without mYear\nfm2 <- nls(log(Y) ~ cbind(k = (1/z) * log(Value^z + g*Amount^z), mColor), df,\n start = list(z = 1), algorithm = \"plinear\")\n\nsummary(fm2)\n\ngiving\nFormula: log(Y) ~ cbind(k = (1/z) * log(Value^z + g * Amount^z), mColor)\n\nParameters:\n Estimate Std. Error t value Pr(>|t|) \nz 0.97166 5.47654 0.177 0.859525 \n.lin.k 0.16467 0.01472 11.185 < 2e-16 ***\n.lin.Colorbrown 0.81941 0.15972 5.130 1.37e-06 ***\n.lin.Colorgreen 1.98067 0.17444 11.354 < 2e-16 ***\n.lin.Colororange 0.60442 0.14776 4.091 8.55e-05 ***\n.lin.Colorpurple 0.53150 0.15857 3.352 0.001124 ** \n.lin.Colorred 1.70567 0.16161 10.554 < 2e-16 ***\n.lin.Colorwhite 1.07264 0.16924 6.338 6.24e-09 ***\n.lin.Coloryellow -0.60455 0.16543 -3.654 0.000408 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nResidual standard error: 0.4083 on 103 degrees of freedom\n\nNumber of iterations to convergence: 7 \nAchieved convergence tolerance: 9.09e-06\n\n", "How about this:\n df <- data.frame(Year=c(1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1993, 1993, 1993, 1993,\n 1993, 1993, 1993, 1993, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1996,\n 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 2000, 2000, 2000, 2000,\n 2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003),\n Color=c(\"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \n \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \n \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\",\n \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\",\n \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\",\n \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \n \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \n \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\"),\n Y=c(6.9, 53.6, 3.9, 7.6, 17.3, 29.9, 35.1, 6.2, 6.9, 53.6, 3.6, 8.8, 10.6, 29.9, 23.2, 8.8, 5.8, 51.0, 5.8, 3.9, 9.9, 21.0, 35.8, 6.9, 3.9, 69.5, 5.4, 3.6,\n 13.2, 32.8, 27.3, 8.0, 6.2, 66.2, 3.2, 3.9, 10.6, 27.6, 23.9, 11.7, 8.8, 49.5, 4.3, 4.7, 7.3, 33.2, 18.8, 18.4, 8.8, 49.9, 2.5, 27.6, 11.4, 56.9, 16.9, 9.9,\n 3.6, 59.9, 0.6, 19.9, 16.2, 38.4, 19.9, 12.8, 7.3, 49.5, 2.5, 11.4, 11.4, 32.5, 25.8, 31.4, 4.7, 60.6, 5.4, 14.3, 16.5, 51.4, 26.5, 21.4, 6.5, 61.4, 5.1, 14.7,\n 12.1, 53.6, 22.1, 15.8, 6.5, 61.0, 3.9, 14.3, 12.1, 69.1, 28.4, 18.8, 6.5, 76.9, 1.7, 8.0, 9.1, 43.9, 21.0, 17.3, 3.6, 63.6, 2.8, 9.9, 5.1, 35.1, 20.6, 16.5),\n Value=c(45048.7, 218638.3, 39069.9, 10740.1, 62575.7, 76967.4, 226646.2, 36693.8, 40915.0, 247665.1, 43910.4, 11429.4, 60295.5, 76426.6, 244191.4,\n 36749.2, 35005.8, 228515.1, 42248.2, 10285.1, 60681.4, 72030.6, 229893.0, 36404.7, 43749.9, 268866.1, 38835.1, 11899.6, 58424.4, 82731.1,\n 255466.1, 31277.1, 55047.2, 305402.5, 39084.3, 13398.4, 65122.4, 79750.5, 281509.4, 35542.1, 47780.8, 327010.6, 44074.8, 14565.8, 70142.8,\n 104683.1, 315443.8, 46939.5, 41387.0, 327226.5, 44330.9, 16046.2, 67922.8, 122232.1, 323685.2, 44895.5, 36323.1, 346799.2, 43400.6, 16547.5,\n 77243.2, 111932.1, 331698.8, 47992.3, 34636.8, 357551.3, 41798.8, 17346.3, 87586.4, 99095.4, 366299.7, 53745.3, 39918.4, 357564.7, 43367.9,\n 17921.5, 96130.4, 101582.7, 399612.1, 40792.3, 45870.7, 360308.6, 46312.0, 20444.3, 101972.7, 96745.6, 439824.2, 49499.2, 48152.0, 346522.2,\n 54800.0, 20503.6, 98936.7, 105203.3, 436226.9, 40983.5, 53812.9, 351838.8, 55071.2, 20865.7, 99782.6, 112538.4, 474671.2, 43175.7, 53994.5,\n 333412.4, 54407.9, 19528.1, 95297.1, 101047.5, 470599.2, 33293.8),\n Amount=c(22357.1, 45323.2, 7060.7, 0.2, 103671.4, 100515.1, 122229.3, 1254.9, 78600.7, 48483.2, 6291.6, 1059.7, 28861.1, 179036.4, 40044.7,\n 12921.4, 19601.9, 6095.1, 4667.4, 2194.7, 22358.8, 161020.1, 40368.1, 4000.5, 139611.6, 45724.9, 1262.3, 86.4, 88898.4, 85844.9,\n 262167.2, 19233.5, 21174.3, 16797.2, 246.0, 4284.0, 124309.9, 109092.7, 80172.1, 5315.0, 17300.8, 58570.1, 4240.7, 29715.0, 67126.6,\n 42928.3, 132263.8, 12182.9, 77751.4, 117453.7, 443.9, 21868.6, 63683.6, 212790.1, 28990.6, 0.2, 39413.4, 134290.1, 4665.5, 0.2,\n 135307.1, 114914.2, 258602.7, 0.2, 3391.7, 74113.6, 3070.4, 17796.6, 6223.9, 188960.2, 260430.1, 0.2, 16379.0, 37389.8, 2587.3,\n 1149.9, 54814.3, 183559.8, 55877.1, 0.2, 5835.3, 39010.5, 8263.9, 13463.9, 40232.7, 152270.9, 314975.1, 119611.4, 5811.2, 102397.5,\n 6479.1, 890.6, 24356.6, 68414.0, 85800.6, 16564.8, 9218.9, 170079.5, 5181.0, 3378.0, 37603.9, 98078.2, 533192.3, 5753.8, 41286.3,\n 43227.9, 2494.7, 9025.1, 20819.6, 45227.4, 563984.9, 7129.6))\n\nlibrary(minpack.lm)\n### I set the following starting values for z, k and g:\nz <- 10\nk <- 0.1\ng <- 1\n\n\ndf$Year <- as.factor(df$Year)\ndf$Color <- as.factor(df$Color)\nX <- model.matrix(~Color + Year, data=df)[,-1]\ndf <- cbind(df, X)\n\nform <- paste0(\"log(Y) ~ (k/z)*log(Value^z + g*Amount^z) + \", paste(paste0(\"b\", 1:ncol(X)), \"*\", colnames(X), collapse=\" + \"))\n\nnlsfit <- nlsLM(formula = form ,\n data = df,\n control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280),\n start = list(z = z, k = k, g = g, b1=0, \n b2=0, b3=0, b4=0, b5=0, b6=0, \n b7=0, b8=0, b9=0, b10=0, \n b11=0, b12=0, b13=0, b14=0, \n b15=0, b16=0, b17=0, b18=0, \n b19=0, b20=0))\npars <- nlsfit$m$getPars()\npars\n#> z k g b1 b2 \n#> -2.176726e+00 1.697185e-01 -1.520116e-12 7.285176e-01 1.961322e+00 \n#> b3 b4 b5 b6 b7 \n#> 6.062530e-01 5.360258e-01 1.722828e+00 1.062541e+00 -6.178919e-01 \n#> b8 b9 b10 b11 b12 \n#> -6.618152e-02 -1.544231e-01 -1.186151e-01 -1.567786e-01 -1.044543e-01 \n#> b13 b14 b15 b16 b17 \n#> 6.997504e-02 -1.969730e-01 -4.729006e-02 2.103823e-01 1.488066e-01 \n#> b18 b19 b20 \n#> 1.950499e-01 -1.005054e-01 -2.060658e-01\nb <- pars[4:23]\nxb <- X %*% b\nfit <- (pars[2]/pars[1])*log(df$Value^pars[1] + pars[3]*df$Amount^pars[1]) + xb\nplot(fit, log(df$Y))\n\n\nCreated on 2022-12-02 by the reprex package (v2.0.1)\nYou get some warnings about NaNs being created throughout the optimization, but the final results don't produce any NaN values.\n" ]
[ 1, 0 ]
[]
[]
[ "categorical", "controls", "nls", "r" ]
stackoverflow_0074658727_categorical_controls_nls_r.txt
Q: Converting an uml class diagram to c# code I have this UML diagram: I have tried to convert it to C# code: internal class Task:Organizer { public string Name { get; } public string Description { get; set; } public int Priority { get; set; } private bool done=false; public bool Done { get { return done; } set { done = value;} } Is this how it's supposed to look like? A: No, this is not supposed to look like this: Task:Organizer is inheritance in C#. In UML it would be represented as follows: This would be obviously wrong, because your diagram does not express inheritance but shared aggregation. Bu the way, your input diagram seems not correct. It uses an association with the shared aggregation symbol (white diamond) on the wrong side. The corrected version would look like: But since the aggregation does not add any semantic, the rest of my answer is valid also for the incorrect input diagram. The diagram could as well use a simple association without diamond and have exactly the same implementation. To implement this, you need to create two classes, Organizer and Task with a collection of Task as property of Organizer. class Task { ... } class Organizer { ... public List<Task> Tasks { get; } ... }
Converting an uml class diagram to c# code
I have this UML diagram: I have tried to convert it to C# code: internal class Task:Organizer { public string Name { get; } public string Description { get; set; } public int Priority { get; set; } private bool done=false; public bool Done { get { return done; } set { done = value;} } Is this how it's supposed to look like?
[ "No, this is not supposed to look like this: Task:Organizer is inheritance in C#. In UML it would be represented as follows:\n\nThis would be obviously wrong, because your diagram does not express inheritance but shared aggregation.\nBu the way, your input diagram seems not correct. It uses an association with the shared aggregation symbol (white diamond) on the wrong side. The corrected version would look like:\n\nBut since the aggregation does not add any semantic, the rest of my answer is valid also for the incorrect input diagram. The diagram could as well use a simple association without diamond and have exactly the same implementation.\nTo implement this, you need to create two classes, Organizer and Task with a collection of Task as property of Organizer.\nclass Task\n{\n ...\n}\n\nclass Organizer\n{\n ...\n public List<Task> Tasks { get; }\n ...\n}\n\n" ]
[ 2 ]
[]
[]
[ "c#", "class_diagram", "inheritance", "properties", "uml" ]
stackoverflow_0074667698_c#_class_diagram_inheritance_properties_uml.txt
Q: Cannot connect to socket.io with Golang So, basically here is the code of my socketio server : package main import ( "log" "net/http" socketio "github.com/googollee/go-socket.io" ) func main() { server := socketio.NewServer(nil) server.OnConnect("/socket.io/", func(s socketio.Conn) error { s.SetContext("c") log.Println("connected:", s.ID()) s.Emit("connection", "connected") return nil }) server.OnDisconnect("/", func(s socketio.Conn, reason string) { log.Println("closed", reason, s.Context()) }) go server.Serve() defer server.Close() http.Handle("/socket.io/", server) http.Handle("/", http.FileServer(http.Dir("./"))) log.Println("Serving at localhost:4000...") log.Fatal(http.ListenAndServe(":4000", nil)) } and here is how I try to access it within my client (a webpage) : const socket = io('ws://localhost:4000/socket.io/') console.log(socket); My problem is that nothing is logged on the client console and the server console when the client should be connecting. More information : I access my webpage client at http://localhost:4000 The webpage is loaded correctly When I refresh the client, on the server clode closed client namespace disconnect <nil> A: There are a few potential issues with the code you provided that could be preventing the client and server from communicating. First, in your client code, you are trying to connect to the socket server using the ws:// protocol, but the socket server is actually using the http:// protocol. This means that the client is trying to connect to the wrong protocol and will not be able to establish a connection to the server. To fix this, you can change the ws:// protocol in the client code to http://: const socket = io('http://localhost:4000/socket.io/') console.log(socket); Another potential issue is that your server code is using the /socket.io/ namespace for the OnConnect and OnDisconnect events, but your client code is not specifying this namespace when connecting to the server. This means that the client and server are not using the same namespace and will not be able to communicate. To fix this, you can specify the /socket.io/ namespace in the client code when connecting to the server: const socket = io('http://localhost:4000/socket.io/', { path: '/socket.io/' }) console.log(socket); Finally, your server code is not listening for any events from the client, so even if the client is able to connect to the server, it will not be able to send any events or messages to the server. To fix this, you can add event handlers to your server code that listen for events from the client and respond to them. For example, you could add an OnEvent handler that listens for a message event from the client and logs the message to the server console: server.OnEvent("/socket.io/", "message", func(s socketio.Conn, msg string) string { log.Println("received message:", msg) return "" }) With these changes, your client and server code should be able to communicate and you should see messages logged to the client and server consoles.
Cannot connect to socket.io with Golang
So, basically here is the code of my socketio server : package main import ( "log" "net/http" socketio "github.com/googollee/go-socket.io" ) func main() { server := socketio.NewServer(nil) server.OnConnect("/socket.io/", func(s socketio.Conn) error { s.SetContext("c") log.Println("connected:", s.ID()) s.Emit("connection", "connected") return nil }) server.OnDisconnect("/", func(s socketio.Conn, reason string) { log.Println("closed", reason, s.Context()) }) go server.Serve() defer server.Close() http.Handle("/socket.io/", server) http.Handle("/", http.FileServer(http.Dir("./"))) log.Println("Serving at localhost:4000...") log.Fatal(http.ListenAndServe(":4000", nil)) } and here is how I try to access it within my client (a webpage) : const socket = io('ws://localhost:4000/socket.io/') console.log(socket); My problem is that nothing is logged on the client console and the server console when the client should be connecting. More information : I access my webpage client at http://localhost:4000 The webpage is loaded correctly When I refresh the client, on the server clode closed client namespace disconnect <nil>
[ "There are a few potential issues with the code you provided that could be preventing the client and server from communicating.\nFirst, in your client code, you are trying to connect to the socket server using the ws:// protocol, but the socket server is actually using the http:// protocol. This means that the client is trying to connect to the wrong protocol and will not be able to establish a connection to the server. To fix this, you can change the ws:// protocol in the client code to http://:\nconst socket = io('http://localhost:4000/socket.io/')\nconsole.log(socket);\n\nAnother potential issue is that your server code is using the /socket.io/ namespace for the OnConnect and OnDisconnect events, but your client code is not specifying this namespace when connecting to the server. This means that the client and server are not using the same namespace and will not be able to communicate. To fix this, you can specify the /socket.io/ namespace in the client code when connecting to the server:\nconst socket = io('http://localhost:4000/socket.io/', {\n path: '/socket.io/'\n})\nconsole.log(socket);\n\nFinally, your server code is not listening for any events from the client, so even if the client is able to connect to the server, it will not be able to send any events or messages to the server. To fix this, you can add event handlers to your server code that listen for events from the client and respond to them. For example, you could add an OnEvent handler that listens for a message event from the client and logs the message to the server console:\nserver.OnEvent(\"/socket.io/\", \"message\", func(s socketio.Conn, msg string) string {\n log.Println(\"received message:\", msg)\n return \"\"\n})\n\nWith these changes, your client and server code should be able to communicate and you should see messages logged to the client and server consoles.\n" ]
[ 0 ]
[]
[]
[ "go", "socket.io", "websocket" ]
stackoverflow_0074667804_go_socket.io_websocket.txt
Q: Select Statement using Stored Procedure May I ask on how to call a method when the content of the stored procedure is about select statement? (Using postgreSQL) CREATE OR REPLACE PROCEDURE select_table(table_name VARCHAR(255)) language plpgsql as $$ BEGIN EXECUTE('SELECT * FROM' || ' ' || quote_ident(table_name)); END $$; CALL select_table('employee_table'); EDITED(USING FUNCTION) CREATE OR REPLACE FUNCTION select_table(table_name VARCHAR(255)) language plpgsql as $$ BEGIN SELECT * FROM table_name RETURN table_name; END $$; A: In PostgreSQL procedures doesn't execute any select statements and doesn't have return. For returning data you can use functions. But functions also cannot return different structural data, examples: CREATE OR REPLACE FUNCTION fr_test() RETURNS TABLE(id integer, bookname character varying) LANGUAGE plpgsql AS $function$ begin return QUERY SELECT tb.id, tb.bookname from rbac.books tb; end; $function$ ; or CREATE OR REPLACE FUNCTION fr_test() RETURNS setof public.books LANGUAGE plpgsql AS $function$ begin return QUERY SELECT * from public.books; end; $function$ ; But for returning difference tables you can do it using procedures and using out refcursor, like as in Oracle. For example: create or replace procedure pr_test(OUT r1 refcursor) as $$ begin open r1 for select * from public.books; end; $$ language plpgsql;
Select Statement using Stored Procedure
May I ask on how to call a method when the content of the stored procedure is about select statement? (Using postgreSQL) CREATE OR REPLACE PROCEDURE select_table(table_name VARCHAR(255)) language plpgsql as $$ BEGIN EXECUTE('SELECT * FROM' || ' ' || quote_ident(table_name)); END $$; CALL select_table('employee_table'); EDITED(USING FUNCTION) CREATE OR REPLACE FUNCTION select_table(table_name VARCHAR(255)) language plpgsql as $$ BEGIN SELECT * FROM table_name RETURN table_name; END $$;
[ "In PostgreSQL procedures doesn't execute any select statements and doesn't have return.\nFor returning data you can use functions. But functions also cannot return different structural data, examples:\nCREATE OR REPLACE FUNCTION fr_test()\nRETURNS TABLE(id integer, bookname character varying)\nLANGUAGE plpgsql\nAS $function$ \nbegin\n return QUERY\n SELECT tb.id, tb.bookname from rbac.books tb;\nend;\n$function$\n;\n\nor\nCREATE OR REPLACE FUNCTION fr_test()\nRETURNS setof public.books \nLANGUAGE plpgsql\nAS $function$ \nbegin\n return QUERY\n SELECT * from public.books;\nend;\n$function$\n;\n\nBut for returning difference tables you can do it using procedures and using out refcursor, like as in Oracle. For example:\ncreate or replace procedure pr_test(OUT r1 refcursor) \nas $$\nbegin\n open r1 for \n select * from public.books;\nend; \n$$ language plpgsql;\n\n" ]
[ 0 ]
[]
[]
[ "postgresql" ]
stackoverflow_0074609697_postgresql.txt
Q: Viewpager 2 causing index issue when opening fast I am working in ViewPager 2 with Paging 3 library in my application. When I am opening my view pager screen again and again i.e. Open the screen and close it and again so on and so. The first few times it opens the correct page number but sometimes it gives me the wrong page number to open when doing fast open and close. I asked a similar question and it solve the issue, but something is similar issue came and 100% confident this issue is related to ViewPager 2 class activity : BaseActivity() { private val viewModel: ViewPagerViewModel by inject() private var adapter = createAdapter() private lateinit var binding: ViewPagerActivityLayoutBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ViewPagerActivityLayoutBinding.inflate(layoutInflater) setContentView(binding.root) setUpRepoAndAdapter() } private fun setUpRepoAndAdapter() { val viewRepository = ViewRepository() lifecycleScope.launchWhenCreated { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.createRepositoryData(viewRepository).collect { data -> adapter = createAdapter() binding.viewViewpager.adapter = adapter adapter.submitData(data) } } } } private fun createAdapter(): ViewPagerAdapter { return ViewPagerAdapter(action = { launchScreen() }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == DAILY_VIEW) { data?.let { intent -> (intent.extras?.get(BUNDLE_KEY) as? Date)?.let { clickedDate -> viewModel.initialDate = clickedDate setUpRepoAndAdapter() } } } } } I am adding a screencast of my original application. I am clicking on 1st Dec. Date and it's opening as 2nd Dec sometime and sometimes opening correct date. I am not understanding why this is happening this. The above stack overflow link inside has my GitHub sample project link. A: There is an official issue reported in the Android issue tracker related to this issue. The issue is still open and there is no resolution yet. However, some people have suggested a few possible solutions to this problem: Make sure your adapter is correctly implementing the getItemId() method. Don't use setCurrentItem() in the onCreate() callback. Use smoothScrollToPosition() instead of setCurrentItem(). Try using setOffscreenPageLimit() to limit the number of pages kept in memory. Make sure you are using the latest version of the ViewPager2 library.
Viewpager 2 causing index issue when opening fast
I am working in ViewPager 2 with Paging 3 library in my application. When I am opening my view pager screen again and again i.e. Open the screen and close it and again so on and so. The first few times it opens the correct page number but sometimes it gives me the wrong page number to open when doing fast open and close. I asked a similar question and it solve the issue, but something is similar issue came and 100% confident this issue is related to ViewPager 2 class activity : BaseActivity() { private val viewModel: ViewPagerViewModel by inject() private var adapter = createAdapter() private lateinit var binding: ViewPagerActivityLayoutBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ViewPagerActivityLayoutBinding.inflate(layoutInflater) setContentView(binding.root) setUpRepoAndAdapter() } private fun setUpRepoAndAdapter() { val viewRepository = ViewRepository() lifecycleScope.launchWhenCreated { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.createRepositoryData(viewRepository).collect { data -> adapter = createAdapter() binding.viewViewpager.adapter = adapter adapter.submitData(data) } } } } private fun createAdapter(): ViewPagerAdapter { return ViewPagerAdapter(action = { launchScreen() }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == DAILY_VIEW) { data?.let { intent -> (intent.extras?.get(BUNDLE_KEY) as? Date)?.let { clickedDate -> viewModel.initialDate = clickedDate setUpRepoAndAdapter() } } } } } I am adding a screencast of my original application. I am clicking on 1st Dec. Date and it's opening as 2nd Dec sometime and sometimes opening correct date. I am not understanding why this is happening this. The above stack overflow link inside has my GitHub sample project link.
[ "There is an official issue reported in the Android issue tracker related to this issue. The issue is still open and there is no resolution yet. However, some people have suggested a few possible solutions to this problem:\n\nMake sure your adapter is correctly implementing the getItemId() method.\nDon't use setCurrentItem() in the onCreate() callback.\nUse smoothScrollToPosition() instead of setCurrentItem().\nTry using setOffscreenPageLimit() to limit the number of pages kept in memory.\nMake sure you are using the latest version of the ViewPager2 library.\n\n" ]
[ 0 ]
[]
[]
[ "android", "android_adapter", "android_paging_3", "android_viewpager2", "kotlin" ]
stackoverflow_0070593277_android_android_adapter_android_paging_3_android_viewpager2_kotlin.txt
Q: How i can use socket.io inside express router controllers I have some main index.js: require('dotenv').config() const express = require("express") const sequelize = require('./db') const PORT = process.env.PORT || 5000 const models = require('./models/models') const app = express() const cors = require('cors') const router = require('./routes/index') const http = require('http'); const server = http.createServer(app); const { Server } = require("socket.io"); const io = new Server(server); app.use(cors()) app.use(express.json()) app.use('/api/v1', router) const start = async () => { try{ await sequelize.authenticate() await sequelize.sync() app.set("socketio", io) server.listen(PORT, () => console.log(`Server has been stated on port ${PORT}`)) } catch(e) { console.log(e) } } start() And that router index.js: const Router = require('express') const router = new Router() const userRouter = require('./userRouter') const contactsRouter = require('./contactsRouter') const messagesRouter = require('./messagesRouter') router.use('/user', userRouter) router.use('/contacts', contactsRouter) router.use('/messages', messagesRouter) module.exports = router And that messagesRouter: const Router = require('express') const messagesController = require('../controllers/messagesController') const router = new Router() router.post('/add', messagesController.add) router.get('/get', messagesController.get) module.exports = router And that messagesController: const ApiError = require("../error/ApiErorr"); const { Messages } = require("../models/models"); const io = require("../node_modules/socket.io/client-dist/socket.io.js") class MessagesController{ async add(req, res){ const {request_number, response_number, message} = req.body const send_message = await Messages.create({request_number, response_number, message}) //here i need socket.emit return res.json(send_message) } async get(req, res){ const {request_number, response_number} = req.body const messages = await Messages.findAll({where: { request_number, response_number }}) return res.json(messages) } } module.exports = new MessagesController But i dont understand how i can use socket.io.emit inside messagesController, because socket.io documentation tell about using sockets with server side rendering, but me need use thah without rendering, only on server. Thank you in advance A: To use Socket.IO inside your MessagesController class, you can simply require the socket.io module and use the instance of the Socket.IO server that is attached to the Express app. Here is an example of how you could do this: const ApiError = require("../error/ApiErorr"); const { Messages } = require("../models/models"); // Import the socket.io module const io = require('socket.io'); class MessagesController { // Add a constructor method to the class constructor() { // Attach a Socket.IO instance to the Express app const app = require('express')(); const server = require('http').createServer(app); this.io = require('socket.io')(server); } async add(req, res) { const { request_number, response_number, message } = req.body; const send_message = await Messages.create({ request_number, response_number, message, }); // Use the Socket.IO instance to emit an event to connected clients this.io.emit('my_event', { message: 'Hello from the Express router controller!' }); return res.json(send_message); } async get(req, res) { const { request_number, response_number } = req.body; const messages = await Messages.findAll({ where: { request_number, response_number, }, }); return res.json(messages); } } module.exports = new MessagesController; In this example, the MessagesController class creates a new instance of Socket.IO and attaches it to the Express app in the constructor method. This allows you to use the io object to emit events to connected clients from the add method. I hope this helps! Let me know if you have any other questions.
How i can use socket.io inside express router controllers
I have some main index.js: require('dotenv').config() const express = require("express") const sequelize = require('./db') const PORT = process.env.PORT || 5000 const models = require('./models/models') const app = express() const cors = require('cors') const router = require('./routes/index') const http = require('http'); const server = http.createServer(app); const { Server } = require("socket.io"); const io = new Server(server); app.use(cors()) app.use(express.json()) app.use('/api/v1', router) const start = async () => { try{ await sequelize.authenticate() await sequelize.sync() app.set("socketio", io) server.listen(PORT, () => console.log(`Server has been stated on port ${PORT}`)) } catch(e) { console.log(e) } } start() And that router index.js: const Router = require('express') const router = new Router() const userRouter = require('./userRouter') const contactsRouter = require('./contactsRouter') const messagesRouter = require('./messagesRouter') router.use('/user', userRouter) router.use('/contacts', contactsRouter) router.use('/messages', messagesRouter) module.exports = router And that messagesRouter: const Router = require('express') const messagesController = require('../controllers/messagesController') const router = new Router() router.post('/add', messagesController.add) router.get('/get', messagesController.get) module.exports = router And that messagesController: const ApiError = require("../error/ApiErorr"); const { Messages } = require("../models/models"); const io = require("../node_modules/socket.io/client-dist/socket.io.js") class MessagesController{ async add(req, res){ const {request_number, response_number, message} = req.body const send_message = await Messages.create({request_number, response_number, message}) //here i need socket.emit return res.json(send_message) } async get(req, res){ const {request_number, response_number} = req.body const messages = await Messages.findAll({where: { request_number, response_number }}) return res.json(messages) } } module.exports = new MessagesController But i dont understand how i can use socket.io.emit inside messagesController, because socket.io documentation tell about using sockets with server side rendering, but me need use thah without rendering, only on server. Thank you in advance
[ "To use Socket.IO inside your MessagesController class, you can simply require the socket.io module and use the instance of the Socket.IO server that is attached to the Express app.\nHere is an example of how you could do this:\nconst ApiError = require(\"../error/ApiErorr\");\nconst { Messages } = require(\"../models/models\");\n\n// Import the socket.io module\nconst io = require('socket.io');\n\nclass MessagesController {\n // Add a constructor method to the class\n constructor() {\n // Attach a Socket.IO instance to the Express app\n const app = require('express')();\n const server = require('http').createServer(app);\n this.io = require('socket.io')(server);\n }\n\n async add(req, res) {\n const { request_number, response_number, message } = req.body;\n const send_message = await Messages.create({\n request_number,\n response_number,\n message,\n });\n // Use the Socket.IO instance to emit an event to connected clients\n this.io.emit('my_event', { message: 'Hello from the Express router controller!' });\n\n return res.json(send_message);\n }\n\n async get(req, res) {\n const { request_number, response_number } = req.body;\n const messages = await Messages.findAll({\n where: {\n request_number,\n response_number,\n },\n });\n return res.json(messages);\n }\n}\n\nmodule.exports = new MessagesController;\n\nIn this example, the MessagesController class creates a new instance of Socket.IO and attaches it to the Express app in the constructor method. This allows you to use the io object to emit events to connected clients from the add method.\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 0 ]
[]
[]
[ "express", "socket.io" ]
stackoverflow_0074667762_express_socket.io.txt
Q: Add memoization to recursive function, Python Python. First of all, I did recursive code that find how many the shortests paths has matrix, path from last cell in matrix to frist cell in matrix. This is my code that work: def matrix_explorer(n,m): """ Recursive function that find number of the shortest paths from beginning cell of matrix to last cell :param n: Integer, how many rows has matrix :param m: Integer, how many columns has matrix :return: Number of the shortests paths """ count=0 # Number of paths if n == 1 or m == 1: # Stop condition, if one of cells is equal to 1 return count+1 # Add to number of paths 1 else: return matrix_explorer(n-1, m) + matrix_explorer(n, m-1) # Go to cell above or left to current cell I need to add memoization to this recursive function. What I have, but it's not actually working: def matrix_explorer_cache(n ,m): dictionary = {} count = 0 if n == 1 or m == 1: return count+1 else: dictionary[n][m] = matrix_explorer_cache(n-1, m) + matrix_explorer_cache(n, m-1) return dictionary[n][m]
Add memoization to recursive function, Python
Python. First of all, I did recursive code that find how many the shortests paths has matrix, path from last cell in matrix to frist cell in matrix. This is my code that work: def matrix_explorer(n,m): """ Recursive function that find number of the shortest paths from beginning cell of matrix to last cell :param n: Integer, how many rows has matrix :param m: Integer, how many columns has matrix :return: Number of the shortests paths """ count=0 # Number of paths if n == 1 or m == 1: # Stop condition, if one of cells is equal to 1 return count+1 # Add to number of paths 1 else: return matrix_explorer(n-1, m) + matrix_explorer(n, m-1) # Go to cell above or left to current cell I need to add memoization to this recursive function. What I have, but it's not actually working: def matrix_explorer_cache(n ,m): dictionary = {} count = 0 if n == 1 or m == 1: return count+1 else: dictionary[n][m] = matrix_explorer_cache(n-1, m) + matrix_explorer_cache(n, m-1) return dictionary[n][m]
[]
[]
[ "To add memoization to your matrix_explorer function, you can use a dictionary to store the results of previously computed paths. When the function is called, you can check if the result for the given n and m values has already been computed. If so, you can simply return the stored result from the dictionary instead of recomputing it. If not, you can compute the result and store it in the dictionary for future use.\ndictionary = {}\ndef matrix_explorer_cache(n ,m):\n if n == 1 or m == 1:\n return 1\n else:\n # Check if the result for the given n and m values has already been computed.\n if (n, m) not in dictionary:\n # Compute and store results\n dictionary[(n, m)] = matrix_explorer_cache(n-1, m) + matrix_explorer_cache(n, m-1)\n # At this point, dictionary[(n, m)] is guaranteed to exist\n return dictionary[(n, m)]\n\n" ]
[ -3 ]
[ "function", "matrix", "memoization", "python", "recursion" ]
stackoverflow_0074667818_function_matrix_memoization_python_recursion.txt
Q: How does docker store uploaded file? in a ram or hard disk? I try to make a simple file upload server. I wonder if it stores the uploaded file in a ram or hard disk since the container itself run as a virtual-machine in ram so it should not be able to have access to the disk right? unless I specify the bind-mounted volume option. So if the user upload a lot of files to the server at some points it's going to crash since it doesn't have ram space to store the files. A: Docker containers are isolated environments that run in memory. By default, any data that is created or modified inside a Docker container is not persisted when the container is stopped or removed. This means that if you upload a file to a Docker container, it will only be stored in the container's memory and will be lost when the container is stopped or removed. However, Docker provides a way to persist data created or modified inside a container. This is done using Docker volumes. A Docker volume is a persistent storage location that is outside of the container's filesystem and can be shared or reused across containers. When you create a Docker container, you can use the -v or --volume flag to specify a volume for the container to use. For example, you can use the following command to create a Docker container and mount the host machine's /tmp directory as a volume for the container: docker run -d -v /tmp:/tmp <image> If you want to store the uploaded files in a Docker volume, you can mount a volume when you create the container and specify a directory inside the volume as the destination for the uploaded files. This way, the files will be persisted in the volume and will not be lost when the container is stopped or removed. A: This heavily depends on the implementation of the program inside the container. If the program stores documents in memory, they'll be in memory in a container too; if it does a streaming upload to external storage, it will work that way in a container; if it stores the documents on disk, they'll be stored on disk in a container. It is true that, without any mounted storage, the container filesystem is temporary, and anything you write there will be lost when the container exits. It is stored on disk, however, unless you specifically set up a RAM disk mount. The program should use more or less the same amount of memory in a container or not.
How does docker store uploaded file? in a ram or hard disk?
I try to make a simple file upload server. I wonder if it stores the uploaded file in a ram or hard disk since the container itself run as a virtual-machine in ram so it should not be able to have access to the disk right? unless I specify the bind-mounted volume option. So if the user upload a lot of files to the server at some points it's going to crash since it doesn't have ram space to store the files.
[ "Docker containers are isolated environments that run in memory. By default, any data that is created or modified inside a Docker container is not persisted when the container is stopped or removed. This means that if you upload a file to a Docker container, it will only be stored in the container's memory and will be lost when the container is stopped or removed.\nHowever, Docker provides a way to persist data created or modified inside a container. This is done using Docker volumes. A Docker volume is a persistent storage location that is outside of the container's filesystem and can be shared or reused across containers.\nWhen you create a Docker container, you can use the -v or --volume flag to specify a volume for the container to use. For example, you can use the following command to create a Docker container and mount the host machine's /tmp directory as a volume for the container:\ndocker run -d -v /tmp:/tmp <image>\n\nIf you want to store the uploaded files in a Docker volume, you can mount a volume when you create the container and specify a directory inside the volume as the destination for the uploaded files. This way, the files will be persisted in the volume and will not be lost when the container is stopped or removed.\n", "This heavily depends on the implementation of the program inside the container. If the program stores documents in memory, they'll be in memory in a container too; if it does a streaming upload to external storage, it will work that way in a container; if it stores the documents on disk, they'll be stored on disk in a container.\nIt is true that, without any mounted storage, the container filesystem is temporary, and anything you write there will be lost when the container exits. It is stored on disk, however, unless you specifically set up a RAM disk mount. The program should use more or less the same amount of memory in a container or not.\n" ]
[ 1, 1 ]
[]
[]
[ "docker" ]
stackoverflow_0074667658_docker.txt
Q: Access SQL Server with Integrated security from .NET Core app running on Linux container using AWS ECS I have a .NET Core application running on Linux container using AWS ECS Fargate. How to connect from that application to SQL Server using integrated security? A: Step 1: ensure that SQL Server supports Kerberos authentication # Using SQL Server Management Studio (SSMS), connect to your database and execute following statement: select auth_scheme from sys.dm_exec_connections where session_id = @@spid If result of the query is KERBEROS, you are all set and proceed to Step 2. Otherwise, if result is NTLM, this means that Kerberos authentication failed, and SSMS silently fell back to using NTLM authentication. Since integrated security between SQL Server and clients running in Linux environments solely rely on Kerberos authentication, this issue must be addressed first. Note: when connecting to SQL Server, it is important to use server hostname or FQDN instead of IP address, otherwise Kerberos authentication will not work. Check SPN configuration Ensure that SPN is properly configured for SQL Server. Microsoft has also released several diagnostic tools that can help with SPN verification and configuration: Microsoft Kerberos Configuration Manager for SQL Server SQL Connectivity Settings Check (SQLCHECK) Last but not least, you can use following setspn command to query for a specific SPN(s): setspn -T CONTOSO.COM -F -Q MSSQLSvc/your_sql_server.contoso.com Query above does support * for a wildcard (replace CONTOSO.COM with your domain) Configure encryption types allowed for Kerberos Within Active Directory, find an account under which SQL Server is running. Under Account tab and Account options section, confirm that applicable Kerberos cyphers are selected. Example: Step 2: Configure ECS Task To use Kerberos authentication, Application Task within ECS Service will be composed of two containers: A container that will periodically (re)obtain and cache Kerberos ticket-granting tickets (TGT) using kinit command. A container that will run application, and use TGT acquired by first task to authenticate against MS SQL Server. Both containers will mount the same volume. 1st container will cache/write TGT ticket to it, 2nd container will read cached TGT ticket from it. TGT acquisition container (sidecar container) There are only 3 files needed to setup TGT acquisition container: krb5.conf - a Kerberos configuration file. renew.sh - script file with commands to renew TGT. Dockerfile - packages all into a docker image. # krb5.conf [libdefaults] dns_lookup_realm = true dns_lookup_kdc = true forwardable = true default_ccache_name = FILE:/var/kerberos/krbcache # TGT cache location default_realm = CONTOSO.COM permitted_enctypes = aes256-cts aes128-cts [realms] CONTOSO.COM = { kdc = CONTOSO.COM admin_server = CONTOSO.COM } [domain_realm] .contoso.com = SCIF.COM contoso.com = SCIF.COM [logging] default = STDERR # renew.sh #!/bin/bash # Refresh the token periodically. # Set the length of time that the script will wait to refresh the token. [[ "$DELAY_SECONDS" == "" ]] && DELAY_SECONDS=3600 # If the AWS region hasn't been set, get it from instance metadata. This will work in an instance as well as in an ECS container. [[ "$AWS_REGION" == "" ]] && AWS_REGION=$(curl --silent http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region) # Use the ECS container as the source for AWS credentials. This allows the AWS CLI to use the permissions of the task role. aws configure set credential_source EcsContainer while true do echo "Starting ticket renewal at: " + $(date) # Get the credentials from Secrets Manager. CREDENTIALS_SECRET_VALUE=$(aws secretsmanager get-secret-value --secret-id $CREDENTIALS_SECRET_ARN --region $AWS_REGION --query SecretString --output text) # Use `jq` to parse the credentials into username & password. CREDENTIALS_USERNAME=$(echo $CREDENTIALS_SECRET_VALUE | jq -r '.username') CREDENTIALS_PASSWORD=$(echo $CREDENTIALS_SECRET_VALUE | jq -r '.password') # Use the username & password to authenticate to Kerberos. The resulting token is written to the token cache, # which is set up in `krb5.conf` to use the task scratch volume, shared by all containers. echo $CREDENTIALS_PASSWORD | kinit $CREDENTIALS_USERNAME -f -V $OPTIONS echo "Ticket renewal complete, waiting for $DELAY_SECONDS seconds" sleep $DELAY_SECONDS & wait done # Dockerfile FROM amazonlinux:2 COPY renew.sh / COPY krb5.conf /etc/krb5.conf # Install the Kerberos tools -- to authenticate; # `jq` -- to parse the credentials from the AWS Secrets Manager, which returns JSON # `unzip` -- to install the latest version of the AWS CLI RUN yum install -y krb5-workstation jq unzip # Download and install the latest version of the AWS CLI RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" RUN unzip awscliv2.zip RUN ./aws/install VOLUME ["/var/kerberos"] ENTRYPOINT ["/renew.sh"] Based on value specified in CREDENTIALS_SECRET_ARN , renew.sh will periodically renew TGT and cache/save it in location specified at krb5.conf file (e.g. /var/kerberos/krbcache). To test that container successfully acquires TGT for a given principle, establish interactive session with the container and execute klist command. When successful, you should see the details of TGT ticket, containing principle name, expiration date, etc. Application Container Application container runs your .NET Core application. To enable Kerberos on that container add following lines in Dockerfile: ... RUN apt update RUN apt install -y krb5-config krb5-user COPY krb5.conf /etc/krb5.conf VOLUME ["/var/kerberos"] ... The content of krb5.conf file should be identical to one in TGT acquisition container, and it will instruct application to locate Kerberos TGT at FILE:/var/kerberos/krbcache . Your application SQL connection string should look similar to this: Server=yourSqlServer.contoso.com;Initial Catalog=YourDB;Integrated Security=true; To test that container has access to cached TGT, establish interactive session with the container and execute klist . When successful, you should see same TGT ticket, as in another container. If everything went well, you should be able to successfully connect to SQL Server using Integrated Security from your .NET Core application running on Linux. Additional resources Using Windows Authentication with Linux Containers on Amazon ECS Authenticate .NET Core Client of SQL Server with Integrated Security from Linux Docker Container
Access SQL Server with Integrated security from .NET Core app running on Linux container using AWS ECS
I have a .NET Core application running on Linux container using AWS ECS Fargate. How to connect from that application to SQL Server using integrated security?
[ "Step 1: ensure that SQL Server supports Kerberos authentication #\nUsing SQL Server Management Studio (SSMS), connect to your database and execute following statement:\nselect auth_scheme \nfrom sys.dm_exec_connections \nwhere session_id = @@spid\n\nIf result of the query is KERBEROS, you are all set and proceed to Step 2. Otherwise, if result is NTLM, this means that Kerberos authentication failed, and SSMS silently fell back to using NTLM authentication. Since integrated security between SQL Server and clients running in Linux environments solely rely on Kerberos authentication, this issue must be addressed first.\nNote: when connecting to SQL Server, it is important to use server hostname or FQDN instead of IP address, otherwise Kerberos authentication will not work.\nCheck SPN configuration\nEnsure that SPN is properly configured for SQL Server.\nMicrosoft has also released several diagnostic tools that can help with SPN verification and configuration:\n\nMicrosoft Kerberos Configuration Manager for SQL Server\nSQL Connectivity Settings Check (SQLCHECK)\n\nLast but not least, you can use following setspn command to query for a specific SPN(s):\nsetspn -T CONTOSO.COM -F -Q MSSQLSvc/your_sql_server.contoso.com\n\nQuery above does support * for a wildcard (replace CONTOSO.COM with your domain)\nConfigure encryption types allowed for Kerberos\nWithin Active Directory, find an account under which SQL Server is running. Under Account tab and Account options section, confirm that applicable Kerberos cyphers are selected.\nExample:\n\nStep 2: Configure ECS Task\nTo use Kerberos authentication, Application Task within ECS Service will be composed of two containers:\n\nA container that will periodically (re)obtain and cache Kerberos ticket-granting tickets (TGT) using kinit command.\nA container that will run application, and use TGT acquired by first task to authenticate against MS SQL Server.\n\nBoth containers will mount the same volume. 1st container will cache/write TGT ticket to it, 2nd container will read cached TGT ticket from it.\nTGT acquisition container (sidecar container)\nThere are only 3 files needed to setup TGT acquisition container:\n\nkrb5.conf - a Kerberos configuration file.\nrenew.sh - script file with commands to renew TGT.\nDockerfile - packages all into a docker image.\n\n# krb5.conf\n[libdefaults]\ndns_lookup_realm = true\ndns_lookup_kdc = true\nforwardable = true\ndefault_ccache_name = FILE:/var/kerberos/krbcache # TGT cache location\ndefault_realm = CONTOSO.COM\npermitted_enctypes = aes256-cts aes128-cts\n\n[realms]\nCONTOSO.COM = {\n kdc = CONTOSO.COM\n admin_server = CONTOSO.COM\n}\n\n[domain_realm]\n.contoso.com = SCIF.COM\ncontoso.com = SCIF.COM\n\n[logging]\ndefault = STDERR\n\n# renew.sh\n#!/bin/bash\n\n# Refresh the token periodically.\n# Set the length of time that the script will wait to refresh the token.\n[[ \"$DELAY_SECONDS\" == \"\" ]] && DELAY_SECONDS=3600\n\n# If the AWS region hasn't been set, get it from instance metadata. This will work in an instance as well as in an ECS container.\n[[ \"$AWS_REGION\" == \"\" ]] && AWS_REGION=$(curl --silent http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)\n\n# Use the ECS container as the source for AWS credentials. This allows the AWS CLI to use the permissions of the task role.\naws configure set credential_source EcsContainer\n\n\nwhile true\ndo\n echo \"Starting ticket renewal at: \" + $(date)\n\n # Get the credentials from Secrets Manager.\n CREDENTIALS_SECRET_VALUE=$(aws secretsmanager get-secret-value --secret-id $CREDENTIALS_SECRET_ARN --region $AWS_REGION --query SecretString --output text)\n\n # Use `jq` to parse the credentials into username & password.\n CREDENTIALS_USERNAME=$(echo $CREDENTIALS_SECRET_VALUE | jq -r '.username')\n CREDENTIALS_PASSWORD=$(echo $CREDENTIALS_SECRET_VALUE | jq -r '.password')\n\n # Use the username & password to authenticate to Kerberos. The resulting token is written to the token cache, \n # which is set up in `krb5.conf` to use the task scratch volume, shared by all containers.\n echo $CREDENTIALS_PASSWORD | kinit $CREDENTIALS_USERNAME -f -V $OPTIONS\n\n echo \"Ticket renewal complete, waiting for $DELAY_SECONDS seconds\"\n\n\n sleep $DELAY_SECONDS &\n wait\ndone\n\n# Dockerfile\n\nFROM amazonlinux:2\n\nCOPY renew.sh /\nCOPY krb5.conf /etc/krb5.conf\n\n# Install the Kerberos tools -- to authenticate;\n# `jq` -- to parse the credentials from the AWS Secrets Manager, which returns JSON\n# `unzip` -- to install the latest version of the AWS CLI\nRUN yum install -y krb5-workstation jq unzip \n\n# Download and install the latest version of the AWS CLI\nRUN curl \"https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip\" -o \"awscliv2.zip\"\nRUN unzip awscliv2.zip\nRUN ./aws/install\n\nVOLUME [\"/var/kerberos\"]\n\nENTRYPOINT [\"/renew.sh\"]\n\nBased on value specified in CREDENTIALS_SECRET_ARN , renew.sh will periodically renew TGT and cache/save it in location specified at krb5.conf file (e.g. /var/kerberos/krbcache).\nTo test that container successfully acquires TGT for a given principle, establish interactive session with the container and execute klist command. When successful, you should see the details of TGT ticket, containing principle name, expiration date, etc.\nApplication Container\nApplication container runs your .NET Core application. To enable Kerberos on that container add following lines in Dockerfile:\n...\nRUN apt update\nRUN apt install -y krb5-config krb5-user \nCOPY krb5.conf /etc/krb5.conf\nVOLUME [\"/var/kerberos\"]\n...\n\nThe content of krb5.conf file should be identical to one in TGT acquisition container, and it will instruct application to locate Kerberos TGT at FILE:/var/kerberos/krbcache .\nYour application SQL connection string should look similar to this:\nServer=yourSqlServer.contoso.com;Initial Catalog=YourDB;Integrated Security=true;\n\nTo test that container has access to cached TGT, establish interactive session with the container and execute klist . When successful, you should see same TGT ticket, as in another container.\nIf everything went well, you should be able to successfully connect to SQL Server using Integrated Security from your .NET Core application running on Linux.\nAdditional resources\n\nUsing Windows Authentication with Linux Containers on Amazon ECS\n\nAuthenticate .NET Core Client of SQL Server with Integrated Security from Linux Docker Container\n\n\n" ]
[ 1 ]
[]
[]
[ ".net", "amazon_ecs", "amazon_web_services", "docker", "sql_server" ]
stackoverflow_0074667855_.net_amazon_ecs_amazon_web_services_docker_sql_server.txt
Q: How to get values from one table that are not being used by top 3 results in another table? I need to figure out what beers from table 'Beer' were not ordered by top 3 buyers from table 'Buyers'. Beer.BeerId is foreign key in Buyers.BeerId. Other important columns in 'Buyers' are: BuyId, PubId, StoreId and Quantity dbo.Beer BeerId 1 2 3 4 5 dbo.Buyers BuyId PubId StoreId BeerId Quantity 1 1 NULL 1 30 2 NULL 1 2 40 3 2 NULL 3 50 4 NULL 2 4 10 I tried doing this query but it gives me no results. SELECT Be.BeerId FROM Beer be left outer join Buyer bu ON be.BeerId=bu.BeerId WHERE not exists ( SELECT TOP(3) BuyId, bu.BeerId, SUM(Quantity) as TotalOrdered FROM Buyer bu GROUP BY BuyId, bu.BeerId ORDER BY SUM(Quantity) DESC) What I would expect to see is that from the top 3 results, beers that are not ordered are BeerId=4 and BeerId=5 A: This seems like a classic window function problem. You can use ROW_NUMBER() to enumerate the rows in order of their Quantity totals descending, and filter out the top 3 like so: WITH _BuyersTotalsRanked AS ( SELECT BeerId, -- Same BeerId might've been ordered by different Buyers ROW_NUMBER() OVER (ORDER BY TotalOrderedPerBeer DESC) AS BuyersRanked FROM ( SELECT BeerId, SUM(Quantity) AS TotalOrderedPerBeer FROM dbo.Buyer GROUP BY BuyId, BeerId ) AS BuyersTotals ) SELECT DISTINCT BeerId -- Same BeerId might've been ordered by different Buyers FROM _BuyersTotalsRanked WHERE BuyersRanked > 3 -- Filter out the top 3 Buyers Beers Note that if there's a tie for the top 3, this will return nondeterminsitic (semi-random) results because of the ORDER BY clause in the ROW_NUMBER() function not being unique (same problem with your ORDER BY clause in your example query). To correct that, you would need to add a uniquifying field to deterministically decide which row wins in a tie. Usually you would use the key of the table. I'm not sure what the key is for your dbo.Buyer table. But whatever it is, or whichever combination of fields are unique, you can update the ROW_NUMBER() clause like so ROW_NUMBER() OVER (ORDER BY TotalOrderedPerBeer DESC, UnqiueSetOfFields). Then those fields would be used to determine the winning row(s) in a tie. Alternatively, if when there are ties for top 3, and you want to exclude all of those ties as well, you can use a different window function such as DENSE_RANK() like so: WITH _BuyersTotalsRanked AS ( SELECT BeerId, DENSE_RANK() OVER (ORDER BY TotalOrderedPerBeer DESC) AS BuyersRanked FROM ( SELECT BeerId, SUM(Quantity) AS TotalOrderedPerBeer FROM dbo.Buyer GROUP BY BuyId, BeerId ) AS BuyersTotals ) SELECT DISTINCT BeerId -- Same BeerId might've been ordered by different Buyers FROM _BuyersTotalsRanked WHERE BuyersRanked > 3 -- Filter out the top 3 Buyers Beers DENSE_RANK() will enumerate all tied rows with the same value, instead of randomly deciding which one comes first like ROW_NUMBER() does. Finally, your question (and data / schema) is a little unclear. Based on your example code, I'm interpreting that what you're asking for is to exclude the top 3 Buyers of any single Beer, not top 3 by their told purchases of all Beers. E.g. Buyer1 may have only purchased one type of beer, BeerA for a quantity of 50, but Buyer2 purchased two types of beer, BeerB for 30, and BeerC for 40. In the above code (and your attempted code) Buyer1 would be ranked #1 even though Buyer2 has a greater total purchase of Beers, totaling 70. If you wanted to rank the Buyers by their total purchases across all Beers, then you'd want to do something like the following: WITH _BuyersTotalsRanked AS ( SELECT BuyId, DENSE_RANK() OVER (ORDER BY TotalOrderedAll DESC) AS BuyersRanked FROM ( SELECT BuyId, SUM(Quantity) AS TotalOrderedAll FROM dbo.Buyer GROUP BY BuyId ) AS BuyersTotals ) SELECT DISTINCT B.BeerId -- Same BeerId might've been ordered by different Buyers FROM dbo.Buyer AS B INNER JOIN _BuyersTotalsRanked AS BTR ON B.BuyId = BTR.BuyId WHERE B.BuyersRanked > 3 -- Filter out the top 3 Buyers Beers A: select top (3)BeerId from ( SELECT BeerId, SUM(Quantity) Be.BeerId FROM Beer be left outer join Buyer bu ON be.BeerId=bu.BeerId Group by BeerId) my_derived_table ORDER BY BeerId
How to get values from one table that are not being used by top 3 results in another table?
I need to figure out what beers from table 'Beer' were not ordered by top 3 buyers from table 'Buyers'. Beer.BeerId is foreign key in Buyers.BeerId. Other important columns in 'Buyers' are: BuyId, PubId, StoreId and Quantity dbo.Beer BeerId 1 2 3 4 5 dbo.Buyers BuyId PubId StoreId BeerId Quantity 1 1 NULL 1 30 2 NULL 1 2 40 3 2 NULL 3 50 4 NULL 2 4 10 I tried doing this query but it gives me no results. SELECT Be.BeerId FROM Beer be left outer join Buyer bu ON be.BeerId=bu.BeerId WHERE not exists ( SELECT TOP(3) BuyId, bu.BeerId, SUM(Quantity) as TotalOrdered FROM Buyer bu GROUP BY BuyId, bu.BeerId ORDER BY SUM(Quantity) DESC) What I would expect to see is that from the top 3 results, beers that are not ordered are BeerId=4 and BeerId=5
[ "This seems like a classic window function problem. You can use ROW_NUMBER() to enumerate the rows in order of their Quantity totals descending, and filter out the top 3 like so:\nWITH _BuyersTotalsRanked AS\n(\n SELECT \n BeerId, -- Same BeerId might've been ordered by different Buyers\n ROW_NUMBER() OVER (ORDER BY TotalOrderedPerBeer DESC) AS BuyersRanked\n FROM \n (\n SELECT \n BeerId, \n SUM(Quantity) AS TotalOrderedPerBeer\n FROM dbo.Buyer\n GROUP BY BuyId, BeerId\n ) AS BuyersTotals\n)\n\nSELECT DISTINCT BeerId -- Same BeerId might've been ordered by different Buyers\nFROM _BuyersTotalsRanked\nWHERE BuyersRanked > 3 -- Filter out the top 3 Buyers Beers\n\nNote that if there's a tie for the top 3, this will return nondeterminsitic (semi-random) results because of the ORDER BY clause in the ROW_NUMBER() function not being unique (same problem with your ORDER BY clause in your example query).\nTo correct that, you would need to add a uniquifying field to deterministically decide which row wins in a tie. Usually you would use the key of the table. I'm not sure what the key is for your dbo.Buyer table. But whatever it is, or whichever combination of fields are unique, you can update the ROW_NUMBER() clause like so ROW_NUMBER() OVER (ORDER BY TotalOrderedPerBeer DESC, UnqiueSetOfFields). Then those fields would be used to determine the winning row(s) in a tie.\n\nAlternatively, if when there are ties for top 3, and you want to exclude all of those ties as well, you can use a different window function such as DENSE_RANK() like so:\nWITH _BuyersTotalsRanked AS\n(\n SELECT \n BeerId,\n DENSE_RANK() OVER (ORDER BY TotalOrderedPerBeer DESC) AS BuyersRanked\n FROM \n (\n SELECT \n BeerId, \n SUM(Quantity) AS TotalOrderedPerBeer\n FROM dbo.Buyer\n GROUP BY BuyId, BeerId\n ) AS BuyersTotals\n)\n\nSELECT DISTINCT BeerId -- Same BeerId might've been ordered by different Buyers\nFROM _BuyersTotalsRanked\nWHERE BuyersRanked > 3 -- Filter out the top 3 Buyers Beers\n\nDENSE_RANK() will enumerate all tied rows with the same value, instead of randomly deciding which one comes first like ROW_NUMBER() does.\n\nFinally, your question (and data / schema) is a little unclear. Based on your example code, I'm interpreting that what you're asking for is to exclude the top 3 Buyers of any single Beer, not top 3 by their told purchases of all Beers. E.g. Buyer1 may have only purchased one type of beer, BeerA for a quantity of 50, but Buyer2 purchased two types of beer, BeerB for 30, and BeerC for 40. In the above code (and your attempted code) Buyer1 would be ranked #1 even though Buyer2 has a greater total purchase of Beers, totaling 70.\nIf you wanted to rank the Buyers by their total purchases across all Beers, then you'd want to do something like the following:\nWITH _BuyersTotalsRanked AS\n(\n SELECT \n BuyId,\n DENSE_RANK() OVER (ORDER BY TotalOrderedAll DESC) AS BuyersRanked\n FROM \n (\n SELECT \n BuyId, \n SUM(Quantity) AS TotalOrderedAll\n FROM dbo.Buyer\n GROUP BY BuyId\n ) AS BuyersTotals\n)\n\nSELECT DISTINCT B.BeerId -- Same BeerId might've been ordered by different Buyers\nFROM dbo.Buyer AS B\nINNER JOIN _BuyersTotalsRanked AS BTR\n ON B.BuyId = BTR.BuyId\nWHERE B.BuyersRanked > 3 -- Filter out the top 3 Buyers Beers\n\n", "select top (3)BeerId \nfrom (\nSELECT BeerId, SUM(Quantity) Be.BeerId\n FROM Beer be\n left outer join Buyer bu\n ON be.BeerId=bu.BeerId\nGroup by BeerId) my_derived_table\nORDER BY BeerId\n\n" ]
[ 0, 0 ]
[]
[]
[ "sql", "sql_server", "sql_server_2019", "subquery" ]
stackoverflow_0074666005_sql_sql_server_sql_server_2019_subquery.txt
Q: switch case matching with array index value I have this function in which I want to assign the values of img array that has 1 to 4 numbers, and I want to put red,yellow,green,blue into array matrixColored, but when I use switch case it gives erros in 4th line, help me thanks. def colorPrint(): for i in range(r): for j in range(c): match img[i][j]: case 1: matrixColored[i][j] = 'red' case 2: matrixColored[i][j] = 'green' case 3: matrixColored[i][j] = 'blue' case 4: matrixColored[i][j] = 'yellow' case _: return "something went wrong" A: Can't say what the problem is without the error message but, match is not the only way to do this. Here's an example using a dictionary: colorDict = {1:'red', 2:'green', 3:'blue', 4:'yellow'} img = 3 color = colorDict.get(img) if img in colorDict: matrixColored = colorDict[img] print(matrixColored) else: print('something went wrong') In your code example, this would transpose to : def colorPrint(): colorDict = {1:'red', 2:'green', 3:'blue', 4:'yellow'} for i in range(r): for j in range(c): if img[i][j] in colorDict: matrixColored[i][j] = colorDict[img[i][j]] else: print('something went wrong')
switch case matching with array index value
I have this function in which I want to assign the values of img array that has 1 to 4 numbers, and I want to put red,yellow,green,blue into array matrixColored, but when I use switch case it gives erros in 4th line, help me thanks. def colorPrint(): for i in range(r): for j in range(c): match img[i][j]: case 1: matrixColored[i][j] = 'red' case 2: matrixColored[i][j] = 'green' case 3: matrixColored[i][j] = 'blue' case 4: matrixColored[i][j] = 'yellow' case _: return "something went wrong"
[ "Can't say what the problem is without the error message but, match is not the only way to do this.\nHere's an example using a dictionary:\ncolorDict = {1:'red', 2:'green', 3:'blue', 4:'yellow'}\n\nimg = 3\ncolor = colorDict.get(img)\nif img in colorDict:\n matrixColored = colorDict[img]\n print(matrixColored)\nelse:\n print('something went wrong')\n\nIn your code example, this would transpose to :\ndef colorPrint():\n colorDict = {1:'red', 2:'green', 3:'blue', 4:'yellow'}\n for i in range(r):\n for j in range(c):\n if img[i][j] in colorDict:\n matrixColored[i][j] = colorDict[img[i][j]]\n else:\n print('something went wrong')\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "for_loop", "indexing", "python", "range" ]
stackoverflow_0074644591_arrays_for_loop_indexing_python_range.txt
Q: Android Webview is not loading redirected url I am try to load URL which internally redirect another URL in android WebView, but it is showing blank page. I have checked and found that I am trying to load http://erp1.stmarysschoolbxr.org/StudentReportCard.aspx?card=admitcard&AdmNo=22L001 which indirect to another URL http://erp1.stmarysschoolbxr.org/ReportPage.aspx but it is showing blank page. But when I try to load it in browser, it is loading fine. Below is my webview code binding.webView.getSettings().setJavaScriptEnabled(true); binding.webView.getSettings().setLoadWithOverviewMode(true); binding.webView.getSettings().setUseWideViewPort(true); binding.webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, final String url) { hideLoader(); } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); hideLoader(); } }); binding.webView.loadUrl(url); } A: According to WebView doc: Note: Do not call WebView#loadUrl(String) with the request's URL and then return true. This unnecessarily cancels the current load and starts a new load with the same URL. The correct way to continue loading a given URL is to simply return false, without calling WebView#loadUrl(String). just return false in shouldOverrideUrlLoading without callingview.loadUrl(url);
Android Webview is not loading redirected url
I am try to load URL which internally redirect another URL in android WebView, but it is showing blank page. I have checked and found that I am trying to load http://erp1.stmarysschoolbxr.org/StudentReportCard.aspx?card=admitcard&AdmNo=22L001 which indirect to another URL http://erp1.stmarysschoolbxr.org/ReportPage.aspx but it is showing blank page. But when I try to load it in browser, it is loading fine. Below is my webview code binding.webView.getSettings().setJavaScriptEnabled(true); binding.webView.getSettings().setLoadWithOverviewMode(true); binding.webView.getSettings().setUseWideViewPort(true); binding.webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, final String url) { hideLoader(); } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); hideLoader(); } }); binding.webView.loadUrl(url); }
[ "According to WebView doc:\nNote: Do not call WebView#loadUrl(String) with the request's URL and then return true. \nThis unnecessarily cancels the current load and starts a new load with the same URL. \nThe correct way to continue loading a given URL is to simply return false, \nwithout calling WebView#loadUrl(String).\n\njust return false in shouldOverrideUrlLoading without callingview.loadUrl(url);\n" ]
[ 0 ]
[]
[]
[ "android", "android_webview" ]
stackoverflow_0074664149_android_android_webview.txt
Q: Which proxy mode to use if host company terminates TLS on reverse proxy Friendly Disclaimer: I am new to working with Keycloak and IdP in general. So it's likely that I use incorrect terminology and/or am more confused than I think I am. Corrections are gratefully accepted. My question is conceptual. I have a TLS certificate that is terminated on my host machine by my host company. My reverse proxy (Traefik) is picking up that certificate. Which of the following proxy modes should I use now to be able to deploy Keycloak to production: edge, reencrypt or passthrough? (see here for relevant documentation) I can pretty much rule out passthrough, because as I wrote, the TLS certificate is terminated on the server. But I am unsure if I have to bring my own certificate and reencrypt or if it is considered safe to go along with edge? I have done my best to keep this question short and general. However, I am happy to share configurations or further details if needed. A: As far as I know, most organizations consider a request to be safe when the proxy validated and terminated the TLS. It also removes the performance overhead (depends on your load). Unless your organization is going for Zero Trust for its internal network, using the edge should be totally acceptable.
Which proxy mode to use if host company terminates TLS on reverse proxy
Friendly Disclaimer: I am new to working with Keycloak and IdP in general. So it's likely that I use incorrect terminology and/or am more confused than I think I am. Corrections are gratefully accepted. My question is conceptual. I have a TLS certificate that is terminated on my host machine by my host company. My reverse proxy (Traefik) is picking up that certificate. Which of the following proxy modes should I use now to be able to deploy Keycloak to production: edge, reencrypt or passthrough? (see here for relevant documentation) I can pretty much rule out passthrough, because as I wrote, the TLS certificate is terminated on the server. But I am unsure if I have to bring my own certificate and reencrypt or if it is considered safe to go along with edge? I have done my best to keep this question short and general. However, I am happy to share configurations or further details if needed.
[ "As far as I know, most organizations consider a request to be safe when the proxy validated and terminated the TLS. It also removes the performance overhead (depends on your load). Unless your organization is going for Zero Trust for its internal network, using the edge should be totally acceptable.\n" ]
[ 1 ]
[]
[]
[ "keycloak", "reverse_proxy", "ssl", "tls1.2", "traefik" ]
stackoverflow_0074606650_keycloak_reverse_proxy_ssl_tls1.2_traefik.txt
Q: No user defined conversion when using standard variants and visitor pattern Could you please help me figure out why is this not working i.e. refering to the comment in the code //I need to do this but I can't. I thought this the goal!? I have no idea why this is not working, it's inspired by examples I have seen online. #include <variant> #include <iostream> template<typename... args> class Visitor //: public boost_base_visitor<double>... { public: virtual ~Visitor() = default; virtual double visit(typename std::variant<args...> visitable) { auto op = [this](typename std::variant<args...> visitable) -> double { return this->apply(visitable); }; return std::visit(std::ref(op), visitable); } virtual double apply(typename std::variant<args...> visitable) = 0; Visitor() = default; }; class SubVisitor : public Visitor<std::string, double> { public: virtual ~SubVisitor() = default; SubVisitor() : Visitor<std::string, double>() {}; virtual double apply(std::variant<std::string, double> visitable) override { //return process(visitable); //I need to do this but I can't. I thought this the goal! return process(std::get<std::string>(visitable)); //I DON'T KNOW IF THIS IS REALLY A STRING?? }; virtual double process(std::string visitable) { std::cout << "STRING HANDLED" << std::endl; return 0.0; } virtual double process(double visitable) { std::cout << "DOUBLE HANDLED" << std::endl; return 1.0; } }; int main(int argc, char* argv[]) { SubVisitor v; v.apply("dd"); //v.apply(1.0); //This will fail as we only handle string?? What is the purpose of variant then? return 1; } I am getting error when uncommenting the process function above: Error C2664: 'double SubVisitor::process(std::string)': cannot convert argument 1 from 'std::variantstd::string,double' to 'std::string' A: you can use std:visit to operate on the variant class SubVisitor{ virtual double apply(std::variant<std::string, double> visitable) override { // std::visit expect `operator()`, not `process` // so wrap `this` inside a lambda here return std::visit( [this](auto&& v){return process(v);}, visitable ); }; } or if you want, you can also check the type manually class SubVisitor{ virtual double apply(std::variant<std::string, double> visitable) override { if(auto* s = std::get_if<std::string>(&visitable)) return process(*s); else if(auto* d = std::get_if<double>(&visitable)) return process(*d); throw std::bad_variant_access(); } }; A: in addition to the answer, imo the base class should be something like template<typename... args> class Visitor{ public: Visitor() = default; virtual ~Visitor() = default; // this should be non-virtual double visit(std::variant<args...> visitable) { // dispatch via the customization point `this->apply` return this->apply(visitable); } virtual double apply(std::variant<args...> visitable) = 0; };
No user defined conversion when using standard variants and visitor pattern
Could you please help me figure out why is this not working i.e. refering to the comment in the code //I need to do this but I can't. I thought this the goal!? I have no idea why this is not working, it's inspired by examples I have seen online. #include <variant> #include <iostream> template<typename... args> class Visitor //: public boost_base_visitor<double>... { public: virtual ~Visitor() = default; virtual double visit(typename std::variant<args...> visitable) { auto op = [this](typename std::variant<args...> visitable) -> double { return this->apply(visitable); }; return std::visit(std::ref(op), visitable); } virtual double apply(typename std::variant<args...> visitable) = 0; Visitor() = default; }; class SubVisitor : public Visitor<std::string, double> { public: virtual ~SubVisitor() = default; SubVisitor() : Visitor<std::string, double>() {}; virtual double apply(std::variant<std::string, double> visitable) override { //return process(visitable); //I need to do this but I can't. I thought this the goal! return process(std::get<std::string>(visitable)); //I DON'T KNOW IF THIS IS REALLY A STRING?? }; virtual double process(std::string visitable) { std::cout << "STRING HANDLED" << std::endl; return 0.0; } virtual double process(double visitable) { std::cout << "DOUBLE HANDLED" << std::endl; return 1.0; } }; int main(int argc, char* argv[]) { SubVisitor v; v.apply("dd"); //v.apply(1.0); //This will fail as we only handle string?? What is the purpose of variant then? return 1; } I am getting error when uncommenting the process function above: Error C2664: 'double SubVisitor::process(std::string)': cannot convert argument 1 from 'std::variantstd::string,double' to 'std::string'
[ "you can use std:visit to operate on the variant\nclass SubVisitor{\n virtual double apply(std::variant<std::string, double> visitable) override\n {\n // std::visit expect `operator()`, not `process`\n // so wrap `this` inside a lambda here\n return std::visit( \n [this](auto&& v){return process(v);},\n visitable\n );\n };\n}\n\n\nor if you want, you can also check the type manually\nclass SubVisitor{\n virtual double apply(std::variant<std::string, double> visitable) override\n {\n if(auto* s = std::get_if<std::string>(&visitable))\n return process(*s);\n \n else if(auto* d = std::get_if<double>(&visitable))\n return process(*d);\n\n throw std::bad_variant_access();\n }\n};\n\n", "in addition to the answer, imo the base class should be something like\ntemplate<typename... args>\nclass Visitor{\npublic:\n Visitor() = default;\n virtual ~Visitor() = default;\n\n // this should be non-virtual\n double visit(std::variant<args...> visitable)\n {\n // dispatch via the customization point `this->apply`\n return this->apply(visitable);\n }\n virtual double apply(std::variant<args...> visitable) = 0;\n};\n\n" ]
[ 2, 1 ]
[]
[]
[ "c++", "compiler_errors", "templates", "variant", "visitor_pattern" ]
stackoverflow_0074667477_c++_compiler_errors_templates_variant_visitor_pattern.txt
Q: Trying to run the multiple powershell scripts from wix installer Here I have tried something but it dose not work at all can anyone guide me how to run the multiple scripts from installer <SetProperty Id="PS1" Before="PS1" Sequence="execute" Value ="&quot;C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe&quot;-NoLogo -NonInteractive -ExecutionPolicy Bypass -InputFormat None -NoProfile -File &quot;-Command &quot;cd '[INSTALLLOCATION]'; &amp; '[#ps1]' ; exit $$($Error.Count)&quot;" /> <CustomAction Id="PS1" BinaryKey="WixCA" DllEntry="WixQuietExec" Execute="deferred" Return="check" Impersonate="no" /> <InstallExecuteSequence> <Custom Action="PS1" After='InstallFiles'> <![CDATA[NOT Installed]]> </Custom> </InstallExecuteSequence> to destination folder files get copied but it said like this why I dont know ,Inside a log file it shows like this WixQuietExec: Processing -File '-Command cd' failed because the file does not have a '.ps1' extension. Specify a valid Windows PowerShell script file name, and then try again. WixQuietExec: Windows PowerShell WixQuietExec: Copyright (C) Microsoft Corporation. All rights reserved. WixQuietExec: WixQuietExec: Try the new cross-platform PowerShell https://aka.ms/pscore6 WixQuietExec: WixQuietExec: Error 0xfffd0000: Command line returned an error. WixQuietExec: Error 0xfffd0000: QuietExec Failed WixQuietExec: Error 0xfffd0000: Failed in ExecCommon method CustomAction PS1 returned actual error code 1603 (note this may not be 100% accurate if translation happened inside sandbox) A: This doesn't always happen, but the error message is pretty clear. Here it is word-wrapped, so it is easier to read: WixQuietExec: Processing -File '-Command cd' failed because the file does not have a '.ps1' extension. Specify a valid Windows PowerShell script file name, and then try again. That's a PowerShell error message.
Trying to run the multiple powershell scripts from wix installer
Here I have tried something but it dose not work at all can anyone guide me how to run the multiple scripts from installer <SetProperty Id="PS1" Before="PS1" Sequence="execute" Value ="&quot;C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe&quot;-NoLogo -NonInteractive -ExecutionPolicy Bypass -InputFormat None -NoProfile -File &quot;-Command &quot;cd '[INSTALLLOCATION]'; &amp; '[#ps1]' ; exit $$($Error.Count)&quot;" /> <CustomAction Id="PS1" BinaryKey="WixCA" DllEntry="WixQuietExec" Execute="deferred" Return="check" Impersonate="no" /> <InstallExecuteSequence> <Custom Action="PS1" After='InstallFiles'> <![CDATA[NOT Installed]]> </Custom> </InstallExecuteSequence> to destination folder files get copied but it said like this why I dont know ,Inside a log file it shows like this WixQuietExec: Processing -File '-Command cd' failed because the file does not have a '.ps1' extension. Specify a valid Windows PowerShell script file name, and then try again. WixQuietExec: Windows PowerShell WixQuietExec: Copyright (C) Microsoft Corporation. All rights reserved. WixQuietExec: WixQuietExec: Try the new cross-platform PowerShell https://aka.ms/pscore6 WixQuietExec: WixQuietExec: Error 0xfffd0000: Command line returned an error. WixQuietExec: Error 0xfffd0000: QuietExec Failed WixQuietExec: Error 0xfffd0000: Failed in ExecCommon method CustomAction PS1 returned actual error code 1603 (note this may not be 100% accurate if translation happened inside sandbox)
[ "This doesn't always happen, but the error message is pretty clear. Here it is word-wrapped, so it is easier to read:\nWixQuietExec: Processing -File '-Command cd' failed because \n the file does not have a '.ps1' extension. \n Specify a valid Windows PowerShell script file\n name, and then try again.\n\nThat's a PowerShell error message.\n" ]
[ 0 ]
[]
[]
[ "installation", "windows", "wix3.5", "wix3.6", "wix3.7" ]
stackoverflow_0074657930_installation_windows_wix3.5_wix3.6_wix3.7.txt
Q: How would I use regular expression to match a word with at least 5 characters with 's' as the last one? I'm trying to use regex to match: a word that's at least 5 characters long and ends with an 's', but the 's' is included in the 5 characters. Say for example, I have the following words: hexes pixies major prairies caveman zipfiles oxes I tried doing ([a-z]s?){5,} A: The pattern ([a-z]s?){5,} repeats 5 or more times a character in the range a-z followed by an optional s char If you only want to match characters a-z and "words" are determined by word boundaries \b, you can match 4 or more times the range a-z and end the match with an s char \b[a-z]{4,}s\b Regex demo A: To add to The fourth bird's answer: if you also want to match for capital letters, add A-Z like this: \b[A-Za-z]{4,}s\b You can also match for special alphabetical characters like (æøåäöüß...) with À-ȕ, like this: \b[A-Za-zÀ-ȕ]{4,}s\b Regex demo
How would I use regular expression to match a word with at least 5 characters with 's' as the last one?
I'm trying to use regex to match: a word that's at least 5 characters long and ends with an 's', but the 's' is included in the 5 characters. Say for example, I have the following words: hexes pixies major prairies caveman zipfiles oxes I tried doing ([a-z]s?){5,}
[ "The pattern ([a-z]s?){5,} repeats 5 or more times a character in the range a-z followed by an optional s char\nIf you only want to match characters a-z and \"words\" are determined by word boundaries \\b, you can match 4 or more times the range a-z and end the match with an s char\n\\b[a-z]{4,}s\\b\n\nRegex demo\n", "To add to The fourth bird's answer: if you also want to match for capital letters, add A-Z like this:\n\\b[A-Za-z]{4,}s\\b\n\nYou can also match for special alphabetical characters like (æøåäöüß...) with À-ȕ, like this:\n\\b[A-Za-zÀ-ȕ]{4,}s\\b\n\nRegex demo\n" ]
[ 2, 0 ]
[]
[]
[ "regex" ]
stackoverflow_0074667424_regex.txt
Q: How do I entry every single 1 min bar after a certain delay (like 6 sec) in pinescript? Im building a strategy on pinescript that entries in every single candle in the minute timeframe, and of course exit before the close, and the entry should happen after a short delay after the open of the candle has formed, anyone has any idea how to do this? pls help cause I cant find how anywhere on the internet, I really need a solution A: You cannot do that in a strategy. It is also not so easy with an indicator. You should use timenow built-in variable and get the current time in UNIX format which will be in milliseconds. Then find the difference between open time and current time in milliseconds and convert it to seconds. You should also be using a varip variable to see if 6 seconds has elapsed and if you entered a position. You need a varip because you want this variable(s) to keep their value(s) between the updates of a real-time bar.
How do I entry every single 1 min bar after a certain delay (like 6 sec) in pinescript?
Im building a strategy on pinescript that entries in every single candle in the minute timeframe, and of course exit before the close, and the entry should happen after a short delay after the open of the candle has formed, anyone has any idea how to do this? pls help cause I cant find how anywhere on the internet, I really need a solution
[ "You cannot do that in a strategy.\nIt is also not so easy with an indicator.\nYou should use timenow built-in variable and get the current time in UNIX format which will be in milliseconds. Then find the difference between open time and current time in milliseconds and convert it to seconds.\nYou should also be using a varip variable to see if 6 seconds has elapsed and if you entered a position. You need a varip because you want this variable(s) to keep their value(s) between the updates of a real-time bar.\n" ]
[ 0 ]
[]
[]
[ "pine_script", "pinescript_v5", "tradingview_api" ]
stackoverflow_0074667817_pine_script_pinescript_v5_tradingview_api.txt
Q: I want to blur the back surface using filtering and make the middle part normal <style> .Parallax{ width:100vw; height: 100vh; background-repeat: no-repeat; background-size: cover; background-position: center; } .ImageLayer { width: 80%; height: 80%; backdrop-filter:blur(10px); position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> <div class="Parallax" style="background-image: url('https://images.pexels.com/photos/2478248/pexels-photo-2478248.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1')"> <div class="ImageLayer"></div> </div> The output of the code makes the middle part blurry, and I want to do the opposite. I tried a few times but it didn't turn out the way I wanted. I wrote this code just as an example A: Perhaps you'll need another layer of image .Parallax-blur { position: relative; width: 100vw; height: 100vh; background-repeat: no-repeat; background-size: cover; background-position: center; background-image: url('https://images.pexels.com/photos/2478248/pexels-photo-2478248.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1'); filter: blur(10px); clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%); } .Parallax { position: absolute; width: 100vw; height: 100vh; top: 0; left: 0; background-repeat: no-repeat; background-size: cover; background-position: center; background-image: url('https://images.pexels.com/photos/2478248/pexels-photo-2478248.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1'); z-index: 1; } .ImageLayer { width: 80%; height: 80%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 2; } <div class="Parallax"> <div class="Parallax-blur"> <div class="ImageLayer"></div> </div> </div> For clip-path values, check here: https://bennettfeely.com/clippy/
I want to blur the back surface using filtering and make the middle part normal
<style> .Parallax{ width:100vw; height: 100vh; background-repeat: no-repeat; background-size: cover; background-position: center; } .ImageLayer { width: 80%; height: 80%; backdrop-filter:blur(10px); position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> <div class="Parallax" style="background-image: url('https://images.pexels.com/photos/2478248/pexels-photo-2478248.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1')"> <div class="ImageLayer"></div> </div> The output of the code makes the middle part blurry, and I want to do the opposite. I tried a few times but it didn't turn out the way I wanted. I wrote this code just as an example
[ "Perhaps you'll need another layer of image\n\n\n.Parallax-blur {\n position: relative;\n width: 100vw;\n height: 100vh;\n background-repeat: no-repeat;\n background-size: cover;\n background-position: center;\n background-image: url('https://images.pexels.com/photos/2478248/pexels-photo-2478248.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1');\n filter: blur(10px);\n clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%);\n}\n\n.Parallax {\n position: absolute;\n width: 100vw;\n height: 100vh;\n top: 0;\n left: 0;\n background-repeat: no-repeat;\n background-size: cover;\n background-position: center;\n background-image: url('https://images.pexels.com/photos/2478248/pexels-photo-2478248.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1');\n z-index: 1;\n}\n\n.ImageLayer {\n width: 80%;\n height: 80%;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n z-index: 2;\n}\n<div class=\"Parallax\">\n <div class=\"Parallax-blur\">\n <div class=\"ImageLayer\"></div>\n </div>\n</div>\n\n\n\nFor clip-path values, check here:\nhttps://bennettfeely.com/clippy/\n" ]
[ 0 ]
[]
[]
[ "background", "blur", "css", "filter" ]
stackoverflow_0074667708_background_blur_css_filter.txt
Q: How to create Aggregate UDF in Oracle PL/SQL Say I have a table: CREATE TABLE staff ( id INT, name CHAR(9) ); With data: INSERT INTO staff (id, name) VALUES (1, 'Joe'); INSERT INTO staff (id, name) VALUES (2, 'Bob'); INSERT INTO staff (id, name) VALUES (3, 'Alice'); I need to create a multi row UDF, something like the built-in AVG function, such that I can call it in the following manner: SELECT vowel_count(name) FROM staff; And assuming vowels are [AaEeIiOoUu], get the following result: | vowel_count(name) | |-------------------| | 6 | What is the syntax to take a table column as input to a UDF? CREATE OR REPLACE FUNCTION vowel_cnt(/* what goes here? */) RETURN NUMBER IS ... BEGIN ... END; The function must be table agnostic, just like SUM, AVG, etc. I am using Oracle PL/SQL and SQL Developer. A: As @WilliamRoberston said, you can define your own aggregate function with OCI Data Cartridge. Partly because I haven't done this for a while and wanted to remind myself, here's a working implementation to count vowels. First, create an object type with the required functions, and a numeric variable to hold the total count: create or replace type t_vowel_count as object ( g_count number, static function ODCIAggregateInitialize( p_ctx in out t_vowel_count ) return number, member function ODCIAggregateIterate( self in out t_vowel_count, p_string varchar2 ) return number, member function ODCIAggregateTerminate( self in out t_vowel_count, p_result out number, p_flags in number ) return number, member function ODCIAggregateMerge( self in out t_vowel_count, p_ctx in t_vowel_count ) return number ); / Then create the type body, with - in this case - fairly straightforward function bodies: create or replace type body t_vowel_count as static function ODCIAggregateInitialize( p_ctx in out t_vowel_count ) return number is begin p_ctx := t_vowel_count(null); -- initialise count to zero p_ctx.g_count := 0; return ODCIConst.success; end ODCIAggregateInitialize; member function ODCIAggregateIterate( self in out t_vowel_count, p_string varchar2 ) return number is begin -- regex is clearer... -- self.g_count := self.g_count + regexp_count(p_string, '[aeiou]', 1, 'i'); -- but translate is faster... self.g_count := self.g_count + coalesce(length(p_string), 0) - coalesce(length(translate(p_string, 'xaAeEiIoOuU', 'x')), 0); return ODCIConst.success; end ODCIAggregateIterate; member function ODCIAggregateTerminate( self in out t_vowel_count, p_result out number, p_flags in number ) return number is begin p_result := self.g_count; return ODCIConst.success; end ODCIAggregateTerminate; member function ODCIAggregateMerge( self in out t_vowel_count, p_ctx in t_vowel_count ) return number is begin self.g_count := self.g_count + p_ctx.g_count; return ODCIConst.success; end ODCIAggregateMerge; end t_vowel_count; / The count of vowels in each individual string could be done in various ways; regular expressions are clear but slow, so I've shown a translate() version which should be fast. I've included @MTO's suggestion to wrap that in coalesce for a null result (for the edge case where the string consists only of vowels, and also to handle null inputs (though it gets the right result without those changes; it's safer to assume it might not one day...). And finally create the function that uses that type: create or replace function vowel_count (p_string varchar2) return number parallel_enable aggregate using t_vowel_count; / With your sample data you can now do: SELECT vowel_count(name) FROM staff; VOWEL_COUNT(NAME) 6 fiddle including the edge cases. A: Don't write a custom aggregation function. Write a scalar function: CREATE FUNCTION vowel_count( value IN VARCHAR2 ) RETURN NUMBER DETERMINISTIC IS BEGIN RETURN LENGTH(value) - COALESCE(LENGTH(TRANSLATE(value, '_AaEeIiOoUu', '_')), 0); END; / Then, if you want to aggregate an entire column you can use: SELECT SUM(vowel_count(name)) AS total_vowel_count FROM staff; Which, for the sample data: CREATE TABLE staff (id, name) AS SELECT 1, 'Alice' FROM DUAL UNION ALL SELECT 2, 'Betty' FROM DUAL UNION ALL SELECT 3, 'Carol' FROM DUAL UNION ALL SELECT 4, 'Aeia' FROM DUAL; Outputs: TOTAL_VOWEL_COUNT 10 Then if you want to find the minimum, maximum, average, etc. number of vowels then you can easily find it using the scalar function and wrapping it with a built-in aggregation function rather than having to create many different user-defined aggregation functions for each individual use-case. fiddle
How to create Aggregate UDF in Oracle PL/SQL
Say I have a table: CREATE TABLE staff ( id INT, name CHAR(9) ); With data: INSERT INTO staff (id, name) VALUES (1, 'Joe'); INSERT INTO staff (id, name) VALUES (2, 'Bob'); INSERT INTO staff (id, name) VALUES (3, 'Alice'); I need to create a multi row UDF, something like the built-in AVG function, such that I can call it in the following manner: SELECT vowel_count(name) FROM staff; And assuming vowels are [AaEeIiOoUu], get the following result: | vowel_count(name) | |-------------------| | 6 | What is the syntax to take a table column as input to a UDF? CREATE OR REPLACE FUNCTION vowel_cnt(/* what goes here? */) RETURN NUMBER IS ... BEGIN ... END; The function must be table agnostic, just like SUM, AVG, etc. I am using Oracle PL/SQL and SQL Developer.
[ "As @WilliamRoberston said, you can define your own aggregate function with OCI Data Cartridge.\nPartly because I haven't done this for a while and wanted to remind myself, here's a working implementation to count vowels.\nFirst, create an object type with the required functions, and a numeric variable to hold the total count:\ncreate or replace type t_vowel_count as object (\n g_count number,\n static function ODCIAggregateInitialize(\n p_ctx in out t_vowel_count\n ) return number,\n member function ODCIAggregateIterate(\n self in out t_vowel_count, p_string varchar2\n ) return number,\n member function ODCIAggregateTerminate(\n self in out t_vowel_count, p_result out number, p_flags in number\n ) return number,\n member function ODCIAggregateMerge(\n self in out t_vowel_count, p_ctx in t_vowel_count\n ) return number\n);\n/\n\nThen create the type body, with - in this case - fairly straightforward function bodies:\ncreate or replace type body t_vowel_count as\n static function ODCIAggregateInitialize(\n p_ctx in out t_vowel_count\n ) return number is\n begin\n p_ctx := t_vowel_count(null);\n -- initialise count to zero\n p_ctx.g_count := 0;\n return ODCIConst.success;\n end ODCIAggregateInitialize;\n\n member function ODCIAggregateIterate(\n self in out t_vowel_count, p_string varchar2\n ) return number is\n begin\n -- regex is clearer...\n -- self.g_count := self.g_count + regexp_count(p_string, '[aeiou]', 1, 'i');\n -- but translate is faster...\n self.g_count := self.g_count\n + coalesce(length(p_string), 0)\n - coalesce(length(translate(p_string, 'xaAeEiIoOuU', 'x')), 0);\n return ODCIConst.success;\n end ODCIAggregateIterate;\n\n member function ODCIAggregateTerminate(\n self in out t_vowel_count, p_result out number, p_flags in number\n ) return number is\n begin\n p_result := self.g_count;\n return ODCIConst.success;\n end ODCIAggregateTerminate;\n\n member function ODCIAggregateMerge(\n self in out t_vowel_count, p_ctx in t_vowel_count\n ) return number is\n begin\n self.g_count := self.g_count + p_ctx.g_count;\n return ODCIConst.success;\n end ODCIAggregateMerge;\nend t_vowel_count;\n/\n\nThe count of vowels in each individual string could be done in various ways; regular expressions are clear but slow, so I've shown a translate() version which should be fast. I've included @MTO's suggestion to wrap that in coalesce for a null result (for the edge case where the string consists only of vowels, and also to handle null inputs (though it gets the right result without those changes; it's safer to assume it might not one day...).\nAnd finally create the function that uses that type:\ncreate or replace function vowel_count (p_string varchar2)\nreturn number\nparallel_enable\naggregate using t_vowel_count;\n/\n\nWith your sample data you can now do:\nSELECT vowel_count(name) FROM staff;\n\n\n\n\n\nVOWEL_COUNT(NAME)\n\n\n\n\n6\n\n\n\n\nfiddle including the edge cases.\n", "Don't write a custom aggregation function.\nWrite a scalar function:\nCREATE FUNCTION vowel_count(\n value IN VARCHAR2\n) RETURN NUMBER DETERMINISTIC\nIS\nBEGIN\n RETURN LENGTH(value) - COALESCE(LENGTH(TRANSLATE(value, '_AaEeIiOoUu', '_')), 0);\nEND;\n/\n\nThen, if you want to aggregate an entire column you can use:\nSELECT SUM(vowel_count(name)) AS total_vowel_count\nFROM staff;\n\nWhich, for the sample data:\nCREATE TABLE staff (id, name) AS\n SELECT 1, 'Alice' FROM DUAL UNION ALL\n SELECT 2, 'Betty' FROM DUAL UNION ALL\n SELECT 3, 'Carol' FROM DUAL UNION ALL\n SELECT 4, 'Aeia' FROM DUAL;\n\nOutputs:\n\n\n\n\nTOTAL_VOWEL_COUNT\n\n\n\n\n10\n\n\n\n\nThen if you want to find the minimum, maximum, average, etc. number of vowels then you can easily find it using the scalar function and wrapping it with a built-in aggregation function rather than having to create many different user-defined aggregation functions for each individual use-case.\nfiddle\n" ]
[ 4, 1 ]
[ "You can't get your desired result with:\nSELECT vowel_count(name) FROM staff;\n\nbecouse select works row by row meaning that the function will get parameters:\n\n'Joe' for row 1\n'Bob' for row 2\n'Alice' for row 3\nThe result would be:\n\n\n\n\n\nvowel_count(name)\n\n\n\n\n2\n\n\n1\n\n\n3\n\n\n\n\nIf you sum it up afterwords you will get 6.\nHere are 2 functions:\nOne to count vowels from string\nand\nOne to get you count of 6 vowels from table (I named it A_TBL) column \"NAME\"\n...\ncreate or replace Function VOWEL_COUNT_FROM_STRING(p_string VarChar2) RETURN Number IS\nBEGIN\n Declare\n vowels VarChar2(5) := 'AEIOU';\n mRet Number(6) := 0;\n Begin\n For i in 1..Length(p_string) Loop\n If InStr(vowels, SubStr(Upper(p_string), i, 1)) > 0 Then\n mRet := mRet + 1;\n End If;\n End Loop;\n RETURN mRet; \n End;\nEND VOWEL_COUNT_FROM_STRING;\n\n-- ----------------------------------------------------------\n\ncreate or replace Function VOWEL_COUNT RETURN Number IS\nBEGIN\n Declare\n CURSOR c IS SELECT Upper(NAME) FROM A_TBL;\n vowels VarChar2(5) := 'AEIOU';\n mName A_TBL.NAME%TYPE;\n mRet Number(6) := 0;\n Begin\n OPEN c;\n LOOP\n FETCH c InTo mName;\n EXIT WHEN c%NOTFOUND;\n For i in 1..Length(mName) Loop\n If InStr(vowels, SubStr(mName, i, 1)) > 0 Then\n mRet := mRet + 1;\n End If;\n End Loop;\n END LOOP;\n Close c;\n RETURN mRet; \n End;\nEND VOWEL_COUNT;\n\nIf you call them from select statement like here:\nSelect ID, NAME, VOWEL_COUNT_FROM_STRING(NAME) \"VOWELS\", VOWEL_COUNT() \"TOTAL_VOWELS\" From A_TBL\n\n... the result would be\n\n\n\n\nID\nNAME\nVOWELS\nTOTAL_VOWELS\n\n\n\n\n1\nJoe\n2\n6\n\n\n2\nBob\n1\n6\n\n\n3\nAlice\n3\n6\n\n\n\n\nBut, the same result you can get using analytic function Sum() Over() with the first function.\nSelect ID, NAME, VOWEL_COUNT_FROM_STRING(NAME) \"VOWELS\", Sum(VOWEL_COUNT_FROM_STRING(NAME)) OVER() \"TOTAL_VOWELS\" From A_TBL\n\nThe second one is here just as an example as it doesn't make sense anyway for it is fixed to one table and one column of the table.\nIt would make more sense to create function that will count vowels from any table's column:\ncreate or replace Function VOWEL_COUNT_FROM_TABLE_COLUMN(p_table VarChar2, p_column VarChar2) RETURN Number IS\nBEGIN\n Declare\n vowels VarChar2(5) := 'AEIOU';\n mCmd VarChar2(1000);\n mString VarChar2(32000); -- NOTE the limitation in this variable length\n mRet Number(6) := 0;\n Begin\n mCmd := 'Select LISTAGG(' || p_column || ', '','') WITHIN GROUP (Order By ' || p_column || ') From ' || p_table;\n Execute Immediate mCmd Into mString;\n --\n For i in 1..Length(mString) Loop\n If InStr(vowels, SubStr(Upper(mString), i, 1)) > 0 Then\n mRet := mRet + 1;\n End If;\n End Loop;\n --\n RETURN mRet; \n End;\nEND VOWEL_COUNT_FROM_TABLE_COLUMN;\n\nNOTE: there is a limitation using LISTAGG into VarChar2 variable - for many rows or aggregated string too long - the function should be changed to do some looping instead...\nusage in this sample\nSelect VOWEL_COUNT_FROM_TABLE_COLUMN('A_TBL', 'NAME') \"TOTAL_VOWELS\" From Dual;\n\n-- Result:\n-- TOTAL_VOWELS\n-- ------------\n-- 6\n\n" ]
[ -1 ]
[ "oracle", "plsql", "user_defined_functions" ]
stackoverflow_0074663654_oracle_plsql_user_defined_functions.txt
Q: npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use Alright, After quite some reinstalling, reading I still can't figure what is going on. I'm trying to run npm install --force on a codecanyon script, reinstalled node to latest version, same as python and build tools, added VCINSTALLDIR to path, restarted windows multiple times and still the same issue. npm ERR! code 1 npm ERR! path C:\Users\denis\OneDrive\Documents\Website\node_modules\node-sass npm ERR! command failed npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node scripts/build.js npm ERR! Building: C:\Program Files\nodejs\node.exe C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library= npm ERR! gyp info it worked if it ends with ok npm ERR! gyp verb cli [ npm ERR! gyp verb cli 'C:\\Program Files\\nodejs\\node.exe', npm ERR! gyp verb cli 'C:\\Users\\denis\\OneDrive\\Documents\\Website\\node_modules\\node-gyp\\bin\\node-gyp.js', npm ERR! gyp verb cli 'rebuild', npm ERR! gyp verb cli '--verbose', npm ERR! gyp verb cli '--libsass_ext=', npm ERR! gyp verb cli '--libsass_cflags=', npm ERR! gyp verb cli '--libsass_ldflags=', npm ERR! gyp verb cli '--libsass_library=' npm ERR! gyp verb cli ] npm ERR! gyp info using [email protected] npm ERR! gyp info using [email protected] | win32 | x64 npm ERR! gyp verb command rebuild [] npm ERR! gyp verb command clean [] npm ERR! gyp verb clean removing "build" directory npm ERR! gyp verb command configure [] npm ERR! gyp verb find Python checking Python explicitly set from command line or npm configuration npm ERR! gyp verb find Python - "--python=" or "npm config get python" is "C:\Python311\python.exe" npm ERR! gyp verb find Python - executing "C:\Python311\python.exe" to get executable path npm ERR! gyp verb find Python - executable path is "C:\Python311\python.exe" npm ERR! gyp verb find Python - executing "C:\Python311\python.exe" to get version npm ERR! gyp verb find Python - version is "3.11.0" npm ERR! gyp info find Python using Python version 3.11.0 found at "C:\Python311\python.exe" npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 19.2.0 npm ERR! gyp verb command install [ '19.2.0' ] npm ERR! gyp verb install input version string "19.2.0" npm ERR! gyp verb install installing version: 19.2.0 npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed npm ERR! gyp verb install version is already installed, need to check "installVersion" npm ERR! gyp verb got "installVersion" 9 npm ERR! gyp verb needs "installVersion" 9 npm ERR! gyp verb install version is good npm ERR! gyp verb get node dir target node version installed: 19.2.0 npm ERR! gyp verb build dir attempting to create "build" dir: C:\Users\denis\OneDrive\Documents\Website\node_modules\node-sass\build npm ERR! gyp verb build dir "build" dir needed to be created? Yes npm ERR! gyp verb find VS msvs_version was set from command line or npm config npm ERR! gyp verb find VS - looking for Visual Studio version 2022 npm ERR! gyp verb find VS running in VS Command Prompt, installation path is: npm ERR! gyp verb find VS "C:\Program Files (x86)\Microsoft Visual Studio\2022\Community" npm ERR! gyp verb find VS - will only use this version npm ERR! gyp verb find VS checking VS2022 (17.4.33122.133) found at: npm ERR! gyp verb find VS "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools" npm ERR! gyp verb find VS - found "Visual Studio C++ core features" npm ERR! gyp verb find VS - found VC++ toolset: v143 npm ERR! gyp verb find VS - missing any Windows SDK npm ERR! gyp verb find VS could not find a version of Visual Studio 2017 or newer to use npm ERR! gyp verb find VS looking for Visual Studio 2015 npm ERR! gyp verb find VS - not found npm ERR! gyp verb find VS not looking for VS2013 as it is only supported up to Node.js 8 npm ERR! gyp ERR! find VS npm ERR! gyp ERR! find VS msvs_version was set from command line or npm config npm ERR! gyp ERR! find VS - looking for Visual Studio version 2022 npm ERR! gyp ERR! find VS running in VS Command Prompt, installation path is: npm ERR! gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2022\Community" npm ERR! gyp ERR! find VS - will only use this version npm ERR! gyp ERR! find VS checking VS2022 (17.4.33122.133) found at: npm ERR! gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools" npm ERR! gyp ERR! find VS - found "Visual Studio C++ core features" npm ERR! gyp ERR! find VS - found VC++ toolset: v143 npm ERR! gyp ERR! find VS - missing any Windows SDK npm ERR! gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use npm ERR! gyp ERR! find VS looking for Visual Studio 2015 npm ERR! gyp ERR! find VS - not found npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8 npm ERR! gyp ERR! find VS msvs_version does not match this VS Command Prompt or the npm ERR! gyp ERR! find VS installation cannot be used. npm ERR! gyp ERR! find VS npm ERR! gyp ERR! find VS ************************************************************** npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload. npm ERR! gyp ERR! find VS For more information consult the documentation at: npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows npm ERR! gyp ERR! find VS ************************************************************** npm ERR! gyp ERR! find VS npm ERR! gyp ERR! configure error npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use npm ERR! gyp ERR! stack at VisualStudioFinder.fail (C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:122:47) npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:75:16 npm ERR! gyp ERR! stack at VisualStudioFinder.findVisualStudio2013 (C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:363:14) npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:71:14 npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:384:16 npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\util.js:54:7 npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\util.js:33:16 npm ERR! gyp ERR! stack at ChildProcess.exithandler (node:child_process:427:5) npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:513:28) npm ERR! gyp ERR! stack at maybeClose (node:internal/child_process:1098:16) npm ERR! gyp ERR! stack at ChildProcess._handle.onexit (node:internal/child_process:304:5) npm ERR! gyp ERR! System Windows_NT 10.0.22621 npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\denis\\OneDrive\\Documents\\Website\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library=" npm ERR! gyp ERR! cwd C:\Users\denis\OneDrive\Documents\Website\node_modules\node-sass npm ERR! gyp ERR! node -v v19.2.0 npm ERR! gyp ERR! node-gyp -v v8.4.1 npm ERR! gyp ERR! not ok npm ERR! Build failed with error code: 1 System Information Build tools 2022 Installed + SDK for windows 11 Env path Visual Studio Code output of python and msvs_version All mentioned in pictures. A: It seems it has something to do with Windows 11, running a VM of Win10 Pro where it executes perfectly with the latest packages. PS: Windows Build Tools are now embedded in the latest Node, so no need to install them manually. Just Node, Git, Visual Studio Code and restart for PATH to update automatically.
npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use
Alright, After quite some reinstalling, reading I still can't figure what is going on. I'm trying to run npm install --force on a codecanyon script, reinstalled node to latest version, same as python and build tools, added VCINSTALLDIR to path, restarted windows multiple times and still the same issue. npm ERR! code 1 npm ERR! path C:\Users\denis\OneDrive\Documents\Website\node_modules\node-sass npm ERR! command failed npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node scripts/build.js npm ERR! Building: C:\Program Files\nodejs\node.exe C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library= npm ERR! gyp info it worked if it ends with ok npm ERR! gyp verb cli [ npm ERR! gyp verb cli 'C:\\Program Files\\nodejs\\node.exe', npm ERR! gyp verb cli 'C:\\Users\\denis\\OneDrive\\Documents\\Website\\node_modules\\node-gyp\\bin\\node-gyp.js', npm ERR! gyp verb cli 'rebuild', npm ERR! gyp verb cli '--verbose', npm ERR! gyp verb cli '--libsass_ext=', npm ERR! gyp verb cli '--libsass_cflags=', npm ERR! gyp verb cli '--libsass_ldflags=', npm ERR! gyp verb cli '--libsass_library=' npm ERR! gyp verb cli ] npm ERR! gyp info using [email protected] npm ERR! gyp info using [email protected] | win32 | x64 npm ERR! gyp verb command rebuild [] npm ERR! gyp verb command clean [] npm ERR! gyp verb clean removing "build" directory npm ERR! gyp verb command configure [] npm ERR! gyp verb find Python checking Python explicitly set from command line or npm configuration npm ERR! gyp verb find Python - "--python=" or "npm config get python" is "C:\Python311\python.exe" npm ERR! gyp verb find Python - executing "C:\Python311\python.exe" to get executable path npm ERR! gyp verb find Python - executable path is "C:\Python311\python.exe" npm ERR! gyp verb find Python - executing "C:\Python311\python.exe" to get version npm ERR! gyp verb find Python - version is "3.11.0" npm ERR! gyp info find Python using Python version 3.11.0 found at "C:\Python311\python.exe" npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 19.2.0 npm ERR! gyp verb command install [ '19.2.0' ] npm ERR! gyp verb install input version string "19.2.0" npm ERR! gyp verb install installing version: 19.2.0 npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed npm ERR! gyp verb install version is already installed, need to check "installVersion" npm ERR! gyp verb got "installVersion" 9 npm ERR! gyp verb needs "installVersion" 9 npm ERR! gyp verb install version is good npm ERR! gyp verb get node dir target node version installed: 19.2.0 npm ERR! gyp verb build dir attempting to create "build" dir: C:\Users\denis\OneDrive\Documents\Website\node_modules\node-sass\build npm ERR! gyp verb build dir "build" dir needed to be created? Yes npm ERR! gyp verb find VS msvs_version was set from command line or npm config npm ERR! gyp verb find VS - looking for Visual Studio version 2022 npm ERR! gyp verb find VS running in VS Command Prompt, installation path is: npm ERR! gyp verb find VS "C:\Program Files (x86)\Microsoft Visual Studio\2022\Community" npm ERR! gyp verb find VS - will only use this version npm ERR! gyp verb find VS checking VS2022 (17.4.33122.133) found at: npm ERR! gyp verb find VS "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools" npm ERR! gyp verb find VS - found "Visual Studio C++ core features" npm ERR! gyp verb find VS - found VC++ toolset: v143 npm ERR! gyp verb find VS - missing any Windows SDK npm ERR! gyp verb find VS could not find a version of Visual Studio 2017 or newer to use npm ERR! gyp verb find VS looking for Visual Studio 2015 npm ERR! gyp verb find VS - not found npm ERR! gyp verb find VS not looking for VS2013 as it is only supported up to Node.js 8 npm ERR! gyp ERR! find VS npm ERR! gyp ERR! find VS msvs_version was set from command line or npm config npm ERR! gyp ERR! find VS - looking for Visual Studio version 2022 npm ERR! gyp ERR! find VS running in VS Command Prompt, installation path is: npm ERR! gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2022\Community" npm ERR! gyp ERR! find VS - will only use this version npm ERR! gyp ERR! find VS checking VS2022 (17.4.33122.133) found at: npm ERR! gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools" npm ERR! gyp ERR! find VS - found "Visual Studio C++ core features" npm ERR! gyp ERR! find VS - found VC++ toolset: v143 npm ERR! gyp ERR! find VS - missing any Windows SDK npm ERR! gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use npm ERR! gyp ERR! find VS looking for Visual Studio 2015 npm ERR! gyp ERR! find VS - not found npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8 npm ERR! gyp ERR! find VS msvs_version does not match this VS Command Prompt or the npm ERR! gyp ERR! find VS installation cannot be used. npm ERR! gyp ERR! find VS npm ERR! gyp ERR! find VS ************************************************************** npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload. npm ERR! gyp ERR! find VS For more information consult the documentation at: npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows npm ERR! gyp ERR! find VS ************************************************************** npm ERR! gyp ERR! find VS npm ERR! gyp ERR! configure error npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use npm ERR! gyp ERR! stack at VisualStudioFinder.fail (C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:122:47) npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:75:16 npm ERR! gyp ERR! stack at VisualStudioFinder.findVisualStudio2013 (C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:363:14) npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:71:14 npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\find-visualstudio.js:384:16 npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\util.js:54:7 npm ERR! gyp ERR! stack at C:\Users\denis\OneDrive\Documents\Website\node_modules\node-gyp\lib\util.js:33:16 npm ERR! gyp ERR! stack at ChildProcess.exithandler (node:child_process:427:5) npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:513:28) npm ERR! gyp ERR! stack at maybeClose (node:internal/child_process:1098:16) npm ERR! gyp ERR! stack at ChildProcess._handle.onexit (node:internal/child_process:304:5) npm ERR! gyp ERR! System Windows_NT 10.0.22621 npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\denis\\OneDrive\\Documents\\Website\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library=" npm ERR! gyp ERR! cwd C:\Users\denis\OneDrive\Documents\Website\node_modules\node-sass npm ERR! gyp ERR! node -v v19.2.0 npm ERR! gyp ERR! node-gyp -v v8.4.1 npm ERR! gyp ERR! not ok npm ERR! Build failed with error code: 1 System Information Build tools 2022 Installed + SDK for windows 11 Env path Visual Studio Code output of python and msvs_version All mentioned in pictures.
[ "It seems it has something to do with Windows 11, running a VM of Win10 Pro where it executes perfectly with the latest packages.\nPS: Windows Build Tools are now embedded in the latest Node, so no need to install them manually. Just Node, Git, Visual Studio Code and restart for PATH to update automatically.\n" ]
[ 0 ]
[]
[]
[ "node.js", "npm", "python" ]
stackoverflow_0074632361_node.js_npm_python.txt
Q: Dart - Subtracting some double values gives wrong result I have picked two random double numbers: double a = 7918.52; double b = 5000.00; I would expect to get 2918.52 from a - b. Well, it gives me a result of 2918.5200000000004, which seems odd. print(a - b); // -> 2918.5200000000004 But if I change double a to 7918.54, I will get the expected result of 2918.54. Can someone explain to me why some double values result in unexpected rounding issues and others do not? A: The reason for this is floating-point arithmetic and the fact that Dart uses the IEEE 754 standard as far as I am concerned. This happens for all languages that use floating-point arithmetic. You can read through similar questions regarding other programming languages. General question about floating-point arithmetic in modern programming languages. A: creativecreatorormaybenot is right, this is issue comes from the Dart language itself. The best solution I came up with was to manually round it to the precision you expect : double substract(double a, double b, int precision) { return (a - b).precision(precision); } double precision(int fractionDigits) { num mod = pow(10.0, fractionDigits); return ((this * mod).round().toDouble() / mod); } A: A simple solution would be: depending on how many decimals you expect (lets assume 2, you can make it more generic...) ((a * 100).toInt() - (b * 100)).toInt() / 100.
Dart - Subtracting some double values gives wrong result
I have picked two random double numbers: double a = 7918.52; double b = 5000.00; I would expect to get 2918.52 from a - b. Well, it gives me a result of 2918.5200000000004, which seems odd. print(a - b); // -> 2918.5200000000004 But if I change double a to 7918.54, I will get the expected result of 2918.54. Can someone explain to me why some double values result in unexpected rounding issues and others do not?
[ "The reason for this is floating-point arithmetic and the fact that Dart uses the IEEE 754 standard as far as I am concerned.\nThis happens for all languages that use floating-point arithmetic. You can read through similar questions regarding other programming languages.\nGeneral question about floating-point arithmetic in modern programming languages.\n", "creativecreatorormaybenot is right, this is issue comes from the Dart language itself.\nThe best solution I came up with was to manually round it to the precision you expect :\ndouble substract(double a, double b, int precision) {\n return (a - b).precision(precision);\n}\n\ndouble precision(int fractionDigits) {\n num mod = pow(10.0, fractionDigits);\n return ((this * mod).round().toDouble() / mod);\n}\n\n", "A simple solution would be:\n\ndepending on how many decimals you expect (lets assume 2, you can make it more generic...)\n((a * 100).toInt() - (b * 100)).toInt() / 100.\n\n" ]
[ 6, 0, 0 ]
[]
[]
[ "dart", "double", "floating_accuracy", "floating_point" ]
stackoverflow_0056619416_dart_double_floating_accuracy_floating_point.txt
Q: startActivity not working public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(getApplicationContext(), "Position of selected item is: "+ position, Toast.LENGTH_LONG).show(); if ("Abiding in Christ".equals(categories[position])) {startActivity(AbidingInChrist.class);} else if ("Abundant Living".equals(categories[position])) {startActivity(AbundantLiving.class);} else if ("Access to God".equals(categories[position])) {startActivity(AccessToGod.class);} else if ("Adoration of God".equals(categories[position])) {startActivity(AdorationOfGod.class);} else if ("Amazing Grace".equals(categories[position])) {startActivity(AmazingGrace.class);} all of the startActivity s are underlined in red and want me to change to something or create a method same name. I did add all the activities to the manifest, but some of them didn't work: <activity android:name=".AbidingInChrist"</activity> <activity android:name=".AbundantLiving</activity> <activity android:name=".AccessToGod</activity> <activity android:name=".AdorationOfGod</activity> <activity android:name=".AmazingGrace</activity> <activity android:name=".AnsweredPrayer</activity> <activity android:name=".Atonement</activity> <activity android:name=".Attitudes</activity> <activity android:name=".Belief</activity> <activity android:name=".Blessing</activity> <activity android:name=".BloodOfJesus</activity> <activity android:name=".Boldness</activity> <activity android:name=".Brokenness</activity> <activity android:name=".Calling</activity> <activity android:name=".Comfort</activity> <activity android:name=".Commitment</activity> It's hard to tell here, but every other one was in red saying that it was missing the android namespace prefix. Appreciate ya'll! A: In your code try to use an intent to start activity: Intent i = new Intent(ACTUALACTIVITY.this, OTHERACTIVITY.class); startActivity(i); and in your manifest put your activity full address (package.activity) like below: <application> (...) <activity android:name="packagename.YOURACTIVITY"> </activity> </application> A: Try to create Intent and start Activity passing this intent like // Create intent to start new Activity Intent intent = new Intent(context, YourActivity.class); startActivity(intent); A: I know that this is an old question. Might be a bit irrelevant to the question details. But hopefully, might help someone who lands on this question for a similar issue. In my case, "context.startActivity(...)" was supposed to launch an activity in a pendingIntent (when the app is in the background). It wasn't working because I had "Display over other apps" set as "Not allowed", in the application settings. Added the permission for the same and enabled it, to resolve the issue.
startActivity not working
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(getApplicationContext(), "Position of selected item is: "+ position, Toast.LENGTH_LONG).show(); if ("Abiding in Christ".equals(categories[position])) {startActivity(AbidingInChrist.class);} else if ("Abundant Living".equals(categories[position])) {startActivity(AbundantLiving.class);} else if ("Access to God".equals(categories[position])) {startActivity(AccessToGod.class);} else if ("Adoration of God".equals(categories[position])) {startActivity(AdorationOfGod.class);} else if ("Amazing Grace".equals(categories[position])) {startActivity(AmazingGrace.class);} all of the startActivity s are underlined in red and want me to change to something or create a method same name. I did add all the activities to the manifest, but some of them didn't work: <activity android:name=".AbidingInChrist"</activity> <activity android:name=".AbundantLiving</activity> <activity android:name=".AccessToGod</activity> <activity android:name=".AdorationOfGod</activity> <activity android:name=".AmazingGrace</activity> <activity android:name=".AnsweredPrayer</activity> <activity android:name=".Atonement</activity> <activity android:name=".Attitudes</activity> <activity android:name=".Belief</activity> <activity android:name=".Blessing</activity> <activity android:name=".BloodOfJesus</activity> <activity android:name=".Boldness</activity> <activity android:name=".Brokenness</activity> <activity android:name=".Calling</activity> <activity android:name=".Comfort</activity> <activity android:name=".Commitment</activity> It's hard to tell here, but every other one was in red saying that it was missing the android namespace prefix. Appreciate ya'll!
[ "In your code try to use an intent to start activity:\n Intent i = new Intent(ACTUALACTIVITY.this, OTHERACTIVITY.class);\n startActivity(i);\n\nand in your manifest put your activity full address (package.activity) like below:\n<application>\n(...)\n <activity\n android:name=\"packagename.YOURACTIVITY\">\n </activity>\n</application>\n\n", "Try to create Intent and start Activity passing this intent like \n// Create intent to start new Activity\nIntent intent = new Intent(context, YourActivity.class);\nstartActivity(intent);\n\n", "I know that this is an old question. Might be a bit irrelevant to the question details. But hopefully, might help someone who lands on this question for a similar issue.\nIn my case, \"context.startActivity(...)\" was supposed to launch an activity in a pendingIntent (when the app is in the background).\nIt wasn't working because I had \"Display over other apps\" set as \"Not allowed\", in the application settings.\nAdded the permission for the same and enabled it, to resolve the issue.\n" ]
[ 10, 0, 0 ]
[ "The startActivity method takes an Intent as parameter. Yo are trying to pass a class and that's why you get the \"red underline\"\ntry this:\n if (\"Abiding in Christ\".equals(categories[position]))\n {startActivity(new Intent(this, AbidingInChrist.class));}\n else if (\"Abundant Living\".equals(categories[position]))\n {startActivity(new Intent(this, AbundantLiving.class));}\n else if (\"Access to God\".equals(categories[position]))\n {startActivity(new Intent(this, AccessToGod.class));}\n else if (\"Adoration of God\".equals(categories[position]))\n {startActivity(new Intent(this, AdorationOfGod.class));}\n else if (\"Amazing Grace\".equals(categories[position]))\n {startActivity(new Intent(this, AmazingGrace.class));}\n\nAlso in you manifest don't forget to close the quotes when you declare an activity\n <activity android:name=\".AbidingInChrist\"></activity>\n <activity android:name=\".AbundantLiving\"></activity>\n <activity android:name=\".AccessToGod\"></activity>\n\netc\n" ]
[ -2 ]
[ "android", "start_activity" ]
stackoverflow_0024808094_android_start_activity.txt
Q: update a value by running through every row in a data frame with conditions (extension) This is an extension to the question, 'update a value by running through every row in a data frame with conditions' update a value by running through every row in a data frame with conditions Working with the same data frame: Df: Index A B A_yes B_yes 0 2.43 1.55 1 0 1 2.58 1.49 0 1 2 1.61 2.32 1 0 3 2.7 1.46 1 0 I've attached an image of the new conditions. (For example, for the first row: I have the 500 at the start, halve it into two 250's. I take one of the 250's and multiply this by the row to get 607.5 but then before proceeding onto the next row, I add the other half (250) so now I have 857.5. Then I continue this pattern through all the rows.) Desired output: Df: Index A B A_yes B_yes Points 0 2.43 1.55 1 0 875.5 1 2.58 1.49 0 1 1067.5875 2 1.61 2.32 1 0 1393.2017 3 2.7 1.46 1 0 2557.42324 A: You could try the following with df your dataframe: start = 500 weights = (df["A"].where(df["A_yes"].eq(1), df["B"]) * 0.5 + 0.5).cumprod() df["Points"] = start * weights Use .where to select between the value in A or B based on the A_yes and B_yes entries (my assumption here is that there's a 1 either in A_yes or B_yes, but not in both). Calculate the average between the selected value and 1. Build the actual weights with .cumprod. Multiply the weights with the start value to get the Points. Result for df = A B A_yes B_yes 0 2.43 1.55 1 0 1 2.58 1.49 0 1 2 1.61 2.32 1 0 3 2.70 1.46 1 0 is A B A_yes B_yes Points 0 2.43 1.55 1 0 857.500000 1 2.58 1.49 0 1 1067.587500 2 1.61 2.32 1 0 1393.201688 3 2.70 1.46 1 0 2577.423122
update a value by running through every row in a data frame with conditions (extension)
This is an extension to the question, 'update a value by running through every row in a data frame with conditions' update a value by running through every row in a data frame with conditions Working with the same data frame: Df: Index A B A_yes B_yes 0 2.43 1.55 1 0 1 2.58 1.49 0 1 2 1.61 2.32 1 0 3 2.7 1.46 1 0 I've attached an image of the new conditions. (For example, for the first row: I have the 500 at the start, halve it into two 250's. I take one of the 250's and multiply this by the row to get 607.5 but then before proceeding onto the next row, I add the other half (250) so now I have 857.5. Then I continue this pattern through all the rows.) Desired output: Df: Index A B A_yes B_yes Points 0 2.43 1.55 1 0 875.5 1 2.58 1.49 0 1 1067.5875 2 1.61 2.32 1 0 1393.2017 3 2.7 1.46 1 0 2557.42324
[ "You could try the following with df your dataframe:\nstart = 500\nweights = (df[\"A\"].where(df[\"A_yes\"].eq(1), df[\"B\"]) * 0.5 + 0.5).cumprod()\ndf[\"Points\"] = start * weights\n\n\nUse .where to select between the value in A or B based on the A_yes and B_yes entries (my assumption here is that there's a 1 either in A_yes or B_yes, but not in both).\nCalculate the average between the selected value and 1.\nBuild the actual weights with .cumprod.\nMultiply the weights with the start value to get the Points.\n\nResult for df =\n A B A_yes B_yes\n0 2.43 1.55 1 0\n1 2.58 1.49 0 1\n2 1.61 2.32 1 0\n3 2.70 1.46 1 0\n\nis\n A B A_yes B_yes Points\n0 2.43 1.55 1 0 857.500000\n1 2.58 1.49 0 1 1067.587500\n2 1.61 2.32 1 0 1393.201688\n3 2.70 1.46 1 0 2577.423122\n\n" ]
[ 0 ]
[]
[]
[ "conditional_statements", "dataframe", "loops", "pandas", "python" ]
stackoverflow_0074662788_conditional_statements_dataframe_loops_pandas_python.txt
Q: Adding event listener to FontAwesome icons I'm currently trying to make a media player that is OOP. A requirement is that I make custom media player buttons, and not use the ones inherent within the audio object. I've pulled icons from Font Awesome, and am having trouble giving them eventlisteners. I put the icons into a span class called clickable <span class="clickable"> <span class="fa fa-backward fa-4x fa-fw" aria-hidden="true" id="Back"></span> <span class="fa fa-pause fa-4x fa-fw" aria-hidden="true" id="Pause"></span> <span class="fa fa-play fa-4x fa-fw" aria-hidden="true" id="Play"></span> <span class="fa fa-forward fa-4x fa-fw" aria-hidden="true" id="Forward"></span> </span> Then in the CSS I made the #clickable class clickable #clickable { cursor:pointer; } Then in the JS added an eventListener that does not detect anything.Right now I'm just having it log hello to see if the function executes, but ultimately I want to call an object method. document.getElementById('Back').addEventListener("click", function(e){ e.preventDefault console.log(hello); // myPlaylist.play(); }) A: To put in code what other people already pointed out in comments: Change the css, using class instead of id: .clickable { cursor:pointer; } or, as i personally suggest, make the cursor a pointer only for the span inside: .clickable span { cursor:pointer; } Change your javascript, fixing a missing variable hello and using preventdefault as a function. document.getElementById('Back').addEventListener("click", function(e){ e.preventDefault() console.log('hello'); // myPlaylist.play(); }) A: I don't know why but in my case addEventListener does not see an awesome icon either. I ended up at setting a custom attribute ('data-index', index) to font-awsome class variable. icon.setAttribute('data-index', 1) icon.addEventListener('click', e => { a=e.target.getAttribute('data-index') if a=1 { console.log('hello') }
Adding event listener to FontAwesome icons
I'm currently trying to make a media player that is OOP. A requirement is that I make custom media player buttons, and not use the ones inherent within the audio object. I've pulled icons from Font Awesome, and am having trouble giving them eventlisteners. I put the icons into a span class called clickable <span class="clickable"> <span class="fa fa-backward fa-4x fa-fw" aria-hidden="true" id="Back"></span> <span class="fa fa-pause fa-4x fa-fw" aria-hidden="true" id="Pause"></span> <span class="fa fa-play fa-4x fa-fw" aria-hidden="true" id="Play"></span> <span class="fa fa-forward fa-4x fa-fw" aria-hidden="true" id="Forward"></span> </span> Then in the CSS I made the #clickable class clickable #clickable { cursor:pointer; } Then in the JS added an eventListener that does not detect anything.Right now I'm just having it log hello to see if the function executes, but ultimately I want to call an object method. document.getElementById('Back').addEventListener("click", function(e){ e.preventDefault console.log(hello); // myPlaylist.play(); })
[ "To put in code what other people already pointed out in comments:\nChange the css, using class instead of id:\n .clickable {\n cursor:pointer;\n }\n\nor, as i personally suggest, make the cursor a pointer only for the span inside:\n.clickable span {\n cursor:pointer;\n}\n\nChange your javascript, fixing a missing variable hello and using preventdefault as a function.\ndocument.getElementById('Back').addEventListener(\"click\", \nfunction(e){\n e.preventDefault()\n console.log('hello');\n // myPlaylist.play();\n})\n\n", "I don't know why but in my case addEventListener does not see an awesome icon either.\nI ended up at setting a custom attribute ('data-index', index) to font-awsome class variable.\nicon.setAttribute('data-index', 1)\n\nicon.addEventListener('click', e => {\na=e.target.getAttribute('data-index')\nif a=1 {\nconsole.log('hello')\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "css", "font_awesome", "html", "javascript" ]
stackoverflow_0041687035_css_font_awesome_html_javascript.txt
Q: Lambda is not authorized to perform: cognito-idp:AdminInitiateAuth I am following AWS Cognito and API Gateway tutorials from part1, part 2 and part 3. From part 1, I created the following lambdas: signup confirm signup forgot pwd resend verify code successful registration and each of these lambdas has a separate role automatically generated for them. From part 2, I connected these lambdas to various API endpoints in API Gateway, with the /login route being connected to the "successful registration" lambda. From the part 3 tutorial, I created a refresh_access_token lambda function and also the test_user. Then, in the API Gateway, I created a new resource /user/test-user and added a GET method, which I connected to the test_user lambda. (The refresh_access_token isn't connected to a route). After that, I go to the Create a New authorizer section from part 3, and when I run the /login route, I end up getting the following error: HTTP/1.1 200 OK Date: Tue, 27 Oct 2020 19:42:15 GMT Content-Type: application/json Content-Length: 423 Connection: close x-amzn-RequestId: 86e522e3-1843-4c05-8d70-c6731c5f110f x-amz-apigw-id: VFezhGcvFiAFqOQ= X-Amzn-Trace-Id: Root=1-5f987816-65f557256f2ccd172032ff15;Sampled=0 { "message": "An error occurred (AccessDeniedException) when calling the AdminInitiateAuth operation: User: arn:aws:sts::xxxxxxxx:assumed-role/cognito-successful-registration-role-ck5hni20/cognito-successful-registration is not authorized to perform: cognito-idp:AdminInitiateAuth on resource: arn:aws:cognito-idp:eu-central-1:xxxxxxxx:userpool/eu-central-1_xxxx, "error": true, "success": false, "data": null } The cognito-successful-registration-role-ck5hni20 just has AWSBasicExecutionRole attached to it and the trust relationship looks as follows: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } What is the mistake I am doing here? A: Locate the role cognito-successful-registration-role-ck5hni20 in AWS console. Once you do this, you can add an inline policy to in the following form: { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "cognito-idp:AdminInitiateAuth", "Resource": { "AWS": "arn:aws:cognito-idp:eu-central-1:xxxxxxxx:userpool/eu-central-1_xxxx" } } ] } or use more general form: { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "cognito-idp:AdminInitiateAuth", "Resource": "*" } ] } A: For people who are new to AWS like this, here is a more detailed solution: go to your lambda function Under configuration, click permission, and then you'll see Execution role and the corresponding role name. click on role name then edit the permission and add a new inline policy, as suggested by @Marcin. finally, click create policy A: I had a similar issue with AdminInitiateAuth, but mine was slightly different: Auth flow not enabled for this client. I could not solve the issue with any kind of role, the problem was not with the function but with the Cognito client used in the login handler. The solution was to go to the Cognito User Pool in the AWS Console, then to 'App clients' and to check the boxes for ALLOW_ADMIN_USER_PASSWORD_AUTH and ALLOW_USER_PASSWORD_AUTH
Lambda is not authorized to perform: cognito-idp:AdminInitiateAuth
I am following AWS Cognito and API Gateway tutorials from part1, part 2 and part 3. From part 1, I created the following lambdas: signup confirm signup forgot pwd resend verify code successful registration and each of these lambdas has a separate role automatically generated for them. From part 2, I connected these lambdas to various API endpoints in API Gateway, with the /login route being connected to the "successful registration" lambda. From the part 3 tutorial, I created a refresh_access_token lambda function and also the test_user. Then, in the API Gateway, I created a new resource /user/test-user and added a GET method, which I connected to the test_user lambda. (The refresh_access_token isn't connected to a route). After that, I go to the Create a New authorizer section from part 3, and when I run the /login route, I end up getting the following error: HTTP/1.1 200 OK Date: Tue, 27 Oct 2020 19:42:15 GMT Content-Type: application/json Content-Length: 423 Connection: close x-amzn-RequestId: 86e522e3-1843-4c05-8d70-c6731c5f110f x-amz-apigw-id: VFezhGcvFiAFqOQ= X-Amzn-Trace-Id: Root=1-5f987816-65f557256f2ccd172032ff15;Sampled=0 { "message": "An error occurred (AccessDeniedException) when calling the AdminInitiateAuth operation: User: arn:aws:sts::xxxxxxxx:assumed-role/cognito-successful-registration-role-ck5hni20/cognito-successful-registration is not authorized to perform: cognito-idp:AdminInitiateAuth on resource: arn:aws:cognito-idp:eu-central-1:xxxxxxxx:userpool/eu-central-1_xxxx, "error": true, "success": false, "data": null } The cognito-successful-registration-role-ck5hni20 just has AWSBasicExecutionRole attached to it and the trust relationship looks as follows: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } What is the mistake I am doing here?
[ "Locate the role cognito-successful-registration-role-ck5hni20 in AWS console. Once you do this, you can add an inline policy to in the following form:\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"VisualEditor0\",\n \"Effect\": \"Allow\",\n \"Action\": \"cognito-idp:AdminInitiateAuth\",\n \"Resource\": {\n \"AWS\": \"arn:aws:cognito-idp:eu-central-1:xxxxxxxx:userpool/eu-central-1_xxxx\"\n }\n }\n ]\n}\n\nor use more general form:\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"VisualEditor0\",\n \"Effect\": \"Allow\",\n \"Action\": \"cognito-idp:AdminInitiateAuth\",\n \"Resource\": \"*\"\n }\n ]\n}\n\n", "For people who are new to AWS like this, here is a more detailed solution:\n\ngo to your lambda function\nUnder configuration, click permission, and then you'll see Execution role and the corresponding role name.\nclick on role name\nthen edit the permission and add a new inline policy, as suggested by @Marcin.\nfinally, click create policy\n\n", "I had a similar issue with AdminInitiateAuth, but mine was slightly different: Auth flow not enabled for this client.\nI could not solve the issue with any kind of role, the problem was not with the function but with the Cognito client used in the login handler.\nThe solution was to go to the Cognito User Pool in the AWS Console, then to 'App clients' and to check the boxes for ALLOW_ADMIN_USER_PASSWORD_AUTH and ALLOW_USER_PASSWORD_AUTH\n" ]
[ 6, 2, 0 ]
[]
[]
[ "amazon_cognito", "amazon_iam", "amazon_web_services", "aws_api_gateway", "aws_lambda" ]
stackoverflow_0064562190_amazon_cognito_amazon_iam_amazon_web_services_aws_api_gateway_aws_lambda.txt
Q: How to acces all the file from the directory using Python? for i in os.listdir(r"C:\Users\Xmall\same-resume-year-wise-master\same-resume-year-wise-master"): print(i) if i.endswith('.pdf'): a=open(i) s=PyPDF2.PdfFileReader(a) for j in range(s.numPages): z=s.getPage(j) er=z.extractText() print(re.findall('\S+@\S+',er)) I am not able to read the file using this code I want to extract E-mail address from the pdf A: I'll post two solutions using two different libraries . I'm not sure if this will work , or is what you are looking for but it could lead you somewhere . #extract email addresses using pyPDF2 def extractEmails(pdfFile): pdfReader = PyPDF2.PdfFileReader(pdfFile) emails = [] for pageNum in range(pdfReader.numPages): pageObj = pdfReader.getPage(pageNum) text = pageObj.extractText() emailRegex = re.compile(r'[\w\.-]+@[\w\.-]+') mo = emailRegex.findall(text) if mo != []: emails.extend(mo) return emails #extract email addresses using pdfminer def extractEmails2(pdfFile): emails = [] for pageNum in range(pdfReader.numPages): pageObj = pdfReader.getPage(pageNum) text = pageObj.extractText() emailRegex = re.compile(r'[\w\.-]+@[\w\.-]+') mo = emailRegex.findall(text) if mo != []: emails.extend(mo) return emails
How to acces all the file from the directory using Python?
for i in os.listdir(r"C:\Users\Xmall\same-resume-year-wise-master\same-resume-year-wise-master"): print(i) if i.endswith('.pdf'): a=open(i) s=PyPDF2.PdfFileReader(a) for j in range(s.numPages): z=s.getPage(j) er=z.extractText() print(re.findall('\S+@\S+',er)) I am not able to read the file using this code I want to extract E-mail address from the pdf
[ "I'll post two solutions using two different libraries .\nI'm not sure if this will work , or is what you are looking for but it could lead you somewhere .\n #extract email addresses using pyPDF2\ndef extractEmails(pdfFile):\n pdfReader = PyPDF2.PdfFileReader(pdfFile)\n emails = []\n for pageNum in range(pdfReader.numPages):\n pageObj = pdfReader.getPage(pageNum)\n text = pageObj.extractText()\n emailRegex = re.compile(r'[\\w\\.-]+@[\\w\\.-]+')\n mo = emailRegex.findall(text)\n if mo != []:\n emails.extend(mo)\n return emails\n#extract email addresses using pdfminer\ndef extractEmails2(pdfFile):\n emails = []\n for pageNum in range(pdfReader.numPages):\n pageObj = pdfReader.getPage(pageNum)\n text = pageObj.extractText()\n emailRegex = re.compile(r'[\\w\\.-]+@[\\w\\.-]+')\n mo = emailRegex.findall(text)\n if mo != []:\n emails.extend(mo)\n return emails\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074667852_python.txt
Q: MYSQL_ROOT_PASSWORD is set but getting "Access denied for user 'root'@'localhost' (using password: YES)" in docker container I have a docker-compose file and a Dockerfile. MySQL is installed properly. I have set MYSQL_ROOT_PASSWORD. But when trying to access mysql db, getting the error - Access denied. I have read the other threads of this site, but couldn't get that much help. :( Here is my docker-compose file: version: '3' volumes: db_data: {} services: db: build: context: . dockerfile: ./db/Dockerfile args: - database=iTel - password=123 image: db_image volumes: - db_data:/var/lib/mysql ports: - "3306:3306" and Dockerfile: FROM mysql:5.7.15 ARG database ARG password RUN echo ${database} RUN echo ${password} MAINTAINER me ENV MYSQL_DATABASE=${database} \ MYSQL_ROOT_PASSWORD=${password} ADD ./db/database100.sql /docker-entrypoint-initdb.d EXPOSE 3306 Here are logs for build: docker-compose up -d Building db Step 1/9 : FROM mysql:5.7.15 5.7.15: Pulling from library/mysql 6a5a5368e0c2: Pull complete 0689904e86f0: Pull complete 486087a8071d: Pull complete 3eff318f6785: Pull complete 3df41d8a4cfb: Pull complete 1b4a00485931: Pull complete 0bab0b2c2630: Pull complete 264fc9ce512d: Pull complete e0181dcdbbe8: Pull complete 53b082fa47c7: Pull complete e5cf4fe00c4c: Pull complete Digest: sha256:966490bda4576655dc940923c4883db68cca0b3607920be5efff7514e0379aa7 Status: Downloaded newer image for mysql:5.7.15 ---> 18f13d72f7f0 Step 2/9 : ARG database ---> Running in 62819f9fc38b Removing intermediate container 62819f9fc38b ---> 863fd3212046 Step 3/9 : ARG password ---> Running in ea9d36c1a954 Removing intermediate container ea9d36c1a954 ---> 056100b1d5eb Step 4/9 : RUN echo ${database} ---> Running in 941bd2f4fc58 iTel Removing intermediate container 941bd2f4fc58 ---> 7b2b48e7bd8c Step 5/9 : RUN echo ${password} ---> Running in 9cb80396bb62 123 Removing intermediate container 9cb80396bb62 ---> 155d184c78ba Step 6/9 : MAINTAINER me ---> Running in 8e3b3b53ce7b Removing intermediate container 8e3b3b53ce7b ---> 9a7617a24800 Step 7/9 : ENV MYSQL_DATABASE=${database} MYSQL_ROOT_PASSWORD=${password} ---> Running in e483e65caf55 Removing intermediate container e483e65caf55 ---> acf8ac829607 Step 8/9 : ADD ./db/database100.sql /docker-entrypoint-initdb.d ---> 42d992439f98 Step 9/9 : EXPOSE 3306 ---> Running in 4e138502c6f9 Removing intermediate container 4e138502c6f9 ---> a0818deda593 Successfully built a0818deda593 Successfully tagged db_image:latest WARNING: Image for service db was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`. Creating reve_db_1 ... done to see the containers: docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 49419cb9980a db_image "docker-entrypoint.s…" 10 seconds ago Up 8 seconds 0.0.0.0:3306->3306/tcp reve_db_1 That is log for this container: docker logs 49419cb9980a 2020-01-21T07:53:13.050129Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). 2020-01-21T07:53:13.051767Z 0 [Note] mysqld (mysqld 5.7.15) starting as process 1 ... 2020-01-21T07:53:13.054945Z 0 [Note] InnoDB: PUNCH HOLE support available 2020-01-21T07:53:13.055053Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins 2020-01-21T07:53:13.055103Z 0 [Note] InnoDB: Uses event mutexes 2020-01-21T07:53:13.055179Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier 2020-01-21T07:53:13.055226Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3 2020-01-21T07:53:13.055268Z 0 [Note] InnoDB: Using Linux native AIO 2020-01-21T07:53:13.055608Z 0 [Note] InnoDB: Number of pools: 1 2020-01-21T07:53:13.055791Z 0 [Note] InnoDB: Using CPU crc32 instructions 2020-01-21T07:53:13.061164Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M 2020-01-21T07:53:13.072998Z 0 [Note] InnoDB: Completed initialization of buffer pool 2020-01-21T07:53:13.075325Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority(). 2020-01-21T07:53:13.101337Z 0 [Note] InnoDB: Highest supported file format is Barracuda. 2020-01-21T07:53:13.142134Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables 2020-01-21T07:53:13.142356Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ... 2020-01-21T07:53:13.184613Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB. 2020-01-21T07:53:13.185628Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active. 2020-01-21T07:53:13.185733Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active. 2020-01-21T07:53:13.186108Z 0 [Note] InnoDB: Waiting for purge to start 2020-01-21T07:53:13.236391Z 0 [Note] InnoDB: 5.7.15 started; log sequence number 12146163 2020-01-21T07:53:13.236828Z 0 [Note] Plugin 'FEDERATED' is disabled. 2020-01-21T07:53:13.237186Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool 2020-01-21T07:53:13.252074Z 0 [Warning] Failed to set up SSL because of the following SSL library error: SSL context is not usable without certificate and private key 2020-01-21T07:53:13.252900Z 0 [Note] Server hostname (bind-address): '*'; port: 3306 2020-01-21T07:53:13.253023Z 0 [Note] IPv6 is available. 2020-01-21T07:53:13.253076Z 0 [Note] - '::' resolves to '::'; 2020-01-21T07:53:13.253184Z 0 [Note] Server socket created on IP: '::'. 2020-01-21T07:53:13.269950Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. 2020-01-21T07:53:13.270581Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. 2020-01-21T07:53:13.277379Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200121 7:53:13 2020-01-21T07:53:13.295467Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. 2020-01-21T07:53:13.367019Z 0 [Note] Event Scheduler: Loaded 0 events 2020-01-21T07:53:13.368851Z 0 [Note] mysqld: ready for connections. Version: '5.7.15' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL) Now entered in the container: docker exec -it 49419cb9980a bash root@49419cb9980a:/# I have checked if MYSQL_ROOT_PASSWORD is set correctly(in the container): root@49419cb9980a:/# echo $MYSQL_ROOT_PASSWORD 123 Then tried to log into mysql: root@49419cb9980a:/# mysql -u root -p Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) My question is, how to solve this problem? Why can't I access mysql? I tried with no password option too. That gave me this error: mysql -u root ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) This is my project structure: tree . ├── db │   ├── Dockerfile │   └── database100.sql └── docker-compose.yml 1 directory, 3 files A: The below description is specifically for MySQL but many other official db docker images (postgres, mongodb....) work a similar way. Hence the symptom (i.e. access denied with configured credentials) and workaround (i.e. delete the data volume to start initialization from scratch) are the same. Taking for granted you have shown your entire start log, it appears you started your mysql container against a pre-existing db_data volume already containing a mysql database filesystem. In this case, absolutely nothing will be initialized on container start and environment variables are useless. Quoting the official image documentation in the "Environment Variables" section: Do note that none of the variables below will have any effect if you start the container with a data directory that already contains a database: any pre-existing database will always be left untouched on container startup. If you want your instance to be initialized, you have to start from scratch. It is quite easy to do with docker compose when using a named volume like in your case. Warning: this will permanently delete the contents in your db_data volume, wiping out any previous database you had there. Create a backup first if you need to keep the contents. docker-compose down -v docker-compose up -d If you ever convert to a bind mount, you will have to delete all it's content yourself (i.e. rm -rf /path/to/bind/mount/*) A: If you are on a development server you could simply remove all unused local volumes. Unused local volumes are those which are not referenced by any containers: docker volume prune A: I've tested with all of the possible solutions posted in this thread. However, after try and error, I identified for any reason complex passwords were not recognized. I've changed mariadb: container_name: dev_db image: mariadb:10.5 restart: always environment: MARIADB_ROOT_PASSWORD: a8Gh@c8wi#gL^ MARIADB_DATABASE: wp_my_database MARIADB_USER: wp MARIADB_PASSWORD: a8Gh@c8wi#gL^ by mariadb: container_name: dev_db image: mariadb:10.5 restart: always environment: MARIADB_ROOT_PASSWORD: qwerty MARIADB_DATABASE: wp_my_database MARIADB_USER: wp MARIADB_PASSWORD: qwerty docker compose version: '3.9'. services: nginx:1.20-alpine php:7.2.34-fpm-alpine mariadb:mariadb:10.5 phpmyadmin: phpmyadmin/phpmyadmin:latest.
MYSQL_ROOT_PASSWORD is set but getting "Access denied for user 'root'@'localhost' (using password: YES)" in docker container
I have a docker-compose file and a Dockerfile. MySQL is installed properly. I have set MYSQL_ROOT_PASSWORD. But when trying to access mysql db, getting the error - Access denied. I have read the other threads of this site, but couldn't get that much help. :( Here is my docker-compose file: version: '3' volumes: db_data: {} services: db: build: context: . dockerfile: ./db/Dockerfile args: - database=iTel - password=123 image: db_image volumes: - db_data:/var/lib/mysql ports: - "3306:3306" and Dockerfile: FROM mysql:5.7.15 ARG database ARG password RUN echo ${database} RUN echo ${password} MAINTAINER me ENV MYSQL_DATABASE=${database} \ MYSQL_ROOT_PASSWORD=${password} ADD ./db/database100.sql /docker-entrypoint-initdb.d EXPOSE 3306 Here are logs for build: docker-compose up -d Building db Step 1/9 : FROM mysql:5.7.15 5.7.15: Pulling from library/mysql 6a5a5368e0c2: Pull complete 0689904e86f0: Pull complete 486087a8071d: Pull complete 3eff318f6785: Pull complete 3df41d8a4cfb: Pull complete 1b4a00485931: Pull complete 0bab0b2c2630: Pull complete 264fc9ce512d: Pull complete e0181dcdbbe8: Pull complete 53b082fa47c7: Pull complete e5cf4fe00c4c: Pull complete Digest: sha256:966490bda4576655dc940923c4883db68cca0b3607920be5efff7514e0379aa7 Status: Downloaded newer image for mysql:5.7.15 ---> 18f13d72f7f0 Step 2/9 : ARG database ---> Running in 62819f9fc38b Removing intermediate container 62819f9fc38b ---> 863fd3212046 Step 3/9 : ARG password ---> Running in ea9d36c1a954 Removing intermediate container ea9d36c1a954 ---> 056100b1d5eb Step 4/9 : RUN echo ${database} ---> Running in 941bd2f4fc58 iTel Removing intermediate container 941bd2f4fc58 ---> 7b2b48e7bd8c Step 5/9 : RUN echo ${password} ---> Running in 9cb80396bb62 123 Removing intermediate container 9cb80396bb62 ---> 155d184c78ba Step 6/9 : MAINTAINER me ---> Running in 8e3b3b53ce7b Removing intermediate container 8e3b3b53ce7b ---> 9a7617a24800 Step 7/9 : ENV MYSQL_DATABASE=${database} MYSQL_ROOT_PASSWORD=${password} ---> Running in e483e65caf55 Removing intermediate container e483e65caf55 ---> acf8ac829607 Step 8/9 : ADD ./db/database100.sql /docker-entrypoint-initdb.d ---> 42d992439f98 Step 9/9 : EXPOSE 3306 ---> Running in 4e138502c6f9 Removing intermediate container 4e138502c6f9 ---> a0818deda593 Successfully built a0818deda593 Successfully tagged db_image:latest WARNING: Image for service db was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`. Creating reve_db_1 ... done to see the containers: docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 49419cb9980a db_image "docker-entrypoint.s…" 10 seconds ago Up 8 seconds 0.0.0.0:3306->3306/tcp reve_db_1 That is log for this container: docker logs 49419cb9980a 2020-01-21T07:53:13.050129Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). 2020-01-21T07:53:13.051767Z 0 [Note] mysqld (mysqld 5.7.15) starting as process 1 ... 2020-01-21T07:53:13.054945Z 0 [Note] InnoDB: PUNCH HOLE support available 2020-01-21T07:53:13.055053Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins 2020-01-21T07:53:13.055103Z 0 [Note] InnoDB: Uses event mutexes 2020-01-21T07:53:13.055179Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier 2020-01-21T07:53:13.055226Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3 2020-01-21T07:53:13.055268Z 0 [Note] InnoDB: Using Linux native AIO 2020-01-21T07:53:13.055608Z 0 [Note] InnoDB: Number of pools: 1 2020-01-21T07:53:13.055791Z 0 [Note] InnoDB: Using CPU crc32 instructions 2020-01-21T07:53:13.061164Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M 2020-01-21T07:53:13.072998Z 0 [Note] InnoDB: Completed initialization of buffer pool 2020-01-21T07:53:13.075325Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority(). 2020-01-21T07:53:13.101337Z 0 [Note] InnoDB: Highest supported file format is Barracuda. 2020-01-21T07:53:13.142134Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables 2020-01-21T07:53:13.142356Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ... 2020-01-21T07:53:13.184613Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB. 2020-01-21T07:53:13.185628Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active. 2020-01-21T07:53:13.185733Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active. 2020-01-21T07:53:13.186108Z 0 [Note] InnoDB: Waiting for purge to start 2020-01-21T07:53:13.236391Z 0 [Note] InnoDB: 5.7.15 started; log sequence number 12146163 2020-01-21T07:53:13.236828Z 0 [Note] Plugin 'FEDERATED' is disabled. 2020-01-21T07:53:13.237186Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool 2020-01-21T07:53:13.252074Z 0 [Warning] Failed to set up SSL because of the following SSL library error: SSL context is not usable without certificate and private key 2020-01-21T07:53:13.252900Z 0 [Note] Server hostname (bind-address): '*'; port: 3306 2020-01-21T07:53:13.253023Z 0 [Note] IPv6 is available. 2020-01-21T07:53:13.253076Z 0 [Note] - '::' resolves to '::'; 2020-01-21T07:53:13.253184Z 0 [Note] Server socket created on IP: '::'. 2020-01-21T07:53:13.269950Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. 2020-01-21T07:53:13.270581Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. 2020-01-21T07:53:13.277379Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200121 7:53:13 2020-01-21T07:53:13.295467Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. 2020-01-21T07:53:13.367019Z 0 [Note] Event Scheduler: Loaded 0 events 2020-01-21T07:53:13.368851Z 0 [Note] mysqld: ready for connections. Version: '5.7.15' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL) Now entered in the container: docker exec -it 49419cb9980a bash root@49419cb9980a:/# I have checked if MYSQL_ROOT_PASSWORD is set correctly(in the container): root@49419cb9980a:/# echo $MYSQL_ROOT_PASSWORD 123 Then tried to log into mysql: root@49419cb9980a:/# mysql -u root -p Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) My question is, how to solve this problem? Why can't I access mysql? I tried with no password option too. That gave me this error: mysql -u root ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) This is my project structure: tree . ├── db │   ├── Dockerfile │   └── database100.sql └── docker-compose.yml 1 directory, 3 files
[ "The below description is specifically for MySQL but many other official db docker images (postgres, mongodb....) work a similar way. Hence the symptom (i.e. access denied with configured credentials) and workaround (i.e. delete the data volume to start initialization from scratch) are the same.\n\nTaking for granted you have shown your entire start log, it appears you started your mysql container against a pre-existing db_data volume already containing a mysql database filesystem.\nIn this case, absolutely nothing will be initialized on container start and environment variables are useless. Quoting the official image documentation in the \"Environment Variables\" section:\n\nDo note that none of the variables below will have any effect if you start the container with a data directory that already contains a database: any pre-existing database will always be left untouched on container startup.\n\nIf you want your instance to be initialized, you have to start from scratch. It is quite easy to do with docker compose when using a named volume like in your case. Warning: this will permanently delete the contents in your db_data volume, wiping out any previous database you had there. Create a backup first if you need to keep the contents.\ndocker-compose down -v\ndocker-compose up -d\n\nIf you ever convert to a bind mount, you will have to delete all it's content yourself (i.e. rm -rf /path/to/bind/mount/*)\n", "If you are on a development server you could simply remove all unused local volumes. Unused local volumes are those which are not referenced by any containers:\ndocker volume prune\n\n", "I've tested with all of the possible solutions posted in this thread.\nHowever, after try and error, I identified for any reason complex passwords were not recognized.\nI've changed\n mariadb:\n container_name: dev_db\n image: mariadb:10.5\n restart: always\n environment:\n MARIADB_ROOT_PASSWORD: a8Gh@c8wi#gL^\n MARIADB_DATABASE: wp_my_database\n MARIADB_USER: wp\n MARIADB_PASSWORD: a8Gh@c8wi#gL^\n\nby\n mariadb:\n container_name: dev_db\n image: mariadb:10.5\n restart: always\n environment:\n MARIADB_ROOT_PASSWORD: qwerty\n MARIADB_DATABASE: wp_my_database\n MARIADB_USER: wp\n MARIADB_PASSWORD: qwerty\n\n\ndocker compose version: '3.9'.\nservices:\n\nnginx:1.20-alpine\nphp:7.2.34-fpm-alpine\nmariadb:mariadb:10.5\nphpmyadmin: phpmyadmin/phpmyadmin:latest.\n\n\n\n" ]
[ 159, 3, 3 ]
[ "I found a better way, no need to delete all volume etc.\n1 - change your docker compose file to keep mysql container alive like this;\nunder mysql service;\ncommand: tail -F anything\n\nafter this operation, you can undo this, don't worry with the previous value.\n2 - then, stop mysql container and run with\ndocker-compose up --build --force-recreate YOUR_SERVICE_NAME\n\nthis doesn't delete your volume.\n3 - enter to mysql container;\ndocker exec -it YOUR_SERVICE_NAME bash\n\nfinally follow any mysql reset password guide like this;\nhttps://www.a2hosting.com/kb/developer-corner/mysql/reset-mysql-root-password\n", "I have the same problem, and after delete the volume the problem still there, then I find this solution:\nPLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !\nTo do so, start the server, then issue the following commands:\n/usr/local/mysql/bin/mysqladmin -u root password 'new-password'\n/usr/local/mysql/bin/mysqladmin -u root -h password 'new-password'\nAlternatively you can run:\n/usr/local/mysql/bin/mysql_secure_installation\n", "maybe a little too late. I had this same issue yesterday and today.\nTo solve this I had to remove the volume (in this example db_data)\n$docker volume ls\n$docker volume rm db_data\nanother way to fix it was running the container pointing to new volume (e.g. -v db_data2:/var/lib/mysql)\ni thought that passwords were being stored on the volumes and hence its complaining. However, the volume was empty as shown by $ls -al db_data\ndon't understand why empty volume cannot be mounted to a new run\n", "None of the suggested solutions were appropriate in my case, but I solved the same issue by replacing\nPASSWORD=$pecialcharacter$\n with\nPASSWORD='$pecialcharacter$'\nin my .env file. The presence of $ in the variable and the variable not being wrapped in single quotes was causing my issue. Hope this helps someone.\n", "I had the same problem with mariadb.\nmy solution was to upgrade the mariadb image from 10 to 10.8-jammy, of course after cleaning the docker environment images and running containers. I deleted everything and did a clean pull.\n" ]
[ -1, -1, -1, -1, -1 ]
[ "docker", "docker_compose", "dockerfile", "mysql" ]
stackoverflow_0059838692_docker_docker_compose_dockerfile_mysql.txt
Q: Dialog box in VS code extension I want to create the dialog/modal window in vs code. How to create it? I have tried using web view but not got successes. Can any one help me? Thanks in advance. A: It's not possible to show more than a simple input or yes/no dialog in VS Code. This is an IDE focused on editing code, not creating entire workflows. Hence the only way to accomplish a wizard like style is to implement that yourself using a webview (as mentioned a few times in the comments). However, webviews are normal tabs, not modal dialogs, which is all what you can get. On the other hand, it's not really a limitation if the user can switch to other places in VS Code while running your wizard. The webview is in itself modal and you cannot do anything else in that webview while the wizard is running. And finally: modal dialogs are considered problematic UI, as they force the user into some special mode, which is often counter productive. Which means, they should be used with great care. A: There's a project on GitHub that solves this problem. I have used it already and it seems to work: https://github.com/jasongin/vscode-webview-dialog
Dialog box in VS code extension
I want to create the dialog/modal window in vs code. How to create it? I have tried using web view but not got successes. Can any one help me? Thanks in advance.
[ "It's not possible to show more than a simple input or yes/no dialog in VS Code. This is an IDE focused on editing code, not creating entire workflows.\nHence the only way to accomplish a wizard like style is to implement that yourself using a webview (as mentioned a few times in the comments). However, webviews are normal tabs, not modal dialogs, which is all what you can get.\nOn the other hand, it's not really a limitation if the user can switch to other places in VS Code while running your wizard. The webview is in itself modal and you cannot do anything else in that webview while the wizard is running.\nAnd finally: modal dialogs are considered problematic UI, as they force the user into some special mode, which is often counter productive. Which means, they should be used with great care.\n", "There's a project on GitHub that solves this problem. I have used it already and it seems to work: https://github.com/jasongin/vscode-webview-dialog\n" ]
[ 1, 0 ]
[]
[]
[ "vscode_extensions" ]
stackoverflow_0070860521_vscode_extensions.txt
Q: Prevent WheelUp on !WheelUp I am trying to send the letter "a" when ALT is pressed and the mouse wheel is scrolled up. This code works partially: !WheelUp:: Send, a return In Vscode or just the plain Windows Texteditor however, I notice some scrolling if I scroll to hard with my mouse while pressing ALT. Can this be fixed? A: First thing is to check for running applications with high priority. These may interfere with AHK. For example I had similar issues while running AIMP (music player) in the background. Setting the script's priority might be worth trying too.
Prevent WheelUp on !WheelUp
I am trying to send the letter "a" when ALT is pressed and the mouse wheel is scrolled up. This code works partially: !WheelUp:: Send, a return In Vscode or just the plain Windows Texteditor however, I notice some scrolling if I scroll to hard with my mouse while pressing ALT. Can this be fixed?
[ "First thing is to check for running applications with high priority. These may interfere with AHK. For example I had similar issues while running AIMP (music player) in the background.\nSetting the script's priority might be worth trying too.\n" ]
[ 0 ]
[]
[]
[ "autohotkey" ]
stackoverflow_0074503261_autohotkey.txt
Q: How can I "wrap" a capacitor plugin in React so that I can manage it centrally? Today, Capacitor had a new release that replaced the @capacitor-community/http plugin with a CapacitorHttp plugin. I'm using Ionic React for my app so all my code is in TypeScript/React. I want to test out the new CapacitorHttp plugin, but I also want to make it easy to revert back to using the http plugin if things don't work out. Throughout my app, I have a lot of import statements like import { Http } from '@capacitor-community/http';. In React, is there a way to somehow wrap this import so that I can import MyCustomHttp everywhere, and then in MyCustomHttp, import CapacitorHttp or http? This would simplify my code by putting the import in one place, but I don't know how to do this. A: As commented by @Konrad, you can use the { A as B } in a custom file. Here is a code example for the Capacitor Push Notifications plugin: PluginPushNotifications.ts import { ActionPerformed, PushNotifications, Token, } from '@capacitor/push-notifications'; export type { ActionPerformed as PluginActionPerformed }; export type { Token as PluginToken }; export { PushNotifications as PluginPushNotifactions }; To help myself with my IDE's autocomplete, I re-exported everything with a Plugin prefix. A: To "wrap" a capacitor plugin in ReactJS, you can create a custom React component that acts as a wrapper for the plugin. This wrapper component can handle the plugin's initialization, configuration, and usage, and expose the plugin's functionality as props or methods that can be used by other components in the React app. For example, let's say you have a capacitor plugin called MyPlugin that you want to wrap in a React component. You can create a React component called MyPluginWrapper that imports the MyPlugin plugin and initializes it in the componentDidMount lifecycle method. import React, { Component } from 'react'; import { MyPlugin } from 'capacitor-plugin-my-plugin'; class MyPluginWrapper extends Component { componentDidMount() { MyPlugin.init(); } // ... } Next, you can add methods to the MyPluginWrapper component that allow you to use the plugin's functionality from other components in your app. For example, if MyPlugin has a method called doSomething, you can add a method called doSomething to MyPluginWrapper that calls the doSomething method on MyPlugin. class MyPluginWrapper extends Component { // ... doSomething = (options) => { MyPlugin.doSomething(options); } // ... } Finally, you can use the MyPluginWrapper component in other components in your React app, and call the doSomething method on the MyPluginWrapper component to use the MyPlugin plugin's functionality. import React from 'react'; import MyPluginWrapper from './MyPluginWrapper'; const MyComponent = () => { // ... const handleSomething = () => { MyPluginWrapper.doSomething({ ... }); } // ... } By creating a custom React component that wraps the MyPlugin capacitor plugin, you can manage the plugin's initialization, configuration, and usage centrally, and expose its functionality as props or methods that can be used by other components in your app.
How can I "wrap" a capacitor plugin in React so that I can manage it centrally?
Today, Capacitor had a new release that replaced the @capacitor-community/http plugin with a CapacitorHttp plugin. I'm using Ionic React for my app so all my code is in TypeScript/React. I want to test out the new CapacitorHttp plugin, but I also want to make it easy to revert back to using the http plugin if things don't work out. Throughout my app, I have a lot of import statements like import { Http } from '@capacitor-community/http';. In React, is there a way to somehow wrap this import so that I can import MyCustomHttp everywhere, and then in MyCustomHttp, import CapacitorHttp or http? This would simplify my code by putting the import in one place, but I don't know how to do this.
[ "As commented by @Konrad, you can use the { A as B } in a custom file. Here is a code example for the Capacitor Push Notifications plugin:\nPluginPushNotifications.ts\nimport {\n ActionPerformed,\n PushNotifications,\n Token,\n} from '@capacitor/push-notifications';\n\nexport type { ActionPerformed as PluginActionPerformed };\n\nexport type { Token as PluginToken };\n\nexport { PushNotifications as PluginPushNotifactions };\n\nTo help myself with my IDE's autocomplete, I re-exported everything with a Plugin prefix.\n", "To \"wrap\" a capacitor plugin in ReactJS, you can create a custom React component that acts as a wrapper for the plugin. This wrapper component can handle the plugin's initialization, configuration, and usage, and expose the plugin's functionality as props or methods that can be used by other components in the React app.\nFor example, let's say you have a capacitor plugin called MyPlugin that you want to wrap in a React component. You can create a React component called MyPluginWrapper that imports the MyPlugin plugin and initializes it in the componentDidMount lifecycle method.\nimport React, { Component } from 'react';\nimport { MyPlugin } from 'capacitor-plugin-my-plugin';\n\nclass MyPluginWrapper extends Component {\n componentDidMount() {\n MyPlugin.init();\n }\n\n // ...\n}\n\n\nNext, you can add methods to the MyPluginWrapper component that allow you to use the plugin's functionality from other components in your app. For example, if MyPlugin has a method called doSomething, you can add a method called doSomething to MyPluginWrapper that calls the doSomething method on MyPlugin.\nclass MyPluginWrapper extends Component {\n // ...\n\n doSomething = (options) => {\n MyPlugin.doSomething(options);\n }\n\n // ...\n}\n\n\nFinally, you can use the MyPluginWrapper component in other components in your React app, and call the doSomething method on the MyPluginWrapper component to use the MyPlugin plugin's functionality.\nimport React from 'react';\nimport MyPluginWrapper from './MyPluginWrapper';\n\nconst MyComponent = () => {\n // ...\n\n const handleSomething = () => {\n MyPluginWrapper.doSomething({ ... });\n }\n\n // ...\n}\n\n\nBy creating a custom React component that wraps the MyPlugin capacitor plugin, you can manage the plugin's initialization, configuration, and usage centrally, and expose its functionality as props or methods that can be used by other components in your app.\n" ]
[ 0, 0 ]
[]
[]
[ "capacitor", "capacitor_plugin", "reactjs" ]
stackoverflow_0073817081_capacitor_capacitor_plugin_reactjs.txt
Q: Why does the output to my quadratic equation function in Haskell, return (NaN, NaN)? I have a question, the output to my function here gives (NaN, NaN). Did I miss something in the code or? roots :: (Float, Float, Float) -> (Float, Float) roots (a,b,c) = let s = sqrt (b*b - 4.0*a*c) d = 2.0*a in ((-b + s)/d, (-b - s)/d) I searched up and found that NaN is not a number, but why is it displaying when I execute my quadratic equation code in Haskell? Thanks. A: Since the roots can be complex, they can't be represented in a Float in all cases. A possible fix is to switch the result type to involve Complex Float, which stores both the real and imaginary part. Below, x :+ y stands for a complex number with real part x and imaginary part y. import Data.Complex roots :: (Float, Float, Float) -> (Complex Float, Complex Float) roots (a,b,c) = let s = sqrt ((b*b - 4.0*a*c) :+ 0) d = 2.0*a :+ 0 b' = b :+ 0 in ((-b' + s)/d, (-b' - s)/d) Now, complex roots are printed instead of NaNs. > roots (1,0,1) (0.0 :+ 1.0,(-0.0) :+ (-1.0)) (Note that if a is zero we can still get a NaN if we try to compute 0/0. But that's a distinct issue.) By the way, in Haskell we usually define functions in their curried form, i.e. roots :: Float -> Float -> Float -> (Complex Float, Complex Float) roots a b c = ...
Why does the output to my quadratic equation function in Haskell, return (NaN, NaN)?
I have a question, the output to my function here gives (NaN, NaN). Did I miss something in the code or? roots :: (Float, Float, Float) -> (Float, Float) roots (a,b,c) = let s = sqrt (b*b - 4.0*a*c) d = 2.0*a in ((-b + s)/d, (-b - s)/d) I searched up and found that NaN is not a number, but why is it displaying when I execute my quadratic equation code in Haskell? Thanks.
[ "Since the roots can be complex, they can't be represented in a Float in all cases. A possible fix is to switch the result type to involve Complex Float, which stores both the real and imaginary part.\nBelow, x :+ y stands for a complex number with real part x and imaginary part y.\nimport Data.Complex\n\nroots :: (Float, Float, Float) \n -> (Complex Float, Complex Float)\nroots (a,b,c) = \n let s = sqrt ((b*b - 4.0*a*c) :+ 0)\n d = 2.0*a :+ 0\n b' = b :+ 0\n in ((-b' + s)/d, (-b' - s)/d)\n\nNow, complex roots are printed instead of NaNs.\n> roots (1,0,1)\n(0.0 :+ 1.0,(-0.0) :+ (-1.0))\n\n(Note that if a is zero we can still get a NaN if we try to compute 0/0. But that's a distinct issue.)\nBy the way, in Haskell we usually define functions in their curried form, i.e.\nroots :: Float -> Float -> Float \n -> (Complex Float, Complex Float)\nroots a b c = ...\n\n" ]
[ 3 ]
[]
[]
[ "haskell" ]
stackoverflow_0074666705_haskell.txt
Q: Move button closer to the expand button In Vuetify, if I want to move my delete button closer to the expand button. How do I do that ? <v-expansion-panel-header> {{ vehicle.VIN }} <v-icon v-if="type == 'saved'" color="teal"> mdi-check </v-icon> <v-btn text v-if="type == 'saved'" color="red" @click="remove(index, type)" > DELETE </v-btn> </v-expansion-panel-header> A: You can reset the flex-grow property on the delete button using a Vuetify helper class. class="flex-grow-0" Snippet: <div id="app"> <v-app> <v-expansion-panel-header> {{ vehicle.VIN }} <v-icon v-if="type == 'saved'" color="teal"> mdi-check </v-icon> <v-btn class="flex-grow-0" text v-if="type == 'saved'" color="red" @click="remove(index, type)" > DELETE </v-btn> </v-expansion-panel-header> </v-app> </div> Example: Codepen Vuetify Docs: https://vuetifyjs.com/en/styles/flex/#flex-grow-and-shrink A: It can also be achieved using row and column- <v-expansion-panel-header> <v-row no-gutters> <v-col> hello </v-col> <v-col> <v-icon color="teal"> mdi-check </v-icon> </v-col> <v-col align="right"> <v-btn text color="red"> DELETE </v-btn> </v-col> </v-row> </v-expansion-panel-header>
Move button closer to the expand button
In Vuetify, if I want to move my delete button closer to the expand button. How do I do that ? <v-expansion-panel-header> {{ vehicle.VIN }} <v-icon v-if="type == 'saved'" color="teal"> mdi-check </v-icon> <v-btn text v-if="type == 'saved'" color="red" @click="remove(index, type)" > DELETE </v-btn> </v-expansion-panel-header>
[ "You can reset the flex-grow property on the delete button using a Vuetify helper class.\nclass=\"flex-grow-0\"\n\nSnippet:\n<div id=\"app\">\n <v-app>\n <v-expansion-panel-header>\n {{ vehicle.VIN }}\n <v-icon v-if=\"type == 'saved'\" color=\"teal\"> mdi-check </v-icon>\n <v-btn\n class=\"flex-grow-0\"\n text\n v-if=\"type == 'saved'\"\n color=\"red\"\n @click=\"remove(index, type)\"\n >\n DELETE\n </v-btn>\n </v-expansion-panel-header>\n </v-app>\n</div>\n\nExample: Codepen\nVuetify Docs: https://vuetifyjs.com/en/styles/flex/#flex-grow-and-shrink\n", "It can also be achieved using row and column-\n<v-expansion-panel-header>\n <v-row no-gutters>\n <v-col>\n hello\n </v-col>\n <v-col>\n <v-icon color=\"teal\"> mdi-check </v-icon>\n </v-col>\n <v-col align=\"right\">\n <v-btn text color=\"red\">\n DELETE\n </v-btn>\n </v-col>\n </v-row>\n </v-expansion-panel-header>\n\n" ]
[ 1, 1 ]
[]
[]
[ "vue.js", "vuejs2", "vuetify.js" ]
stackoverflow_0074662348_vue.js_vuejs2_vuetify.js.txt
Q: python sqlite3 update binary field SELECT from one database sqlite3 gives me result: b'\n\x0b24 JUN 1974"-\x08\x01\x10\x00\x18\x00 \x18(\x060\xb6\x0f8\x00@\x00H\x00P\x00X\xbf\x84=`\x00h\x00p\x00x\x00\x80\x01\x00\x88\x01\x01\x90\x01\xa0\xdc\x90^' This is field data (VARCHAR(255)) of database My heritage and i want to save the same result to the same database. conn = sqlite3.connect(robocza+"database.ftb") conn.text_factory = bytes cursor = conn.cursor() cursor.execute( "SELECT date FROM individual_fact_main_data where guid ='xxxxxx' " ) rows = cursor.fetchone() given result: b'\n\x0b24 JUN 1974"-\x08\x01\x10\x00\x18\x00 \x18(\x060\xb6\x0f8\x00@\x00H\x00P\x00X\xbf\x84=`\x00h\x00p\x00x\x00\x80\x01\x00\x88\x01\x01\x90\x01\xa0\xdc\x90^' How can i do command UPDATE in the same but new database to write give result properly? A: To update a field in a SQLite database using Python, you can use the UPDATE statement in combination with the execute() method provided by the sqlite3 module. For example, if you want to update the date field of the individual_fact_main_data table in your database, you can use the following Python code: import sqlite3 # Connect to the database conn = sqlite3.connect(robocza+"database.ftb") conn.text_factory = bytes # Create a cursor object cursor = conn.cursor() # Define the UPDATE query query = "UPDATE individual_fact_main_data SET date = ? WHERE guid = ?" # Define the values to update values = (b'\n\x0b24 JUN 1974"-\x08\x01\x10\x00\x18\x00 \x18(\x060\xb6\x0f8\x00@\x00H\x00P\x00X\xbf\x84=`\x00h\x00p\x00x\x00\x80\x01\x00\x88\x01\x01\x90\x01\xa0\xdc\x90^', 'xxxxxx') # Execute the UPDATE query cursor.execute(query, values) # Save the changes to the database conn.commit() # Close the database connection conn.close() This code will update the date field of the individual_fact_main_data table with the specified value, where the guid field has the value xxxxxx. The b'\n\x0b24 JUN 1974"-\x08\x01\x10\x00\x18\x00 \x18(\x060\xb6\x0f8\x00@\x00H\x00P\x00X\xbf\x84=\x00h\x00p\x00x\x00\x80\x01\x00\x88\x01\x01\x90\x01\xa0\xdc\x90^'` value is the binary representation of the date, which is the default representation for VARCHAR(255) fields in SQLite. For more information about the UPDATE statement and other SQLite commands, you can refer to the SQLite documentation.
python sqlite3 update binary field
SELECT from one database sqlite3 gives me result: b'\n\x0b24 JUN 1974"-\x08\x01\x10\x00\x18\x00 \x18(\x060\xb6\x0f8\x00@\x00H\x00P\x00X\xbf\x84=`\x00h\x00p\x00x\x00\x80\x01\x00\x88\x01\x01\x90\x01\xa0\xdc\x90^' This is field data (VARCHAR(255)) of database My heritage and i want to save the same result to the same database. conn = sqlite3.connect(robocza+"database.ftb") conn.text_factory = bytes cursor = conn.cursor() cursor.execute( "SELECT date FROM individual_fact_main_data where guid ='xxxxxx' " ) rows = cursor.fetchone() given result: b'\n\x0b24 JUN 1974"-\x08\x01\x10\x00\x18\x00 \x18(\x060\xb6\x0f8\x00@\x00H\x00P\x00X\xbf\x84=`\x00h\x00p\x00x\x00\x80\x01\x00\x88\x01\x01\x90\x01\xa0\xdc\x90^' How can i do command UPDATE in the same but new database to write give result properly?
[ "To update a field in a SQLite database using Python, you can use the UPDATE statement in combination with the execute() method provided by the sqlite3 module.\nFor example, if you want to update the date field of the individual_fact_main_data table in your database, you can use the following Python code:\nimport sqlite3\n\n# Connect to the database\nconn = sqlite3.connect(robocza+\"database.ftb\")\nconn.text_factory = bytes\n\n# Create a cursor object\ncursor = conn.cursor()\n\n# Define the UPDATE query\nquery = \"UPDATE individual_fact_main_data SET date = ? WHERE guid = ?\"\n\n# Define the values to update\nvalues = (b'\\n\\x0b24 JUN 1974\"-\\x08\\x01\\x10\\x00\\x18\\x00 \\x18(\\x060\\xb6\\x0f8\\x00@\\x00H\\x00P\\x00X\\xbf\\x84=`\\x00h\\x00p\\x00x\\x00\\x80\\x01\\x00\\x88\\x01\\x01\\x90\\x01\\xa0\\xdc\\x90^', 'xxxxxx')\n\n# Execute the UPDATE query\ncursor.execute(query, values)\n\n# Save the changes to the database\nconn.commit()\n\n# Close the database connection\nconn.close()\n\nThis code will update the date field of the individual_fact_main_data table with the specified value, where the guid field has the value xxxxxx. The b'\\n\\x0b24 JUN 1974\"-\\x08\\x01\\x10\\x00\\x18\\x00 \\x18(\\x060\\xb6\\x0f8\\x00@\\x00H\\x00P\\x00X\\xbf\\x84=\\x00h\\x00p\\x00x\\x00\\x80\\x01\\x00\\x88\\x01\\x01\\x90\\x01\\xa0\\xdc\\x90^'` value is the binary representation of the date, which is the default representation for VARCHAR(255) fields in SQLite.\nFor more information about the UPDATE statement and other SQLite commands, you can refer to the SQLite documentation.\n" ]
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074667914_python_sqlite.txt
Q: error while making get api request in flutter This is my homeView code calling from main.dart, I don't know what is the error I tried many times but not been solved, I am trying to debug but I don't know why there is no msg print in the console or run tab. I am taking JSON placeholder demo api from the website and creating a model from quicktype, but finally i could not check why I didn't receive any response. api is also checked in website and postman it worked but in code not get any request please help import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import '../models/userModel.dart'; class HomeView extends StatefulWidget { const HomeView({Key? key}) : super(key: key); @override State<HomeView> createState() => _HomeViewState(); } class _HomeViewState extends State<HomeView> { //create an empty array or list List<Users> userDetails = []; //future response from server (get users details from api) Future<List<Users>> getUsers() async { print("api method calling"); final response = await http.get(Uri.parse("https://jsonplaceholder.typicode.com/users"),); print('api response check'); var data = jsonDecode(response.body.toString()); print('api data received'); if (response.statusCode == 200) { for (Map<String, dynamic> index in data) { userDetails.add(Users.fromJson(index)); } return userDetails; } else { return userDetails; } } @override Widget build(BuildContext context) { return FutureBuilder( future: getUsers(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { print('no connection error'); if (snapshot.hasData) { print('snapshot has data'); return ListView.builder( itemCount: 1, itemBuilder: (context, index) { return Container( margin: const EdgeInsets.all(10), height: 100, color: Colors.greenAccent, padding: const EdgeInsets.symmetric( vertical: 10, horizontal: 20), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: const [ Text('User Id : data'), Text('User Id : data'), Text('User Id : data'), Text('User Id : data'), ], ), ); }); } else { print('snapshot has no data'); return const Center( child: CircularProgressIndicator(), ); } }else{ return Center( child: Text("connection error"), ); } }); } } Here is my Model // To parse this JSON data, do // // final users = usersFromJson(jsonString); import 'dart:convert'; List<Users> usersFromJson(String str) => List<Users>.from(json.decode(str).map((x) => Users.fromJson(x))); String usersToJson(List<Users> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class Users { Users({ required this.id, required this.name, required this.username, required this.email, required this.address, required this.phone, required this.website, required this.company, }); int id; String name; String username; String email; Address address; String phone; String website; Company company; factory Users.fromJson(Map<String, dynamic> json) => Users( id: json["id"], name: json["name"], username: json["username"], email: json["email"], address: Address.fromJson(json["address"]), phone: json["phone"], website: json["website"], company: Company.fromJson(json["company"]), ); Map<String, dynamic> toJson() => { "id": id, "name": name, "username": username, "email": email, "address": address.toJson(), "phone": phone, "website": website, "company": company.toJson(), }; } class Address { Address({ required this.street, required this.suite, required this.city, required this.zipcode, required this.geo, }); String street; String suite; String city; String zipcode; Geo geo; factory Address.fromJson(Map<String, dynamic> json) => Address( street: json["street"], suite: json["suite"], city: json["city"], zipcode: json["zipcode"], geo: Geo.fromJson(json["geo"]), ); Map<String, dynamic> toJson() => { "street": street, "suite": suite, "city": city, "zipcode": zipcode, "geo": geo.toJson(), }; } class Geo { Geo({ required this.lat, required this.lng, }); String lat; String lng; factory Geo.fromJson(Map<String, dynamic> json) => Geo( lat: json["lat"], lng: json["lng"], ); Map<String, dynamic> toJson() => { "lat": lat, "lng": lng, }; } class Company { Company({ required this.name, required this.catchPhrase, required this.bs, }); String name; String catchPhrase; String bs; factory Company.fromJson(Map<String, dynamic> json) => Company( name: json["name"], catchPhrase: json["catchPhrase"], bs: json["bs"], ); Map<String, dynamic> toJson() => { "name": name, "catchPhrase": catchPhrase, "bs": bs, }; } Here is main.dart file import 'package:flutter/material.dart'; import 'package:responsive_login_ui/views/home_view.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar(title: Text('User Data From Api'),), body: HomeView() ), ); } } A: Add the following line in HomeView page late Future<List<Users>> userAlbum; @override void initState() { super.initState(); userAlbum = getUsers(); } And change future: getUsers(), to future: userAlbum, The main reason for your code not working might be the future being called later. The above snippet is from the docs for HTTP request in flutter. Hope this helps. Happy Coding:)
error while making get api request in flutter
This is my homeView code calling from main.dart, I don't know what is the error I tried many times but not been solved, I am trying to debug but I don't know why there is no msg print in the console or run tab. I am taking JSON placeholder demo api from the website and creating a model from quicktype, but finally i could not check why I didn't receive any response. api is also checked in website and postman it worked but in code not get any request please help import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import '../models/userModel.dart'; class HomeView extends StatefulWidget { const HomeView({Key? key}) : super(key: key); @override State<HomeView> createState() => _HomeViewState(); } class _HomeViewState extends State<HomeView> { //create an empty array or list List<Users> userDetails = []; //future response from server (get users details from api) Future<List<Users>> getUsers() async { print("api method calling"); final response = await http.get(Uri.parse("https://jsonplaceholder.typicode.com/users"),); print('api response check'); var data = jsonDecode(response.body.toString()); print('api data received'); if (response.statusCode == 200) { for (Map<String, dynamic> index in data) { userDetails.add(Users.fromJson(index)); } return userDetails; } else { return userDetails; } } @override Widget build(BuildContext context) { return FutureBuilder( future: getUsers(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { print('no connection error'); if (snapshot.hasData) { print('snapshot has data'); return ListView.builder( itemCount: 1, itemBuilder: (context, index) { return Container( margin: const EdgeInsets.all(10), height: 100, color: Colors.greenAccent, padding: const EdgeInsets.symmetric( vertical: 10, horizontal: 20), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: const [ Text('User Id : data'), Text('User Id : data'), Text('User Id : data'), Text('User Id : data'), ], ), ); }); } else { print('snapshot has no data'); return const Center( child: CircularProgressIndicator(), ); } }else{ return Center( child: Text("connection error"), ); } }); } } Here is my Model // To parse this JSON data, do // // final users = usersFromJson(jsonString); import 'dart:convert'; List<Users> usersFromJson(String str) => List<Users>.from(json.decode(str).map((x) => Users.fromJson(x))); String usersToJson(List<Users> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class Users { Users({ required this.id, required this.name, required this.username, required this.email, required this.address, required this.phone, required this.website, required this.company, }); int id; String name; String username; String email; Address address; String phone; String website; Company company; factory Users.fromJson(Map<String, dynamic> json) => Users( id: json["id"], name: json["name"], username: json["username"], email: json["email"], address: Address.fromJson(json["address"]), phone: json["phone"], website: json["website"], company: Company.fromJson(json["company"]), ); Map<String, dynamic> toJson() => { "id": id, "name": name, "username": username, "email": email, "address": address.toJson(), "phone": phone, "website": website, "company": company.toJson(), }; } class Address { Address({ required this.street, required this.suite, required this.city, required this.zipcode, required this.geo, }); String street; String suite; String city; String zipcode; Geo geo; factory Address.fromJson(Map<String, dynamic> json) => Address( street: json["street"], suite: json["suite"], city: json["city"], zipcode: json["zipcode"], geo: Geo.fromJson(json["geo"]), ); Map<String, dynamic> toJson() => { "street": street, "suite": suite, "city": city, "zipcode": zipcode, "geo": geo.toJson(), }; } class Geo { Geo({ required this.lat, required this.lng, }); String lat; String lng; factory Geo.fromJson(Map<String, dynamic> json) => Geo( lat: json["lat"], lng: json["lng"], ); Map<String, dynamic> toJson() => { "lat": lat, "lng": lng, }; } class Company { Company({ required this.name, required this.catchPhrase, required this.bs, }); String name; String catchPhrase; String bs; factory Company.fromJson(Map<String, dynamic> json) => Company( name: json["name"], catchPhrase: json["catchPhrase"], bs: json["bs"], ); Map<String, dynamic> toJson() => { "name": name, "catchPhrase": catchPhrase, "bs": bs, }; } Here is main.dart file import 'package:flutter/material.dart'; import 'package:responsive_login_ui/views/home_view.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar(title: Text('User Data From Api'),), body: HomeView() ), ); } }
[ "Add the following line in HomeView page\nlate Future<List<Users>> userAlbum;\n\n@override\nvoid initState() {\n super.initState();\n userAlbum = getUsers();\n}\n\nAnd change\nfuture: getUsers(),\n\nto\nfuture: userAlbum,\n\nThe main reason for your code not working might be the future being called later. The above snippet is from the docs for HTTP request in flutter.\nHope this helps. Happy Coding:)\n" ]
[ 0 ]
[]
[]
[ "android", "dart", "flutter", "flutter_dependencies" ]
stackoverflow_0074667736_android_dart_flutter_flutter_dependencies.txt
Q: How to loop event in ReactJS site I I am writing chrome extension to ReactJS Website(it's not my). I have function to put data in field and press button. Something like that(for example): ` function pressBTN(btn) { let mouseClickEvents = ['mousedown', 'click', 'mouseup']; mouseClickEvents.forEach(mouseEventType => btn.dispatchEvent( new MouseEvent(mouseEventType, { view: window, bubbles: true, cancelable: true, buttons: 1 }))); } But if I try to put it to the loop: for(x=0;x<4;x++) { let btn=document.querySelectorAll('button#my_good_btn')[x]; pressBTN(btn); } It's make one move and die. May be somebady have this problem and help me? Thank you so much I tried to delete created elements. But without result. If I click on button with this element 4 time it's work...but I need to automaticaly 4 events in one loop. A: It looks like the problem is that you are using x as the loop variable in the for loop, but you are using i as the index when you try to access the element in the document.querySelectorAll call. This means that on the first iteration of the loop, you are trying to access the element at index i, which is undefined and causes the script to fail. To fix this problem, you can simply use x as the index when you access the element in the querySelectorAll call: for(let x=0; x<4; x++) { let btn=document.querySelectorAll('button#my_good_btn')[x]; pressBTN(btn); } This should fix the problem and allow your loop to run correctly.
How to loop event in ReactJS site
I I am writing chrome extension to ReactJS Website(it's not my). I have function to put data in field and press button. Something like that(for example): ` function pressBTN(btn) { let mouseClickEvents = ['mousedown', 'click', 'mouseup']; mouseClickEvents.forEach(mouseEventType => btn.dispatchEvent( new MouseEvent(mouseEventType, { view: window, bubbles: true, cancelable: true, buttons: 1 }))); } But if I try to put it to the loop: for(x=0;x<4;x++) { let btn=document.querySelectorAll('button#my_good_btn')[x]; pressBTN(btn); } It's make one move and die. May be somebady have this problem and help me? Thank you so much I tried to delete created elements. But without result. If I click on button with this element 4 time it's work...but I need to automaticaly 4 events in one loop.
[ "It looks like the problem is that you are using x as the loop variable in the for loop, but you are using i as the index when you try to access the element in the document.querySelectorAll call. This means that on the first iteration of the loop, you are trying to access the element at index i, which is undefined and causes the script to fail.\nTo fix this problem, you can simply use x as the index when you access the element in the querySelectorAll call:\nfor(let x=0; x<4; x++) { \n let btn=document.querySelectorAll('button#my_good_btn')[x]; \n pressBTN(btn); \n}\n\nThis should fix the problem and allow your loop to run correctly.\n" ]
[ 0 ]
[]
[]
[ "javascript", "loops", "mouseevent", "reactjs" ]
stackoverflow_0074667298_javascript_loops_mouseevent_reactjs.txt
Q: How to group by data in a column with pandas? I have a table with 8,000 rows of data and a small sample of it here: Customer ItemDescription Invoice PurchaseDate 1064 Produce 55514 22-01 1064 Snack 55514 22-01 1080 Drink 56511 23-01 1080 Snack 56511 23-01 1230 Drink 55551 26-03 1230 Snack 55551 26-03 1128 Meat 55003 04-03 1128 Snack 55003 04-03 1229 Drink 55100 06-03 1229 Snack 55100 06-03 1230 Meat 55102 07-03 1230 Snack 55102 07-03 I am trying to find the top 3 items that customers have bought along with "Snack". So the printed result should look like this: 0 Drink 1 Meat 2 Produce I have tried df.groupby but it doesn't sort them based on what was purchased along with "snacks". A: You can use groupby. By using groupby, you can group the products according to the customers and store them in the form of a list. dfx=df.groupby('Customer').agg({'ItemDescription':list}) ''' ItemDescription Customer 1064 [Produce, Snack] 1080 [Drink, Snack] 1128 [Meat, Snack] 1229 [Drink, Snack] 1230 [Drink, Snack, Meat, Snack] ''' Here we will need to filter out customers who have not purchased a snack. dfx=dfx[pd.DataFrame(dfx.ItemDescription.tolist()).isin(['Snack']).any(1).values] # https://stackoverflow.com/a/53343080/15415267 Then, convert the remaining rows into a list and get distributions with the Counter function. products=dfx.explode('ItemDescription')['ItemDescription'].to_list() #['Produce', 'Snack', 'Drink', 'Snack', 'Meat', 'Snack', 'Drink', 'Snack', 'Drink', 'Snack', 'Meat', 'Snack'] from collections import Counter occurence_count = Counter(top) occurence_count.most_common(4) #get top 4 product #[('Snack', 6), ('Drink', 3), ('Meat', 2), ('Produce', 1)] If you convert results to dataframe: final =pd.DataFrame(occurence_count.most_common(4),columns=['product','count']) ''' product count 0 Snack 6 1 Drink 3 2 Meat 2 3 Produce 1 ''' or (shorter): dfx=df.groupby('Customer').agg({'ItemDescription':list}) ''' ItemDescription Customer 1064 [Produce, Snack] 1080 [Drink, Snack] 1128 [Meat, Snack] 1229 [Drink, Snack] 1230 [Drink, Snack, Meat, Snack] ''' dfx=dfx[pd.DataFrame(dfx.ItemDescription.tolist()).isin(['Snack']).any(1).values] # https://stackoverflow.com/a/53343080/15415267 products=dfx2.explode('ItemDescription')['ItemDescription'].value_counts()[0:4] ''' ItemDescription Snack 6 Drink 3 Meat 2 Produce 1 ''' A: To find the top 3 items that customers have bought along with "Snack", you can use the groupby() and value_counts() methods in pandas. Here is an example of how you can do this: import pandas as pd # Create a sample DataFrame df = pd.DataFrame({'Customer': [1064, 1064, 1080, 1080, 1230, 1230, 1128, 1128, 1229, 1229, 1230, 1230], 'ItemDescription': ['Produce', 'Snack', 'Drink', 'Snack', 'Drink', 'Snack', 'Meat', 'Snack', 'Drink', 'Snack', 'Meat', 'Snack'], 'Invoice': [55514, 55514, 56511, 56511, 55551, 55551, 55003, 55003, 55100, 55100, 55102, 55102], 'PurchaseDate': ['22-01', '22-01', '23-01', '23-01', '26-03', '26-03', '04-03', '04-03', '06-03', '06-03', '07-03', '07-03']}) # Group the data by Customer df_grouped = df.groupby('Customer') # Create a dictionary to store the counts of items bought along with "Snack" for each customer item_counts = {} # Loop through each customer group for customer, group in df_grouped: # Create a new DataFrame that only includes rows where the ItemDescription is "Snack" snacks = group[group['ItemDescription'] == 'Snack'] # Loop through each row in the snacks DataFrame for index, row in snacks.iterrows(): # Get the Invoice number for the current row invoice = row['Invoice'] # Get the rows in the original DataFrame that have the same Invoice number as the current row invoice_rows = df[df['Invoice'] == invoice] # Loop through each row in the invoice_rows DataFrame for i, r in invoice_rows.iterrows(): # If the ItemDescription is not "Snack", increment the count for that item in the item_counts dictionary if r['ItemDescription'] != 'Snack': item = r['ItemDescription'] if item not in item_counts: item_counts[item] = 0 item_counts[item] += 1 # Sort the item_counts dictionary by value in descending order sorted_items = sorted(item_counts.items(), key=lambda x: x[1], reverse=True) # Print the top 3 items that customers have bought along with "Snack" for i in range(3): print(i, sorted_items[i][0]) In the example above, the data in the DataFrame is first grouped by the values in the Customer column. Then, for each customer group, the rows where the ItemDescription is "Snack" are extracted and stored in a new DataFrame. For each row in the snacks DataFrame, the rows in the original DataFrame that have the same Invoice number are extracted and stored in a new DataFrame. Finally, for each row in the invoice_rows DataFrame, the ItemDescription is checked. If the ItemDescription is not "Snack", the count for that item is incremented in the item_counts dictionary. After all the customer groups have been processed, the item_counts dictionary is sorted by value in descending order, and the top 3 items are printed. A: IIUC your requirement is to get the top items that were taken along with "Snack". So you first want to filter those Customers who didn't buy snack. Use groupby.filter for that. And then you want to compute the top items in terms of count. For that you use value_counts and then you take top 3 other than "Snack". s = ( df.groupby("Customer") .filter(lambda x: "Snack" not in x)["ItemDescription"] .value_counts() ) top_3 = s.loc[s.index.difference(["Snack"])][:3] print(top_3): Drink 3 Meat 2 Produce 1
How to group by data in a column with pandas?
I have a table with 8,000 rows of data and a small sample of it here: Customer ItemDescription Invoice PurchaseDate 1064 Produce 55514 22-01 1064 Snack 55514 22-01 1080 Drink 56511 23-01 1080 Snack 56511 23-01 1230 Drink 55551 26-03 1230 Snack 55551 26-03 1128 Meat 55003 04-03 1128 Snack 55003 04-03 1229 Drink 55100 06-03 1229 Snack 55100 06-03 1230 Meat 55102 07-03 1230 Snack 55102 07-03 I am trying to find the top 3 items that customers have bought along with "Snack". So the printed result should look like this: 0 Drink 1 Meat 2 Produce I have tried df.groupby but it doesn't sort them based on what was purchased along with "snacks".
[ "You can use groupby. By using groupby, you can group the products according to the customers and store them in the form of a list.\ndfx=df.groupby('Customer').agg({'ItemDescription':list})\n'''\n ItemDescription\nCustomer \n1064 [Produce, Snack]\n1080 [Drink, Snack]\n1128 [Meat, Snack]\n1229 [Drink, Snack]\n1230 [Drink, Snack, Meat, Snack]\n'''\n\nHere we will need to filter out customers who have not purchased a snack.\ndfx=dfx[pd.DataFrame(dfx.ItemDescription.tolist()).isin(['Snack']).any(1).values] # https://stackoverflow.com/a/53343080/15415267\n\nThen, convert the remaining rows into a list and get distributions with the Counter function.\nproducts=dfx.explode('ItemDescription')['ItemDescription'].to_list()\n#['Produce', 'Snack', 'Drink', 'Snack', 'Meat', 'Snack', 'Drink', 'Snack', 'Drink', 'Snack', 'Meat', 'Snack']\n\nfrom collections import Counter\noccurence_count = Counter(top)\noccurence_count.most_common(4) #get top 4 product \n#[('Snack', 6), ('Drink', 3), ('Meat', 2), ('Produce', 1)]\n\nIf you convert results to dataframe:\nfinal =pd.DataFrame(occurence_count.most_common(4),columns=['product','count'])\n'''\n product count\n0 Snack 6\n1 Drink 3\n2 Meat 2\n3 Produce 1\n\n'''\n\nor (shorter):\ndfx=df.groupby('Customer').agg({'ItemDescription':list})\n'''\n ItemDescription\nCustomer \n1064 [Produce, Snack]\n1080 [Drink, Snack]\n1128 [Meat, Snack]\n1229 [Drink, Snack]\n1230 [Drink, Snack, Meat, Snack]\n'''\n\ndfx=dfx[pd.DataFrame(dfx.ItemDescription.tolist()).isin(['Snack']).any(1).values] # https://stackoverflow.com/a/53343080/15415267\nproducts=dfx2.explode('ItemDescription')['ItemDescription'].value_counts()[0:4]\n'''\n ItemDescription\nSnack 6\nDrink 3\nMeat 2\nProduce 1\n\n'''\n\n\n", "To find the top 3 items that customers have bought along with \"Snack\", you can use the groupby() and value_counts() methods in pandas. Here is an example of how you can do this:\nimport pandas as pd\n\n# Create a sample DataFrame\ndf = pd.DataFrame({'Customer': [1064, 1064, 1080, 1080, 1230, 1230, 1128, 1128, 1229, 1229, 1230, 1230],\n 'ItemDescription': ['Produce', 'Snack', 'Drink', 'Snack', 'Drink', 'Snack', 'Meat', 'Snack', 'Drink', 'Snack', 'Meat', 'Snack'],\n 'Invoice': [55514, 55514, 56511, 56511, 55551, 55551, 55003, 55003, 55100, 55100, 55102, 55102],\n 'PurchaseDate': ['22-01', '22-01', '23-01', '23-01', '26-03', '26-03', '04-03', '04-03', '06-03', '06-03', '07-03', '07-03']})\n\n# Group the data by Customer\ndf_grouped = df.groupby('Customer')\n\n# Create a dictionary to store the counts of items bought along with \"Snack\" for each customer\nitem_counts = {}\n\n# Loop through each customer group\nfor customer, group in df_grouped:\n # Create a new DataFrame that only includes rows where the ItemDescription is \"Snack\"\n snacks = group[group['ItemDescription'] == 'Snack']\n\n # Loop through each row in the snacks DataFrame\n for index, row in snacks.iterrows():\n # Get the Invoice number for the current row\n invoice = row['Invoice']\n\n # Get the rows in the original DataFrame that have the same Invoice number as the current row\n invoice_rows = df[df['Invoice'] == invoice]\n\n # Loop through each row in the invoice_rows DataFrame\n for i, r in invoice_rows.iterrows():\n # If the ItemDescription is not \"Snack\", increment the count for that item in the item_counts dictionary\n if r['ItemDescription'] != 'Snack':\n item = r['ItemDescription']\n if item not in item_counts:\n item_counts[item] = 0\n item_counts[item] += 1\n\n# Sort the item_counts dictionary by value in descending order\nsorted_items = sorted(item_counts.items(), key=lambda x: x[1], reverse=True)\n\n# Print the top 3 items that customers have bought along with \"Snack\"\nfor i in range(3):\n print(i, sorted_items[i][0])\n\nIn the example above, the data in the DataFrame is first grouped by the values in the Customer column.\nThen, for each customer group, the rows where the ItemDescription is \"Snack\" are extracted and stored in a new DataFrame.\nFor each row in the snacks DataFrame, the rows in the original DataFrame that have the same Invoice number are extracted and stored in a new DataFrame.\nFinally, for each row in the invoice_rows DataFrame, the ItemDescription is checked. If the ItemDescription is not \"Snack\", the count for that item is incremented in the item_counts dictionary. After all the customer groups have been processed, the item_counts dictionary is sorted by value in descending order, and the top 3 items are printed.\n", "IIUC your requirement is to get the top items that were taken along with \"Snack\". So you first want to filter those Customers who didn't buy snack.\nUse groupby.filter for that. And then you want to compute the top items in terms of count. For that you use value_counts and then you take top 3 other than \"Snack\".\ns = (\n df.groupby(\"Customer\")\n .filter(lambda x: \"Snack\" not in x)[\"ItemDescription\"]\n .value_counts()\n)\ntop_3 = s.loc[s.index.difference([\"Snack\"])][:3]\n\nprint(top_3):\nDrink 3\nMeat 2\nProduce 1\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074666835_dataframe_pandas_python.txt
Q: Maui "The current Activity can not be detected. Ensure that you have called Init in your Activity or Application class." I am using Xam.Plugin.Media nuget package. await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { SaveToAlbum = true, PhotoSize = PhotoSize.MaxWidthHeight, Name = fullFileName, DefaultCamera = CameraDevice.Rear, MaxWidthHeight = 1000, AllowCropping = false }); A: You can do one thing. public class MainActivity : MauiAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { Xamarin.Essentials.Platform.Init(this, savedInstanceState); base.OnCreate(savedInstanceState); } } just update this in MainActivity.cs under Platform>Android folder in MAUI. Mine has worked perfectly I hope you will find it useful too.
Maui "The current Activity can not be detected. Ensure that you have called Init in your Activity or Application class."
I am using Xam.Plugin.Media nuget package. await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { SaveToAlbum = true, PhotoSize = PhotoSize.MaxWidthHeight, Name = fullFileName, DefaultCamera = CameraDevice.Rear, MaxWidthHeight = 1000, AllowCropping = false });
[ "You can do one thing.\npublic class MainActivity : MauiAppCompatActivity\n{\n protected override void OnCreate(Bundle savedInstanceState)\n {\n Xamarin.Essentials.Platform.Init(this, savedInstanceState);\n base.OnCreate(savedInstanceState);\n }\n}\n\njust update this in MainActivity.cs under Platform>Android folder in MAUI.\nMine has worked perfectly I hope you will find it useful too.\n" ]
[ 1 ]
[]
[]
[ ".net", "maui", "plugin.media.crossmedia" ]
stackoverflow_0074667227_.net_maui_plugin.media.crossmedia.txt
Q: Is there a thing such as border-padding? I have two SVG icons, and all I want to do is apply a background, add some padding, and make the padding appear round (border-radius). When adding the padding all is fine and appears as expected, it's only when trying to make it round. No matter what the amount of padding is, the SVG's are cut off. SVG with 10px padding and 50% border-radius: For reference, this is what the SVG normally looks like: As I explained above, I tried many different padding sizes, but all result in a part of the SVG being cutoff. I've searched on the topic, but the only things I could find were: Link 1 - It was about another topic not related to mine. Link 2 - I tried border-block-start, but unfortunately nothing happened. Can anyone help me? A: Well there is somewhat of a easy solution for this. Some time ago I needed a svg camera icon with number in it, so I found this website for creating custom svg it is easy to use and you can copy paste any existing svg into the program and edit or add styling/drawings to it. Website: https://pixelied.com/ Top right click 'Explore editor' You could just create your svg with the desired spacing with the round edge/border. A: This is what I was referring to. Idk if this is what you are asking or not. .container { display: flex; justify-content: center; align-items: center; background: linear-gradient(45deg, blue, green); border-radius: 50%; width: 200px; height: 200px; } .img-container{ display: flex; justify-content: center; align-items: center; height: 65%; width: 65%; border-radius: 23px; object-fit: contain; overflow: hidden; } .img-container > img { height: 138%; width: 149%; } <div class="container"> <div class="img-container"> <img src="https://i.stack.imgur.com/831mz.png"> </div> </div>
Is there a thing such as border-padding?
I have two SVG icons, and all I want to do is apply a background, add some padding, and make the padding appear round (border-radius). When adding the padding all is fine and appears as expected, it's only when trying to make it round. No matter what the amount of padding is, the SVG's are cut off. SVG with 10px padding and 50% border-radius: For reference, this is what the SVG normally looks like: As I explained above, I tried many different padding sizes, but all result in a part of the SVG being cutoff. I've searched on the topic, but the only things I could find were: Link 1 - It was about another topic not related to mine. Link 2 - I tried border-block-start, but unfortunately nothing happened. Can anyone help me?
[ "Well there is somewhat of a easy solution for this.\nSome time ago I needed a svg camera icon with number in it, so I found this website for creating custom svg it is easy to use and you can copy paste any existing svg into the program and edit or add styling/drawings to it.\nWebsite: https://pixelied.com/\nTop right click 'Explore editor'\nYou could just create your svg with the desired spacing with the round edge/border.\n", "This is what I was referring to. Idk if this is what you are asking or not.\n\n\n.container {\n display: flex;\n justify-content: center;\n align-items: center;\n background: linear-gradient(45deg, blue, green);\n border-radius: 50%;\n width: 200px;\n height: 200px;\n}\n.img-container{\n display: flex;\n justify-content: center;\n align-items: center;\n height: 65%;\n width: 65%;\n border-radius: 23px;\n object-fit: contain;\n overflow: hidden;\n \n}\n\n.img-container > img {\n height: 138%;\n width: 149%;\n }\n<div class=\"container\">\n <div class=\"img-container\">\n <img src=\"https://i.stack.imgur.com/831mz.png\">\n </div>\n</div>\n\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "css", "frontend", "html", "padding", "sass" ]
stackoverflow_0074667386_css_frontend_html_padding_sass.txt
Q: Convert a three column dataframe to JSON for a multi line plot I have a data frame as attached. And I'm trying to get to convert it to a JSON. Table: id date count A 01-Nov 20 A 02-Nov 30 A 03-Nov 50 B 01-Nov 10 B 02-Nov 45 B 03-Nov 23 C 01-Nov 12 C 02-Nov 34 C 03-Nov 45 df = pd.DataFrame({'id': ['A']*3+['B']*3+['C']*3 , 'date': ['01-Nov','02-Nov','03-Nov']*3 , 'count': [20,30,50,10,45,23,12,34,45]}) Expecting the output as: { "date": [ "01 Nov", "02 Nov", "03 Nov", ], "values": [ { "id": "A", "count": [20,30,50] }, { "id": "B", "count": [10,45,23] }, { "id": "C", "count": [12,34,45] } ] } Any pointers would be helpful… I was able to use to_json but it isn't giving me the format as above. A: try this: dfx=df.groupby('id').agg(list).reset_index() #groupby id and keep values in a list. ''' id date count 0 A [01-Nov, 02-Nov, 03-Nov] [20, 30, 50] 1 B [01-Nov, 02-Nov, 03-Nov] [10, 45, 23] 2 C [01-Nov, 02-Nov, 03-Nov] [12, 34, 45] ''' out= {'date':dfx['date'][0],'values':dfx[['id','count']].to_dict('records')} ''' { "date": [ "01-Nov", "02-Nov", "03-Nov", ], "values": [ { "id": "A", "count": [20,30,50] }, { "id": "B", "count": [10,45,23] }, { "id": "C", "count": [12,34,45] } ] } '''
Convert a three column dataframe to JSON for a multi line plot
I have a data frame as attached. And I'm trying to get to convert it to a JSON. Table: id date count A 01-Nov 20 A 02-Nov 30 A 03-Nov 50 B 01-Nov 10 B 02-Nov 45 B 03-Nov 23 C 01-Nov 12 C 02-Nov 34 C 03-Nov 45 df = pd.DataFrame({'id': ['A']*3+['B']*3+['C']*3 , 'date': ['01-Nov','02-Nov','03-Nov']*3 , 'count': [20,30,50,10,45,23,12,34,45]}) Expecting the output as: { "date": [ "01 Nov", "02 Nov", "03 Nov", ], "values": [ { "id": "A", "count": [20,30,50] }, { "id": "B", "count": [10,45,23] }, { "id": "C", "count": [12,34,45] } ] } Any pointers would be helpful… I was able to use to_json but it isn't giving me the format as above.
[ "try this:\ndfx=df.groupby('id').agg(list).reset_index() #groupby id and keep values in a list.\n'''\n id date count\n0 A [01-Nov, 02-Nov, 03-Nov] [20, 30, 50]\n1 B [01-Nov, 02-Nov, 03-Nov] [10, 45, 23]\n2 C [01-Nov, 02-Nov, 03-Nov] [12, 34, 45]\n'''\nout= {'date':dfx['date'][0],'values':dfx[['id','count']].to_dict('records')}\n\n'''\n{\n \"date\": [\n \"01-Nov\",\n \"02-Nov\",\n \"03-Nov\",\n ], \"values\": [\n {\n \"id\": \"A\",\n \"count\": [20,30,50]\n },\n {\n \"id\": \"B\",\n \"count\": [10,45,23]\n },\n {\n \"id\": \"C\",\n \"count\": [12,34,45]\n }\n ]\n}\n'''\n\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python_3.x" ]
stackoverflow_0074667523_dataframe_numpy_pandas_python_3.x.txt
Q: Fit data with a function that equals 0 and could not be converted to the form f(x) = x I have 2 columns and 31 rows in a pandas dataframe. I want to plot this x,y data and fit them to a complex function with 4 parameters. The function looks something like this. The function has to be 0 # Data: T,p = df["T"], df["p"] #31 rows # known constants: a,b,Ta,c0,x def c(T,v,VP,a=...,b=...,Ta=...,c0=...): c = c0 + a*(T-Ta) + b*t_r(T)**v/(t_r(T)**v-K(T,VP)) return c # t_r and K are other functions def function(p,T,p0,v,N,VP,a,b,c0,x): return np.log(1-p) + p + (x*c(T,v,VP))*p**2 + (p0/N)*(R-0.5*R**3) # =0 I am interested in fitting the parameters N,p0,Vp I tried to use Lmfit and changed my function to -> function(params,T,p) from Lmfit import minimize, Parameters ## add Parameters params = Parameters() ##Class with a list of parameters # add all constant Parameters with vary = False params.add("a", value=...,vary=False) ... ## add variables to fit with vary = True, limits with min,max params.add("N",value=..., vary=True,min=0,max=...) ... output = minimize(function,params) #Fit Results output.params.pretty_print() #Show Results Now I acquired the parameters, but I want to check if this makes sense by plot(T,p) for a more continous array, like: Ts = np.linspace(10,60,1000) # x-array ps = ... ? # y-array plt.plot(Ts,ps,label="Fit") # Plot Data How could I obtain a function to calculate p for T on each point to plot it ? A: I find an answer myself. First I wrap my function in a way that the y-value p is the first argument. And I used lmfit parameter class as arguments. Lmfit Parameters are basically dictionaries. p_solvable = lambda p,T,parameter : function(p,T,parameter["p0"],parameter["v"],...) Then I solve the equation by scipy.optimize.root_scalar with the brentq method. The brentq method needs Brackets where the signs are changing. I chose 1 as lower limit so np.log(1-p > 0) is defined and just the doubled maximum as upper limit. p_max = np.max(p) def p(T): P_Init = [root_scalar(p_solvable,args=(T,parameter), method="brentq", bracket=[1,p_max*2]).root for T in T] return P_Init Now I have a function where I can input f(x) = y and fit it with lmfit or scipy curve_fit
Fit data with a function that equals 0 and could not be converted to the form f(x) = x
I have 2 columns and 31 rows in a pandas dataframe. I want to plot this x,y data and fit them to a complex function with 4 parameters. The function looks something like this. The function has to be 0 # Data: T,p = df["T"], df["p"] #31 rows # known constants: a,b,Ta,c0,x def c(T,v,VP,a=...,b=...,Ta=...,c0=...): c = c0 + a*(T-Ta) + b*t_r(T)**v/(t_r(T)**v-K(T,VP)) return c # t_r and K are other functions def function(p,T,p0,v,N,VP,a,b,c0,x): return np.log(1-p) + p + (x*c(T,v,VP))*p**2 + (p0/N)*(R-0.5*R**3) # =0 I am interested in fitting the parameters N,p0,Vp I tried to use Lmfit and changed my function to -> function(params,T,p) from Lmfit import minimize, Parameters ## add Parameters params = Parameters() ##Class with a list of parameters # add all constant Parameters with vary = False params.add("a", value=...,vary=False) ... ## add variables to fit with vary = True, limits with min,max params.add("N",value=..., vary=True,min=0,max=...) ... output = minimize(function,params) #Fit Results output.params.pretty_print() #Show Results Now I acquired the parameters, but I want to check if this makes sense by plot(T,p) for a more continous array, like: Ts = np.linspace(10,60,1000) # x-array ps = ... ? # y-array plt.plot(Ts,ps,label="Fit") # Plot Data How could I obtain a function to calculate p for T on each point to plot it ?
[ "I find an answer myself.\nFirst I wrap my function in a way that the y-value p is the first argument.\nAnd I used lmfit parameter class as arguments. Lmfit Parameters are basically dictionaries.\np_solvable = lambda p,T,parameter : function(p,T,parameter[\"p0\"],parameter[\"v\"],...)\n\nThen I solve the equation by scipy.optimize.root_scalar with the brentq method.\nThe brentq method needs Brackets where the signs are changing. I chose 1 as lower limit so np.log(1-p > 0) is defined and just the doubled maximum as upper limit.\np_max = np.max(p)\n\ndef p(T):\n P_Init = [root_scalar(p_solvable,args=(T,parameter), method=\"brentq\", bracket=[1,p_max*2]).root for T in T]\n return P_Init\n\nNow I have a function where I can input f(x) = y and fit it with lmfit or scipy curve_fit\n" ]
[ 0 ]
[]
[]
[ "curve_fitting", "lmfit", "pandas", "python", "scipy_optimize" ]
stackoverflow_0074437309_curve_fitting_lmfit_pandas_python_scipy_optimize.txt
Q: Why animation can be reusable after change display why animation can be reusable after im changing elemets display property with js can some one explain i couldnt find any answer for this can someone explain me this my codes downbelow ` <style> * { margin: 0; padding: 0; box-sizing: border-box; } aside { display: none; position: relative; left: -100%; height: 100vh; background-color: red; width: 20%; animation: openit 800ms ease-in forwards ; } @keyframes openit { to{ left: 0; } } aside a { display: block; } .open { position: absolute; z-index: -1; } </style> ` A: I found this: When we want to use transition for display:none to display:block, transition properties do not work. The reason for this is, display:none property is used for removing block and display:block property is used for displaying block. A block cannot be partly displayed. Either it is available or unavailable. That is why the transition property does not work. form this link. I hope this help.
Why animation can be reusable after change display
why animation can be reusable after im changing elemets display property with js can some one explain i couldnt find any answer for this can someone explain me this my codes downbelow ` <style> * { margin: 0; padding: 0; box-sizing: border-box; } aside { display: none; position: relative; left: -100%; height: 100vh; background-color: red; width: 20%; animation: openit 800ms ease-in forwards ; } @keyframes openit { to{ left: 0; } } aside a { display: block; } .open { position: absolute; z-index: -1; } </style> `
[ "I found this:\nWhen we want to use transition for display:none to display:block, transition properties do not work. The reason for this is, display:none property is used for removing block and display:block property is used for displaying block. A block cannot be partly displayed. Either it is available or unavailable. That is why the transition property does not work.\nform this link. I hope this help.\n" ]
[ 0 ]
[]
[]
[ "css", "display" ]
stackoverflow_0074666969_css_display.txt
Q: How do i invoke method on a generic type in dart There are several models have a same structure, { type: xxx, settings: xxx}, so i would like to use a parent class "WidgetConfig" with a generic type "T" to implement this, but problem occurs when i add "fromJson" methods. How can i invoke method on a generic type or any other ways to implement this? class BannerWidgetViewModel extends ChangeNotifier { WidgetConfig<BannerWidgetConfig> config; BannerWidgetViewModel(String configJson){ config = WidgetConfig.fromJson(configJson); } } class BannerWidgetConfig { String imgUrl; String padImgUrl; String lessonId; BannerWidgetConfig.fromJson(json){ if (json != null) { this.imgUrl = json['imgUrl']; this.padImgUrl = json['padImgUrl']; this.lessonId = json['lessonId']; } } } class WidgetConfig<T> { WidgetType type; WidgetConfig.fromJson(json){ if (json != null) { this.type = json['type']; // this.settings = T.fromJson(json['settings']); // T doesn't have fromJson method } } } then i use a abstract class but still not working. abstract class BaseWidgetConfig { BaseWidgetConfig.fromJson(dynamic json); } class WidgetConfig<T extends BaseWidgetConfig> { WidgetType type; T settings; WidgetConfig.fromJson(json){ if (json != null) { this.type = json['type']; this.settings = T.fromJson(); } } } code picture A: Directly show the function as a reference. send function as a reference here. FireStoreHelper.getList<ModelLesson>('grade4', ModelLesson.fromJson); get the method here. static Future<List<T>> getList<T>(String path, Function fromJson)
How do i invoke method on a generic type in dart
There are several models have a same structure, { type: xxx, settings: xxx}, so i would like to use a parent class "WidgetConfig" with a generic type "T" to implement this, but problem occurs when i add "fromJson" methods. How can i invoke method on a generic type or any other ways to implement this? class BannerWidgetViewModel extends ChangeNotifier { WidgetConfig<BannerWidgetConfig> config; BannerWidgetViewModel(String configJson){ config = WidgetConfig.fromJson(configJson); } } class BannerWidgetConfig { String imgUrl; String padImgUrl; String lessonId; BannerWidgetConfig.fromJson(json){ if (json != null) { this.imgUrl = json['imgUrl']; this.padImgUrl = json['padImgUrl']; this.lessonId = json['lessonId']; } } } class WidgetConfig<T> { WidgetType type; WidgetConfig.fromJson(json){ if (json != null) { this.type = json['type']; // this.settings = T.fromJson(json['settings']); // T doesn't have fromJson method } } } then i use a abstract class but still not working. abstract class BaseWidgetConfig { BaseWidgetConfig.fromJson(dynamic json); } class WidgetConfig<T extends BaseWidgetConfig> { WidgetType type; T settings; WidgetConfig.fromJson(json){ if (json != null) { this.type = json['type']; this.settings = T.fromJson(); } } } code picture
[ "Directly show the function as a reference.\nsend function as a reference here.\nFireStoreHelper.getList<ModelLesson>('grade4', ModelLesson.fromJson);\n\nget the method here.\nstatic Future<List<T>> getList<T>(String path, Function fromJson)\n\n" ]
[ 0 ]
[]
[]
[ "dart", "flutter" ]
stackoverflow_0064801305_dart_flutter.txt
Q: How to serialize optional vector of DateTime object in Rust? I have a struct defined like the following (other fields removed for brevity): use chrono::{ DateTime, Utc }; use serde::{ Deserialize, Serialize }; #[derive( Clone, Debug, PartialEq, Eq, Serialize, Deserialize )] pub struct Test { #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")] pub time_period: Option<Vec<DateTime<Utc>>> } And I'm using the following dependencies: bson = { version = "^2.4", default-features = false, features = [ "chrono-0_4" ] } chrono = "^0.4" serde = { version = "^1.0", default-features = false, features = [ "derive" ] } But serde derivations throw error, because there is type mismatch. It expects a DateTime object, but we have an optional vector here. Any ideas how to serialize optional vector of DateTime objects? A: Why doesn't the OP's code work The bson::serde_helpers::chrono_datetime_as_bson_datetime module contains helper functions that (de)serializes a single chrono::DateTime object, so it doesn't work with the field of type Option<Vec<DateTime<Utc>>>. Solution using nested struct To (de)serialize such data, you can define a struct TestInner that contains the inner DateTime<Utc> object, along with the #[serde(transparent)] container attribute so that it's (de)serialized in the same way as a single DateTime<Utc> object. For example, the struct Test in the question can be changed into something like this. #[derive(Debug, Serialize, Deserialize)] pub struct Test { #[serde(skip_serializing_if = "Option::is_none")] pub time_period: Option<Vec<TestInner>>, } #[derive(Debug, Serialize, Deserialize)] #[serde(transparent)] pub struct TestInner { #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")] datetime: DateTime<Utc>, } A: serde's with attribute can only be used if your function/module expects the exact type of the field. That is not possible to change and sometimes you see *_opt functions/modules to provide support for Options, but never for arbitrary nesting. The bson crate has a feature to use serde_with to work around that. You need to enable the serde_with feature of bson and import serde_with v1 into your code. Note the extra default attribute to serde. That is unnecessary for v2 of serde_with, but bson is still on v1. #[serde_with::serde_as] #[derive( Clone, Debug, PartialEq, Eq, Serialize, Deserialize )] pub struct Test { #[serde(skip_serializing_if = "Option::is_none", default)] #[serde_as(as = "Option<Vec<bson::DateTime>>")] pub time_period: Option<Vec<DateTime<Utc>>> } Run on Rustexplorer
How to serialize optional vector of DateTime object in Rust?
I have a struct defined like the following (other fields removed for brevity): use chrono::{ DateTime, Utc }; use serde::{ Deserialize, Serialize }; #[derive( Clone, Debug, PartialEq, Eq, Serialize, Deserialize )] pub struct Test { #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")] pub time_period: Option<Vec<DateTime<Utc>>> } And I'm using the following dependencies: bson = { version = "^2.4", default-features = false, features = [ "chrono-0_4" ] } chrono = "^0.4" serde = { version = "^1.0", default-features = false, features = [ "derive" ] } But serde derivations throw error, because there is type mismatch. It expects a DateTime object, but we have an optional vector here. Any ideas how to serialize optional vector of DateTime objects?
[ "Why doesn't the OP's code work\nThe bson::serde_helpers::chrono_datetime_as_bson_datetime module contains helper functions that (de)serializes a single chrono::DateTime object, so it doesn't work with the field of type Option<Vec<DateTime<Utc>>>.\nSolution using nested struct\nTo (de)serialize such data, you can define a struct TestInner that contains the inner DateTime<Utc> object, along with the #[serde(transparent)] container attribute so that it's (de)serialized in the same way as a single DateTime<Utc> object. For example, the struct Test in the question can be changed into something like this.\n#[derive(Debug, Serialize, Deserialize)]\npub struct Test {\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub time_period: Option<Vec<TestInner>>,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\n#[serde(transparent)]\npub struct TestInner {\n #[serde(with = \"bson::serde_helpers::chrono_datetime_as_bson_datetime\")]\n datetime: DateTime<Utc>,\n}\n\n", "serde's with attribute can only be used if your function/module expects the exact type of the field. That is not possible to change and sometimes you see *_opt functions/modules to provide support for Options, but never for arbitrary nesting.\nThe bson crate has a feature to use serde_with to work around that. You need to enable the serde_with feature of bson and import serde_with v1 into your code. Note the extra default attribute to serde. That is unnecessary for v2 of serde_with, but bson is still on v1.\n#[serde_with::serde_as]\n#[derive(\n Clone, Debug, PartialEq, Eq, Serialize, Deserialize\n)]\npub struct Test {\n #[serde(skip_serializing_if = \"Option::is_none\", default)]\n #[serde_as(as = \"Option<Vec<bson::DateTime>>\")]\n pub time_period: Option<Vec<DateTime<Utc>>>\n}\n\nRun on Rustexplorer\n" ]
[ 1, 1 ]
[]
[]
[ "rust", "serde" ]
stackoverflow_0074667250_rust_serde.txt
Q: Unable to add value to a java generic list Here's my sample code: public class MyList<T extends Number> { private List<T> items; public void func() { items.add(Integer.valueOf(1)); } } I think I should be able to add integer to items, but compilation fails: Required type: T Provided: Integer Anyone knows what's wrong here? A: Let us consider a more complete version of your example: public class MyList<T extends Number> { private List<T> items = new ArrayList<>(); public void func() { items.add(Integer.valueOf(1)); } } Suppose for the sake of argument that the compiler says that is OK. And now we will create an instance and call the func method: MyList<Double> myDoubles = new MyList<>(); myDoubles.func(); Here is what happens. We create a MyList instance where T is Double. That's OK: the Double class implements the Number interface. The items has a notional type of List<Double> and we initialize it with an ArrayList. So we now have a list what should only contain Double values. In the call to func we attempt to add an Integer to the List<Double>. That is wrong! That is what the compilation error is saying with the Required type: T Provided: Integer message. To spell it out, the compiler expects a value whose type is the type that T is going to be at runtime. But you have given it Integer. While Integer implements the Number interface, it is not necessary the same as what T will be at runtime. That is the root cause of your compilation error. So what is the solution? Well it depends on what the (actual) problem that this example is intended to solve. If you want item to be able to hold any Number, you should change private List<T> items = new ArrayList<>(); to private List<Number> items = new ArrayList<>(); and items.add(Integer.valueOf(1)) should work. On the other hand, if you want to add 1 to items as an instance of the runtime type of T, that is much more difficult. The problem is that the code of MyList (as written) does not and cannot know what that type is! So, you need to EITHER pass the T instance representing 1 as a parameter to func OR pass a Class<T> parameter to func or the constructor and use reflection to create the instance of that class to represent 1. But if you want something to auto-magically convert the Integer to what ever the actual runtime type of T is ... that is not possible. A: When you're using a so-called bounded type parameter <T extends Number> means that type T is restricted by an upper bound expected to be a Number or one of its subtypes. There are plenty of options if you would think about subtypes of Number: BigDecimal, AtomicLong, etc. That mean that your List<T> at runtime might appear to be a List<AtomicLong> and since behavior of generic types is invariant we would not be able to add anything that is not of type AtomicLong into such list (no Strings, no Integers, etc.). Therefore, compiler would disallow to add an Integer into a List<T>, where T can be anything that extends Number (or the Number itself), because it can't be sure that it's type-safe.
Unable to add value to a java generic list
Here's my sample code: public class MyList<T extends Number> { private List<T> items; public void func() { items.add(Integer.valueOf(1)); } } I think I should be able to add integer to items, but compilation fails: Required type: T Provided: Integer Anyone knows what's wrong here?
[ "Let us consider a more complete version of your example:\npublic class MyList<T extends Number> {\n\n private List<T> items = new ArrayList<>();\n\n public void func() {\n items.add(Integer.valueOf(1));\n }\n}\n\nSuppose for the sake of argument that the compiler says that is OK.\nAnd now we will create an instance and call the func method:\nMyList<Double> myDoubles = new MyList<>();\nmyDoubles.func();\n\nHere is what happens.\n\nWe create a MyList instance where T is Double. That's OK: the Double class implements the Number interface.\n\nThe items has a notional type of List<Double> and we initialize it with an ArrayList. So we now have a list what should only contain Double values.\n\nIn the call to func we attempt to add an Integer to the List<Double>. That is wrong!\n\n\nThat is what the compilation error is saying with the Required type: T Provided: Integer message.\nTo spell it out, the compiler expects a value whose type is the type that T is going to be at runtime. But you have given it Integer. While Integer implements the Number interface, it is not necessary the same as what T will be at runtime. That is the root cause of your compilation error.\n\nSo what is the solution?\nWell it depends on what the (actual) problem that this example is intended to solve. If you want item to be able to hold any Number, you should change\n private List<T> items = new ArrayList<>();\n\nto\n private List<Number> items = new ArrayList<>();\n\nand items.add(Integer.valueOf(1)) should work.\nOn the other hand, if you want to add 1 to items as an instance of the runtime type of T, that is much more difficult. The problem is that the code of MyList (as written) does not and cannot know what that type is! So, you need to EITHER pass the T instance representing 1 as a parameter to func OR pass a Class<T> parameter to func or the constructor and use reflection to create the instance of that class to represent 1.\nBut if you want something to auto-magically convert the Integer to what ever the actual runtime type of T is ... that is not possible.\n", "When you're using a so-called bounded type parameter <T extends Number> means that type T is restricted by an upper bound expected to be a Number or one of its subtypes.\nThere are plenty of options if you would think about subtypes of Number: BigDecimal, AtomicLong, etc. That mean that your List<T> at runtime might appear to be a List<AtomicLong> and since behavior of generic types is invariant we would not be able to add anything that is not of type AtomicLong into such list (no Strings, no Integers, etc.).\nTherefore, compiler would disallow to add an Integer into a List<T>, where T can be anything that extends Number (or the Number itself), because it can't be sure that it's type-safe.\n" ]
[ 1, 0 ]
[]
[]
[ "bounded_types", "generics", "java" ]
stackoverflow_0074667577_bounded_types_generics_java.txt
Q: React useState function not changing value when inside useEffect/Event listener I am currently trying to create a piece of code that will mode a div when the user scrolls past a certain place. to do this i used window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection)) where i pass both of the variables returned from React.useState(0), then from within the event listener i check to see if the window.scrollY property is more than the value in the scrollSection state and if so translate it with js. but no matter what i do the function provided to update the state isnt updating the state, its not slow its just not updating at all. I was wondering if this is because i passed it into an event listener? Event Listener and useState Initialization function SideNav(props: any) { const [scrollSection, setScrollSection] = React.useState(0); React.useEffect(() => { window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection)); return () => { window.removeEventListener('scroll', () => checkSection(scrollSection, setScrollSection)); }; }, []); Function passed to event listener function checkSection(scrollSection: number, setScrollSection: Function){ let scrollSections = [0, 1538, 2583, 2089, 3089] const scrollY = window.scrollY; setScrollSection(1); console.log("scroll Y: "+scrollY); console.log("section: "+scrollSection) } A: setState is asynchronous. you will not see the updated value immediately after setting the value. use useEffect to catch the updated values useEffect(() => { console.log("section: "+scrollSection) }, [scrollSection])
React useState function not changing value when inside useEffect/Event listener
I am currently trying to create a piece of code that will mode a div when the user scrolls past a certain place. to do this i used window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection)) where i pass both of the variables returned from React.useState(0), then from within the event listener i check to see if the window.scrollY property is more than the value in the scrollSection state and if so translate it with js. but no matter what i do the function provided to update the state isnt updating the state, its not slow its just not updating at all. I was wondering if this is because i passed it into an event listener? Event Listener and useState Initialization function SideNav(props: any) { const [scrollSection, setScrollSection] = React.useState(0); React.useEffect(() => { window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection)); return () => { window.removeEventListener('scroll', () => checkSection(scrollSection, setScrollSection)); }; }, []); Function passed to event listener function checkSection(scrollSection: number, setScrollSection: Function){ let scrollSections = [0, 1538, 2583, 2089, 3089] const scrollY = window.scrollY; setScrollSection(1); console.log("scroll Y: "+scrollY); console.log("section: "+scrollSection) }
[ "setState is asynchronous. you will not see the updated value immediately after setting the value. use useEffect to catch the updated values\nuseEffect(() => {\n console.log(\"section: \"+scrollSection)\n\n}, [scrollSection])\n\n" ]
[ 1 ]
[]
[]
[ "javascript", "reactjs" ]
stackoverflow_0074667961_javascript_reactjs.txt
Q: how to use $inc, $addfields inside $set in updatingr inserting a document in mongodb collection I have a collection with documents in below format {"_id": {"$oid": "6389fe414b13037521582cbb"}, "name": "Ann", "version": 1, "amount_paid": 1000, "createDate": 2022-12-02T13:31:45.416+00:00 "studentId": 111, "purchased": [ { "item_name": "notebooks", "price": 300 }, { "item_name": "textbooks", "price": 700 } ] } amount paid is the sum of purchased.price. I am trying to update the document, if studentId not present it should insert the new document. if the document is getting updated the version should change from 1 to 2, if creating new version should be 1. What I tried is db.students.update_one({ 'studentId': 111}, { '$set': { "name":"Ann", "version":{"$inc": { "version": 1 }}, "purchased":[{"item_name":"notebooks","price":500}, {"item_name":"uniform","price":500}], "$addFields" : { "amount_paid" : {"$sum" : "$purchased.price"}}, "createDate":datetime.datetime.now(),, } } ,upsert=true) but this is giving me an error WriteError: The dollar ($) prefixed field '$addFields' in '$addFields' is not allowed in the context of an update's replacement document. Consider using an aggregation pipeline with $replaceWith., full error: {'index': 0, 'code': 52, 'errmsg': "The dollar ($) prefixed field '$addFields' in '$addFields' is not allowed in the context of an update's replacement document. Consider using an aggregation pipeline with $replaceWith."} A: Use update with aggregation pipeline. This allows you to perform a sum of the field value in the document. While the $set stage will add a field if the field does not exist as long the value is provided (not null or undefined), hence the $addFields stage is not needed. db.collection.update({ "studentId": 111 }, [ { "$set": { "name": "Ann", "version": { "$sum": [ "$version", 1 ] }, "purchased": [ { "item_name": "notebooks", "price": 500 }, { "item_name": "uniform", "price": 500 } ] } }, { $set: { "amount_paid": { "$sum": "$purchased.price" }, created_date: new Date() } } ], { upsert: true }) Demo @ Mongo Playground
how to use $inc, $addfields inside $set in updatingr inserting a document in mongodb collection
I have a collection with documents in below format {"_id": {"$oid": "6389fe414b13037521582cbb"}, "name": "Ann", "version": 1, "amount_paid": 1000, "createDate": 2022-12-02T13:31:45.416+00:00 "studentId": 111, "purchased": [ { "item_name": "notebooks", "price": 300 }, { "item_name": "textbooks", "price": 700 } ] } amount paid is the sum of purchased.price. I am trying to update the document, if studentId not present it should insert the new document. if the document is getting updated the version should change from 1 to 2, if creating new version should be 1. What I tried is db.students.update_one({ 'studentId': 111}, { '$set': { "name":"Ann", "version":{"$inc": { "version": 1 }}, "purchased":[{"item_name":"notebooks","price":500}, {"item_name":"uniform","price":500}], "$addFields" : { "amount_paid" : {"$sum" : "$purchased.price"}}, "createDate":datetime.datetime.now(),, } } ,upsert=true) but this is giving me an error WriteError: The dollar ($) prefixed field '$addFields' in '$addFields' is not allowed in the context of an update's replacement document. Consider using an aggregation pipeline with $replaceWith., full error: {'index': 0, 'code': 52, 'errmsg': "The dollar ($) prefixed field '$addFields' in '$addFields' is not allowed in the context of an update's replacement document. Consider using an aggregation pipeline with $replaceWith."}
[ "Use update with aggregation pipeline. This allows you to perform a sum of the field value in the document.\nWhile the $set stage will add a field if the field does not exist as long the value is provided (not null or undefined), hence the $addFields stage is not needed.\ndb.collection.update({\n \"studentId\": 111\n},\n[\n {\n \"$set\": {\n \"name\": \"Ann\",\n \"version\": {\n \"$sum\": [\n \"$version\",\n 1\n ]\n },\n \"purchased\": [\n {\n \"item_name\": \"notebooks\",\n \"price\": 500\n },\n {\n \"item_name\": \"uniform\",\n \"price\": 500\n }\n ]\n }\n },\n {\n $set: {\n \"amount_paid\": {\n \"$sum\": \"$purchased.price\"\n },\n created_date: new Date()\n }\n }\n],\n{\n upsert: true\n})\n\nDemo @ Mongo Playground\n" ]
[ 0 ]
[]
[]
[ "mongodb" ]
stackoverflow_0074667737_mongodb.txt
Q: VS Code autocomplete not working for CSS properties in GlobalStyles used in other styled components I'm currently working on a Project where I defined Global Styles in a different file and declared styling in another file. Still, somehow the custom properties defined in GlobalStyles don't get autocomplete. I am using, VScode Styled component extension // GlobalStyles.tsx import React from 'react'; import { createGlobalStyle } from 'styled-components'; import { COLORS } from '../constants'; const GlobalStyles = createGlobalStyle` /* CSS Reset */ :root { /* Primary */ --color-primary-10: hsl(25, 35%, 93%); } `; // Search.tsx import styled from 'styled-components'; const Wrapper = styled.section` /* VS Code doesn't autocomplete */ color: var(--) `;
VS Code autocomplete not working for CSS properties in GlobalStyles used in other styled components
I'm currently working on a Project where I defined Global Styles in a different file and declared styling in another file. Still, somehow the custom properties defined in GlobalStyles don't get autocomplete. I am using, VScode Styled component extension // GlobalStyles.tsx import React from 'react'; import { createGlobalStyle } from 'styled-components'; import { COLORS } from '../constants'; const GlobalStyles = createGlobalStyle` /* CSS Reset */ :root { /* Primary */ --color-primary-10: hsl(25, 35%, 93%); } `; // Search.tsx import styled from 'styled-components'; const Wrapper = styled.section` /* VS Code doesn't autocomplete */ color: var(--) `;
[]
[]
[ "There Are a Couple Settings that Will Helpl\n\nTo start, I want to just point out, that you might change your VS Code configuration based on the settings that I have included below. There is a good chance when you do, the results will be helpful. There is also the posibility that the settings might not appear to work as you desire at first. The thing is, this is actually a pretty advanced subject for VS Code, not because of the settings specifically referenced below, but because of how configurable VS Code, VS Code's suggestions feature, & VS Code's Intellicode extension all are. Each have advanced configurations, long lists of settings, and are more advanced features offered by VS Code. With that said, a big part of you being able to get VS Code to work how you want it to is going to be contingent on your ability to configure VS Code, and to use it. Hopefully your somewhat experianced with the editor already.\nMy Advice is this:\nRead the answer below, check the settings out, but don't stop there: Open up your settings menu (not settings.json, but the menu you can search from) and type in suggestions, then go through each configuration, reading each one, and configuring each one. Then (using the settings menu search box) type in, IntelliCode (or just Intell) a bunch more settings will pop up, configure each one (tip: a couple intellicode settings ask that you let the extension configure itself). Proceed to do the same thing, and search for \"quick suggestions\", and \"auto-complete\". Keep going until you have gained complete control over your Development Environments Auto-completion A.I. software, and the environments \"suggestions-widget\".\nOkay, lets get down to business.\nFirst off, lets start with this setting\n\"editor.suggest.shareSuggestSelections\": true\n\nI believe by default the setting above is deactivated. Turn the feature on.\nPlay with it, see if it helps. Also remember when you reconfigure your editor, always restart it.\nIf the setting above doesn't work for you, then...\nWord Based Suggestions Can Help\n\n\nWhy Word Based Suggestions?\nThe only means that I have ever found for extending VS Code's Intellicode range beyond the document I am working in was through Word based suggestions.\n\n\n\n\nWhat are Word Based Suggestions?\nYou need to set up VS-Codes version of the \"Word Based Suggestions\" feature. \"Word Based Suggestions\" is a feature found in most contemporary popular code editors (i.e. Sublime, Atom, TextMate, etc...).\n\n\n\n\nHow Does the Word Based Suggestions Feature Work?\nWhen word based suggestions is enabled, the Visual Studio auto-complete functionality works by A.I.-analysis preformed on words typed rather than code, &/or built-in language features (i.e. static typed systems, compilers, etc...).\n\n\n\n\n \nConfiguring Word Based Suggestions\n\n\nEnabling Word Based Suggestions\nOpen your settings.json file — which ever scope of your vs code config file you prefer — and then copy and paste the setting below to it.\n\n \"editor.wordBasedSuggestions\": true\n\n\n\n\n\n\nConfigure Suggestions to Reach Beyond the Singular Open File in Focus\nYou will want to set \"editor.wordBasedSuggestionsMode\" to either \"allDocuments\", which will suggest words from all open files, or \"matchingDocuments\" which will suggest words from all open files that are written in the same programming language.\n\n // This setting can also be set to \"matchingDocuments\"\n\n \"editor.wordBasedSuggestionsMode\": \"AllDocuments\" \n\n\n\n\nI rarely use intellisense w/ word based suggestions enabled. I feel that it suggest too many irrelevant words, however, there are situations, like when I want suggestions from CSS files or JSON files, and I am writing TypeScript or whatever, that I will turn it on for.\nIts the one, and the only, \"suggestions feature\" that allows you to configure its range beyond the current file in focus. That isn't to say that turning it off won't offer you suggestions from other places than the current flie, it seems to me that they will, but I am pretty certain that the language needs to be one that has built-in IDE-like features, such as a static-type system, or a compiler. Those features I mentioned allow extensions/tooling the ability to provide info that couldn't be provided with out them, so a big part of what suggestions, auto-complete, hints, etc, are offered is contingent on the language, and the extensions you have downloaded for the language.\nLet me know if you made any progress, or if you were unable to make progress (which is even more important to me) in the comments sections below.\n" ]
[ -1 ]
[ "styled_components", "visual_studio_code" ]
stackoverflow_0074613198_styled_components_visual_studio_code.txt
Q: Counting repeated Sequences of a String in JAVA? i'm currently trying to solve a problem by counting the repeated sequences of character for example:- input:"aaabbcc" output should be printed as 3; input:"aabbcde" output:2. even if a repeated sequencce occurs two or more time it should be considered as 1? private int stringocc1(String m) { int count=0; for (int i = 0; i < m.length(); i++) { for (int j = 0; j < m.length(); j++) { if(m.charAt(i)==m.charAt(j)) { count++; } } } return count; } A: import java.util.*; import java.util.stream.*; public class MyClass { public static void main(String args[]) { Map<Character, Integer> sequences = new HashMap<>(); String input = "aabbcdeaa"; for (Character character : input.toCharArray()) { if (!sequences.containsKey(character)) { sequences.put(character, 0); } else { sequences.put(character, 1); } } Long countOfSequences = sequences.entrySet().stream().filter(e -> e.getValue() == 1).count(); System.out.println("Sequences: " + countOfSequences); } } Output: 2 (so it counts separate sequences of the same character as one sequence, as per your requirement). You can use a Hashmap to store each different character of the string and a value associated to it (0 if it's present once, 1 if it's present multiple times; this could be any value though, you could for example have it be the number of times each character appears if you needed that value as well), then filter the HashMap and count how many entries have a value different from zero. A: Here is one way to do it using regular expressions. String [] testData = {"aabbccddefghh", "aabb", "aab", "aaabbbaaa", "abcdeggggdddee", "abcdefg"}; for (String s : testData) { System.out.println(s + " -> " + stringocc1(s)); } prints aabbccddefghh -> 5 aabb -> 2 aab -> 1 aaabbbaaa -> 3 abcdeggggdddee -> 3 abcdefg -> 0 (\\w+)\\1+ - says match any thing that has a character followed one or more of the same character. The \\1 is a backreference to the capture group in (). find() - keeps searching until it returns false use group() to get the match. then the count is returned. private static int stringocc1(String m) { int count = 0; Matcher matcher = Pattern.compile("(\\w)\\1+").matcher(m); while (matcher.find()) { count++; } return count; } You can also do it with a single loop. assign the first character to c iterate over the loop and checking if a different character is seen then compare the starting and ending locations to see if the length > 1 and bump the count accordingly. then return the count. Note: If the string ends in a sequence, the loop will terminate without adjusting the count. So this needs to be done prior to returning. private static int stringocc1(String m) { int count = 0; char [] chars = m.toCharArray(); char c = chars[0]; int k = 0; int i = 1; for (; i < chars.length; i++) { if (chars[i] != c) { if (i - k > 1) { count++; } c = chars[i]; k = i; } } return count + ((i-k > 1) ? 1 : 0); }
Counting repeated Sequences of a String in JAVA?
i'm currently trying to solve a problem by counting the repeated sequences of character for example:- input:"aaabbcc" output should be printed as 3; input:"aabbcde" output:2. even if a repeated sequencce occurs two or more time it should be considered as 1? private int stringocc1(String m) { int count=0; for (int i = 0; i < m.length(); i++) { for (int j = 0; j < m.length(); j++) { if(m.charAt(i)==m.charAt(j)) { count++; } } } return count; }
[ "import java.util.*;\nimport java.util.stream.*;\npublic class MyClass {\n public static void main(String args[]) {\n Map<Character, Integer> sequences = new HashMap<>();\n String input = \"aabbcdeaa\";\n \n for (Character character : input.toCharArray()) {\n if (!sequences.containsKey(character)) {\n sequences.put(character, 0);\n } else {\n sequences.put(character, 1);\n }\n }\n \n Long countOfSequences = sequences.entrySet().stream().filter(e -> e.getValue() == 1).count();\n \n System.out.println(\"Sequences: \" + countOfSequences);\n }\n}\n\nOutput: 2 (so it counts separate sequences of the same character as one sequence, as per your requirement).\nYou can use a Hashmap to store each different character of the string and a value associated to it (0 if it's present once, 1 if it's present multiple times; this could be any value though, you could for example have it be the number of times each character appears if you needed that value as well), then filter the HashMap and count how many entries have a value different from zero.\n", "Here is one way to do it using regular expressions.\nString [] testData = {\"aabbccddefghh\", \"aabb\", \"aab\", \"aaabbbaaa\", \n \"abcdeggggdddee\", \"abcdefg\"};\n for (String s : testData) { \n System.out.println(s + \" -> \" + stringocc1(s));\n }\n\nprints\naabbccddefghh -> 5\naabb -> 2\naab -> 1\naaabbbaaa -> 3\nabcdeggggdddee -> 3\nabcdefg -> 0\n\n\n(\\\\w+)\\\\1+ - says match any thing that has a character followed one or more of the same character. The \\\\1 is a backreference to the capture group in ().\nfind() - keeps searching until it returns false\nuse group() to get the match.\nthen the count is returned.\n\nprivate static int stringocc1(String m) {\n int count = 0;\n Matcher matcher = Pattern.compile(\"(\\\\w)\\\\1+\").matcher(m);\n while (matcher.find()) {\n count++; \n }\n return count;\n}\n\nYou can also do it with a single loop.\n\nassign the first character to c\niterate over the loop and checking if a different character is seen\nthen compare the starting and ending locations to see if the length > 1\nand bump the count accordingly.\nthen return the count.\n\nNote: If the string ends in a sequence, the loop will terminate without adjusting the count. So this needs to be done prior to returning.\nprivate static int stringocc1(String m) {\n int count = 0;\n char [] chars = m.toCharArray();\n char c = chars[0];\n int k = 0;\n int i = 1;\n for (; i < chars.length; i++) {\n if (chars[i] != c) {\n if (i - k > 1) {\n count++;\n }\n c = chars[i];\n k = i;\n }\n }\n return count + ((i-k > 1) ? 1 : 0);\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "data_structures", "hashmap", "java" ]
stackoverflow_0074667776_data_structures_hashmap_java.txt
Q: Add Authentification in .NET MAUI development? I an new to .NET MAUI and i am developing an App. But i don’t know where to start in implementing Authentification. I have a ASP.NET Core WebApp running Identity already. So What is the best approach to add Authentification in .NET MAUI development? I have not tried anything A: Actually best thing is to implement custom authentication service so there won't be any limitation in future. However, MAUI got "Microsoft.Identity.Web" package to help you out. Microsoft has provided better guide here https://learn.microsoft.com/en-us/azure/developer/mobile-apps/azure-mobile-apps/quickstarts/maui/authentication?pivots=vs2022-windows
Add Authentification in .NET MAUI development?
I an new to .NET MAUI and i am developing an App. But i don’t know where to start in implementing Authentification. I have a ASP.NET Core WebApp running Identity already. So What is the best approach to add Authentification in .NET MAUI development? I have not tried anything
[ "Actually best thing is to implement custom authentication service so there won't be any limitation in future.\nHowever, MAUI got \"Microsoft.Identity.Web\" package to help you out.\nMicrosoft has provided better guide here\nhttps://learn.microsoft.com/en-us/azure/developer/mobile-apps/azure-mobile-apps/quickstarts/maui/authentication?pivots=vs2022-windows\n" ]
[ 0 ]
[]
[]
[ ".net_core", "asp.net_identity", "maui" ]
stackoverflow_0074667956_.net_core_asp.net_identity_maui.txt
Q: How do I let a parent window access my frame's content if I control the frame? I am making a little script that has to open an API window like: var api = window.open("https://example.com", "Poppout", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=350,height=400,top="+(screen.height-400)+",left="+(screen.width-840)); when ever I try to access it like: api.document.getElementById('ex').value; I get the error: Uncaught DOMException: Blocked a frame with origin "https://example.com" from accessing a cross-origin frame. at <anonymous>:1:5 I know why this is happening but since I'm the owner of the API's url can I enable this some way? My index.js code: const express = require('express'); const app = express(); const http = require('http'); const router = express.Router(); const path = require('path') const server = http.createServer(app); const { Server } = require("socket.io"); const i = new Server(server); app.use(express.json()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "*"); next(); }); router.get('/', function(req, res) { res.sendFile(path.join(__dirname, '/index.html')) }); app.use('/', router); app.post('/', (req, res) => { const { chat, username } = req.body; console.log(username, '÷', chat) i.emit('chat', chat, username); }); server.listen(3000, () => { console.log('listening on port: 3000'); });
How do I let a parent window access my frame's content if I control the frame?
I am making a little script that has to open an API window like: var api = window.open("https://example.com", "Poppout", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=350,height=400,top="+(screen.height-400)+",left="+(screen.width-840)); when ever I try to access it like: api.document.getElementById('ex').value; I get the error: Uncaught DOMException: Blocked a frame with origin "https://example.com" from accessing a cross-origin frame. at <anonymous>:1:5 I know why this is happening but since I'm the owner of the API's url can I enable this some way? My index.js code: const express = require('express'); const app = express(); const http = require('http'); const router = express.Router(); const path = require('path') const server = http.createServer(app); const { Server } = require("socket.io"); const i = new Server(server); app.use(express.json()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "*"); next(); }); router.get('/', function(req, res) { res.sendFile(path.join(__dirname, '/index.html')) }); app.use('/', router); app.post('/', (req, res) => { const { chat, username } = req.body; console.log(username, '÷', chat) i.emit('chat', chat, username); }); server.listen(3000, () => { console.log('listening on port: 3000'); });
[]
[]
[ "\nInstall cors npm i cors\n\nimport cors and use it to manage cross orign requests\nconst cors = require('cors');\napp.use(cors()); //allow any url\napp.options('*', cors())\n\n\nYou can also whitelist specific Urls by setting cors options Origin value:\nconst cors = require('cors');\n \n \nconst corsOptions = {\norigin: [\n 'https://example.com',\n'https://yourURL.com',\n'http://anotherURL.com\n],\noptionSuccessStatus:200, //for Legacy browsers\n\n}\napp.use(cors(corsOptions));\napp.options('*', cors());\n\n" ]
[ -1 ]
[ "javascript", "node.js" ]
stackoverflow_0074667853_javascript_node.js.txt
Q: Select children based on parents which are selected by another expression I have heavy query written in another function as expression, by which I can select parent, but how to use this function to select children based on results? public class Parent { public int Id { get; set; } public string Name { get; set; } public DateTime Prop1 { get; set; } public virtual ICollection<Child> Childs { get; set; } } public class Child { public int Id { get; set; } public int ParentId { get; set; } public string Name { get; set; } public virtual Parent Parent { get; set; } } I have function to select parents: private Expression<Func<Parent, bool>> SelectParents( DateTime start, DateTime end, List<string> names = null ) { if (names == null) names = new(); return x => x.Prop1 > start && x.Prop1 < end && (names.Count > 0 ? names.Contains(x.Name) : true); } When I use it to select parents - it works just fine, but how to select children based on this expression? var parentCount = await _dbContext.Parents.where(SelectParents(.....)).CountAsync(); A: await _dbContext.Parents .Where(SelectParents(.....)) .SelectMany(parent => parent.Childs) .ToListAsync();
Select children based on parents which are selected by another expression
I have heavy query written in another function as expression, by which I can select parent, but how to use this function to select children based on results? public class Parent { public int Id { get; set; } public string Name { get; set; } public DateTime Prop1 { get; set; } public virtual ICollection<Child> Childs { get; set; } } public class Child { public int Id { get; set; } public int ParentId { get; set; } public string Name { get; set; } public virtual Parent Parent { get; set; } } I have function to select parents: private Expression<Func<Parent, bool>> SelectParents( DateTime start, DateTime end, List<string> names = null ) { if (names == null) names = new(); return x => x.Prop1 > start && x.Prop1 < end && (names.Count > 0 ? names.Contains(x.Name) : true); } When I use it to select parents - it works just fine, but how to select children based on this expression? var parentCount = await _dbContext.Parents.where(SelectParents(.....)).CountAsync();
[ "await _dbContext.Parents\n .Where(SelectParents(.....))\n .SelectMany(parent => parent.Childs)\n .ToListAsync();\n\n" ]
[ 2 ]
[]
[]
[ "c#", "entity_framework" ]
stackoverflow_0074667918_c#_entity_framework.txt
Q: Error: error:1E08010C:DECODER routines::unsupported with Google auth library I've recently ran into this error with the google cloud storage SDK on Node.js. I know for a fact that this worked in the past without any changes, but I haven't touched the code in a while and might be wrong. Here's the error itself: Error: error:1E08010C:DECODER routines::unsupported at Sign.sign (node:internal/crypto/sig:131:29) at Object.sign (node_modules/jwa/index.js:152:45) at Object.jwsSign [as sign] (node_modules/jws/lib/sign-stream.js:32:24) at GoogleToken.requestToken (node_modules/gtoken/build/src/index.js:232:31) at GoogleToken.getTokenAsyncInner (node_modules/gtoken/build/src/index.js:166:21) at GoogleToken.getTokenAsync (node_modules/gtoken/build/src/index.js:145:55) at GoogleToken.getToken (node_modules/gtoken/build/src/index.js:97:21) at JWT.refreshTokenNoCache (node_modules/google-auth-library/build/src/auth/jwtclient.js:172:36) at JWT.refreshToken (node_modules/google-auth-library/build/src/auth/oauth2client.js:153:24) at JWT.getRequestMetadataAsync (node_modules/google-auth-library/build/src/auth/oauth2client.js:298:28) { library: 'DECODER routines', reason: 'unsupported', code: 'ERR_OSSL_UNSUPPORTED' } The code that throws this error is the following: const credentials = { type: process.env.TYPE, project_id: process.env.PROJECT_ID, private_key_id: process.env.PRIVATE_KEY_ID, private_key: process.env.PRIVATE_KEY, client_email: process.env.CLIENT_EMAIL, client_id: process.env.CLIENT_ID, auth_uri: process.env.AUTH_URI, token_uri: process.env.TOKEN_URI, auth_provider_x509_cert_url: process.env.AUTH_PROVIDER_X509_CERT_URL, client_x509_cert_url: process.env.CLIENT_X509_CERT_URL, }; const storage = new Storage({ credentials, }); if (!req.file) { logger('POST /profile_image', logLevels.error, 'No file uploaded!'); ResponseError.badRequest(res); } const bucketName = process.env.BUCKET_NAME; const bucket = storage.bucket(bucketName); const fileName = `profile_pics/${req.user}/${req.file.originalname}`; const file = bucket.file(fileName); const stream = file.createWriteStream({ metadata: { contentType: req.file.mimetype, }, }); stream.on('error', (err) => { console.error('Error pushing the picture: ', err); <--- error throw err; }); stream.on('finish', () => { return file.makePublic().then(async () => { ... }) }); stream.end(req.file.buffer); The process.env contains all the right values, I've made sure to try with a new private key but same error. Has anyone seen this one before? TIA! A: Answering this as community wiki. As mentioned above in comments by John Hanley Do not store service accounts in environment variables. If you do, do not break the service account into pieces. Base64 encode the entire service account, store it in a variable, and then Base64 decode it when required. Your code is failing because the client is being set up with bad credentials. Most likely a corrupted private key. A: If you have recently upgraded your openssl to version 3, you may have to enable legacy certs in the /etc/ssl/openssl.cnf file: openssl_conf = openssl_init [openssl_init] providers = provider_sect [provider_sect] default = default_sect legacy = legacy_sect [default_sect] activate = 1 [legacy_sect] activate = 1 This information is from the OpenSSL WIKI A: I got same issue and fixed it by replacing raw \n character with the newline character. Probably you get the key as raw data from your environment and \n character in the raw is not treated as a newline character. You can try this: private_key: process.env.PRIVATE_KEY.split(String.raw`\n`).join('\n'),
Error: error:1E08010C:DECODER routines::unsupported with Google auth library
I've recently ran into this error with the google cloud storage SDK on Node.js. I know for a fact that this worked in the past without any changes, but I haven't touched the code in a while and might be wrong. Here's the error itself: Error: error:1E08010C:DECODER routines::unsupported at Sign.sign (node:internal/crypto/sig:131:29) at Object.sign (node_modules/jwa/index.js:152:45) at Object.jwsSign [as sign] (node_modules/jws/lib/sign-stream.js:32:24) at GoogleToken.requestToken (node_modules/gtoken/build/src/index.js:232:31) at GoogleToken.getTokenAsyncInner (node_modules/gtoken/build/src/index.js:166:21) at GoogleToken.getTokenAsync (node_modules/gtoken/build/src/index.js:145:55) at GoogleToken.getToken (node_modules/gtoken/build/src/index.js:97:21) at JWT.refreshTokenNoCache (node_modules/google-auth-library/build/src/auth/jwtclient.js:172:36) at JWT.refreshToken (node_modules/google-auth-library/build/src/auth/oauth2client.js:153:24) at JWT.getRequestMetadataAsync (node_modules/google-auth-library/build/src/auth/oauth2client.js:298:28) { library: 'DECODER routines', reason: 'unsupported', code: 'ERR_OSSL_UNSUPPORTED' } The code that throws this error is the following: const credentials = { type: process.env.TYPE, project_id: process.env.PROJECT_ID, private_key_id: process.env.PRIVATE_KEY_ID, private_key: process.env.PRIVATE_KEY, client_email: process.env.CLIENT_EMAIL, client_id: process.env.CLIENT_ID, auth_uri: process.env.AUTH_URI, token_uri: process.env.TOKEN_URI, auth_provider_x509_cert_url: process.env.AUTH_PROVIDER_X509_CERT_URL, client_x509_cert_url: process.env.CLIENT_X509_CERT_URL, }; const storage = new Storage({ credentials, }); if (!req.file) { logger('POST /profile_image', logLevels.error, 'No file uploaded!'); ResponseError.badRequest(res); } const bucketName = process.env.BUCKET_NAME; const bucket = storage.bucket(bucketName); const fileName = `profile_pics/${req.user}/${req.file.originalname}`; const file = bucket.file(fileName); const stream = file.createWriteStream({ metadata: { contentType: req.file.mimetype, }, }); stream.on('error', (err) => { console.error('Error pushing the picture: ', err); <--- error throw err; }); stream.on('finish', () => { return file.makePublic().then(async () => { ... }) }); stream.end(req.file.buffer); The process.env contains all the right values, I've made sure to try with a new private key but same error. Has anyone seen this one before? TIA!
[ "Answering this as community wiki. As mentioned above in comments by John Hanley\n\nDo not store service accounts in environment variables.\nIf you do, do not break the service account into pieces. Base64 encode the entire service account, store it in a variable, and then Base64 decode it when required.\nYour code is failing because the client is being set up with bad credentials. Most likely a corrupted private key.\n\n", "If you have recently upgraded your openssl to version 3, you may have to enable legacy certs in the /etc/ssl/openssl.cnf file:\n openssl_conf = openssl_init\n \n [openssl_init]\n providers = provider_sect\n \n [provider_sect]\n default = default_sect\n legacy = legacy_sect\n \n [default_sect]\n activate = 1\n \n [legacy_sect]\n activate = 1\n\nThis information is from the OpenSSL WIKI\n", "I got same issue and fixed it by replacing raw \\n character with the newline character. Probably you get the key as raw data from your environment and \\n character in the raw is not treated as a newline character. You can try this:\n private_key: process.env.PRIVATE_KEY.split(String.raw`\\n`).join('\\n'),\n\n\n" ]
[ 3, 0, 0 ]
[]
[]
[ "google_api_nodejs_client", "google_cloud_storage", "node.js" ]
stackoverflow_0074131595_google_api_nodejs_client_google_cloud_storage_node.js.txt
Q: alexa sdk: can't get persitentAttributes i'm trying to add persistent attributes to my lambda function. i created a dynamoDB table and added it to the triggers of my lambda function. i copied a sample code from github, but when i try to launch the skill i get an error. The console log shows: { "errorMessage": "Could not read item (amzn1.ask.account.AGIIYNRXWDLBD6XEPW72QS2BHGXNP7NWYBEWSH2XLSXZP64X3NCYEMVK233VFDWH77ZB6DAK6YJ53SZLNUFVQ56CYOVCILS7QFZI4CIRDWC3PAHS4QG27YUY5PTT6QEIK46YFNTJT54YAKNGOWV2UO66XZACFDQ5SEXKJYOBNFNIZNUXKNTIAAYZG4R5ZU4FMLPDZZN64KLINNA) from table (Spiele): The provided key element does not match the schema", "errorType": "AskSdk.DynamoDbPersistenceAdapter Error", "stackTrace": [ "Object.createAskSdkError (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/utils/AskSdkUtils.js:22:17)", "DynamoDbPersistenceAdapter.<anonymous> (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:123:49)", "step (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:44:23)", "Object.throw (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:25:53)", "rejected (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:17:65)", "<anonymous>", "process._tickDomainCallback (internal/process/next_tick.js:228:7)" ] } the table contains a primary key "name" and sort key "UserId". is that wrong? here is my index.js: const Alexa = require('ask-sdk'); // Define the skill features let skill; /** * If this is the first start of the skill, grab the user's data from Dynamo and * set the session attributes to the persistent data. */ const GetUserDataInterceptor = { process(handlerInput) { let attributes = handlerInput.attributesManager.getSessionAttributes(); if (handlerInput.requestEnvelope.request.type === 'LaunchRequest' && !attributes['isInitialized']) { return new Promise((resolve, reject) => { handlerInput.attributesManager.getPersistentAttributes() .then((attributes) => { attributes['isInitialized'] = true; saveUser(handlerInput, attributes, 'session'); resolve(); }) .catch((error) => { reject(error); }) }); } } }; function saveUser(handlerInput, attributes, mode) { if(mode === 'session'){ handlerInput.attributesManager.setSessionAttributes(attributes); } else if(mode === 'persistent') { console.info("Saving to Dynamo: ",attributes); return new Promise((resolve, reject) => { handlerInput.attributesManager.getPersistentAttributes() .then((persistent) => { delete attributes['isInitialized']; handlerInput.attributesManager.setPersistentAttributes(attributes); resolve(handlerInput.attributesManager.savePersistentAttributes()); }) .catch((error) => { reject(error); }); }); } } const LaunchHandler = { canHandle(handlerInput) { return handlerInput.requestEnvelope.request.type === 'LaunchRequest'; }, handle(handlerInput) { console.info("LaunchRequest"); let attributes = handlerInput.attributesManager.getSessionAttributes(); console.info("Test the load: " + attributes['isInitialized']); attributes['FOO'] = "BAR"; saveUser(handlerInput, attributes, 'persistent'); return handlerInput.responseBuilder .speak('Hello') .reprompt('Hello') .getResponse(); } } exports.handler = Alexa.SkillBuilders.standard() .addRequestHandlers( LaunchHandler ) .addRequestInterceptors(GetUserDataInterceptor) .withTableName('Spiele') .withAutoCreateTable(true) .withDynamoDbClient() .lambda(); can anyone tell me what i'm doing wrong? A: please confirm the partition key is 'userId' not 'UserId' (notice the uppercase U). Also I would suggest using 'this' object. Let me know if that helps. Cheers A: Below code is for python lambda function Step1: from ask_sdk_core.skill_builder import CustomSkillBuilder Step2: from ask_sdk_dynamodb.adapter import DynamoDbAdapter Step3: sb = SkillBuilder() Step4: sb = CustomSkillBuilder(persistence_adapter = dynamodb_adapter)
alexa sdk: can't get persitentAttributes
i'm trying to add persistent attributes to my lambda function. i created a dynamoDB table and added it to the triggers of my lambda function. i copied a sample code from github, but when i try to launch the skill i get an error. The console log shows: { "errorMessage": "Could not read item (amzn1.ask.account.AGIIYNRXWDLBD6XEPW72QS2BHGXNP7NWYBEWSH2XLSXZP64X3NCYEMVK233VFDWH77ZB6DAK6YJ53SZLNUFVQ56CYOVCILS7QFZI4CIRDWC3PAHS4QG27YUY5PTT6QEIK46YFNTJT54YAKNGOWV2UO66XZACFDQ5SEXKJYOBNFNIZNUXKNTIAAYZG4R5ZU4FMLPDZZN64KLINNA) from table (Spiele): The provided key element does not match the schema", "errorType": "AskSdk.DynamoDbPersistenceAdapter Error", "stackTrace": [ "Object.createAskSdkError (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/utils/AskSdkUtils.js:22:17)", "DynamoDbPersistenceAdapter.<anonymous> (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:123:49)", "step (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:44:23)", "Object.throw (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:25:53)", "rejected (/var/task/node_modules/ask-sdk-dynamodb-persistence-adapter/lib/attributes/persistence/DynamoDbPersistenceAdapter.js:17:65)", "<anonymous>", "process._tickDomainCallback (internal/process/next_tick.js:228:7)" ] } the table contains a primary key "name" and sort key "UserId". is that wrong? here is my index.js: const Alexa = require('ask-sdk'); // Define the skill features let skill; /** * If this is the first start of the skill, grab the user's data from Dynamo and * set the session attributes to the persistent data. */ const GetUserDataInterceptor = { process(handlerInput) { let attributes = handlerInput.attributesManager.getSessionAttributes(); if (handlerInput.requestEnvelope.request.type === 'LaunchRequest' && !attributes['isInitialized']) { return new Promise((resolve, reject) => { handlerInput.attributesManager.getPersistentAttributes() .then((attributes) => { attributes['isInitialized'] = true; saveUser(handlerInput, attributes, 'session'); resolve(); }) .catch((error) => { reject(error); }) }); } } }; function saveUser(handlerInput, attributes, mode) { if(mode === 'session'){ handlerInput.attributesManager.setSessionAttributes(attributes); } else if(mode === 'persistent') { console.info("Saving to Dynamo: ",attributes); return new Promise((resolve, reject) => { handlerInput.attributesManager.getPersistentAttributes() .then((persistent) => { delete attributes['isInitialized']; handlerInput.attributesManager.setPersistentAttributes(attributes); resolve(handlerInput.attributesManager.savePersistentAttributes()); }) .catch((error) => { reject(error); }); }); } } const LaunchHandler = { canHandle(handlerInput) { return handlerInput.requestEnvelope.request.type === 'LaunchRequest'; }, handle(handlerInput) { console.info("LaunchRequest"); let attributes = handlerInput.attributesManager.getSessionAttributes(); console.info("Test the load: " + attributes['isInitialized']); attributes['FOO'] = "BAR"; saveUser(handlerInput, attributes, 'persistent'); return handlerInput.responseBuilder .speak('Hello') .reprompt('Hello') .getResponse(); } } exports.handler = Alexa.SkillBuilders.standard() .addRequestHandlers( LaunchHandler ) .addRequestInterceptors(GetUserDataInterceptor) .withTableName('Spiele') .withAutoCreateTable(true) .withDynamoDbClient() .lambda(); can anyone tell me what i'm doing wrong?
[ "please confirm the partition key is 'userId' not 'UserId' (notice the uppercase U).\nAlso I would suggest using 'this' object.\nLet me know if that helps.\nCheers\n", "Below code is for python lambda function\nStep1: from ask_sdk_core.skill_builder import CustomSkillBuilder\nStep2: from ask_sdk_dynamodb.adapter import DynamoDbAdapter\nStep3: sb = SkillBuilder()\nStep4: sb = CustomSkillBuilder(persistence_adapter = dynamodb_adapter)\n" ]
[ 0, 0 ]
[]
[]
[ "alexa_skills_kit" ]
stackoverflow_0056426145_alexa_skills_kit.txt
Q: Jest React Native Unable to find an element with testID: I'm using Jest to test my React Native app but im having a lots of trouble. One of them is this error: Unable to find an element with testID: loginButton This is my JSX code: <Button testID="loginButton" onPress={() => navigation.navigate('Home')}> Join for free </Button> and my test code: import React from 'react'; import Login from '../screens/Login'; import {fireEvent, render} from '@testing-library/react-native'; describe('Login screen', () => { it('should go to dashboard', () => { const navigation = {navigate: () => {}}; jest.spyOn(navigation, 'navigate'); const page = render(<Login navigation={navigation} />); const loginButton = page.getByTestId('loginButton'); fireEvent.press(loginButton); expect(navigation.navigate).toHaveBeenCalledWith('Home'); }); }); EDIT: If i do const loginButton = page.queryAllByTestId('loginButton'); the test passes. What am i doing wrong here? Thanks! A: I forgot to mention that im using NativeBase and my app was wrapped in a <NativeBaseProvider>. To fix the above issue, you can simply pass initialWindowMetrics to NativeBaseProvider in your tests. const inset = { frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }; <NativeBaseProvider initialWindowMetrics={inset}> {children} </NativeBaseProvider>;
Jest React Native Unable to find an element with testID:
I'm using Jest to test my React Native app but im having a lots of trouble. One of them is this error: Unable to find an element with testID: loginButton This is my JSX code: <Button testID="loginButton" onPress={() => navigation.navigate('Home')}> Join for free </Button> and my test code: import React from 'react'; import Login from '../screens/Login'; import {fireEvent, render} from '@testing-library/react-native'; describe('Login screen', () => { it('should go to dashboard', () => { const navigation = {navigate: () => {}}; jest.spyOn(navigation, 'navigate'); const page = render(<Login navigation={navigation} />); const loginButton = page.getByTestId('loginButton'); fireEvent.press(loginButton); expect(navigation.navigate).toHaveBeenCalledWith('Home'); }); }); EDIT: If i do const loginButton = page.queryAllByTestId('loginButton'); the test passes. What am i doing wrong here? Thanks!
[ "I forgot to mention that im using NativeBase and my app was wrapped in a <NativeBaseProvider>.\nTo fix the above issue, you can simply pass initialWindowMetrics to NativeBaseProvider in your tests.\nconst inset = {\n frame: { x: 0, y: 0, width: 0, height: 0 },\n insets: { top: 0, left: 0, right: 0, bottom: 0 },\n};\n\n<NativeBaseProvider initialWindowMetrics={inset}>\n {children}\n</NativeBaseProvider>;\n\n" ]
[ 0 ]
[]
[]
[ "jestjs", "react_native", "unit_testing" ]
stackoverflow_0074657482_jestjs_react_native_unit_testing.txt
Q: How to use CreateLink() MS Graph C# SDK for Scope type User I cannot find a MS Graph SDK c# example for how to use the "user" scope parameter. The source docs gives no examples how to use this "user" parameter. Do you put the email addresses in string format or some other format? https://learn.microsoft.com/en-us/graph/api/driveitem-createlink?view=graph-rest-1.0&tabs=http public async Task<Permission> GetFilePreviewLinkAsync(string DriveID, string DriveItemID, string Scope, string Type) { Permission response = null; try { response = await _graphServiceClient.Me.Drives[DriveID].Items[DriveItemID] .CreateLink(Type, Scope, null, null, null, true) .Request() .PostAsync(); } catch (ServiceException ex) { Console.WriteLine($"Error uploading: {ex.ToString()}"); } return response; } A: The first step is to create a link with user scope. The second step is to grant users access to a link. The first request returns an Permission object with ShareId property var permission = await graphClient.Me.Drive.Items["{driveItem-id}"] .CreateLink(type,scope,null,null,null,null) .Request() .PostAsync(); Use ShareId in the second call to grant users access. Users are specified in DriveRecipient collection either by email or by id. var recipients = new List<DriveRecipient>() { new DriveRecipient { Email = "[email protected]" // ObjectId = <User.Id> }, new DriveRecipient { Email = "[email protected]" } }; var roles = new List<String>() { "read" }; await graphClient.Shares[permission.ShareId].Permission .Grant(roles,recipients) .Request() .PostAsync(); Documentation: Grant access to sharing link
How to use CreateLink() MS Graph C# SDK for Scope type User
I cannot find a MS Graph SDK c# example for how to use the "user" scope parameter. The source docs gives no examples how to use this "user" parameter. Do you put the email addresses in string format or some other format? https://learn.microsoft.com/en-us/graph/api/driveitem-createlink?view=graph-rest-1.0&tabs=http public async Task<Permission> GetFilePreviewLinkAsync(string DriveID, string DriveItemID, string Scope, string Type) { Permission response = null; try { response = await _graphServiceClient.Me.Drives[DriveID].Items[DriveItemID] .CreateLink(Type, Scope, null, null, null, true) .Request() .PostAsync(); } catch (ServiceException ex) { Console.WriteLine($"Error uploading: {ex.ToString()}"); } return response; }
[ "The first step is to create a link with user scope. The second step is to grant users access to a link.\nThe first request returns an Permission object with ShareId property\nvar permission = await graphClient.Me.Drive.Items[\"{driveItem-id}\"]\n .CreateLink(type,scope,null,null,null,null)\n .Request()\n .PostAsync();\n\nUse ShareId in the second call to grant users access. Users are specified in DriveRecipient collection either by email or by id.\nvar recipients = new List<DriveRecipient>()\n{\n new DriveRecipient\n {\n Email = \"[email protected]\"\n // ObjectId = <User.Id>\n },\n new DriveRecipient\n {\n Email = \"[email protected]\"\n }\n};\n\nvar roles = new List<String>()\n{\n \"read\"\n};\n\nawait graphClient.Shares[permission.ShareId].Permission\n .Grant(roles,recipients)\n .Request()\n .PostAsync();\n\nDocumentation:\nGrant access to sharing link\n" ]
[ 1 ]
[]
[]
[ "asp.net_core", "c#", "msgraph" ]
stackoverflow_0074649729_asp.net_core_c#_msgraph.txt
Q: Program that should create a list doesnt work I am currently working on a program that should create a list out of your own inputs. It should list your inputs under each other but if I try to press the "Hinzufügen" button (Enter button), nothing happens and my inputs aren't listed. This is for a school project and I am stuck with this for some time. I already tried to look if I made some spelling mistakes and I corrected them. I really don't know what makes my programme not working. I would appreciate any help. var enterButton = document.getElementById("enter"); var input = document.getElementById("benutzerInput"); var ul = document.querySelector("ul"); var item = document.getElementsByTagName("li"); function erstellenEintrag() { var li = document.createElement("li"); ul.appendChild(li); } enterButton.addEventListener("click", erstellenEintrag); body { background: #1d1e22; text-align: center; font-family: "Arial", sans-serif; color: #ffffff; } h1 { text-transform: uppercase; font-weight: 800; } input { border-radius: 5px; min-width: 80%; padding: 20px; margin-top: 10px; } #enter { border: none; padding: 20px; border-radius: 5px; color: #ffffff; background-color: #4eb9cd; transition: all 0.75s ease; font-weight: normal; } ul { padding-left: 15px; padding-right: 15px; } li { text-align: left; margin-top: 20px; list-style: none; padding: 20px; color: #ffffff; text-transform: capitalize; font-weight: 600; border-radius: 5px; margin-bottom: 10; background: #4eb9cd; transition: all 0.75s ease; } li:hover { background: none; border: none; float: right; color: #ffffff; font-weight: 800; } .done { background: #51df51 !important; color: #00891f; text-decoration: line-through; } .delete { display: none; } body { background: #1d1e22; color: rgb(255, 0, 153) } <h1>Kühlflex</h1> <div> <input id="benutzerInput" type="text" placeholder="Neuer Eintrag..." /> <button id="enter">Hinzufügen</button> </div> </ul> A: There are a few issues with your code that are preventing the items from being added to the list. First, in your erstellenEintrag() function, you are creating a new element but you are not adding any content to it. This means that when the function is called, an empty element will be added to the list, but it will not have any text or content. To fix this, you can add the value of the input element to the element when you create it. Second, in your erstellenEintrag() function, you are adding the new element to the element, but you are not resetting the value of the input element after the element is added. This means that if the user enters multiple items, the value of the input element will not be reset and the same item will be added multiple times. To fix this, you can reset the value of the input element after the element is added to the list. Here is an example of how you could modify your erstellenEintrag() function to fix these issues: function erstellenEintrag() { var li = document.createElement("li"); // Set the content of the <li> element to the value of the input element li.innerHTML = input.value; ul.appendChild(li); // Reset the value of the input element input.value = ""; } With these changes, your code should work as expected and items should be added to the list when the user clicks the "Hinzufügen" button.
Program that should create a list doesnt work
I am currently working on a program that should create a list out of your own inputs. It should list your inputs under each other but if I try to press the "Hinzufügen" button (Enter button), nothing happens and my inputs aren't listed. This is for a school project and I am stuck with this for some time. I already tried to look if I made some spelling mistakes and I corrected them. I really don't know what makes my programme not working. I would appreciate any help. var enterButton = document.getElementById("enter"); var input = document.getElementById("benutzerInput"); var ul = document.querySelector("ul"); var item = document.getElementsByTagName("li"); function erstellenEintrag() { var li = document.createElement("li"); ul.appendChild(li); } enterButton.addEventListener("click", erstellenEintrag); body { background: #1d1e22; text-align: center; font-family: "Arial", sans-serif; color: #ffffff; } h1 { text-transform: uppercase; font-weight: 800; } input { border-radius: 5px; min-width: 80%; padding: 20px; margin-top: 10px; } #enter { border: none; padding: 20px; border-radius: 5px; color: #ffffff; background-color: #4eb9cd; transition: all 0.75s ease; font-weight: normal; } ul { padding-left: 15px; padding-right: 15px; } li { text-align: left; margin-top: 20px; list-style: none; padding: 20px; color: #ffffff; text-transform: capitalize; font-weight: 600; border-radius: 5px; margin-bottom: 10; background: #4eb9cd; transition: all 0.75s ease; } li:hover { background: none; border: none; float: right; color: #ffffff; font-weight: 800; } .done { background: #51df51 !important; color: #00891f; text-decoration: line-through; } .delete { display: none; } body { background: #1d1e22; color: rgb(255, 0, 153) } <h1>Kühlflex</h1> <div> <input id="benutzerInput" type="text" placeholder="Neuer Eintrag..." /> <button id="enter">Hinzufügen</button> </div> </ul>
[ "There are a few issues with your code that are preventing the items from being added to the list.\nFirst, in your erstellenEintrag() function, you are creating a new element but you are not adding any content to it. This means that when the function is called, an empty element will be added to the list, but it will not have any text or content. To fix this, you can add the value of the input element to the element when you create it.\nSecond, in your erstellenEintrag() function, you are adding the new element to the element, but you are not resetting the value of the input element after the element is added. This means that if the user enters multiple items, the value of the input element will not be reset and the same item will be added multiple times. To fix this, you can reset the value of the input element after the element is added to the list.\nHere is an example of how you could modify your erstellenEintrag() function to fix these issues:\nfunction erstellenEintrag() {\n var li = document.createElement(\"li\");\n // Set the content of the <li> element to the value of the input element\n li.innerHTML = input.value;\n ul.appendChild(li);\n // Reset the value of the input element\n input.value = \"\";\n}\n\nWith these changes, your code should work as expected and items should be added to the list when the user clicks the \"Hinzufügen\" button.\n" ]
[ 0 ]
[ "enterButton it is taking a null value as it is executed before DOM gets loaded. So, we are waiting for DOM to completely load and then fetch values as required.\nJS code - (rest is same)\n window.onload = function() {\n var enterButton = document.getElementById(\"enter\");\n \n function erstellenEintrag() {\n var ul = document.querySelector(\"ul\");\n var input = document.getElementById(\"benutzerInput\").value;\n var li = document.createElement(\"li\");\n li.append(input);\n ul.appendChild(li);\n }\n } \n\n\n" ]
[ -1 ]
[ "javascript" ]
stackoverflow_0074667823_javascript.txt
Q: Typescript ReferenceError: exports is not defined Trying to implement a module following the official handbook, I get this error message: Uncaught ReferenceError: exports is not defined at app.js:2 But nowhere in my code do I ever use the name exports. How can I fix this? Files app.ts let a = 2; let b:number = 3; import Person = require ('./mods/module-1'); module-1.t export class Person { constructor(){ console.log('Person Class'); } } export default Person; tsconfig.json { "compilerOptions": { "module": "commonjs", "target": "es5", "noImplicitAny": false, "sourceMap": true, "outDir": "scripts/" }, "exclude": [ "node_modules" ] } A: Add the following line before other references to JavaScript. This is a nice little hack. <script>var exports = {};</script> A: EDIT: This answer might not work depending if you're not targeting es5 anymore, I'll try to make the answer more complete. Original Answer If CommonJS isn't installed (which defines exports), you have to remove this line from your tsconfig.json: "module": "commonjs", As per the comments, this alone may not work with later versions of tsc. If that is the case, you can install a module loader like CommonJS, SystemJS or RequireJS and then specify that. Note: Look at your main.js file that tsc generated. You will find this at the very top: Object.defineProperty(exports, "__esModule", { value: true }); It is the root of the error message, and after removing "module": "commonjs",, it will vanish. A: A solution: Remove "type": "module" from package.json. A: This is fixed by setting the module compiler option to es6: { "compilerOptions": { "module": "es6", "target": "es5", } } A: npm install @babel/plugin-transform-modules-commonjs and add to to .babelrc plugins resolved my question. A: I ran into this issue a few weeks ago and used the exports hack above in the short term but finally figured out another way around this that's working great for me. So unlike some of the other responses above, I actually wanted the code I'm compiling to be a module. By setting "target": "es6", "module": "esnext" and then linking to my compiled JS file with type="module" instead of type="text/javascript", my compiled code no longer has the Object.defineProperty(exports, "__esModule", { value: true }); line and it's still a module My tsconfig: { "compilerOptions": { "target": "es6", "experimentalDecorators": true, "emitDecoratorMetadata": true, "module": "esnext", "moduleResolution": "node", "lib": ["es2016", "esnext", "dom"], "outDir": "build", "strict": true, "strictNullChecks": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "declaration": true, }, "include": ["src/index.ts"], "exclude": ["build"] } My link to my compiled code in HTML head tags: <script src="../build/index.js" type="module" defer></script> As a bonus, now I can also import anything that I export in that index.js file in a separate type="module" script down below the main HTML body code: <script type="module"> import { coolEncodingFunction, coolDecodingFunction } from "../build/index.js"; /* Do stuff with coolEncodingFunction and coolDecodingFunction */ /* ... */ </script> A: my solution is a sum up of everything above with little tricks I added, basically I added this to my html code <script>var exports = {"__esModule": true};</script> <script src="js/file.js"></script> this even allows you to use import instead of require if you're using electron or something, and it works fine with typescript 3.5.1, target: es3 -> esnext. A: I had the same problem and solved it adding "es5" library to tsconfig.json like this: { "compilerOptions": { "target": "es5", //defines what sort of code ts generates, es5 because it's what most browsers currently UNDERSTANDS. "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, //for angular to be able to use metadata we specify in our components. "experimentalDecorators": true, //angular needs decorators like @Component, @Injectable, etc. "removeComments": false, "noImplicitAny": false, "lib": [ "es2016", "dom", "es5" ] } } A: For people still having this issue, if your compiler target is set to ES6 you need to tell babel to skip module transformation. To do so add this to your .babelrc file { "presets": [ ["env", {"modules": false} ]] } A: I had this same error too. In my case it was because we had an old-fashioned import statement in our TypeScript AngularJS project like this: import { IAttributes, IScope } from "angular"; which was compiled to JavaScript like this: "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); This was needed back in the old days because we then used IAttributes in the code and TypeScript wouldn't have known what to do with it otherwise. But after removing the import statement, and converting IAttributes to ng.IAttributes those two JavaScript lines disappeared - and so did the error message. A: I had similar issue as the original poster of the question: I better tell you what mistakes I made and how I corrected it, that might help someone. I had javascript nodejs project and converted it to typescript. Previously in package.json I had "type":"module" when I was running in JavaScript. When I converted it to TypeScript project and started converting files in .ts files and started running using following command: npx tsc test.ts && node test.ts I would get the above error. I got rid of the error by simply removing the "type":"module" from package.json My tsconfig.json would like below: { "compilerOptions": { "target": "esnext", "lib": ["es6", "es5", "es7", "dom"], "allowJs": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "es6", "outDir": "./build", "moduleResolution": "node", "resolveJsonModule": true, "skipLibCheck": true }, "exclude": ["node_modules", "build"] I am using node 14 and TypeScript 4.2.4 A: for me, removing "esModuleInterop": true from tsconfig.json did the trick. A: Simply add libraryTarget: 'umd', like so const webpackConfig = { output: { libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined". } }; module.exports = webpackConfig; // Export all custom Webpack configs. A: In package.json, add "type": "module" In terminal type in npx tsc --init It will create a tsconfig.json. In tsconfig.json, change "target": "es5" to "target": "es6" comment out //"module": "commonjs", uncomment "moduleResolution": "node", You should be good to go. In package.json, create a build script: "build": "tsc -p tsconfig.json" Then, when you want to build, you just compile npm run build then execute and should be good A: For some ASP.NET projects import and export may not be used at all in your Typescripts. The question's error showed up when I attempted to do so and I only discovered later that I just needed to add the generated JS script to the View like so: <script src="~/scripts/js/[GENERATED_FILE].Index.js" asp-append-version="true"></script> A: Note: This might not be applicable for OP's answer, but I was getting this error, and this how I solved it. So the problem that I was facing was that I was getting this error when I retrieved a 'js' library from a particular CDN. The only wrong thing that I was doing was importing from the CDN's cjs directory like so: https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/cjs/popper.min.js Notice the dist/cjs part? That's where the problem was. I went back to the CDN (jsdelivr) in my case and navigated to find the umd folder. And I could find another set of popper.min.js which was the correct file to import: https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js. A: To solve this issue, put these two lines in your index.html page. <script>var exports = {"__esModule": true};</script> <script type="text/javascript" src="/main.js"> Make sure to check your main.js file path. A: Not answering the question directly, but no stackoverflow thread mentionned this case, took me a while to debug, and so adding it here in case it could help someone in the future. I had the error "exports is not defined" coming from an imported NPM module. Changing my typescript config did nothing as I had no control over the imported third-party code. The problem was an invalid import syntax for that package. For example, I had imported "@mui/material/TextField/TextField", yet the correct import was supposed to be "@mui/material/TextField". A: So this is a super generic TypeScript error and this StackOverflow question is the first result for various queries I made researching my problem. It has 385k views. For those with Angular / TypeScript and an Angular Library using ng-packagr seeing a generic "ReferenceError: exports is not defined", you'll need to define public-api.ts for each feature/component/service such that you include it with index.ts such as found in this repo for this article Node 16 or 18 (18 is LTS next week) Angular 2+ (14 currently) TypeScript 4.6.4-4.8.2 Several shallow examples go something like this referencing Creating Libraries ng new workspace --no-create-application cd workspace ng generate app home --routing=true --style=scss ng generate app admin --routing=true --style=scss ng generate library lib ... # include your library 'lib' into your application 'home' ng build lib --watch & ng serve home --open What's not directly explained is your index.ts and public-api.ts files need to be in each feature/component/service. Such as these example features A, B, and C in the repo below if you have a complex library. repo has the following: src/lib feature-a index.ts (referencing only ./public-api) public-api.ts (referencing only exported files in the directory) feature-b index.ts (referencing only ./public-api) public-api.ts (referencing only exported files in the directory) feature-c index.ts (referencing only ./public-api) public-api.ts (referencing only exported files in the directory) A: Try what @iFreilicht suggested above. If that didn't work after you've installed webpack and all, you may have just copied a webpack configuration from somewhere online and configured there that you want the output to support CommonJS by mistake. Make sure this isn't the case in webpack.config.js: module.exports = { mode: process.env.NODE_ENV || "development", entry: { index: "./src/js/index.ts" }, ... ... output: { libraryTarget: 'commonjs', <==== DELETE THIS LINE path: path.join(__dirname, 'build'), filename: "[name].bundle.js" } }; A: Had the same issue and fixed it by changing the JS packages loading order. Check the order in which the packages you need are being called and load them in an appropriate order. In my specific case (not using module bundler) I needed to load Redux, then Redux Thunk, then React Redux. Loading React Redux before Redux Thunk would give me exports is not defined. A: I had the same issue, but my setup required a different solution. I'm using the create-react-app-rewired package with a config-overrides.js file. Previously, I was using the addBabelPresets import (in the override() method) from customize-cra and decided to abstract those presets to a separate file. Coincidentally, this solved my problem. I added useBabelRc() to the override() method in config-overrides.js and created a babel.config.js file with the following: module.exports = { presets: [ '@babel/preset-react', '@babel/preset-env' ], } A: I stuck with such error in a SSR client part because it used a lib which was built with tsconfig.json compilerOptions as target: ES5 what brought using CommonJS for module resolution tsc CLI Options Compiler Options: target === "ES3" or "ES5" ? "CommonJS" : "ES6". While it used the target ESNext. A: As ES5/ES2009 doesn't support modules (import/export/require) on the client / browser you have to use libraries, which bundle the modules into a single file, which can be included via <script> tag, such as Browserify Webpack See also this answer. A: First, go to your index.html in your public folder find the reference of the script <script src="myScript.js"></script> and add type="module" Like so: <script type="module" src="myScript.js"></script> Secondly, in your tsconfig.json make sure target is set to es5 and module to es2015 "compilerOptions": { "target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ /* Modules */ "module": "es2015", /* Specify what module code is generated. */ } important: make sure to import with the .js extension e.g. import Piece from './classes/piece.js' A: I have this issue too. then I just change "module": "commonjs" to "module": "ESNext" everything is working fine. this my tsconfig.json: { "compilerOptions": { "module": "ESNext", "esModuleInterop": true, "target": "ESNext", "moduleResolution": "node", "sourceMap": true, "outDir": "dist", }, "lib": ["ESNext"], } I hope it can solve your problem!
Typescript ReferenceError: exports is not defined
Trying to implement a module following the official handbook, I get this error message: Uncaught ReferenceError: exports is not defined at app.js:2 But nowhere in my code do I ever use the name exports. How can I fix this? Files app.ts let a = 2; let b:number = 3; import Person = require ('./mods/module-1'); module-1.t export class Person { constructor(){ console.log('Person Class'); } } export default Person; tsconfig.json { "compilerOptions": { "module": "commonjs", "target": "es5", "noImplicitAny": false, "sourceMap": true, "outDir": "scripts/" }, "exclude": [ "node_modules" ] }
[ "Add the following line before other references to JavaScript. This is a nice little hack.\n<script>var exports = {};</script>\n\n", "EDIT:\nThis answer might not work depending if you're not targeting es5 anymore, I'll try to make the answer more complete.\nOriginal Answer\nIf CommonJS isn't installed (which defines exports), you have to remove this line from your tsconfig.json:\n \"module\": \"commonjs\",\n\nAs per the comments, this alone may not work with later versions of tsc. If that is the case, you can install a module loader like CommonJS, SystemJS or RequireJS and then specify that.\nNote:\nLook at your main.js file that tsc generated. You will find this at the very top:\nObject.defineProperty(exports, \"__esModule\", { value: true });\n\nIt is the root of the error message, and after removing \"module\": \"commonjs\",, it will vanish.\n", "A solution:\nRemove \"type\": \"module\" from package.json.\n", "This is fixed by setting the module compiler option to es6:\n{\n \"compilerOptions\": { \n \"module\": \"es6\",\n \"target\": \"es5\", \n }\n}\n\n", "npm install @babel/plugin-transform-modules-commonjs \nand add to to .babelrc plugins resolved my question.\n", "I ran into this issue a few weeks ago and used the exports hack above in the short term but finally figured out another way around this that's working great for me.\nSo unlike some of the other responses above, I actually wanted the code I'm compiling to be a module. By setting \"target\": \"es6\", \"module\": \"esnext\" and then linking to my compiled JS file with type=\"module\" instead of type=\"text/javascript\", my compiled code no longer has the Object.defineProperty(exports, \"__esModule\", { value: true }); line and it's still a module \nMy tsconfig:\n{\n \"compilerOptions\": {\n \"target\": \"es6\",\n \"experimentalDecorators\": true,\n \"emitDecoratorMetadata\": true,\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"lib\": [\"es2016\", \"esnext\", \"dom\"],\n \"outDir\": \"build\",\n \"strict\": true,\n \"strictNullChecks\": true,\n \"esModuleInterop\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"declaration\": true,\n },\n \"include\": [\"src/index.ts\"],\n \"exclude\": [\"build\"]\n}\n\nMy link to my compiled code in HTML head tags:\n<script src=\"../build/index.js\" type=\"module\" defer></script>\n\nAs a bonus, now I can also import anything that I export in that index.js file in a separate type=\"module\" script down below the main HTML body code:\n <script type=\"module\">\n import { coolEncodingFunction, coolDecodingFunction } from \"../build/index.js\";\n /* Do stuff with coolEncodingFunction and coolDecodingFunction */\n /* ... */\n</script>\n\n", "my solution is a sum up of everything above with little tricks I added, basically I added this to my html code\n<script>var exports = {\"__esModule\": true};</script>\n<script src=\"js/file.js\"></script>\n\nthis even allows you to use import instead of require if you're using electron or something, and it works fine with typescript 3.5.1, target: es3 -> esnext.\n", "I had the same problem and solved it adding \"es5\" library to tsconfig.json like this:\n{\n \"compilerOptions\": {\n \"target\": \"es5\", //defines what sort of code ts generates, es5 because it's what most browsers currently UNDERSTANDS.\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"sourceMap\": true,\n \"emitDecoratorMetadata\": true, //for angular to be able to use metadata we specify in our components.\n \"experimentalDecorators\": true, //angular needs decorators like @Component, @Injectable, etc.\n \"removeComments\": false,\n \"noImplicitAny\": false,\n \"lib\": [\n \"es2016\",\n \"dom\",\n \"es5\"\n ]\n }\n}\n\n", "For people still having this issue, if your compiler target is set to ES6 you need to tell babel to skip module transformation. To do so add this to your .babelrc file\n{\n \"presets\": [ [\"env\", {\"modules\": false} ]]\n}\n\n", "I had this same error too. In my case it was because we had an old-fashioned import statement in our TypeScript AngularJS project like this:\nimport { IAttributes, IScope } from \"angular\";\n\nwhich was compiled to JavaScript like this:\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n\nThis was needed back in the old days because we then used IAttributes in the code and TypeScript wouldn't have known what to do with it otherwise.\nBut after removing the import statement, and converting IAttributes to ng.IAttributes those two JavaScript lines disappeared - and so did the error message.\n", "I had similar issue as the original poster of the question:\nI better tell you what mistakes I made and how I corrected it, that might help someone.\nI had javascript nodejs project and converted it to typescript.\nPreviously in package.json I had \"type\":\"module\" when I was running in JavaScript.\nWhen I converted it to TypeScript project and started converting files in .ts files and started running using following command:\nnpx tsc test.ts && node test.ts\n\nI would get the above error.\nI got rid of the error by simply removing the \"type\":\"module\" from package.json\nMy tsconfig.json would like below:\n{\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"lib\": [\"es6\", \"es5\", \"es7\", \"dom\"],\n \"allowJs\": true,\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"module\": \"es6\",\n \"outDir\": \"./build\",\n \"moduleResolution\": \"node\",\n \"resolveJsonModule\": true,\n \"skipLibCheck\": true\n },\n \"exclude\": [\"node_modules\", \"build\"]\n\n\nI am using node 14 and TypeScript 4.2.4\n", "for me, removing \"esModuleInterop\": true from tsconfig.json did the trick.\n", "Simply add libraryTarget: 'umd', like so\nconst webpackConfig = {\n output: {\n libraryTarget: 'umd' // Fix: \"Uncaught ReferenceError: exports is not defined\".\n }\n};\n\nmodule.exports = webpackConfig; // Export all custom Webpack configs.\n\n", "In package.json, add \"type\": \"module\"\nIn terminal type in\nnpx tsc --init\n\nIt will create a tsconfig.json.\nIn tsconfig.json,\n\nchange \"target\": \"es5\" to \"target\": \"es6\"\ncomment out //\"module\": \"commonjs\",\nuncomment \"moduleResolution\": \"node\",\n\nYou should be good to go.\nIn package.json, create a build script:\n\"build\": \"tsc -p tsconfig.json\"\n\nThen, when you want to build, you just compile npm run build\nthen execute and should be good\n", "For some ASP.NET projects import and export may not be used at all in your Typescripts.\nThe question's error showed up when I attempted to do so and I only discovered later that I just needed to add the generated JS script to the View like so:\n<script src=\"~/scripts/js/[GENERATED_FILE].Index.js\" asp-append-version=\"true\"></script>\n\n", "Note: This might not be applicable for OP's answer, but I was getting this error, and this how I solved it. \nSo the problem that I was facing was that I was getting this error when I retrieved a 'js' library from a particular CDN. \nThe only wrong thing that I was doing was importing from the CDN's cjs directory like so:\nhttps://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/cjs/popper.min.js\nNotice the dist/cjs part? That's where the problem was. \nI went back to the CDN (jsdelivr) in my case and navigated to find the umd folder. And I could find another set of popper.min.js which was the correct file to import:\nhttps://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js.\n", "To solve this issue, put these two lines in your index.html page.\n<script>var exports = {\"__esModule\": true};</script>\n<script type=\"text/javascript\" src=\"/main.js\">\n\nMake sure to check your main.js file path.\n", "Not answering the question directly, but no stackoverflow thread mentionned this case, took me a while to debug, and so adding it here in case it could help someone in the future.\nI had the error \"exports is not defined\" coming from an imported NPM module. Changing my typescript config did nothing as I had no control over the imported third-party code. The problem was an invalid import syntax for that package. For example, I had imported \"@mui/material/TextField/TextField\", yet the correct import was supposed to be \"@mui/material/TextField\".\n", "So this is a super generic TypeScript error and this StackOverflow question is the first result for various queries I made researching my problem. It has 385k views.\nFor those with Angular / TypeScript and an Angular Library using ng-packagr seeing a generic \"ReferenceError: exports is not defined\", you'll need to define public-api.ts for each feature/component/service such that you include it with index.ts such as found in this repo for this article\n\nNode 16 or 18 (18 is LTS next week)\nAngular 2+ (14 currently)\nTypeScript 4.6.4-4.8.2\n\nSeveral shallow examples go something like this referencing Creating Libraries\nng new workspace --no-create-application\ncd workspace\nng generate app home --routing=true --style=scss\nng generate app admin --routing=true --style=scss\nng generate library lib\n... # include your library 'lib' into your application 'home'\nng build lib --watch &\nng serve home --open\n\nWhat's not directly explained is your index.ts and public-api.ts files need to be in each feature/component/service. Such as these example features A, B, and C in the repo below if you have a complex library. repo has the following:\n\nsrc/lib\n\nfeature-a\n\nindex.ts (referencing only ./public-api)\npublic-api.ts (referencing only exported files in the directory)\n\n\nfeature-b\n\nindex.ts (referencing only ./public-api)\npublic-api.ts (referencing only exported files in the directory)\n\n\nfeature-c\n\nindex.ts (referencing only ./public-api)\npublic-api.ts (referencing only exported files in the directory)\n\n\n\n\n\n", "Try what @iFreilicht suggested above. If that didn't work after you've installed webpack and all, you may have just copied a webpack configuration from somewhere online and configured there that you want the output to support CommonJS by mistake. Make sure this isn't the case in webpack.config.js:\nmodule.exports = {\n mode: process.env.NODE_ENV || \"development\",\n entry: { \n index: \"./src/js/index.ts\"\n },\n ...\n ...\n output: {\n libraryTarget: 'commonjs', <==== DELETE THIS LINE\n path: path.join(__dirname, 'build'),\n filename: \"[name].bundle.js\"\n }\n};\n\n", "Had the same issue and fixed it by changing the JS packages loading order.\nCheck the order in which the packages you need are being called and load them in an appropriate order.\nIn my specific case (not using module bundler) I needed to load Redux, then Redux Thunk, then React Redux. Loading React Redux before Redux Thunk would give me exports is not defined.\n", "I had the same issue, but my setup required a different solution.\nI'm using the create-react-app-rewired package with a config-overrides.js file. Previously, I was using the addBabelPresets import (in the override() method) from customize-cra and decided to abstract those presets to a separate file. Coincidentally, this solved my problem.\nI added useBabelRc() to the override() method in config-overrides.js and created a babel.config.js file with the following:\nmodule.exports = {\n presets: [\n '@babel/preset-react',\n '@babel/preset-env'\n ],\n}\n\n", "I stuck with such error in a SSR client part because it used a lib which was built with tsconfig.json compilerOptions as target: ES5 what brought using CommonJS for module resolution tsc CLI Options Compiler Options: target === \"ES3\" or \"ES5\" ? \"CommonJS\" : \"ES6\". While it used the target ESNext.\n", "As ES5/ES2009 doesn't support modules (import/export/require) on the client / browser you have to use libraries, which bundle the modules into a single file, which can be included via <script> tag, such as\n\nBrowserify\nWebpack\n\nSee also this answer.\n", "First, go to your index.html in your public folder find the reference of the script <script src=\"myScript.js\"></script> and add type=\"module\"\nLike so:\n<script type=\"module\" src=\"myScript.js\"></script>\n\nSecondly, in your tsconfig.json make sure target is set to es5 and module to es2015\n \"compilerOptions\": {\n \"target\": \"es5\", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */\n /* Modules */\n \"module\": \"es2015\", /* Specify what module code is generated. */\n}\n\nimportant: make sure to import with the .js extension e.g. import Piece from './classes/piece.js'\n", "I have this issue too. then I just change \"module\": \"commonjs\" to \"module\": \"ESNext\" everything is working fine.\nthis my tsconfig.json:\n{\n \"compilerOptions\": {\n \"module\": \"ESNext\",\n \"esModuleInterop\": true,\n \"target\": \"ESNext\",\n \"moduleResolution\": \"node\",\n \"sourceMap\": true,\n \"outDir\": \"dist\",\n },\n \"lib\": [\"ESNext\"],\n }\n\nI hope it can solve your problem!\n" ]
[ 102, 92, 70, 24, 19, 12, 10, 7, 5, 5, 4, 3, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "I think the problem may be the mismatched configuration.\n\nWorking solution 1 below give you a correct configuration for ES Module.\nWorking solution 2 below give you a correct configuration for CommonJS.\nMixed solution 1+2 give you an Error.\n\nI just post partial content here, for clarity.\nGithub project https://github.com/jmmvkr/ts-express/\nhave a complete set of files demonstrate the working solution 1 and solution 2.\nWorking solution 1, ES Module\n/* Configuration for ES Module */\n\n// tsconfig.json\n{\n \"compilerOptions\": {\n \"module\": \"es6\", // or \"esnext\"\n }\n}\n// package.json\n{\n \"type\": \"module\", // type is module\n}\n\nWorking solution 2, CommonJS\n/* Configuration for CommonJS */\n\n// tsconfig.json\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n }\n}\n// package.json\n{\n \"type\": \"\", // type is NOT module\n}\n\nMixed, do NOT work\n/* Mixed, got ReferenceError: exports is not defined in ES module scope */\n\n// tsconfig.json\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n }\n}\n// package.json\n{\n \"type\": \"module\", // type is module\n}\n\n", " {\n \"compileOnSave\": false,\n \"compilerOptions\": {\n \"baseUrl\": \"./\",\n \"outDir\": \"./dist\",\n \"sourceMap\": true,\n \"declaration\": false,\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es5\",\n \"typeRoots\": [\"node_modules/@types\"],\n \"lib\": [\"es2018\", \"dom\"]\n }\n }\n\n", "If you are just using interfaces for types, leave out the export keyword and ts can pick up on the types without needing to import. They key is you cannot use import/export anywhere.\nexport interface Person {\n name: string;\n age: number;\n}\n\ninto\ninterface Person {\n name: string;\n age: number;\n}\n\n" ]
[ -1, -2, -2 ]
[ "module", "typescript" ]
stackoverflow_0043042889_module_typescript.txt
Q: how to add thousand separator for number input fields in react? I want to add thousand separators to an number input however I don't want to change the value. I add the separators but the value will become string. import "./styles.css"; import { useState } from "react"; export default function App() { const [value, setValue] = useState(0); const addCommas = (num) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); const removeNonNumeric = (num) => num.toString().replace(/[^0-9]/g, ""); const handleChange = (event) => setValue(addCommas(removeNonNumeric(event.target.value))); console.log(typeof value) return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <input type="text" value={value} onChange={handleChange} /> </div> ); } In this code as soon as user enters a number, the typeof value will become string since we are using toString method. I was wondering if there is a way to implement an input and only modify its view not its value. A: using this code solve this problem the code is below and another little thing i can say may be none numaric string are not able to convert to number and the thing is that a comma as like none numaric string that's why you got NaN see the code solution: import "./styles.css"; import { useState } from "react"; export default function App() { const [value, setValue] = useState({ displayValue: 0, actualNumberValue: 0 }); const handleChange = (event) => { const strNumber = event.target.value.replace(/\B(?=(\d{3})+(?!\d))/g, ","); setValue({ displayValue: strNumber, actualNumberValue: Number(strNumber.replace(/,/g, "")) }); }; console.log(typeof value.actualNumberValue); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <input type="text" value={value.displayValue} onChange={handleChange} /> </div> ); } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
how to add thousand separator for number input fields in react?
I want to add thousand separators to an number input however I don't want to change the value. I add the separators but the value will become string. import "./styles.css"; import { useState } from "react"; export default function App() { const [value, setValue] = useState(0); const addCommas = (num) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); const removeNonNumeric = (num) => num.toString().replace(/[^0-9]/g, ""); const handleChange = (event) => setValue(addCommas(removeNonNumeric(event.target.value))); console.log(typeof value) return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <input type="text" value={value} onChange={handleChange} /> </div> ); } In this code as soon as user enters a number, the typeof value will become string since we are using toString method. I was wondering if there is a way to implement an input and only modify its view not its value.
[ "using this code solve this problem the code is below and another little thing i can say may be none numaric string are not able to convert to number and the thing is that a comma as like none numaric string that's why you got NaN see the code solution:\n\n\nimport \"./styles.css\";\nimport { useState } from \"react\";\nexport default function App() {\n const [value, setValue] = useState({\n displayValue: 0,\n actualNumberValue: 0\n });\n\n const handleChange = (event) => {\n const strNumber = event.target.value.replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n setValue({\n displayValue: strNumber,\n actualNumberValue: Number(strNumber.replace(/,/g, \"\"))\n });\n };\n\n console.log(typeof value.actualNumberValue);\n\n return (\n <div className=\"App\">\n <h1>Hello CodeSandbox</h1>\n <h2>Start editing to see some magic happen!</h2>\n <input type=\"text\" value={value.displayValue} onChange={handleChange} />\n </div>\n );\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\n\n\n\n" ]
[ 0 ]
[]
[]
[ "input", "javascript", "reactjs" ]
stackoverflow_0074666712_input_javascript_reactjs.txt
Q: Override max width of specific docs (not all docs) I have a specific "doc" in the "docs" section, for which I need the max width to be bigger (because it contains 2 IFrames side by side). I see that the guy specifying the max-width is: DocPageLayouMain: But this component doesn't receive as param a specific page. It is the same for all pages. A child of it, DocItem knows the current page (which may communicate via metadata that it needs the bigger size. However, it doesn't have the "power" to make the width bigger. Any hints of how I could achieve this? Thanks in advance :) A: I achieved my goal w/ the following modifs. However, I don't like that I've swizzeled a component = DocItem/Layout marked as "unsafe". import React from 'react'; import Layout from '@theme-original/DocItem/Layout'; import {useDoc} from '@docusaurus/theme-common/internal'; export default function LayoutWrapper(props) { const doc = useDoc(); return ( <div class={doc.frontMatter.full_width ? "" : "container"}> <Layout {...props} /> </div> ); } custom.css: main > .container { /* We disable this on the "normal" container, i.e. DocPage/Layout/Main. We want ONLY for this, hence we base our selector on the parent, which is a DOM element: <main>. We want to reuse this class in DocItem/Layout. */ max-width: initial !important; } my-page-that-wants-full-width.mdx --- description: Live demo hide_table_of_contents: true sidebar_position: 10 full_width: true --- # Demo ...
Override max width of specific docs (not all docs)
I have a specific "doc" in the "docs" section, for which I need the max width to be bigger (because it contains 2 IFrames side by side). I see that the guy specifying the max-width is: DocPageLayouMain: But this component doesn't receive as param a specific page. It is the same for all pages. A child of it, DocItem knows the current page (which may communicate via metadata that it needs the bigger size. However, it doesn't have the "power" to make the width bigger. Any hints of how I could achieve this? Thanks in advance :)
[ "I achieved my goal w/ the following modifs. However, I don't like that I've swizzeled a component = DocItem/Layout marked as \"unsafe\".\nimport React from 'react';\nimport Layout from '@theme-original/DocItem/Layout';\nimport {useDoc} from '@docusaurus/theme-common/internal';\n\nexport default function LayoutWrapper(props) {\n const doc = useDoc();\n return (\n <div class={doc.frontMatter.full_width ? \"\" : \"container\"}>\n <Layout {...props} />\n </div>\n );\n}\n\ncustom.css:\nmain > .container {\n /* \n We disable this on the \"normal\" container, i.e. DocPage/Layout/Main.\n We want ONLY for this, hence we base our selector on the parent, which is a DOM element: <main>.\n We want to reuse this class in DocItem/Layout.\n */\n max-width: initial !important;\n}\n\nmy-page-that-wants-full-width.mdx\n---\ndescription: Live demo\nhide_table_of_contents: true\nsidebar_position: 10\nfull_width: true\n---\n\n# Demo\n\n...\n\n" ]
[ 0 ]
[]
[]
[ "docusaurus" ]
stackoverflow_0074666779_docusaurus.txt
Q: Is it possible to create a type alias to a generic class in Delphi I would like to define a class type (type alias) for a generic class. I would like to do this so users of unit b can have access to TMyType without using unit a. I have units like this: unit a; interface type TMyNormalObject = class FData: Integer; end; TMyType<T> = class FData: <T>; end; implementation end. unit b; interface type TMyNormalObject = a.TMyNormalObject; // works TMyType<T> = a.TMyType<T>; // E2508 type parameters not allowed on this type implementation end. I already found a possible workaround which I don't like because it can introduce hard to find bugs: TMyType<T> = class(a.TMyType<T>); The problem with this approach is that it introduces a new class type and an a.TMyType instance is not a b.TMyType (while a.TMyNormallClass is a b.TMyNormalClass and vice versa - they are referring to the same class). A: It's currently not possible to declare a class type for a generic class. See QC76605 for more information. Also the update below. Example : TMyClass<T> = class end; TMyClassClass<T> = class of TMyClass<T>; //E2508 type parameters not allowed on this type The workaround that is presented looks like this : TMyIntClass = TMyType<Integer>; TMyIntClassClass = Class of TMyIntClass; But as commented, that would defeat the whole idea of generics, since the class would have to be subclassed for every generic instantiation. Here is also a link to a similar workaround on generating a specialized subclass of a generic type: derive-from-specialized-generic-types. In this case it would look like this : TMySpecialClass = Class(TMyType<Integer>); Update : The workaround proposed by RM: TMyType<T> = class(a.TMyType<T>); can be implemented with type safety using following scheme: unit Unita; interface type TMyType<T> = class Constructor Create; end; implementation uses Unitb; constructor TMyType<T>.Create; begin Inherited Create; //WriteLn( Self.QualifiedClassName,' ',Unitb.TMyType<T>.QualifiedClassName); Assert(Self.QualifiedClassName = Unitb.TMyType<T>.QualifiedClassName); end; end. unit Unitb; interface uses Unita; type TMyType<T> = class(Unita.TMyType<T>); implementation end. Project Test; {$APPTYPE CONSOLE} uses System.SysUtils, Unita in 'Unita.pas', Unitb in 'Unitb.pas'; var t1 : Unita.TMyType<Integer>; t2 : Unitb.TMyType<Integer>; t3 : TMyType<Integer>; begin try //t1 := Unita.TMyType<Integer>.Create; //Exception EAssertionFailed !! t2 := Unitb.TMyType<Integer>.Create; t3 := TMyType<Integer>.Create; ReadLn; finally //t1.Free; t2.Free; t3.Free; end; end. When creating the generic class, a test is made to check that the created class is derived from the type declared in unit b. Thereby all attempts to create this class from unit a is detected. Update 2: Just to be clear, a reference to a generic class, "class of type<T>" is not possible, but a copy of a generic class is fine. A: Since it is not possible to declare a "type alias" for a generic class, here is a solution using an interface. unit UnitA; interface Uses UnitB; type TMyType<T> = class(TInterfacedObject,ITMyType<T>) FData : T; Constructor Create( aV : T); end; implementation constructor TMyType<T>.Create( aV : T); begin Inherited Create; FData := aV; WriteLn( Self.QualifiedClassName); end; end. unit UnitB; interface type ITMyType<T> = Interface End; implementation end. program Test; {$APPTYPE CONSOLE} uses UnitA in 'UnitA.pas', UnitB in 'UnitB.pas'; var it1 : ITMyType<Integer>; begin it1:= TMyType<Integer>.Create(1); ReadLn; end. A: type TMyC = array of T; TMyD = TMyC <...integer...>; procedure x; var t4: TMyD; begin t4 := [1]; for var i:integer := Low(t4) to High(t4) do Memo1.Lines.Add(t4[i].ToString); end;
Is it possible to create a type alias to a generic class in Delphi
I would like to define a class type (type alias) for a generic class. I would like to do this so users of unit b can have access to TMyType without using unit a. I have units like this: unit a; interface type TMyNormalObject = class FData: Integer; end; TMyType<T> = class FData: <T>; end; implementation end. unit b; interface type TMyNormalObject = a.TMyNormalObject; // works TMyType<T> = a.TMyType<T>; // E2508 type parameters not allowed on this type implementation end. I already found a possible workaround which I don't like because it can introduce hard to find bugs: TMyType<T> = class(a.TMyType<T>); The problem with this approach is that it introduces a new class type and an a.TMyType instance is not a b.TMyType (while a.TMyNormallClass is a b.TMyNormalClass and vice versa - they are referring to the same class).
[ "It's currently not possible to declare a class type for a generic class.\nSee QC76605 for more information. Also the update below.\nExample :\nTMyClass<T> = class\nend;\nTMyClassClass<T> = class of TMyClass<T>; //E2508 type parameters not allowed on this type\n\nThe workaround that is presented looks like this :\nTMyIntClass = TMyType<Integer>;\nTMyIntClassClass = Class of TMyIntClass;\n\nBut as commented, that would defeat the whole idea of generics, since the class would have to be subclassed for every generic instantiation.\nHere is also a link to a similar workaround on generating a specialized subclass of a generic type: derive-from-specialized-generic-types. In this case it would look like this :\nTMySpecialClass = Class(TMyType<Integer>);\n\nUpdate :\nThe workaround proposed by RM:\nTMyType<T> = class(a.TMyType<T>);\n\ncan be implemented with type safety using following scheme:\nunit Unita;\ninterface\ntype\n TMyType<T> = class\n Constructor Create;\n end;\n\nimplementation\n\nuses\n Unitb;\n\nconstructor TMyType<T>.Create;\nbegin\n Inherited Create;\n //WriteLn( Self.QualifiedClassName,' ',Unitb.TMyType<T>.QualifiedClassName);\n Assert(Self.QualifiedClassName = Unitb.TMyType<T>.QualifiedClassName);\nend;\n\nend.\n\n\nunit Unitb;\n\ninterface\n\nuses Unita;\n\ntype\n TMyType<T> = class(Unita.TMyType<T>);\nimplementation\nend.\n\n\nProject Test;\n{$APPTYPE CONSOLE} \nuses\n System.SysUtils,\n Unita in 'Unita.pas',\n Unitb in 'Unitb.pas';\n\nvar\n t1 : Unita.TMyType<Integer>;\n t2 : Unitb.TMyType<Integer>;\n t3 : TMyType<Integer>; \nbegin\n try\n //t1 := Unita.TMyType<Integer>.Create; //Exception EAssertionFailed !!\n t2 := Unitb.TMyType<Integer>.Create;\n t3 := TMyType<Integer>.Create;\n ReadLn;\n finally\n //t1.Free;\n t2.Free;\n t3.Free;\n end;\nend.\n\nWhen creating the generic class, a test is made to check that the created class is derived from the type declared in unit b. Thereby all attempts to create this class from unit a is detected.\nUpdate 2:\nJust to be clear, a reference to a generic class, \"class of type<T>\" is not possible, but a copy of a generic class is fine. \n", "Since it is not possible to declare a \"type alias\" for a generic class, here is a solution using an interface. \nunit UnitA;\n\ninterface \n\nUses UnitB; \n\ntype\n TMyType<T> = class(TInterfacedObject,ITMyType<T>)\n FData : T;\n Constructor Create( aV : T);\n end;\n\nimplementation\n\nconstructor TMyType<T>.Create( aV : T);\nbegin\n Inherited Create;\n FData := aV;\n WriteLn( Self.QualifiedClassName);\nend;\n\nend.\n\n\nunit UnitB;\n\ninterface\n\ntype\n ITMyType<T> = Interface\n End;\n\nimplementation\n\nend.\n\n\nprogram Test;\n{$APPTYPE CONSOLE}\nuses\n UnitA in 'UnitA.pas',\n UnitB in 'UnitB.pas';\n\nvar\n it1 : ITMyType<Integer>;\nbegin\n it1:= TMyType<Integer>.Create(1);\n ReadLn;\nend.\n\n", "type \n\nTMyC = array of T;\nTMyD = TMyC <...integer...>;\nprocedure x;\nvar\nt4: TMyD;\nbegin\nt4 := [1];\nfor var i:integer := Low(t4) to High(t4) do\nMemo1.Lines.Add(t4[i].ToString);\nend;\n" ]
[ 12, 0, 0 ]
[]
[]
[ "alias", "declaration", "delphi", "generics", "types" ]
stackoverflow_0010060009_alias_declaration_delphi_generics_types.txt
Q: Unable to find an element with testID in react native testing library I am trying to findByTestId an IconButton (from React native Paper) but I get this error : Unable to find an element with testID: home-settings-button 84 | fireEvent.press(loginButton); 85 | > 86 | const settingsButton = await findByTestId("home-settings-button"); | ^ 87 | 88 | fireEvent.press(settingsButton); 89 | at findByTestId (node_modules/@testing-library/react-native/build/helpers/makeQueries.js:95:35) at _callee5$ (__tests__/navigator.test.js:86:32) at tryCatch (node_modules/regenerator-runtime/runtime.js:63:40) at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:294:22) at Generator.next (node_modules/regenerator-runtime/runtime.js:119:21) at tryCatch (node_modules/regenerator-runtime/runtime.js:63:40) at invoke (node_modules/regenerator-runtime/runtime.js:155:20) at node_modules/regenerator-runtime/runtime.js:165:13 I am not getting this error when I try to render the view and getByTestId the IconButton but when I try to render the AppNavigator and try to findByTestId the same IconButton, it doesn't work. For example, this works: it("renders the home screen", () => { const { getByTestId } = render(<HomeScreen />); getByTestId("home-settings-button"); }); But this doesn't : it("test settings page's logic", async () => { const { findByTestId } = render(<AppNavigator />); //Login and go to settings page const userInput = await findByTestId("login-username-input"); const passwordInput = await findByTestId("login-password-input"); const loginButton = await findByTestId("login-login-button"); fireEvent.changeText(userInput, "admin"); fireEvent.changeText(passwordInput, "admin"); fireEvent.press(loginButton); const settingsButton = await findByTestId("home-settings-button"); fireEvent.press(settingsButton); }); Here's the IconButton : <IconButton icon="cog" size={30} style={homeStyle.settings} onPress={() => { settings(); }} testID={"home-settings-button"} /> I don't quite understand why this happens, is there any reasons why I can't findByTestId this IconButton ? I am just trying to test the navigation with the button. A: If you are using NativeBase, to fix the above issue, you can simply pass initialWindowMetrics to NativeBaseProvider in your tests. const inset = { frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }; <NativeBaseProvider initialWindowMetrics={inset}> {children} </NativeBaseProvider>;
Unable to find an element with testID in react native testing library
I am trying to findByTestId an IconButton (from React native Paper) but I get this error : Unable to find an element with testID: home-settings-button 84 | fireEvent.press(loginButton); 85 | > 86 | const settingsButton = await findByTestId("home-settings-button"); | ^ 87 | 88 | fireEvent.press(settingsButton); 89 | at findByTestId (node_modules/@testing-library/react-native/build/helpers/makeQueries.js:95:35) at _callee5$ (__tests__/navigator.test.js:86:32) at tryCatch (node_modules/regenerator-runtime/runtime.js:63:40) at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:294:22) at Generator.next (node_modules/regenerator-runtime/runtime.js:119:21) at tryCatch (node_modules/regenerator-runtime/runtime.js:63:40) at invoke (node_modules/regenerator-runtime/runtime.js:155:20) at node_modules/regenerator-runtime/runtime.js:165:13 I am not getting this error when I try to render the view and getByTestId the IconButton but when I try to render the AppNavigator and try to findByTestId the same IconButton, it doesn't work. For example, this works: it("renders the home screen", () => { const { getByTestId } = render(<HomeScreen />); getByTestId("home-settings-button"); }); But this doesn't : it("test settings page's logic", async () => { const { findByTestId } = render(<AppNavigator />); //Login and go to settings page const userInput = await findByTestId("login-username-input"); const passwordInput = await findByTestId("login-password-input"); const loginButton = await findByTestId("login-login-button"); fireEvent.changeText(userInput, "admin"); fireEvent.changeText(passwordInput, "admin"); fireEvent.press(loginButton); const settingsButton = await findByTestId("home-settings-button"); fireEvent.press(settingsButton); }); Here's the IconButton : <IconButton icon="cog" size={30} style={homeStyle.settings} onPress={() => { settings(); }} testID={"home-settings-button"} /> I don't quite understand why this happens, is there any reasons why I can't findByTestId this IconButton ? I am just trying to test the navigation with the button.
[ "If you are using NativeBase, to fix the above issue, you can simply pass initialWindowMetrics to NativeBaseProvider in your tests.\nconst inset = {\n frame: { x: 0, y: 0, width: 0, height: 0 },\n insets: { top: 0, left: 0, right: 0, bottom: 0 },\n};\n\n<NativeBaseProvider initialWindowMetrics={inset}>\n {children}\n</NativeBaseProvider>;\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "jestjs", "react_native", "react_native_testing_library", "unit_testing" ]
stackoverflow_0073177741_javascript_jestjs_react_native_react_native_testing_library_unit_testing.txt
Q: SwiftUI: Animate View properties in response to Toggle change I'm trying to change a view in response to changing a Toggle. I figure out a way to do it as long as I mirror the state value the toggle is using. Is there a way to do it without creating another variable? Here's my code. You can see that there are three animations triggered. import SwiftUI struct OverlayView: View { @State var toggle: Bool = false @State var animatedToggle: Bool = false var body: some View { VStack { Image(systemName: "figure.arms.open") .resizable() .scaledToFit() .foregroundColor(animatedToggle ? .green : .red) // << animated .opacity(animatedToggle ? 1 : 0.2) // << animated if animatedToggle { // << animated Spacer() } Toggle("Overlay", isOn: $toggle) .onChange(of: toggle) { newValue in withAnimation { animatedToggle = toggle } } } } } A: Just use the .animation view modifier .animation(.default, value: toggle) Then remove the second variable struct OverlayView: View { @State var toggle: Bool = false var body: some View { VStack { Image(systemName: "figure.arms.open") .resizable() .scaledToFit() .foregroundColor(toggle ? .green : .red) .opacity(toggle ? 1 : 0.2) if toggle { Spacer() } Toggle("Overlay", isOn: $toggle) }.animation(.default, value: toggle) } }
SwiftUI: Animate View properties in response to Toggle change
I'm trying to change a view in response to changing a Toggle. I figure out a way to do it as long as I mirror the state value the toggle is using. Is there a way to do it without creating another variable? Here's my code. You can see that there are three animations triggered. import SwiftUI struct OverlayView: View { @State var toggle: Bool = false @State var animatedToggle: Bool = false var body: some View { VStack { Image(systemName: "figure.arms.open") .resizable() .scaledToFit() .foregroundColor(animatedToggle ? .green : .red) // << animated .opacity(animatedToggle ? 1 : 0.2) // << animated if animatedToggle { // << animated Spacer() } Toggle("Overlay", isOn: $toggle) .onChange(of: toggle) { newValue in withAnimation { animatedToggle = toggle } } } } }
[ "Just use the .animation view modifier\n.animation(.default, value: toggle)\n\nThen remove the second variable\nstruct OverlayView: View {\n @State var toggle: Bool = false\n var body: some View {\n \n VStack {\n Image(systemName: \"figure.arms.open\")\n .resizable()\n .scaledToFit()\n .foregroundColor(toggle ? .green : .red)\n .opacity(toggle ? 1 : 0.2)\n \n if toggle {\n Spacer()\n }\n \n Toggle(\"Overlay\", isOn: $toggle)\n\n }.animation(.default, value: toggle)\n\n }\n}\n\n" ]
[ 1 ]
[]
[]
[ "swiftui" ]
stackoverflow_0074667858_swiftui.txt
Q: How to freeze a requirement with pipenv? For example we have some pipfile (below) and I'd like to freeze the django version. We don't have a requirements.txt and we only use pipenv. How can I freeze the django version? [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" [dev-packages] black = "*" [requires] python_version = "3.6" A: Pipenv do natively implement freezing requirements.txt. It is as simple as: pipenv lock -r > requirements.txt A: Assuming you have your virtual environment activated, you have three simple approaches. I will list them from less verbose to more verbose. pip $ pip freeze > requirements.txt pip3 $ pip3 freeze > requirements.txt If a virtual environment is active, pip is most certainly equivalent to pip3. pipenv run $ pipenv run pip freeze > requirements.txt $ pipenv run pip3 freeze > requirements.txt pipenv run spawns a command installed into the virtual environment, so these commands are equivalent to the ones run without pipenv run. Once again, it is assumed that your virtual environment is active. A: As of v2022.8.13 of pipenv, the "old" lock -r functionality has been removed. Going forward, this should be accomplished with: pipenv requirements > requirements.txt A: By using run You can run given command from virtualenv, with any arguments forwarded $ pipenv run pip freeze > requirements.txt A: Recent pipenv versions (e.g. version 2022.6.7) are using the requirements subcommand and pipenv lock -r is deprecated. To freeze default dependencies pipenv requirements > requirements.txt to freeze development dependencies as well pipenv requirements --dev > dev-requirements.txt A: It's as simple as changing django = "*" to django = "your-preferred-version". So if you wanted to freeze it to 2.1, the latest release at the time of this writing, you could do this: [packages] django="2.1" The pipfile Git repo has some good examples of different ways to specify version strings: https://github.com/pypa/pipfile#pipfile Note that when you generate a lockfile from your pipfile, that lockfile is actually the file that's supposed to "freeze" your dependency to a specific version. That way, you don't have to concern yourself with which version works with your code, since by distributing the lockfile everyone else must use the same dependency versions as you. The developers of pipenv intended for developers to use it like this A: first, you ensure that your virtual environment is active then you open the terminal and run the command pip3 freeze > reqirements.txt (pip3) pip3 freeze > reqirements.txt (pip3) A: This is the way that I was prompted by pipenv to generate a requirements.txt file from the project's Pipfile: pipenv lock --requirements A: Use this as -r flag is deprecated pipenv requirements > requirements.txt A: pipenv run python -m pip freeze > requirements.txt
How to freeze a requirement with pipenv?
For example we have some pipfile (below) and I'd like to freeze the django version. We don't have a requirements.txt and we only use pipenv. How can I freeze the django version? [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" [dev-packages] black = "*" [requires] python_version = "3.6"
[ "Pipenv do natively implement freezing requirements.txt.\nIt is as simple as:\npipenv lock -r > requirements.txt\n\n", "Assuming you have your virtual environment activated, you have three simple approaches. I will list them from less verbose to more verbose.\npip\n$ pip freeze > requirements.txt\n\npip3\n$ pip3 freeze > requirements.txt\n\nIf a virtual environment is active, pip is most certainly equivalent to pip3.\npipenv run\n$ pipenv run pip freeze > requirements.txt\n$ pipenv run pip3 freeze > requirements.txt\n\npipenv run spawns a command installed into the virtual environment, so these commands are equivalent to the ones run without pipenv run. Once again, it is assumed that your virtual environment is active.\n", "As of v2022.8.13 of pipenv, the \"old\" lock -r functionality has been removed.\nGoing forward, this should be accomplished with:\npipenv requirements > requirements.txt\n\n", "By using run You can run given command from virtualenv, with any arguments forwarded\n$ pipenv run pip freeze > requirements.txt \n\n", "Recent pipenv versions (e.g. version 2022.6.7) are using the requirements subcommand and pipenv lock -r is deprecated.\nTo freeze default dependencies\npipenv requirements > requirements.txt\n\nto freeze development dependencies as well\npipenv requirements --dev > dev-requirements.txt\n\n", "It's as simple as changing django = \"*\" to django = \"your-preferred-version\". So if you wanted to freeze it to 2.1, the latest release at the time of this writing, you could do this:\n[packages]\ndjango=\"2.1\"\n\nThe pipfile Git repo has some good examples of different ways to specify version strings: https://github.com/pypa/pipfile#pipfile\nNote that when you generate a lockfile from your pipfile, that lockfile is actually the file that's supposed to \"freeze\" your dependency to a specific version. That way, you don't have to concern yourself with which version works with your code, since by distributing the lockfile everyone else must use the same dependency versions as you. The developers of pipenv intended for developers to use it like this\n", "first, you ensure that your virtual environment is active then you open the terminal and run the command\npip3 freeze > reqirements.txt (pip3)\npip3 freeze > reqirements.txt (pip3)\n", "This is the way that I was prompted by pipenv to generate a requirements.txt file from the project's Pipfile:\npipenv lock --requirements\n\n", "Use this as -r flag is deprecated\npipenv requirements > requirements.txt\n\n", "pipenv run python -m pip freeze > requirements.txt\n\n" ]
[ 99, 26, 24, 11, 9, 1, 0, 0, 0, 0 ]
[ "You can create a requirements.txt using this command : \npip3 freeze > requirements.txt\n\n" ]
[ -3 ]
[ "pipenv", "pipfile", "python" ]
stackoverflow_0051845562_pipenv_pipfile_python.txt
Q: How to use a single .class file in a java package? I want to write a code like this package mypackage; public class A extends B { } But all that I have is the B.class file which is compiled from a single B.java file with no package specified. Could anyone help me out? Thanks! I've tried putting B.class in my ./src and A.java in ./src/mypackage and run javac -cp src ./src/package/A.java but it wouldn't compile. It wouldn't compile neither if I put B.class in the same folder as A.java A: You can't. By your description, class B is in the default (unnamed) package. The Java language rules do not allow classes outside the default package to refer to classes in the default package. The only way you can use this class is to put A in the default package as well. That is, move it one directory up, and remove the package statement. Alternatively, you need to have the sources of class B (or decompile it), move it into a package and add a package statement, and recompile.
How to use a single .class file in a java package?
I want to write a code like this package mypackage; public class A extends B { } But all that I have is the B.class file which is compiled from a single B.java file with no package specified. Could anyone help me out? Thanks! I've tried putting B.class in my ./src and A.java in ./src/mypackage and run javac -cp src ./src/package/A.java but it wouldn't compile. It wouldn't compile neither if I put B.class in the same folder as A.java
[ "You can't. By your description, class B is in the default (unnamed) package. The Java language rules do not allow classes outside the default package to refer to classes in the default package.\nThe only way you can use this class is to put A in the default package as well. That is, move it one directory up, and remove the package statement.\nAlternatively, you need to have the sources of class B (or decompile it), move it into a package and add a package statement, and recompile.\n" ]
[ 0 ]
[]
[]
[ "java" ]
stackoverflow_0074668010_java.txt
Q: How to fetch shopify products based on multiple varying tags which are given dynamically in python? I am trying to fetch products from shopify by filtering based on tags. Tags will be dynamic, more than one, and will change. import json import time import requests API_KEY = 'xxxx' PASSWORD = 'xxxx' SHOP_NAME = 'xxxx' API_VERSION = '2020-04' #change to the API version shop_url = "https://%s:%s@%s.myshopify.com/admin/api/%s" % (API_KEY, PASSWORD, SHOP_NAME, API_VERSION) def callShopifyGraphQL(GraphQLString, data): headers = { "X-Shopify-Storefront-Access-Token": 'xxxxxx', "accept":"application/json" } response = requests.post(shop_url+'/graphql', json={'query': GraphQLString, 'variables': data}, headers=headers) answer = json.loads(response.text) return answer['data'] str1 = '0-12' str2 = 'physical' graphQLquery7 = """ { products(first:100, query:"tag:$tags") { edges { node { id tags title onlineStoreUrl } } } }""" tag = dict({ "tags":[str1,str2] }) resp = callShopifyGraphQL(graphQLquery7, tag) print json.dumps(resp) # This query works fine and gives multiple products # graphQLquery2 = """{ # products(first:100, query:"tag:[0-12, physical]") { # edges { # cursor # node { # id # tags # title # onlineStoreUrl # } # } # } # }""" The Output that I am getting is basically a JSON with products empty {u'extensions': {u'cost': {u'requestedQueryCost': 102, u'throttleStatus': {u'restoreRate': 50.0, u'currentlyAvailable': 998, u'maximumAvailable': 1000.0}, u'actualQueryCost': 2}}, u'data': {u'products': {u'edges': []}}} {"products": {"edges": []}} I am unable to pass my tags as a variable in the query. I am currently using GraphQl because I couldn't find REST APIs fetch product based on multiple tags which would vary. EDIT: Removed Python tag as this was not a python issue and I have added the answer as well lisitng two methods on how to do this A: You must use the flowing syntax: { products(first:10, query:"tag:tag1 OR tag:tag2 OR tag:tag3"){ edges { node { id tags title onlineStoreUrl } } } } Where you can use OR or AND if you like for all of the tags to be included or any of the listed. Install the GraphiQL App and test the queries before implementing them, it helps a lot in the development process. More about the Search Query for GraphQL can be seen here: https://shopify.dev/concepts/about-apis/search-syntax A: I finally found the answer to my own question -> The first way is a workaround(or a cheap python trick) which might be applicable only for the scenario mentioned in the question. Since the query is being passed in as a string(a multiline string), I can simply use placeholders to add variables in it by abusing the line continuation properties of the parenthesis ( and the comma ,. graphQLquery1 = """ { products(first:100, query:"tag:[%s, %s]") { edges { node { id tags title onlineStoreUrl } } } }"""%('3+', 'personal-social') data = None resp = callShopifyGraphQL(graphQLquery1, data) However, this is not how one should use variables in a GraphQl query. Below is a more proper solution of using variables in GraphQl graphQLquery2 = """ query($tags: String){ products(first:100, query:$tags) { edges { node { id tags title onlineStoreUrl } } } }""" str1 = '0-12' str2 = 'physical' tags = dict({ "tags":[str1,str2] }) resp = callShopifyGraphQL(graphQLquery2, tags) A: Since that was also asked in the comments (this comment by Harshit Bajpai), thought I'd answer. To make this a query call with a passable param: const GetProductsByTag = gql` query GetProductsByTag($first: Int!, $query: String!) { products(first: $first, query: $query) { edges { node { id title handle tags } } } } `
How to fetch shopify products based on multiple varying tags which are given dynamically in python?
I am trying to fetch products from shopify by filtering based on tags. Tags will be dynamic, more than one, and will change. import json import time import requests API_KEY = 'xxxx' PASSWORD = 'xxxx' SHOP_NAME = 'xxxx' API_VERSION = '2020-04' #change to the API version shop_url = "https://%s:%s@%s.myshopify.com/admin/api/%s" % (API_KEY, PASSWORD, SHOP_NAME, API_VERSION) def callShopifyGraphQL(GraphQLString, data): headers = { "X-Shopify-Storefront-Access-Token": 'xxxxxx', "accept":"application/json" } response = requests.post(shop_url+'/graphql', json={'query': GraphQLString, 'variables': data}, headers=headers) answer = json.loads(response.text) return answer['data'] str1 = '0-12' str2 = 'physical' graphQLquery7 = """ { products(first:100, query:"tag:$tags") { edges { node { id tags title onlineStoreUrl } } } }""" tag = dict({ "tags":[str1,str2] }) resp = callShopifyGraphQL(graphQLquery7, tag) print json.dumps(resp) # This query works fine and gives multiple products # graphQLquery2 = """{ # products(first:100, query:"tag:[0-12, physical]") { # edges { # cursor # node { # id # tags # title # onlineStoreUrl # } # } # } # }""" The Output that I am getting is basically a JSON with products empty {u'extensions': {u'cost': {u'requestedQueryCost': 102, u'throttleStatus': {u'restoreRate': 50.0, u'currentlyAvailable': 998, u'maximumAvailable': 1000.0}, u'actualQueryCost': 2}}, u'data': {u'products': {u'edges': []}}} {"products": {"edges": []}} I am unable to pass my tags as a variable in the query. I am currently using GraphQl because I couldn't find REST APIs fetch product based on multiple tags which would vary. EDIT: Removed Python tag as this was not a python issue and I have added the answer as well lisitng two methods on how to do this
[ "You must use the flowing syntax:\n{\n products(first:10, query:\"tag:tag1 OR tag:tag2 OR tag:tag3\"){\n edges {\n node {\n id\n tags\n title\n onlineStoreUrl\n }\n }\n }\n}\n\nWhere you can use OR or AND if you like for all of the tags to be included or any of the listed.\nInstall the GraphiQL App and test the queries before implementing them, it helps a lot in the development process.\nMore about the Search Query for GraphQL can be seen here: https://shopify.dev/concepts/about-apis/search-syntax\n", "I finally found the answer to my own question ->\n\nThe first way is a workaround(or a cheap python trick) which might be applicable only for the scenario mentioned in the question. Since the query is being passed in as a string(a multiline string), I can simply use placeholders to add variables in it by abusing the line continuation properties of the parenthesis ( and the comma ,.\n\ngraphQLquery1 = \"\"\" {\n products(first:100, query:\"tag:[%s, %s]\") {\n edges {\n node {\n id\n tags\n title\n onlineStoreUrl\n }\n }\n }\n}\"\"\"%('3+', 'personal-social')\n\ndata = None\nresp = callShopifyGraphQL(graphQLquery1, data)\n\nHowever, this is not how one should use variables in a GraphQl query.\n\nBelow is a more proper solution of using variables in GraphQl\n\ngraphQLquery2 = \"\"\" query($tags: String){\nproducts(first:100, query:$tags) {\n edges {\n node {\n id\n tags\n title\n onlineStoreUrl\n }\n }\n }\n}\"\"\"\n\nstr1 = '0-12'\nstr2 = 'physical'\ntags = dict({\n \"tags\":[str1,str2]\n})\nresp = callShopifyGraphQL(graphQLquery2, tags)\n\n", "Since that was also asked in the comments (this comment by Harshit Bajpai), thought I'd answer.\nTo make this a query call with a passable param:\nconst GetProductsByTag = gql`\n query GetProductsByTag($first: Int!, $query: String!) {\n products(first: $first, query: $query) {\n edges {\n node {\n id\n title\n handle\n tags\n }\n }\n }\n }\n`\n\n" ]
[ 5, 3, 0 ]
[]
[]
[ "graphql", "shopify", "shopify_api", "shopify_api_node" ]
stackoverflow_0062779854_graphql_shopify_shopify_api_shopify_api_node.txt
Q: C main function const char*[] vs char*[] I don't understand what the difference between int main(int argc, char* argv[]){;} and int main(int argc, const char* argv[]){;} is. I'm aware of the difference between a char*[] and const char*[] but I wonder why one would like to use the latter. Are there use cases where one would want to change command line arguments? What's the best practice about adding const? A: int main(int argc, char *argv[]) is a defined way of declaring main for a hosted environment according to the C standard, per C 2018 5.1.2.2.1 1. int main(int argc, const char *argv[]) is not. It is good to use const where applicable to indicate that the pointed-to objects will not change, but it must be used appropriately. The types char *[] and const char *[] are not compatible and are not interchangeable as parameter declarations or argument types. If main is declared with const char *argv[], the behavior is not defined by the C standard. As for why the prescribed declaration is char *argv[] rather than const char *argv[], that is partly historical and partly because some techniques for processing command-line arguments modify the arguments in place. A: The first one (char** argv) is defined by the C11 standard: It shall be defined with a return type of int and with no parameters: int main(void) { /* ... */ } or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared): int main(int argc, char *argv[]) { /* ... */ }` or equivalent¹⁰) or in some other implementation-defined manner. ¹⁰Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char ** argv, and so on. You could argue that const char is "equivalent" to char in the way the C11 standard is defining it. However, the standard also says this about the parameters: The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination. So it would seem const is not C standard. This answer details if it's OK to modify main parameters. The array char **argv is allocated at runtime, and modifying it doesn't affect any program execution. As to why const isn't used as a declaration, it mainly boils down to historical practices. This question's answers detail why const char **argv might be used instead of its non-const.
C main function const char*[] vs char*[]
I don't understand what the difference between int main(int argc, char* argv[]){;} and int main(int argc, const char* argv[]){;} is. I'm aware of the difference between a char*[] and const char*[] but I wonder why one would like to use the latter. Are there use cases where one would want to change command line arguments? What's the best practice about adding const?
[ "int main(int argc, char *argv[]) is a defined way of declaring main for a hosted environment according to the C standard, per C 2018 5.1.2.2.1 1. int main(int argc, const char *argv[]) is not.\nIt is good to use const where applicable to indicate that the pointed-to objects will not change, but it must be used appropriately. The types char *[] and const char *[] are not compatible and are not interchangeable as parameter declarations or argument types. If main is declared with const char *argv[], the behavior is not defined by the C standard.\nAs for why the prescribed declaration is char *argv[] rather than const char *argv[], that is partly historical and partly because some techniques for processing command-line arguments modify the arguments in place.\n", "The first one (char** argv) is defined by the C11 standard:\n\nIt shall be defined with a return type of int and with no parameters:\nint main(void) { /* ... */ }\n\nor with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):\nint main(int argc, char *argv[]) { /* ... */ }`\n\nor equivalent¹⁰) or in some other implementation-defined manner.\n¹⁰Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char ** argv, and so on.\n\nYou could argue that const char is \"equivalent\" to char in the way the C11 standard is defining it. However, the standard also says this about the parameters:\n\nThe parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.\n\nSo it would seem const is not C standard.\nThis answer details if it's OK to modify main parameters. The array char **argv is allocated at runtime, and modifying it doesn't affect any program execution.\nAs to why const isn't used as a declaration, it mainly boils down to historical practices. This question's answers detail why const char **argv might be used instead of its non-const.\n" ]
[ 6, 2 ]
[]
[]
[ "c", "command_line_arguments" ]
stackoverflow_0074667793_c_command_line_arguments.txt
Q: math.randomseed( os.time() ) is cycling. How do I fix this? I'm trying to make a magic 8-ball-esque program, but if I run it repeatedly, it repeats "yes" until os.time increases by 10, then "maybe" until os.time increases by 10, then "no" until os.time increases by 10, then "ask again" until os.time increases by 10. Instead of being pseudorandom, it cycles. Here's my code: math.randomseed( os.time() ) math.random(); math.random(); math.random(); math.random(); math.random(); answer = math.random(1,4) if answer == 1 then io.write("Yes.") end if answer == 2 then io.write("Maybe.") end if answer == 3 then io.write("No.") end if answer == 4 then io.write("Ask Again.") end io.write("\n", answer) io.write("\n", os.time()) I tried to make a variable that was os.time * 10, but that didn't work and even if it did, it would still be cycling every second. A: I suspect that the fragment of your code runs inside of a loop. You should call math.randomseed() only once at the beginning of your program. Never call it inside of a loop. Then all the subsequent calls to math.random() will be pseudorandom numbers with no cycles. Also, may I suggest the following: -- file mb.lua math.randomseed(os.time()) answers = { "No", "Yes", "Maybe", "Ask again" } io.write(answers[math.random(1, 4)] .. "\n") The above program works fine for me, no cycles. EDIT: a bit more googling shows me that the suitability of os.time as a good random seed might be system dependent. The following has been suggested to improve it: math.randomseed( tonumber(tostring(os.time()):reverse():sub(1,6)) )
math.randomseed( os.time() ) is cycling. How do I fix this?
I'm trying to make a magic 8-ball-esque program, but if I run it repeatedly, it repeats "yes" until os.time increases by 10, then "maybe" until os.time increases by 10, then "no" until os.time increases by 10, then "ask again" until os.time increases by 10. Instead of being pseudorandom, it cycles. Here's my code: math.randomseed( os.time() ) math.random(); math.random(); math.random(); math.random(); math.random(); answer = math.random(1,4) if answer == 1 then io.write("Yes.") end if answer == 2 then io.write("Maybe.") end if answer == 3 then io.write("No.") end if answer == 4 then io.write("Ask Again.") end io.write("\n", answer) io.write("\n", os.time()) I tried to make a variable that was os.time * 10, but that didn't work and even if it did, it would still be cycling every second.
[ "I suspect that the fragment of your code runs inside of a loop. You should call math.randomseed() only once at the beginning of your program. Never call it inside of a loop. Then all the subsequent calls to math.random() will be pseudorandom numbers with no cycles.\nAlso, may I suggest the following:\n-- file mb.lua\nmath.randomseed(os.time())\nanswers = { \"No\", \"Yes\", \"Maybe\", \"Ask again\" }\nio.write(answers[math.random(1, 4)] .. \"\\n\")\n\nThe above program works fine for me, no cycles.\nEDIT: a bit more googling shows me that the suitability of os.time as a good random seed might be system dependent. The following has been suggested to improve it:\nmath.randomseed( tonumber(tostring(os.time()):reverse():sub(1,6)) )\n\n" ]
[ 0 ]
[]
[]
[ "lua", "math", "random" ]
stackoverflow_0074662952_lua_math_random.txt
Q: Export Cyrillic characters from R? I have a dataset where one of the columns includes Russian words: raw_data2 = structure(list(word = c("абрикос", "автомобиль", "аист", "ананас", "апрель", "атака", "баклажан"), subject_nr = c(3L, 21L, 12L, 17L, 8L, 1L, 17L), acc = c(98.976109215, 91.8803418803, 94.8979591837, 94.5273631841, 94.4444444444, 94.5355191257, 94.3661971831)), row.names = c(1L, 100L, 200L, 300L, 400L, 500L, 600L), class = "data.frame") When I look at the file in RStudio there's no problem: However, when I export the data into a table to work with them further in Excel I get this UTF-mess which Excel cannot convert back into Russian words (even when UTF-8 is chosen during data importing): "word";"subject_nr";"acc" "<U+0430><U+0431><U+0440><U+0438><U+043A><U+043E><U+0441>";3;98,976109215 "<U+0430><U+0432><U+0442><U+043E><U+043C><U+043E><U+0431><U+0438><U+043B><U+044C>";21;91,8803418803 "<U+0430><U+0438><U+0441><U+0442>";12;94,8979591837 "<U+0430><U+043D><U+0430><U+043D><U+0430><U+0441>";17;94,5273631841 "<U+0430><U+043F><U+0440><U+0435><U+043B><U+044C>";8;94,4444444444 "<U+0430><U+0442><U+0430><U+043A><U+0430>";1;94,5355191257 "<U+0431><U+0430><U+043A><U+043B><U+0430><U+0436><U+0430><U+043D>";17;94,3661971831 Is there any way to force R to replace those strings with corresponding Cyrillic letters when saving the table? It certainly "knows" what these letters are, since it shows them in preview. I use the following code (which does not work): write.table(raw_data2, file = "raw_data2.csv", append = FALSE, quote = TRUE, sep = ";", eol = "\n", na = "NA", dec = ",", row.names = FALSE, col.names = TRUE, qmethod = c("escape", "double"), fileEncoding = "UTF-8") A: Works fine for me if you write it to xlsx file. openxlsx::write.xlsx(raw_data2, 'temp.xlsx') A: For me, Sys.setlocale("LC_CTYPE", "russian") works well (code source: https://www.r-bloggers.com/2013/01/r-and-foreign-characters/)
Export Cyrillic characters from R?
I have a dataset where one of the columns includes Russian words: raw_data2 = structure(list(word = c("абрикос", "автомобиль", "аист", "ананас", "апрель", "атака", "баклажан"), subject_nr = c(3L, 21L, 12L, 17L, 8L, 1L, 17L), acc = c(98.976109215, 91.8803418803, 94.8979591837, 94.5273631841, 94.4444444444, 94.5355191257, 94.3661971831)), row.names = c(1L, 100L, 200L, 300L, 400L, 500L, 600L), class = "data.frame") When I look at the file in RStudio there's no problem: However, when I export the data into a table to work with them further in Excel I get this UTF-mess which Excel cannot convert back into Russian words (even when UTF-8 is chosen during data importing): "word";"subject_nr";"acc" "<U+0430><U+0431><U+0440><U+0438><U+043A><U+043E><U+0441>";3;98,976109215 "<U+0430><U+0432><U+0442><U+043E><U+043C><U+043E><U+0431><U+0438><U+043B><U+044C>";21;91,8803418803 "<U+0430><U+0438><U+0441><U+0442>";12;94,8979591837 "<U+0430><U+043D><U+0430><U+043D><U+0430><U+0441>";17;94,5273631841 "<U+0430><U+043F><U+0440><U+0435><U+043B><U+044C>";8;94,4444444444 "<U+0430><U+0442><U+0430><U+043A><U+0430>";1;94,5355191257 "<U+0431><U+0430><U+043A><U+043B><U+0430><U+0436><U+0430><U+043D>";17;94,3661971831 Is there any way to force R to replace those strings with corresponding Cyrillic letters when saving the table? It certainly "knows" what these letters are, since it shows them in preview. I use the following code (which does not work): write.table(raw_data2, file = "raw_data2.csv", append = FALSE, quote = TRUE, sep = ";", eol = "\n", na = "NA", dec = ",", row.names = FALSE, col.names = TRUE, qmethod = c("escape", "double"), fileEncoding = "UTF-8")
[ "Works fine for me if you write it to xlsx file.\nopenxlsx::write.xlsx(raw_data2, 'temp.xlsx')\n\n", "For me, Sys.setlocale(\"LC_CTYPE\", \"russian\") works well\n(code source: https://www.r-bloggers.com/2013/01/r-and-foreign-characters/)\n" ]
[ 1, 0 ]
[]
[]
[ "encoding", "r", "utf_8" ]
stackoverflow_0065471819_encoding_r_utf_8.txt
Q: Displaying Authenticated User Using Laravel Sanctum Api I want to display the data of the authenticated user and also produce a status code and a status message when the user is not authenticated. I am using Laravel API and Sanctum and this is what I have tried: public function me(Request $request){ $user = $request->user(); if($user) { return response()->json([ 'status'=>200, 'user'=>$user ]); } else { return response()->json([ 'status'=>401, 'message'=>'No access' ]); } } Problem is, it displays the status 200 when authenticated and does not display the status 401 code when not. It only displays the default Sanctum { "message": "Unauthenticated." } There is also a bearer token involved in the authentication. Kindly help A: First, you need to check if the user is authenticated by using the $request->user() method. If it returns null, it means the user is not authenticated and you can return the appropriate response with a status code of 401 and the error message. To check if the user is authenticated, you can use the Auth::check() method in Laravel, like this: public function me(Request $request){ if(Auth::check()) { $user = $request->user(); return response()->json([ 'status'=>200, 'user'=>$user ]); } else { return response()->json([ 'status'=>401, 'message'=>'No access' ]); } } Alternatively, you can also use the $request->user() method and check if it returns a null value, like this: public function me(Request $request){ $user = $request->user(); if($user) { return response()->json([ 'status'=>200, 'user'=>$user ]); } else { return response()->json([ 'status'=>401, 'message'=>'No access' ]); } } In both cases, if the user is not authenticated, it will return a response with a status code of 401 and the error message "No access". A: If you confirmed that the token already involved in Authorization header, maybe you need to check some of this step: You need to verify that in your User model already add HasApiTokens from package Laravel\Sanctum\HasApiTokens. After that, you can check the router middleware. You can use middleware auth:sanctum for protected endpoint. If you were using middleware ability, maybe you can check it too. Go to config/cors.php, enable supports_credentials to true. If you tried it before using your Frontend apps, have you try it with postman ?
Displaying Authenticated User Using Laravel Sanctum Api
I want to display the data of the authenticated user and also produce a status code and a status message when the user is not authenticated. I am using Laravel API and Sanctum and this is what I have tried: public function me(Request $request){ $user = $request->user(); if($user) { return response()->json([ 'status'=>200, 'user'=>$user ]); } else { return response()->json([ 'status'=>401, 'message'=>'No access' ]); } } Problem is, it displays the status 200 when authenticated and does not display the status 401 code when not. It only displays the default Sanctum { "message": "Unauthenticated." } There is also a bearer token involved in the authentication. Kindly help
[ "First, you need to check if the user is authenticated by using the $request->user() method. If it returns null, it means the user is not authenticated and you can return the appropriate response with a status code of 401 and the error message.\nTo check if the user is authenticated, you can use the Auth::check() method in Laravel, like this:\npublic function me(Request $request){ \n \n if(Auth::check())\n {\n $user = $request->user();\n\n return response()->json([\n 'status'=>200,\n 'user'=>$user\n ]);\n\n } else {\n return response()->json([\n 'status'=>401,\n 'message'=>'No access'\n ]);\n }\n\n}\n\nAlternatively, you can also use the $request->user() method and check if it returns a null value, like this:\npublic function me(Request $request){ \n \n $user = $request->user();\n\n if($user)\n {\n return response()->json([\n 'status'=>200,\n 'user'=>$user\n ]);\n\n } else {\n return response()->json([\n 'status'=>401,\n 'message'=>'No access'\n ]);\n }\n\n}\n\nIn both cases, if the user is not authenticated, it will return a response with a status code of 401 and the error message \"No access\".\n", "If you confirmed that the token already involved in Authorization header, maybe you need to check some of this step:\nYou need to verify that in your User model already add HasApiTokens from package Laravel\\Sanctum\\HasApiTokens.\nAfter that, you can check the router middleware. You can use middleware auth:sanctum for protected endpoint. If you were using middleware ability, maybe you can check it too.\nGo to config/cors.php, enable supports_credentials to true.\nIf you tried it before using your Frontend apps, have you try it with postman ?\n" ]
[ 0, 0 ]
[]
[]
[ "bearer_token", "laravel", "laravel_sanctum", "php" ]
stackoverflow_0074667428_bearer_token_laravel_laravel_sanctum_php.txt
Q: Jquery help for single select country state fetch data here is a code for multiselect which is working fine for multiselect but i need this code to be work in single select , in this Code #Country list is simply getting list from option as you can see in code and when we select #country in dropdown the #state data is fetching from data base according to country selection ( Multi select is Working fine but i need this in Single select ) <script src="js/jquery.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script> <label for="country">Country</label> ( Simple Drop Down for Country ) <?php include "fetch_country.php"; ?> <select id="country" name="country[]" multiple class="form-control" > <option value="India" label="India">India</option> <option value="USA" label="USA">USA</option> <option value="UK" label="UK">UK</option> <option value="Canada" label="Canada">Canada</option> <option value="China" label="China">China</option> </select> <div class="col-sm-6"> <label for="state">State</label> ( Fetching State data from Database ) <select id="state" name="state[]" multiple class="form-control" > <option disabled>Select Country First</option> </select> <button class="myButnsbmt" type="submit" name="update" value="Update">Submit</button> </form> <script> $(document).ready(function(){ $('#country').multiselect({ nonSelectedText:'?', buttonWidth:'250px', maxHeight: 400, onChange:function(option, checked){ var selected = this.$select.val(); if(selected.length > 0) { $.ajax({ url:"fetch_country.php", method:"POST", data:{selected:selected}, success:function(data) { $('#state').html(data); $('#state').multiselect('rebuild'); } }) } } }); $('#state').multiselect({ nonSelectedText: '?', allSelectedText: 'All', buttonWidth:'250px', includeSelectAllOption: true, maxHeight: 400, enableFiltering:true }); }); </script> A: Html Part <div class="container mt-5"> <div class="row"> <div class="card"> <div class="card-header"> <h2 class="text-success">Country State City Dropdown List in PHP MySQL Ajax - Tutsmake.COM</h2> </div> <div class="card-body"> <form> <div class="form-group"> <label for="country">Country</label> <select class="form-control" id="country-dropdown"> <option value="">Select Country</option> <?php require_once "db.php"; $result = mysqli_query($conn, "SELECT * FROM countries"); while ($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row['id']; ?>"><?php echo $row["name"]; ?></option> <?php } ?> </select> </div> <div class="form-group"> <label for="state">State</label> <select class="form-control" id="state-dropdown"> </select> </div> <div class="form-group"> <label for="city">City</label> <select class="form-control" id="city-dropdown"> </select> </div> </form> </div> </div> </div> </div> js part $(document).ready(function () { $('#country-dropdown').on('change', function () { var country_id = this.value; $.ajax({ url: "states-by-country.php", type: "POST", data: { country_id: country_id }, cache: false, success: function (result) { $("#state-dropdown").html(result); $('#city-dropdown').html('<option value="">Select State First</option>'); } }); }); $('#state-dropdown').on('change', function () { var state_id = this.value; $.ajax({ url: "cities-by-state.php", type: "POST", data: { state_id: state_id }, cache: false, success: function (result) { $("#city-dropdown").html(result); } }); }); }); states-by-country.php <?php require_once "db.php"; $country_id = $_POST["country_id"]; $result = mysqli_query($conn, "SELECT * FROM states where country_id = $country_id"); ?> <option value="">Select State</option> <?php while ($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option> <?php } ?> cities-by-state.php <?php require_once "db.php"; $state_id = $_POST["state_id"]; $result = mysqli_query($conn, "SELECT * FROM cities where state_id = $state_id"); ?> <option value="">Select City</option> <?php while ($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option> <?php } ?> A: Then try this <label for="country">Country</label> <select id="country" name="country" multiple class="form-control"> <option value="India" label="India">India</option> <option value="USA" label="USA">USA</option> <option value="UK" label="UK">UK</option> <option value="Canada" label="Canada">Canada</option> <option value="China" label="China">China</option> </select> <label for="state">State</label> ( Fetching State data from Database ) <select id="state" name="state[]" multiple class="form-control"> <option disabled>Select Country First</option> </select> <button class="myButnsbmt" type="submit" name="update" value="Update">Submit</button> <script> $(document).ready(function() { $('#country').on('change', function() { var countryname = this.value; $.ajax({ url: "states-by-country.php", type: "POST", data: { country: countryname }, cache: false, success: function(result) { $("#state-dropdown").html(result); $('#city-dropdown').html('<option value="">Select State First</option>'); } }); }); }); </script> states-by-country.php <?php require_once "db.php"; $country = $_POST["country"]; $result = mysqli_query($conn, "SELECT * FROM states where countryname = $country"); ?> <option value="">Select State</option> <?php while ($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option> <?php } ?>
Jquery help for single select country state fetch data
here is a code for multiselect which is working fine for multiselect but i need this code to be work in single select , in this Code #Country list is simply getting list from option as you can see in code and when we select #country in dropdown the #state data is fetching from data base according to country selection ( Multi select is Working fine but i need this in Single select ) <script src="js/jquery.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script> <label for="country">Country</label> ( Simple Drop Down for Country ) <?php include "fetch_country.php"; ?> <select id="country" name="country[]" multiple class="form-control" > <option value="India" label="India">India</option> <option value="USA" label="USA">USA</option> <option value="UK" label="UK">UK</option> <option value="Canada" label="Canada">Canada</option> <option value="China" label="China">China</option> </select> <div class="col-sm-6"> <label for="state">State</label> ( Fetching State data from Database ) <select id="state" name="state[]" multiple class="form-control" > <option disabled>Select Country First</option> </select> <button class="myButnsbmt" type="submit" name="update" value="Update">Submit</button> </form> <script> $(document).ready(function(){ $('#country').multiselect({ nonSelectedText:'?', buttonWidth:'250px', maxHeight: 400, onChange:function(option, checked){ var selected = this.$select.val(); if(selected.length > 0) { $.ajax({ url:"fetch_country.php", method:"POST", data:{selected:selected}, success:function(data) { $('#state').html(data); $('#state').multiselect('rebuild'); } }) } } }); $('#state').multiselect({ nonSelectedText: '?', allSelectedText: 'All', buttonWidth:'250px', includeSelectAllOption: true, maxHeight: 400, enableFiltering:true }); }); </script>
[ "Html Part\n<div class=\"container mt-5\">\n <div class=\"row\">\n <div class=\"card\">\n <div class=\"card-header\">\n <h2 class=\"text-success\">Country State City Dropdown List in PHP MySQL Ajax - Tutsmake.COM</h2>\n </div>\n <div class=\"card-body\">\n <form>\n <div class=\"form-group\">\n <label for=\"country\">Country</label>\n <select class=\"form-control\" id=\"country-dropdown\">\n <option value=\"\">Select Country</option>\n <?php\n require_once \"db.php\";\n $result = mysqli_query($conn, \"SELECT * FROM countries\");\n while ($row = mysqli_fetch_array($result)) {\n ?>\n <option value=\"<?php echo $row['id']; ?>\"><?php echo $row[\"name\"]; ?></option>\n <?php\n }\n ?>\n </select>\n </div>\n <div class=\"form-group\">\n <label for=\"state\">State</label>\n <select class=\"form-control\" id=\"state-dropdown\">\n </select>\n </div>\n <div class=\"form-group\">\n <label for=\"city\">City</label>\n <select class=\"form-control\" id=\"city-dropdown\">\n </select>\n </div>\n </form>\n </div>\n </div>\n </div>\n</div>\n\njs part\n$(document).ready(function () {\n $('#country-dropdown').on('change', function () {\n var country_id = this.value;\n $.ajax({\n url: \"states-by-country.php\",\n type: \"POST\",\n data: {\n country_id: country_id\n },\n cache: false,\n success: function (result) {\n $(\"#state-dropdown\").html(result);\n $('#city-dropdown').html('<option value=\"\">Select State First</option>');\n }\n });\n });\n $('#state-dropdown').on('change', function () {\n var state_id = this.value;\n $.ajax({\n url: \"cities-by-state.php\",\n type: \"POST\",\n data: {\n state_id: state_id\n },\n cache: false,\n success: function (result) {\n $(\"#city-dropdown\").html(result);\n }\n });\n });\n});\n\nstates-by-country.php\n<?php\nrequire_once \"db.php\";\n$country_id = $_POST[\"country_id\"];\n$result = mysqli_query($conn, \"SELECT * FROM states where country_id = $country_id\");\n?>\n<option value=\"\">Select State</option>\n<?php\nwhile ($row = mysqli_fetch_array($result)) {\n?>\n <option value=\"<?php echo $row[\"id\"]; ?>\"><?php echo $row[\"name\"]; ?></option>\n<?php\n}\n?>\n\ncities-by-state.php\n<?php\nrequire_once \"db.php\";\n$state_id = $_POST[\"state_id\"];\n$result = mysqli_query($conn, \"SELECT * FROM cities where state_id = $state_id\");\n?>\n<option value=\"\">Select City</option>\n<?php\nwhile ($row = mysqli_fetch_array($result)) {\n?>\n <option value=\"<?php echo $row[\"id\"]; ?>\"><?php echo $row[\"name\"]; ?></option>\n<?php\n}\n?>\n\n", "Then try this\n<label for=\"country\">Country</label> \n<select id=\"country\" name=\"country\" multiple class=\"form-control\">\n <option value=\"India\" label=\"India\">India</option>\n <option value=\"USA\" label=\"USA\">USA</option>\n <option value=\"UK\" label=\"UK\">UK</option>\n <option value=\"Canada\" label=\"Canada\">Canada</option>\n <option value=\"China\" label=\"China\">China</option>\n</select>\n\n\n<label for=\"state\">State</label> ( Fetching State data from Database )\n<select id=\"state\" name=\"state[]\" multiple class=\"form-control\">\n <option disabled>Select Country First</option>\n</select>\n\n<button class=\"myButnsbmt\" type=\"submit\" name=\"update\" value=\"Update\">Submit</button>\n\n<script>\n $(document).ready(function() {\n $('#country').on('change', function() {\n var countryname = this.value;\n $.ajax({\n url: \"states-by-country.php\",\n type: \"POST\",\n data: {\n country: countryname\n },\n cache: false,\n success: function(result) {\n $(\"#state-dropdown\").html(result);\n $('#city-dropdown').html('<option value=\"\">Select State First</option>');\n }\n });\n });\n });\n</script>\n\nstates-by-country.php\n<?php\nrequire_once \"db.php\";\n$country = $_POST[\"country\"];\n$result = mysqli_query($conn, \"SELECT * FROM states where countryname = $country\");\n?>\n<option value=\"\">Select State</option>\n<?php\nwhile ($row = mysqli_fetch_array($result)) {\n?>\n <option value=\"<?php echo $row[\"id\"]; ?>\"><?php echo $row[\"name\"]; ?></option>\n<?php\n}\n?>\n\n" ]
[ 0, 0 ]
[]
[]
[ "ajax", "arrays", "datatables", "javascript", "jquery" ]
stackoverflow_0074667022_ajax_arrays_datatables_javascript_jquery.txt
Q: Find an element in a list/array (a big list) I'm actually doing an easy CodinGame --> I have to find if an element exists in a list. I've tested a first solution, it was working but it wasn't really optimized (according to the machine). So I've tried another solution but : When I test my code for this 2nd solution, it returns the right answers but when I'm submitting my code, it tells me that my solution is completely wrong (it doesn't work if the list is empty, and also if the list is huge, ...). Please can you help me ? Here is my first naive solution : public static boolean check(int[] ints, int k) { boolean res = false; for(int i : ints){ if(i == k){ res = true; break; } } return res; } Here is the code of my 2nd solution that is supposed to be optimized: static boolean exists(int [] ints, int k){ boolean res = false; int first = 0; int last = ints.length; int mid = (first + last)/2; while(first <= last){ if( ints[mid] < k){ first = mid +1; }else if (ints[mid] == k){ res = true; break; }else{ last = mid -1; } mid = (first + last)/2; } if(first > last){ res = false; } return res; } A: I suppose you are trying to implement Binary search in the second solution. If so, please check this answer. Your input array must be sorted in non-decreasing order, because Binary Search works only with sorted input data. For example, you can simply type Arrays.sort(arr); and then pass your array into exists() method. But the overall time&space complexities will be O(n log n). Fixed some bugs in your implementation: public static boolean exists(int[] ints, int k) { int first = 0; int last = ints.length - 1; while (first <= last) { int mid = first + (last - first) / 2; // to avoid integer overflow in extremely large arrays if (ints[mid] < k) { first = mid + 1; } else if (ints[mid] == k) { return true; } else { last = mid - 1; } } return false; }
Find an element in a list/array (a big list)
I'm actually doing an easy CodinGame --> I have to find if an element exists in a list. I've tested a first solution, it was working but it wasn't really optimized (according to the machine). So I've tried another solution but : When I test my code for this 2nd solution, it returns the right answers but when I'm submitting my code, it tells me that my solution is completely wrong (it doesn't work if the list is empty, and also if the list is huge, ...). Please can you help me ? Here is my first naive solution : public static boolean check(int[] ints, int k) { boolean res = false; for(int i : ints){ if(i == k){ res = true; break; } } return res; } Here is the code of my 2nd solution that is supposed to be optimized: static boolean exists(int [] ints, int k){ boolean res = false; int first = 0; int last = ints.length; int mid = (first + last)/2; while(first <= last){ if( ints[mid] < k){ first = mid +1; }else if (ints[mid] == k){ res = true; break; }else{ last = mid -1; } mid = (first + last)/2; } if(first > last){ res = false; } return res; }
[ "I suppose you are trying to implement Binary search in the second solution.\nIf so, please check this answer. Your input array must be sorted in non-decreasing order, because Binary Search works only with sorted input data. For example, you can simply type Arrays.sort(arr); and then pass your array into exists() method. But the overall time&space complexities will be O(n log n).\nFixed some bugs in your implementation:\npublic static boolean exists(int[] ints, int k) {\n int first = 0;\n int last = ints.length - 1;\n while (first <= last) {\n int mid = first + (last - first) / 2; // to avoid integer overflow in extremely large arrays\n if (ints[mid] < k) {\n first = mid + 1;\n } else if (ints[mid] == k) {\n return true;\n } else {\n last = mid - 1;\n }\n }\n return false;\n}\n\n" ]
[ 0 ]
[]
[]
[ "algorithm", "binary_search", "element", "find", "java" ]
stackoverflow_0074667974_algorithm_binary_search_element_find_java.txt
Q: dart analyzer error: argument_type_not_assignable TrackPoint tp Type: TrackPoint The argument type 'TrackPoint (where TrackPoint is defined in ...lib\trackpoint.dart)' can't be assigned to the parameter type 'TrackPoint (where TrackPoint is defined in ...lib\trackPoint.dart)'.dart (argument_type_not_assignable) trackpoint.dart(8, 7): TrackPoint is defined in ...lib\trackpoint.dart trackPoint.dart(8, 7): TrackPoint is defined in ...lib\trackPoint.dart Here is where the error is: import 'trackpoint.dart' show TrackPoint; class TrackingStatus { // ... static void _triggerEvent(TrackPoint tp) { // ... TrackingStatusChangedEvent.trigger(tp); // <-- error on tp, see above } Here is what causes the error: class TrackingStatusChangedEvent { static void trigger(TrackPoint tp) { // <-- causes error // ... } static void trigger(tp) { // <-- works but tp should not be dynamic // ... } Here is where TrackPoint comes from: class TrackPoint { static final List<TrackPoint> _trackPoints = []; void _addTrackPoint() { _trackPoints.add(this); argument_type_not_assignable is not reasonable for me. Especially because the error message points to the same class in the same file as if they are something different A: I recommend just using prefixes for library import. See below. import 'trackpoint.dart' as tp; Then use it like this. class TrackPoint { static final List<tp.TrackPoint> _trackPoints = []; void _addTrackPoint() { _trackPoints.add(this); A: Putting class TrackPoint and class TrackingStatus the same file solved the problem. May be it was a cross loading issue. Thanks for your help anyway!
dart analyzer error: argument_type_not_assignable
TrackPoint tp Type: TrackPoint The argument type 'TrackPoint (where TrackPoint is defined in ...lib\trackpoint.dart)' can't be assigned to the parameter type 'TrackPoint (where TrackPoint is defined in ...lib\trackPoint.dart)'.dart (argument_type_not_assignable) trackpoint.dart(8, 7): TrackPoint is defined in ...lib\trackpoint.dart trackPoint.dart(8, 7): TrackPoint is defined in ...lib\trackPoint.dart Here is where the error is: import 'trackpoint.dart' show TrackPoint; class TrackingStatus { // ... static void _triggerEvent(TrackPoint tp) { // ... TrackingStatusChangedEvent.trigger(tp); // <-- error on tp, see above } Here is what causes the error: class TrackingStatusChangedEvent { static void trigger(TrackPoint tp) { // <-- causes error // ... } static void trigger(tp) { // <-- works but tp should not be dynamic // ... } Here is where TrackPoint comes from: class TrackPoint { static final List<TrackPoint> _trackPoints = []; void _addTrackPoint() { _trackPoints.add(this); argument_type_not_assignable is not reasonable for me. Especially because the error message points to the same class in the same file as if they are something different
[ "I recommend just using prefixes for library import. See below.\nimport 'trackpoint.dart' as tp;\n\nThen use it like this.\nclass TrackPoint {\n static final List<tp.TrackPoint> _trackPoints = [];\n\n\n\nvoid _addTrackPoint() {\n _trackPoints.add(this);\n\n", "Putting class TrackPoint and class TrackingStatus the same file solved the problem. May be it was a cross loading issue.\nThanks for your help anyway!\n" ]
[ 0, 0 ]
[]
[]
[ "analyzer", "dart" ]
stackoverflow_0074667407_analyzer_dart.txt
Q: Is there an equivalent of lsusb for OS X This question seems to be all over google, but the answers all point to using System Profiler. That's nice, but with System Profiler all you get is something that looks like this: DasKeyboard: Product ID: 0x1919 Vendor ID: 0x04d9 (Holtek Semiconductor, Inc.) Version: 1.06 Speed: Up to 1.5 Mb/sec Location ID: 0x1d114000 / 11 Current Available (mA): 500 Current Required (mA): 100 USB2.0 Hub: Product ID: 0x0608 Vendor ID: 0x05e3 (Genesys Logic, Inc.) Version: 32.98 Speed: Up to 480 Mb/sec Location ID: 0x1d113000 / 10 Current Available (mA): 500 Current Required (mA): 100 Microsoft Basic Optical Mouse v2.0 : Product ID: 0x00cb Vendor ID: 0x045e (Microsoft Corporation) Version: 1.99 Speed: Up to 1.5 Mb/sec Manufacturer: Microsoft Location ID: 0x1d113200 / 12 Current Available (mA): 500 Current Required (mA): 100 That's great if all you want are the contents of a bunch of device descriptors, but lsusb gives you so much more - information on interfaces and endpoints, interface associations, composite devices... where can you find this information in OS X? There must be a tool that does this? A: I got tired of forgetting the system_profiler SPUSBDataType syntax, so I made an lsusb alternative. You can find it here , or install it with homebrew: brew install lsusb A: I typically run this command to list USB devices on macOS, along with details about them: ioreg -p IOUSB -l -w 0 A: Homebrew users: you can get lsusb by installing usbutils formula from my tap: brew install mikhailai/misc/usbutils It installs the REAL lsusb based on Linux sources (version 007). A: In mac osx , you can use the following command: system_profiler SPUSBDataType A: If you are a user of MacPorts, you may simply install usbutils sudo port install usbutils If you are not, this might be a good opportunity to install it, it has ports for several other useful linux tools. A: How about ioreg? The output's much more detailed than the profiler, but it's a bit dense. Source: https://lists.macosforge.org/pipermail/macports-users/2008-July/011115.html A: system_profiler SPUSBDataType it your need command on macos A: At least on 10.10.5, system_profiler SPUSBDataType output is NOT dynamically updated when a new USB device gets plugged in, while ioreg -p IOUSB -l -w 0 does. A: On Mac OS X, the Xcode developer suite includes the USB Proper.app application. This is found in /Developer/Applications/Utilities/. USB Prober will allow you to examine the device and interface descriptors. A: I'll through my hat into this having tried the answers here. The lsusb script is barely working and the macOS port of usbutils doesn't capture string descriptors or support --tree. It lead me to create cyme, a modern cross-platform USB list tool using libusb under the hood and udev on Linux. It supports --lsusb compatible mode, which near matches lsusb's output for all args. It should scratch the macOS lsusb itch and more.
Is there an equivalent of lsusb for OS X
This question seems to be all over google, but the answers all point to using System Profiler. That's nice, but with System Profiler all you get is something that looks like this: DasKeyboard: Product ID: 0x1919 Vendor ID: 0x04d9 (Holtek Semiconductor, Inc.) Version: 1.06 Speed: Up to 1.5 Mb/sec Location ID: 0x1d114000 / 11 Current Available (mA): 500 Current Required (mA): 100 USB2.0 Hub: Product ID: 0x0608 Vendor ID: 0x05e3 (Genesys Logic, Inc.) Version: 32.98 Speed: Up to 480 Mb/sec Location ID: 0x1d113000 / 10 Current Available (mA): 500 Current Required (mA): 100 Microsoft Basic Optical Mouse v2.0 : Product ID: 0x00cb Vendor ID: 0x045e (Microsoft Corporation) Version: 1.99 Speed: Up to 1.5 Mb/sec Manufacturer: Microsoft Location ID: 0x1d113200 / 12 Current Available (mA): 500 Current Required (mA): 100 That's great if all you want are the contents of a bunch of device descriptors, but lsusb gives you so much more - information on interfaces and endpoints, interface associations, composite devices... where can you find this information in OS X? There must be a tool that does this?
[ "I got tired of forgetting the system_profiler SPUSBDataType syntax, so I made an lsusb alternative. You can find it here , or install it with homebrew:\nbrew install lsusb\n\n", "I typically run this command to list USB devices on macOS, along with details about them:\nioreg -p IOUSB -l -w 0\n\n", "Homebrew users: you can get lsusb by installing usbutils formula from my tap:\nbrew install mikhailai/misc/usbutils\n\nIt installs the REAL lsusb based on Linux sources (version 007). \n", "In mac osx , you can use the following command: \nsystem_profiler SPUSBDataType\n\n", "If you are a user of MacPorts, you may simply install usbutils\nsudo port install usbutils\n\nIf you are not, this might be a good opportunity to install it, it has ports for several other useful linux tools.\n", "How about ioreg? The output's much more detailed than the profiler, but it's a bit dense.\nSource: https://lists.macosforge.org/pipermail/macports-users/2008-July/011115.html\n", "system_profiler SPUSBDataType\n\nit your need command on macos\n", "At least on 10.10.5, system_profiler SPUSBDataType output is NOT\ndynamically updated when a new USB device gets plugged in,\nwhile ioreg -p IOUSB -l -w 0 does.\n", "On Mac OS X, the Xcode developer suite includes the USB Proper.app application. This is found in /Developer/Applications/Utilities/. USB Prober will allow you to examine the device and interface descriptors.\n", "I'll through my hat into this having tried the answers here. The lsusb script is barely working and the macOS port of usbutils doesn't capture string descriptors or support --tree.\nIt lead me to create cyme, a modern cross-platform USB list tool using libusb under the hood and udev on Linux. It supports --lsusb compatible mode, which near matches lsusb's output for all args. It should scratch the macOS lsusb itch and more.\n" ]
[ 178, 105, 40, 15, 6, 4, 4, 1, 0, 0 ]
[]
[]
[ "darwin", "lsusb", "macos", "usb" ]
stackoverflow_0017058134_darwin_lsusb_macos_usb.txt
Q: Adding a Dropdown menu to the NavBar in an ASP.Net Core Web App (bootstrap) In Visual Studio, I create a new ASP.Net Core Web App then I add a dropdown menu (as per Bootstrap documentation) https://getbootstrap.com/docs/5.1/components/navbar/ the header porton of the html code looks like this: <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container"> <a class="navbar-brand" asp-area="" asp-page="/Index">WebApplication1</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> </ul> </div> </div> </nav> </header> but the dropdown doesn't work. When I click it, no dropdown appears: https://i.stack.imgur.com/szrE4.png A: Be sure your Bootstrap version is v5.1, you can add the following css and js file to your project _Layout.cshtml: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.1/css/bootstrap.min.css" integrity="sha512-6KY5s6UI5J7SVYuZB4S/CZMyPylqyyNZco376NM2Z8Sb8OxEdp02e1jkKk/wZxIEmjQ6DRCEBhni+gpr9c4tvA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.1/js/bootstrap.min.js" integrity="sha512-ewfXo9Gq53e1q1+WDTjaHAGZ8UvCWq0eXONhwDuIoaH8xz2r96uoAYaQCm1oQhnBfRXrvJztNXFsTloJfgbL5Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> For Bootstrap v4.x, you need change your code to: <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> A: In Bootstrap 5.1, for dropdown, ✅ data-bs-toggle="dropdown" ❌data-toggle="dropdown" In Bootstrap 4.0, for dropdown, ✅ data-toggle="dropdown" ❌data-bs-toggle="dropdown"
Adding a Dropdown menu to the NavBar in an ASP.Net Core Web App (bootstrap)
In Visual Studio, I create a new ASP.Net Core Web App then I add a dropdown menu (as per Bootstrap documentation) https://getbootstrap.com/docs/5.1/components/navbar/ the header porton of the html code looks like this: <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container"> <a class="navbar-brand" asp-area="" asp-page="/Index">WebApplication1</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> </ul> </div> </div> </nav> </header> but the dropdown doesn't work. When I click it, no dropdown appears: https://i.stack.imgur.com/szrE4.png
[ "Be sure your Bootstrap version is v5.1, you can add the following css and js file to your project _Layout.cshtml:\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.1/css/bootstrap.min.css\" integrity=\"sha512-6KY5s6UI5J7SVYuZB4S/CZMyPylqyyNZco376NM2Z8Sb8OxEdp02e1jkKk/wZxIEmjQ6DRCEBhni+gpr9c4tvA==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" />\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.1/js/bootstrap.min.js\" integrity=\"sha512-ewfXo9Gq53e1q1+WDTjaHAGZ8UvCWq0eXONhwDuIoaH8xz2r96uoAYaQCm1oQhnBfRXrvJztNXFsTloJfgbL5Q==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\n\nFor Bootstrap v4.x, you need change your code to:\n<li class=\"nav-item dropdown\">\n <a class=\"nav-link dropdown-toggle\" href=\"#\" id=\"navbarDropdown\" role=\"button\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\n Dropdown\n </a>\n <div class=\"dropdown-menu\" aria-labelledby=\"navbarDropdown\">\n <a class=\"dropdown-item\" href=\"#\">Action</a>\n <a class=\"dropdown-item\" href=\"#\">Another action</a>\n <div class=\"dropdown-divider\"></div>\n <a class=\"dropdown-item\" href=\"#\">Something else here</a>\n </div>\n</li>\n\n", "In Bootstrap 5.1, for dropdown,\n✅ data-bs-toggle=\"dropdown\"\n❌data-toggle=\"dropdown\"\nIn Bootstrap 4.0, for dropdown,\n✅ data-toggle=\"dropdown\"\n❌data-bs-toggle=\"dropdown\"\n" ]
[ 2, 1 ]
[]
[]
[ "asp.net_core", "c#", "html", "razor_pages", "visual_studio_2019" ]
stackoverflow_0069399398_asp.net_core_c#_html_razor_pages_visual_studio_2019.txt
Q: flutter null check operator was used on a null value, causes widget failure D/EGL_emulation( 9253): app_time_stats: avg=1019.37ms min=4.61ms max=25327.36ms count=25 The following RangeError was thrown building StreamBuilder<List<showSummaryReport>>(dirty, state: _StreamBuilderBaseState<List<showSummaryReport>, AsyncSnapshot<List<showSummaryReport>>>#a2976): RangeError (index): Invalid value: Valid value range is empty: 1 The relevant error-causing widget was: StreamBuilder<List<showSummaryReport>> StreamBuilder:file:///C:/Users/limji/StudioProjects/fyp/lib/report/SummaryReport/selectedSummary.dart:225:38 When the exception was thrown, this was the stack: #0 List.[] (dart:core-patch/growable_array.dart:264:36) #1 _selectedSummaryState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:fyp/report/SummaryReport/selectedSummary.dart The code below is my entire code, i don't know which value is null, can i have some help on fixing this ? Visibility( visible: gotChoice, child: StreamBuilder<List<showSummaryReport>>( stream: read('${widget.expChoice.toString()} Sales'), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator(), ); } if (snapshot.hasError) { return Center( child: Text("some error occured"), ); } if (snapshot.hasData) { final userData = snapshot.data; return Expanded( child: ListView.builder( itemCount: userData!.length, itemBuilder: (context, index) { final service = userData[index]; return StreamBuilder<List<showSummaryReport>>( stream: read('${test} Sales'), builder: (context, snapshot) { final searchedData = snapshot.data ?? []; final searched = searchedData[index]; return Column( children: [ ListTile( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context)=> selectedDetailReport(detail: '${service.serviceName} Sales', month: widget.expChoice.toString(),))); }, title: Card( color: 'CAF0F8'.toColor(), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), child: Table( // border: TableBorder(bottom: BorderSide(color: '03045E'.toColor(), width: 1)), children: [ TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), TableRow( children: [ Padding( padding: const EdgeInsets.fromLTRB(30,0,0,0), child: Text('Service Name :',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17)), ), Center(child: Text(service.serviceName.toString(),style: TextStyle(fontFamily: 'MonSemi', fontSize: 17))), ] ), TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), TableRow( children: [ Padding( padding: const EdgeInsets.fromLTRB(30,0,0,0), child: Text('Current Month Sales :',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17)), ), Center(child: Text(service.sales.toString(),style: TextStyle(fontFamily: 'MonSemi', fontSize: 17))), ] ), TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), TableRow( children: [ Padding( padding: const EdgeInsets.fromLTRB(30,0,0,0), child: Text('${test} Sales :',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17)), ), Center(child: Text('${searched.sales}',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17))), ] ), TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), TableRow( children: [ Padding( padding: const EdgeInsets.fromLTRB(30,0,0,0), child: Text('${test} Sales :',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17)), ), Center(child: Text('${searched.sales}',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17))), ] ), TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), ], ), ), ), ], ); } ); }), ); } return Center( child: CircularProgressIndicator(), ); }), ), A: Your snapshot may be null and you use ! on it(searchedData!),so change this: final searchedData = snapshot.data; to this: final searchedData = snapshot.data ?? []; for your next issue(RangeError) you are using listview's index on other list, your listview's index is for userData but you are using that on searchedData, these are not the same list. Also you forgot to set if else condition for second StreamBuilder. do exact same thing that you do for first one.
flutter null check operator was used on a null value, causes widget failure
D/EGL_emulation( 9253): app_time_stats: avg=1019.37ms min=4.61ms max=25327.36ms count=25 The following RangeError was thrown building StreamBuilder<List<showSummaryReport>>(dirty, state: _StreamBuilderBaseState<List<showSummaryReport>, AsyncSnapshot<List<showSummaryReport>>>#a2976): RangeError (index): Invalid value: Valid value range is empty: 1 The relevant error-causing widget was: StreamBuilder<List<showSummaryReport>> StreamBuilder:file:///C:/Users/limji/StudioProjects/fyp/lib/report/SummaryReport/selectedSummary.dart:225:38 When the exception was thrown, this was the stack: #0 List.[] (dart:core-patch/growable_array.dart:264:36) #1 _selectedSummaryState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:fyp/report/SummaryReport/selectedSummary.dart The code below is my entire code, i don't know which value is null, can i have some help on fixing this ? Visibility( visible: gotChoice, child: StreamBuilder<List<showSummaryReport>>( stream: read('${widget.expChoice.toString()} Sales'), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator(), ); } if (snapshot.hasError) { return Center( child: Text("some error occured"), ); } if (snapshot.hasData) { final userData = snapshot.data; return Expanded( child: ListView.builder( itemCount: userData!.length, itemBuilder: (context, index) { final service = userData[index]; return StreamBuilder<List<showSummaryReport>>( stream: read('${test} Sales'), builder: (context, snapshot) { final searchedData = snapshot.data ?? []; final searched = searchedData[index]; return Column( children: [ ListTile( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context)=> selectedDetailReport(detail: '${service.serviceName} Sales', month: widget.expChoice.toString(),))); }, title: Card( color: 'CAF0F8'.toColor(), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), child: Table( // border: TableBorder(bottom: BorderSide(color: '03045E'.toColor(), width: 1)), children: [ TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), TableRow( children: [ Padding( padding: const EdgeInsets.fromLTRB(30,0,0,0), child: Text('Service Name :',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17)), ), Center(child: Text(service.serviceName.toString(),style: TextStyle(fontFamily: 'MonSemi', fontSize: 17))), ] ), TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), TableRow( children: [ Padding( padding: const EdgeInsets.fromLTRB(30,0,0,0), child: Text('Current Month Sales :',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17)), ), Center(child: Text(service.sales.toString(),style: TextStyle(fontFamily: 'MonSemi', fontSize: 17))), ] ), TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), TableRow( children: [ Padding( padding: const EdgeInsets.fromLTRB(30,0,0,0), child: Text('${test} Sales :',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17)), ), Center(child: Text('${searched.sales}',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17))), ] ), TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), TableRow( children: [ Padding( padding: const EdgeInsets.fromLTRB(30,0,0,0), child: Text('${test} Sales :',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17)), ), Center(child: Text('${searched.sales}',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17))), ] ), TableRow(children: [SizedBox(height: 10,), SizedBox(height: 10,)]), ], ), ), ), ], ); } ); }), ); } return Center( child: CircularProgressIndicator(), ); }), ),
[ "Your snapshot may be null and you use ! on it(searchedData!),so change this:\nfinal searchedData = snapshot.data;\n\nto this:\nfinal searchedData = snapshot.data ?? [];\n\nfor your next issue(RangeError) you are using listview's index on other list, your listview's index is for userData but you are using that on searchedData, these are not the same list.\nAlso you forgot to set if else condition for second StreamBuilder. do exact same thing that you do for first one.\n" ]
[ 0 ]
[]
[]
[ "dart", "exception", "flutter", "null", "widget" ]
stackoverflow_0074667991_dart_exception_flutter_null_widget.txt