content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: Search in Json column with Laravel In my emails table, I have a column named To with column-type Json. This is how values are stored: [ { "emailAddress": { "name": "Test", "address": "[email protected]" } }, { "emailAddress": { "name": "Test 2", "address": "[email protected]" } } ] Now I want a collection of all emails sent to "[email protected]". I tried: DB::table('emails')->whereJsonContains('to->emailAddress->address', '[email protected]')->get(); (see https://laravel.com/docs/5.7/queries#json-where-clauses) but I do not get a match. Is there a better way to search using Laravel (Eloquent)? In the debugbar, I can see that this query is "translated" as: select * from `emails` where json_contains(`to`->'$."emailAddress"."address"', '\"[email protected]\"')) A: The arrow operator doesn't work in arrays. Use this instead: DB::table('emails') ->whereJsonContains('to', [['emailAddress' => ['address' => '[email protected]']]]) ->get() A: I haven't used the json column but as the documentation refers, the below code should work fine. DB::table('emails') ->where('to->emailAddresss->address','[email protected]') ->get(); A: In case to store array in json format. And just have an array list of IDs, I did this. items is the column name and $item_id is the term I search for // $item_id = 2 // items = '["2","7","14","1"]' $menus = Menu::whereJsonContains('items', $item_id)->get(); A: Checkout the Laravel API docs for the whereJsonContains method https://laravel.com/api/8.x/Illuminate/Database/Query/Builder.html#method_whereJsonContains A: Using Eloquent => Email::where('to->emailAddress->address','[email protected]')->get();
Search in Json column with Laravel
In my emails table, I have a column named To with column-type Json. This is how values are stored: [ { "emailAddress": { "name": "Test", "address": "[email protected]" } }, { "emailAddress": { "name": "Test 2", "address": "[email protected]" } } ] Now I want a collection of all emails sent to "[email protected]". I tried: DB::table('emails')->whereJsonContains('to->emailAddress->address', '[email protected]')->get(); (see https://laravel.com/docs/5.7/queries#json-where-clauses) but I do not get a match. Is there a better way to search using Laravel (Eloquent)? In the debugbar, I can see that this query is "translated" as: select * from `emails` where json_contains(`to`->'$."emailAddress"."address"', '\"[email protected]\"'))
[ "The arrow operator doesn't work in arrays. Use this instead:\nDB::table('emails')\n ->whereJsonContains('to', [['emailAddress' => ['address' => '[email protected]']]])\n ->get()\n\n", "I haven't used the json column but as the documentation refers, the below code should work fine. \nDB::table('emails')\n ->where('to->emailAddresss->address','[email protected]')\n ->get();\n\n", "In case to store array in json format. And just have an array list of IDs, I did this.\n\nitems is the column name and $item_id is the term I search for\n\n// $item_id = 2\n// items = '[\"2\",\"7\",\"14\",\"1\"]'\n$menus = Menu::whereJsonContains('items', $item_id)->get();\n\n", "Checkout the Laravel API docs for the whereJsonContains method\nhttps://laravel.com/api/8.x/Illuminate/Database/Query/Builder.html#method_whereJsonContains\n", "Using Eloquent => Email::where('to->emailAddress->address','[email protected]')->get();\n" ]
[ 39, 14, 5, 1, 0 ]
[ "You can use where clause with like condition\nDB::table('emails')->where('To','like','%[email protected]%')->get();\n\nAlternatively, if you have Model mapped to emails table names as Email using Eloquent\nEmail::where('To','like','%[email protected]%')->get(); \n\n" ]
[ -2 ]
[ "json", "laravel", "laravel_5", "mysql", "php" ]
stackoverflow_0053641403_json_laravel_laravel_5_mysql_php.txt
Q: Cannot set non-nullable LiveData value to null The error from the title is returned for the following code, which makes no sense private val _error = MutableLiveData<String?>() val error: LiveData<String?> get() = _error _error.postValue(null) //Error Cannot set non-nullable LiveData value to null [NullSafeMutableLiveData] parameter String of _error is obviously nullable, am I doing something wrong? A: This appears to be related to a bug already reported against androidx.lifecycle pre-release of 2.3.0 https://issuetracker.google.com/issues/169249668. Workarounds I have found: turn off or reduce severity of NullSafeMutableLiveData in build.gradle android { ... lintOptions { disable 'NullSafeMutableLiveData' } } or lint.xml in root dir <?xml version="1.0" encoding="UTF-8"?> <lint> <issue id="NullSafeMutableLiveData" severity="warning" /> </lint> Do the work for MutableLiveData encapsulation via backing properties dance (which really hurts my eyes). class ExampleViewModel : ViewModel() { private val _data1 = MutableLiveData<Int>() val data1: LiveData<Int> = _data1 private val _data2 = MutableLiveData<Int?>() val data2: LiveData<Int?> = _data2 fun funct() { _data1.value = 1 _data2.value = null } } A: This has been fixed in version 2.3.1. https://developer.android.com/jetpack/androidx/releases/lifecycle#version_231_2 A: It seems fixed in lifecycle 2.4.0-SNAPSHOT. Please wait for the official release. A: This issue was coming in 2.3.0 also but after upgrading to 2.4.0 it is not coming. A: Add NullSafeMutableLiveData in your function, @Suppress("NullSafeMutableLiveData") fun clearBeforeData(){ _articles.postValue(null) } A: I think this has been fixed in version 2.4.1 this is my working solution private val _roomDataObserver: MutableLiveData<List<Resource<ModelClass?>>?> = MutableLiveData() val roomDataObserver: LiveData<List<Resource<ModelClass?>>?> get() = _classroomDataObserver override fun onCleared() { super.onCleared() Log.d("VIEWMODEL", "CLEARED") _roomDataObserver.value = null }
Cannot set non-nullable LiveData value to null
The error from the title is returned for the following code, which makes no sense private val _error = MutableLiveData<String?>() val error: LiveData<String?> get() = _error _error.postValue(null) //Error Cannot set non-nullable LiveData value to null [NullSafeMutableLiveData] parameter String of _error is obviously nullable, am I doing something wrong?
[ "This appears to be related to a bug already reported against androidx.lifecycle pre-release of 2.3.0 https://issuetracker.google.com/issues/169249668.\nWorkarounds I have found:\n\nturn off or reduce severity of NullSafeMutableLiveData in\n\nbuild.gradle\nandroid {\n ...\n lintOptions {\n disable 'NullSafeMutableLiveData'\n }\n}\n\nor lint.xml in root dir\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<lint>\n <issue id=\"NullSafeMutableLiveData\" severity=\"warning\" />\n</lint>\n\n\nDo the work for MutableLiveData encapsulation via backing properties dance (which really hurts my eyes).\n\nclass ExampleViewModel : ViewModel() {\n\n private val _data1 = MutableLiveData<Int>()\n val data1: LiveData<Int> = _data1\n\n private val _data2 = MutableLiveData<Int?>()\n val data2: LiveData<Int?> = _data2\n\n fun funct() {\n _data1.value = 1\n _data2.value = null\n }\n}\n\n", "This has been fixed in version 2.3.1.\nhttps://developer.android.com/jetpack/androidx/releases/lifecycle#version_231_2\n", "It seems fixed in lifecycle 2.4.0-SNAPSHOT.\nPlease wait for the official release.\n", "This issue was coming in 2.3.0 also but after upgrading to 2.4.0 it is not coming.\n", "Add NullSafeMutableLiveData in your function,\n@Suppress(\"NullSafeMutableLiveData\")\nfun clearBeforeData(){\n _articles.postValue(null)\n}\n\n", "I think this has been fixed in version 2.4.1\nthis is my working solution\nprivate val _roomDataObserver: MutableLiveData<List<Resource<ModelClass?>>?> = MutableLiveData()\nval roomDataObserver: LiveData<List<Resource<ModelClass?>>?>\n get() = _classroomDataObserver\n\n override fun onCleared() {\n super.onCleared()\n Log.d(\"VIEWMODEL\", \"CLEARED\")\n _roomDataObserver.value = null\n}\n\n" ]
[ 38, 2, 0, 0, 0, 0 ]
[]
[]
[ "android", "android_livedata", "kotlin", "kotlin_null_safety" ]
stackoverflow_0065322892_android_android_livedata_kotlin_kotlin_null_safety.txt
Q: Cypress Error: connect ETIMEDOUT cy.visit() I am receiving an abnormal visit error in cypress browser. However if I visit the same url in normal browser, it works. Here is the screenshot of the error. I've tried this: cy.visit(this.hrefLink, { timeout: 30000, headers: { "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.5", "Content-Type": "text/html" } }); A: Have you tried omitting the headers? Perhaps they are not accepted by the server. You should compare them with the ones sent from your regular browser when you successfully visits the site. Also look at what browser you use for running the cypress test automation, make sure its the same one that you know works. (Although this is unlikely to be the problem)
Cypress Error: connect ETIMEDOUT cy.visit()
I am receiving an abnormal visit error in cypress browser. However if I visit the same url in normal browser, it works. Here is the screenshot of the error. I've tried this: cy.visit(this.hrefLink, { timeout: 30000, headers: { "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.5", "Content-Type": "text/html" } });
[ "Have you tried omitting the headers? Perhaps they are not accepted by the server. You should compare them with the ones sent from your regular browser when you successfully visits the site.\nAlso look at what browser you use for running the cypress test automation, make sure its the same one that you know works. (Although this is unlikely to be the problem)\n" ]
[ 0 ]
[]
[]
[ "cypress", "http", "javascript", "networking", "node.js" ]
stackoverflow_0074673147_cypress_http_javascript_networking_node.js.txt
Q: Applying two styler functions simultanesouly to a dataframe Here is the example script I am working with. I am trying to apply two styler functions to a dataframe at the same time but as you can see, it would only call the colors2 function. What would be the best way to apply two functions at the same time? import pandas as pd df = pd.DataFrame(data=[[-100,500,400,0,222,222], [9000,124,0,-147,54,-56],[77,0,110,211,0,222], [111,11,-600,33,0,22,],[213,-124,0,-147,54,-56]]) df.columns = pd.MultiIndex.from_product([['x','y','z'], list('ab')]) def colors(i): if i > 0: return 'background: red' elif i < 0: return 'background: green' elif i == 0: return 'background: yellow' else: '' def colors2(i): if i < 0: return 'background: red' elif i > 0: return 'background: green' elif i == 0: return 'background: yellow' else: '' idx = pd.IndexSlice df.style.applymap (colors, subset=pd.IndexSlice[:, idx['x','b']]) df.style.applymap (colors2, subset=pd.IndexSlice[:, idx[:, 'b']]) A: Chain your applymap commands in the desired order (last one prevails): (df.style .applymap(colors2, subset=pd.IndexSlice[:, pd.IndexSlice[:, 'b']]) .applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice['x','b']]) ) Here pd.IndexSlice['x','b']] is more restrictive than pd.IndexSlice[:, 'b'] so we use it last. Another option could be to use a single function and to decide the color based on the labels inside it. import numpy as np def colors(s): if s.name[0] == 'x': s = s*-1 return np.sign(s).map({-1: 'background: red', 1: 'background: green', 0: 'background: yellow'}) (df.style .apply(colors, subset=pd.IndexSlice[:, pd.IndexSlice[:, 'b']]) ) Output:
Applying two styler functions simultanesouly to a dataframe
Here is the example script I am working with. I am trying to apply two styler functions to a dataframe at the same time but as you can see, it would only call the colors2 function. What would be the best way to apply two functions at the same time? import pandas as pd df = pd.DataFrame(data=[[-100,500,400,0,222,222], [9000,124,0,-147,54,-56],[77,0,110,211,0,222], [111,11,-600,33,0,22,],[213,-124,0,-147,54,-56]]) df.columns = pd.MultiIndex.from_product([['x','y','z'], list('ab')]) def colors(i): if i > 0: return 'background: red' elif i < 0: return 'background: green' elif i == 0: return 'background: yellow' else: '' def colors2(i): if i < 0: return 'background: red' elif i > 0: return 'background: green' elif i == 0: return 'background: yellow' else: '' idx = pd.IndexSlice df.style.applymap (colors, subset=pd.IndexSlice[:, idx['x','b']]) df.style.applymap (colors2, subset=pd.IndexSlice[:, idx[:, 'b']])
[ "Chain your applymap commands in the desired order (last one prevails):\n(df.style\n .applymap(colors2, subset=pd.IndexSlice[:, pd.IndexSlice[:, 'b']])\n .applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice['x','b']])\n )\n\nHere pd.IndexSlice['x','b']] is more restrictive than pd.IndexSlice[:, 'b'] so we use it last.\nAnother option could be to use a single function and to decide the color based on the labels inside it.\nimport numpy as np\ndef colors(s):\n if s.name[0] == 'x':\n s = s*-1\n return np.sign(s).map({-1: 'background: red', 1: 'background: green', 0: 'background: yellow'})\n \n(df.style\n .apply(colors, subset=pd.IndexSlice[:, pd.IndexSlice[:, 'b']])\n )\n\nOutput:\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "multi_index", "pandas", "python" ]
stackoverflow_0074673515_dataframe_multi_index_pandas_python.txt
Q: SharedPreferences data does not have time to be displayed in the widget I created a model class for Provider. Which will fit the function of getting data from SharedPreferences Future getDataPerson() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); id = prefs.getInt('id') ?? 000; name = prefs.getString('name') ?? "Фамилия Имя Отчество"; phone = prefs.getString('phone') ?? "3231313"; email = prefs.getString('email') ?? ""; accessToken = prefs.getString('accessToken') ?? "нет токенааа"; _login = prefs.getString('login') ?? "нет логинааа"; _password = prefs.getString('password') ?? "нет пароляяя"; notifyListeners(); } That's how I implement my Provider body: MultiProvider( providers: [ ChangeNotifierProvider<ApiClient>(create: (_)=>ApiClient()), ChangeNotifierProvider<FinalModel>(create: (_)=>FinalModel()), ], child: FinalScreenState(), ), In initState, I call this function. @override void initState() { super.initState(); finalModel = Provider.of<FinalModel>(context,listen: false); getDataPerson(); } Future getDataPerson() async{ return await finalModel.getDataPerson(); } And in the code I get these variables and paste them into Text idController.text = finalModel.getId.toString(); return Padding(padding: EdgeInsets.only(top: 15, bottom: 10,right: 1,left: 1), child:Center( child: TextField( controller: idController, )) ); However, only the values that I wrote in the code are inserted into the text. In this line it is "3231313" prefs.getString('phone') ?? "3231313"; I tried calling the get Data Person function in different places in the code. In the build method itself. The data I want to insert I take from json immediately after the user logs in using the button and receives a response from the api var statusOne =await apiClient.signIn(_loginEmail1.text, _passwordParol1.text); Map<String, dynamic> map = jsonDecode(rawJson); bool status = map['status']; if (status == true) { //Entry in SharedPreferences setDataPerson(); //The screen on which the data is displayed Navigator.pushReplacementNamed(context, 'final');} method setDataPerson() void setDataPerson() async { final prefs = await SharedPreferences.getInstance(); var statusOne = await apiClient.signIn(_loginEmail1.text, _passwordParol1.text); var rawJson = AuthModel.fromJson(statusOne.data); await prefs.setInt('id', rawJson.data!.performerId!); await prefs.setString('name', rawJson.data!.fullName!); await prefs.setString('phone', rawJson.data!.phone!); await prefs.setString('accessToken', rawJson.data!.accessToken!); } Build method Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ IdWidget(), NameWidget(), PhoneWidget(), EmailWidget(), ], ); } PhoneWidget class PhoneWidget extends StatelessWidget { Widget build(BuildContext context) { var finalModel = Provider.of<FinalModel>(context,listen: true); return Padding(padding: EdgeInsets.only(top: 10, bottom: 10,right: 1,left: 1), child: Consumer<FinalModel>( builder: (context, model, widget) { finalModel.phoneController.text = model.phone; return Center( child: TextField( controller: finalModel.phoneController, enabled: false, decoration: const InputDecoration( labelText: "Телефон", contentPadding: EdgeInsets.only(left: 10, top: 10, bottom: 10), border: OutlineInputBorder(), ), )); }) ); } } However, even if you do not receive this data from the network and just write a regular string, the data will not have time to be displayed on the screen. It's worth noting here that when I restart the screen. And that is, I update the initState and build method. Then the data is updated and immediately displayed on the screen I am not considering inserting the listen:true parameter into provider, , because the getData Person function will be called too often. A: Wrap Consumer widget to your Columnwidget so registered listeners will be called. Widget IdWidget() { return Consumer<YourModelClass>( builder: (context, model, widget) => Padding( padding: EdgeInsets.only(top: 15, bottom: 10, right: 1, left: 1), child: Center( child: TextField( controller: model.id, )))); }
SharedPreferences data does not have time to be displayed in the widget
I created a model class for Provider. Which will fit the function of getting data from SharedPreferences Future getDataPerson() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); id = prefs.getInt('id') ?? 000; name = prefs.getString('name') ?? "Фамилия Имя Отчество"; phone = prefs.getString('phone') ?? "3231313"; email = prefs.getString('email') ?? ""; accessToken = prefs.getString('accessToken') ?? "нет токенааа"; _login = prefs.getString('login') ?? "нет логинааа"; _password = prefs.getString('password') ?? "нет пароляяя"; notifyListeners(); } That's how I implement my Provider body: MultiProvider( providers: [ ChangeNotifierProvider<ApiClient>(create: (_)=>ApiClient()), ChangeNotifierProvider<FinalModel>(create: (_)=>FinalModel()), ], child: FinalScreenState(), ), In initState, I call this function. @override void initState() { super.initState(); finalModel = Provider.of<FinalModel>(context,listen: false); getDataPerson(); } Future getDataPerson() async{ return await finalModel.getDataPerson(); } And in the code I get these variables and paste them into Text idController.text = finalModel.getId.toString(); return Padding(padding: EdgeInsets.only(top: 15, bottom: 10,right: 1,left: 1), child:Center( child: TextField( controller: idController, )) ); However, only the values that I wrote in the code are inserted into the text. In this line it is "3231313" prefs.getString('phone') ?? "3231313"; I tried calling the get Data Person function in different places in the code. In the build method itself. The data I want to insert I take from json immediately after the user logs in using the button and receives a response from the api var statusOne =await apiClient.signIn(_loginEmail1.text, _passwordParol1.text); Map<String, dynamic> map = jsonDecode(rawJson); bool status = map['status']; if (status == true) { //Entry in SharedPreferences setDataPerson(); //The screen on which the data is displayed Navigator.pushReplacementNamed(context, 'final');} method setDataPerson() void setDataPerson() async { final prefs = await SharedPreferences.getInstance(); var statusOne = await apiClient.signIn(_loginEmail1.text, _passwordParol1.text); var rawJson = AuthModel.fromJson(statusOne.data); await prefs.setInt('id', rawJson.data!.performerId!); await prefs.setString('name', rawJson.data!.fullName!); await prefs.setString('phone', rawJson.data!.phone!); await prefs.setString('accessToken', rawJson.data!.accessToken!); } Build method Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ IdWidget(), NameWidget(), PhoneWidget(), EmailWidget(), ], ); } PhoneWidget class PhoneWidget extends StatelessWidget { Widget build(BuildContext context) { var finalModel = Provider.of<FinalModel>(context,listen: true); return Padding(padding: EdgeInsets.only(top: 10, bottom: 10,right: 1,left: 1), child: Consumer<FinalModel>( builder: (context, model, widget) { finalModel.phoneController.text = model.phone; return Center( child: TextField( controller: finalModel.phoneController, enabled: false, decoration: const InputDecoration( labelText: "Телефон", contentPadding: EdgeInsets.only(left: 10, top: 10, bottom: 10), border: OutlineInputBorder(), ), )); }) ); } } However, even if you do not receive this data from the network and just write a regular string, the data will not have time to be displayed on the screen. It's worth noting here that when I restart the screen. And that is, I update the initState and build method. Then the data is updated and immediately displayed on the screen I am not considering inserting the listen:true parameter into provider, , because the getData Person function will be called too often.
[ "Wrap Consumer widget to your Columnwidget so registered listeners will be called.\n Widget IdWidget() {\n return Consumer<YourModelClass>(\n builder: (context, model, widget) => Padding(\n padding: EdgeInsets.only(top: 15, bottom: 10, right: 1, left: 1),\n child: Center(\n child: TextField(\n controller: model.id,\n ))));\n }\n\n" ]
[ 2 ]
[]
[]
[ "flutter", "flutter_futurebuilder", "provider", "sharedpreferences" ]
stackoverflow_0074673548_flutter_flutter_futurebuilder_provider_sharedpreferences.txt
Q: Is there any way to hide a (hidden) YouTube video's title from media controls? I have a hidden YouTube video used in a Heardle clone on my site. The idea is for the user to not know what the song is, however when media controls are changed it shows the currently playing video: https://i.stack.imgur.com/9bzjE.png Is there any way to hide this and show the website's name instead? I'm using react-player for the implementation. I have the following code in my ReactPlayer instance: <ReactPlayer ref={player} url={`https://youtube.com/watch?v=${song.video_id}`} width="100%" height="85%" playing={playing} volume={.8} controls={true} muted={false} onProgress={(state) => { handleProgress(state); }} onReady={() => { handleReady(); }} progressInterval={10} /> I didn't find anything in their documentation that alludes to this problem. A: It is not possible to hide the YouTube video name when using the ReactPlayer component. This is because ReactPlayer is a wrapper around the YouTube player, and it is the player itself that displays the video title and other information. You can try using the showinfo parameter to hide the video title, but this will also hide other information such as the video thumbnail and the channel name. Example: <ReactPlayer ref={player} url={`https://youtube.com/watch?v=${song.video_id}`} width="100%" height="85%" playing={playing} volume={.8} controls={true} muted={false} onProgress={(state) => { handleProgress(state); }} onReady={() => { handleReady(); }} progressInterval={10} config={{ youtube: { playerVars: { showinfo: 0 } } }} />
Is there any way to hide a (hidden) YouTube video's title from media controls?
I have a hidden YouTube video used in a Heardle clone on my site. The idea is for the user to not know what the song is, however when media controls are changed it shows the currently playing video: https://i.stack.imgur.com/9bzjE.png Is there any way to hide this and show the website's name instead? I'm using react-player for the implementation. I have the following code in my ReactPlayer instance: <ReactPlayer ref={player} url={`https://youtube.com/watch?v=${song.video_id}`} width="100%" height="85%" playing={playing} volume={.8} controls={true} muted={false} onProgress={(state) => { handleProgress(state); }} onReady={() => { handleReady(); }} progressInterval={10} /> I didn't find anything in their documentation that alludes to this problem.
[ "It is not possible to hide the YouTube video name when using the ReactPlayer component. This is because ReactPlayer is a wrapper around the YouTube player, and it is the player itself that displays the video title and other information.\nYou can try using the showinfo parameter to hide the video title, but this will also hide other information such as the video thumbnail and the channel name.\nExample:\n<ReactPlayer\n ref={player}\n url={`https://youtube.com/watch?v=${song.video_id}`}\n width=\"100%\"\n height=\"85%\"\n playing={playing}\n volume={.8}\n controls={true}\n muted={false}\n onProgress={(state) => {\n handleProgress(state);\n }}\n onReady={() => {\n handleReady();\n }}\n progressInterval={10}\n config={{\n youtube: {\n playerVars: {\n showinfo: 0\n }\n }\n }}\n/>\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "react_player", "reactjs", "youtube" ]
stackoverflow_0074670676_javascript_react_player_reactjs_youtube.txt
Q: Changing one of the pink squares to a different color This here changes all the squares to pink. https://jsfiddle.net/7cye4hfu/1/ If I wanted to change one of the pink squares to a different color, how would I do that? .channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; background-color: pink; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item { padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .box-color-red { background: red; border-radius: 4px; } .box-color-blue { background: blue; } .box-color-yellow { background: yellow; } .box-color-green { background: green; } <div class="channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-blue"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-yellow"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-green"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> </div> A: Many ways. Here are two. NOTE Do NOT have content:"" if you want to have content .channel-browser__channel-grid-item.box-color-red::after { background-color: red; } .channel-browser__channel-grid-item:nth-of-type(4)::after { background-color: green; } .channel-browser__channel-grid-item::after { position: absolute; inset: 0; background-color: pink; } .channel-browser__channel-grid-item.box-color-red::after { background-color: red; } .channel-browser__channel-grid-item:nth-of-type(4)::after { background-color: green; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item { padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .box-color-red { background: red; border-radius: 4px; } .box-color-blue { background: blue; } .box-color-yellow { background: yellow; } .box-color-green { background: green; } <div class="channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red"><button>Click</button></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-blue"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-yellow"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-green"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> </div> A: Insted of : .box-color-red { background: red; border-radius: 4px; } .box-color-blue { background: blue; } .box-color-yellow { background: yellow; } .box-color-green { background: green; } Try using: .box-color-red::after { background: red; border-radius: 4px; } .box-color-blue::after { background: blue; } .box-color-yellow::after { background: yellow; } .box-color-green::after { background: green; }
Changing one of the pink squares to a different color
This here changes all the squares to pink. https://jsfiddle.net/7cye4hfu/1/ If I wanted to change one of the pink squares to a different color, how would I do that? .channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; background-color: pink; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item { padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .box-color-red { background: red; border-radius: 4px; } .box-color-blue { background: blue; } .box-color-yellow { background: yellow; } .box-color-green { background: green; } <div class="channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-blue"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-yellow"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-green"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="https://via.placeholder.com/465x465" class="responsive-image-component"> </div> </div>
[ "Many ways. Here are two.\nNOTE Do NOT have content:\"\" if you want to have content\n.channel-browser__channel-grid-item.box-color-red::after {\n background-color: red;\n}\n.channel-browser__channel-grid-item:nth-of-type(4)::after {\n background-color: green;\n}\n\n\n\n.channel-browser__channel-grid-item::after {\n position: absolute;\n inset: 0;\n background-color: pink;\n}\n\n.channel-browser__channel-grid-item.box-color-red::after {\n background-color: red;\n}\n.channel-browser__channel-grid-item:nth-of-type(4)::after {\n background-color: green;\n}\n\n.channel-browser__channel-grid {\n display: grid;\n gap: 16px;\n grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));\n margin: 0;\n padding: 0;\n border: 0;\n font-size: 100%;\n font: inherit;\n vertical-align: baseline;\n}\n\n.channel-browser__channel-grid-item {\n position: relative;\n}\n\n.content-item-container--aspect-square .horizontal-content-browser__content-item {\n padding-top: 100%;\n}\n\n.horizontal-content-browser__content-item .horizontal-content-browser__fallback-image,\n.horizontal-content-browser__content-item .responsive-image-component {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: auto;\n border-radius: 4px;\n background-color: #1a1a1a;\n -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n}\n\n.box-color-red {\n background: red;\n border-radius: 4px;\n}\n\n.box-color-blue {\n background: blue;\n}\n\n.box-color-yellow {\n background: yellow;\n}\n\n.box-color-green {\n background: green;\n}\n<div class=\"channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square\">\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red\"><button>Click</button></div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-blue\"></div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-yellow\"></div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-green\"></div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <img width=\"280\" height=\"280\" src=\"https://via.placeholder.com/465x465\" class=\"responsive-image-component\">\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <img width=\"280\" height=\"280\" src=\"https://via.placeholder.com/465x465\" class=\"responsive-image-component\">\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <img width=\"280\" height=\"280\" src=\"https://via.placeholder.com/465x465\" class=\"responsive-image-component\">\n </div>\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <img width=\"280\" height=\"280\" src=\"https://via.placeholder.com/465x465\" class=\"responsive-image-component\">\n </div>\n</div>\n\n\n\n", "Insted of :\n.box-color-red {\n background: red;\n border-radius: 4px;\n }\n\n .box-color-blue {\n background: blue;\n }\n\n .box-color-yellow {\n background: yellow;\n }\n\n .box-color-green {\n background: green;\n }\n\nTry using:\n.box-color-red::after {\n background: red;\n border-radius: 4px;\n }\n\n .box-color-blue::after {\n background: blue;\n }\n\n .box-color-yellow::after {\n background: yellow;\n }\n\n .box-color-green::after {\n background: green;\n }\n\n" ]
[ 1, 1 ]
[]
[]
[ "background", "background_color", "css", "html" ]
stackoverflow_0074673492_background_background_color_css_html.txt
Q: pthread_kill() funktion terminates my program pthread_kill() funktion terminates my program every time I launch it after a creation of a thread and try to send a SIGALRM signal. By the way, it works if I add a sleep() function before pthread_kill(). Then I add sleep() function in thread, because it terminates earlier then sending a signal. void* funkcja_watku(){ struct sigaction new_action = {.sa_handler = obsluga}; sigaction(SIGALRM, &new_action, NULL); sleep(2); return 0; } int main(int argc, const char * argv[]) { pthread_t watek_id; //tworze watek if(pthread_create(&watek_id, NULL, &funkcja_watku, NULL)) printf("Watek nie zostal utworzony\n"); sleep(1); //wysylam sygnal if(pthread_kill(watek_id, SIGALRM)) printf("Sygnal nie zostal wyslany\n"); //usuwam watek if(pthread_join(watek_id, NULL)) printf("Watek nie zostal usuniety\n"); return 0; } I added the sleep function, but I dont think that It is the good way A: It doesn't kill your program. It terminates your thread, so your program exit peacefuly, since the join unblocks. And it doesn't kill your thread neither. Your thread works correctly. But, as you may know or not, sleep is interrupted whenever your receive a signal. man 3 sleep DESCRIPTION sleep() causes the calling thread to sleep either until the number of real-time seconds specified in seconds have elapsed or until a sig‐ nal arrives which is not ignored. That is what sleep does... Just add a second sleep after this one, and you'll. Or add a printf after your sleep, and you'll at least see that your thread is still alive. Its job is just over. void* funkcja_watku(){ struct sigaction new_action = {.sa_handler = obsluga}; sigaction(SIGALRM, &new_action, NULL); sleep(2); printf("sleep over, because 2 sec has elapsed, or a signal was received\n"); sleep(2); printf("second sleep is over\n"); return 0; } Since I guess those sleep were just an experiment, it is just an experiment problem :D Edit - answer to your comment So, again, there is no problem in your code. Just sleep is behaving as expected, that is not sleeping as much as requested if a signal is received. If you want a sleep that sleep the amount of time wanted, you can implement it yourself, by sleeping in a loop, resuming the sleep if it was interrupted by a signal. #include <stdio.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #include <sys/time.h> void obsluga(){ printf("got alarm\n"); } void* funkcja_watku(){ struct sigaction new_action = {.sa_handler = obsluga}; sigaction(SIGALRM, &new_action, NULL); struct timeval tv0, tv; gettimeofday(&tv0, NULL); for(;;){ usleep(10000); gettimeofday(&tv, NULL); float delay=tv.tv_sec-tv0.tv_sec + 1.0e-6*(tv.tv_usec-tv0.tv_usec); printf("\rsleeping... t=%5.2f / 2 ", delay); fflush(stdout); if(delay > 2.0) break; } return 0; } int main(int argc, const char * argv[]) { pthread_t watek_id; //tworze watek if(pthread_create(&watek_id, NULL, &funkcja_watku, NULL)) printf("Watek nie zostal utworzony\n"); sleep(1); //wysylam sygnal if(pthread_kill(watek_id, SIGALRM)) printf("Sygnal nie zostal wyslany\n"); //usuwam watek if(pthread_join(watek_id, NULL)) printf("Watek nie zostal usuniety\n"); return 0; } (In reality, here I do more than needed, because I wanted the cool display of seconds slept, to see the progress. But what I should have done is usleeping 2000000-(tv.tv_sec-tv0.tv_sec)*1000000 - (tv.tv_usec-tv0.tv_usec). That is usleeping the rest of wanted delay. So, if no signal occurs, there will be only one "normal" sleep, lasting 2 seconds. If one signal occurs, then there would be one interrupted sleep, then another, for the remaining of time. But, well, here I just sleep 10ms, and wait until 2 second have elapsed. So it doesn't matter if some of the 10 ms sleep are interrputed, we still exit the for loop only after 2 seconds. You can change the delay to see for yourself that, indeed, the only cause of your problem was the fact that sleep is interrupted #include <stdio.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #include <sys/time.h> void obsluga(){ printf("got alarm\n"); } void* funkcja_watku(){ struct sigaction new_action = {.sa_handler = obsluga}; sigaction(SIGALRM, &new_action, NULL); struct timeval tv0, tv; gettimeofday(&tv0, NULL); for(;;){ // We sleep approx 10 seconds by steps of 1 second sleep(1); gettimeofday(&tv, NULL); float delay=tv.tv_sec-tv0.tv_sec + 1.0e-6*(tv.tv_usec-tv0.tv_usec); printf("sleeping... t=%5.2f / 10\n", delay); // No \r this time: I want to keep track of timings if(delay > 10.0) break; } return 0; } int main(int argc, const char * argv[]) { pthread_t watek_id; //tworze watek if(pthread_create(&watek_id, NULL, &funkcja_watku, NULL)) printf("Watek nie zostal utworzony\n"); // Important part is here to have not a multiple of 1 second. // So that you'll see that, indeed, signal occurs in the middle // of a sleep usleep(3500000); //wysylam sygnal if(pthread_kill(watek_id, SIGALRM)) printf("Sygnal nie zostal wyslany\n"); //usuwam watek if(pthread_join(watek_id, NULL)) printf("Watek nie zostal usuniety\n"); return 0; } Output is sleeping... t= 1.00 / 10 sleeping... t= 2.00 / 10 sleeping... t= 3.01 / 10 got alarm sleeping... t= 3.50 / 10 sleeping... t= 4.51 / 10 sleeping... t= 5.51 / 10 sleeping... t= 6.51 / 10 sleeping... t= 7.51 / 10 sleeping... t= 8.51 / 10 sleeping... t= 9.52 / 10 sleeping... t=10.52 / 10 Not only you see that you, as expected, got your signal after 3.5 seconds; that your thread still continues to run after the alarm is got. That, accordingly, the main thread still continues to pthread_wait until the thread has finished, which occurs only after 10 seconds. So everything is as you expected. But you also see that the 4th sleep is, as I told you, interrupted. It was supposed to last 1 second (between t=3 and t=4). But because the signal was received, it was interrupted, and ended at t=3.5 after half a second. Subsequent sleeps are all uninterrupted (and because of that all end/start at times x.5 seconds) A: If you are using the pthread_kill function to send a signal to a thread, you need to make sure that the thread has registered a signal handler for that signal using the sigaction function before calling pthread_kill. Otherwise, the signal will not be delivered to the thread and your program will terminate. In your code, you are calling sigaction in the thread function to register a signal handler for SIGALRM, but you are calling pthread_kill in the main function before the thread has had a chance to register the signal handler. This is why your program is terminating. One solution to this problem would be to move the call to pthread_kill to the thread function, after the call to sigaction. This way, the thread will register the signal handler before pthread_kill is called, and the signal will be delivered to the thread as expected. Here is an example of how you could modify your code to fix this problem: void* funkcja_watku(){ struct sigaction new_action = {.sa_handler = obsluga}; sigaction(SIGALRM, &new_action, NULL); // send the signal after the signal handler has been registered pthread_kill(pthread_self(), SIGALRM); return 0; } int main(int argc, const char * argv[]) { pthread_t watek_id; // create the thread if(pthread_create(&watek_id, NULL, &funkcja_watku, NULL)) printf("Watek nie zostal utworzony\n"); // wait for the thread to finish if(pthread_join(watek_id, NULL)) printf("Watek nie zostal usuniety\n"); return 0; }
pthread_kill() funktion terminates my program
pthread_kill() funktion terminates my program every time I launch it after a creation of a thread and try to send a SIGALRM signal. By the way, it works if I add a sleep() function before pthread_kill(). Then I add sleep() function in thread, because it terminates earlier then sending a signal. void* funkcja_watku(){ struct sigaction new_action = {.sa_handler = obsluga}; sigaction(SIGALRM, &new_action, NULL); sleep(2); return 0; } int main(int argc, const char * argv[]) { pthread_t watek_id; //tworze watek if(pthread_create(&watek_id, NULL, &funkcja_watku, NULL)) printf("Watek nie zostal utworzony\n"); sleep(1); //wysylam sygnal if(pthread_kill(watek_id, SIGALRM)) printf("Sygnal nie zostal wyslany\n"); //usuwam watek if(pthread_join(watek_id, NULL)) printf("Watek nie zostal usuniety\n"); return 0; } I added the sleep function, but I dont think that It is the good way
[ "It doesn't kill your program. It terminates your thread, so your program exit peacefuly, since the join unblocks.\nAnd it doesn't kill your thread neither. Your thread works correctly.\nBut, as you may know or not, sleep is interrupted whenever your receive a signal.\nman 3 sleep\n\nDESCRIPTION\nsleep() causes the calling thread to sleep either until the number of real-time seconds specified in seconds have elapsed or until a sig‐\nnal arrives which is not ignored.\n\nThat is what sleep does...\nJust add a second sleep after this one, and you'll. Or add a printf after your sleep, and you'll at least see that your thread is still alive. Its job is just over.\nvoid* funkcja_watku(){\n struct sigaction new_action = {.sa_handler = obsluga};\n sigaction(SIGALRM, &new_action, NULL);\n sleep(2);\n printf(\"sleep over, because 2 sec has elapsed, or a signal was received\\n\");\n sleep(2);\n printf(\"second sleep is over\\n\");\n return 0;\n}\n\nSince I guess those sleep were just an experiment, it is just an experiment problem :D\nEdit - answer to your comment\nSo, again, there is no problem in your code. Just sleep is behaving as expected, that is not sleeping as much as requested if a signal is received.\nIf you want a sleep that sleep the amount of time wanted, you can implement it yourself, by sleeping in a loop, resuming the sleep if it was interrupted by a signal.\n#include <stdio.h>\n#include <pthread.h>\n#include <signal.h>\n#include <unistd.h>\n#include <sys/time.h>\n\nvoid obsluga(){\n printf(\"got alarm\\n\");\n}\n\nvoid* funkcja_watku(){\n struct sigaction new_action = {.sa_handler = obsluga};\n sigaction(SIGALRM, &new_action, NULL);\n struct timeval tv0, tv;\n gettimeofday(&tv0, NULL);\n for(;;){\n usleep(10000);\n gettimeofday(&tv, NULL);\n float delay=tv.tv_sec-tv0.tv_sec + 1.0e-6*(tv.tv_usec-tv0.tv_usec);\n printf(\"\\rsleeping... t=%5.2f / 2 \", delay);\n fflush(stdout);\n if(delay > 2.0) break;\n }\n return 0;\n}\n\nint main(int argc, const char * argv[]) {\n pthread_t watek_id;\n \n //tworze watek\n if(pthread_create(&watek_id, NULL, &funkcja_watku, NULL))\n printf(\"Watek nie zostal utworzony\\n\");\n \n sleep(1);\n \n //wysylam sygnal\n if(pthread_kill(watek_id, SIGALRM))\n printf(\"Sygnal nie zostal wyslany\\n\");\n \n //usuwam watek\n if(pthread_join(watek_id, NULL))\n printf(\"Watek nie zostal usuniety\\n\");\n \n return 0;\n}\n\n(In reality, here I do more than needed, because I wanted the cool display of seconds slept, to see the progress. But what I should have done is usleeping 2000000-(tv.tv_sec-tv0.tv_sec)*1000000 - (tv.tv_usec-tv0.tv_usec). That is usleeping the rest of wanted delay. So, if no signal occurs, there will be only one \"normal\" sleep, lasting 2 seconds. If one signal occurs, then there would be one interrupted sleep, then another, for the remaining of time. But, well, here I just sleep 10ms, and wait until 2 second have elapsed. So it doesn't matter if some of the 10 ms sleep are interrputed, we still exit the for loop only after 2 seconds.\nYou can change the delay to see for yourself that, indeed, the only cause of your problem was the fact that sleep is interrupted\n#include <stdio.h>\n#include <pthread.h>\n#include <signal.h>\n#include <unistd.h>\n#include <sys/time.h>\n\nvoid obsluga(){\n printf(\"got alarm\\n\");\n}\n\nvoid* funkcja_watku(){\n struct sigaction new_action = {.sa_handler = obsluga};\n sigaction(SIGALRM, &new_action, NULL);\n struct timeval tv0, tv;\n gettimeofday(&tv0, NULL);\n for(;;){\n // We sleep approx 10 seconds by steps of 1 second\n sleep(1);\n gettimeofday(&tv, NULL);\n float delay=tv.tv_sec-tv0.tv_sec + 1.0e-6*(tv.tv_usec-tv0.tv_usec);\n printf(\"sleeping... t=%5.2f / 10\\n\", delay); // No \\r this time: I want to keep track of timings\n if(delay > 10.0) break;\n }\n return 0;\n}\n\nint main(int argc, const char * argv[]) {\n pthread_t watek_id;\n \n //tworze watek\n if(pthread_create(&watek_id, NULL, &funkcja_watku, NULL))\n printf(\"Watek nie zostal utworzony\\n\");\n \n // Important part is here to have not a multiple of 1 second. \n // So that you'll see that, indeed, signal occurs in the middle \n // of a sleep\n usleep(3500000);\n \n //wysylam sygnal\n if(pthread_kill(watek_id, SIGALRM))\n printf(\"Sygnal nie zostal wyslany\\n\");\n \n //usuwam watek\n if(pthread_join(watek_id, NULL))\n printf(\"Watek nie zostal usuniety\\n\");\n \n return 0;\n}\n\nOutput is\nsleeping... t= 1.00 / 10\nsleeping... t= 2.00 / 10\nsleeping... t= 3.01 / 10\ngot alarm\nsleeping... t= 3.50 / 10\nsleeping... t= 4.51 / 10\nsleeping... t= 5.51 / 10\nsleeping... t= 6.51 / 10\nsleeping... t= 7.51 / 10\nsleeping... t= 8.51 / 10\nsleeping... t= 9.52 / 10\nsleeping... t=10.52 / 10\n\nNot only you see that you, as expected, got your signal after 3.5 seconds; that your thread still continues to run after the alarm is got. That, accordingly, the main thread still continues to pthread_wait until the thread has finished, which occurs only after 10 seconds. So everything is as you expected.\nBut you also see that the 4th sleep is, as I told you, interrupted. It was supposed to last 1 second (between t=3 and t=4). But because the signal was received, it was interrupted, and ended at t=3.5 after half a second.\nSubsequent sleeps are all uninterrupted (and because of that all end/start at times x.5 seconds)\n", "If you are using the pthread_kill function to send a signal to a thread, you need to make sure that the thread has registered a signal handler for that signal using the sigaction function before calling pthread_kill. Otherwise, the signal will not be delivered to the thread and your program will terminate.\nIn your code, you are calling sigaction in the thread function to register a signal handler for SIGALRM, but you are calling pthread_kill in the main function before the thread has had a chance to register the signal handler. This is why your program is terminating.\nOne solution to this problem would be to move the call to pthread_kill to the thread function, after the call to sigaction. This way, the thread will register the signal handler before pthread_kill is called, and the signal will be delivered to the thread as expected.\nHere is an example of how you could modify your code to fix this problem:\nvoid* funkcja_watku(){\n struct sigaction new_action = {.sa_handler = obsluga};\n sigaction(SIGALRM, &new_action, NULL);\n\n // send the signal after the signal handler has been registered\n pthread_kill(pthread_self(), SIGALRM);\n\n return 0;\n}\n\nint main(int argc, const char * argv[]) {\n pthread_t watek_id;\n\n // create the thread\n if(pthread_create(&watek_id, NULL, &funkcja_watku, NULL))\n printf(\"Watek nie zostal utworzony\\n\");\n\n // wait for the thread to finish\n if(pthread_join(watek_id, NULL))\n printf(\"Watek nie zostal usuniety\\n\");\n\n return 0;\n}\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "c", "multithreading" ]
stackoverflow_0074660923_c_multithreading.txt
Q: How to handle Firebase onAuthStateChanged in a React app and route users accordingly? I'm working on a React web app that is integrated with Firebase and I'm trying to authenticate my users. I have setup my route to display Home component if the user is authenticated and the Login page otherwise. But when my app first loads, it shows the Login page and it takes a second or two for it to recognize the user has actually been authenticated and then it switches to the Home page. It just seems messy and I'm guessing I'm not handling onAuthStateChanged quite well or fast enough. In my App component, I am subscribed to a ReactObserver that signals when auth state has changed. What can I do to avoid this weird behaviour? My App.js: import {BrowserRouter, Route} from "react-router-dom"; import Home from "./Home"; import Login from "./Login"; import {loggedIn, firebaseObserver} from "../firebase"; import {useEffect, useState} from "react"; export default function App() { const [authenticated, setAuthenticated] = useState(loggedIn()) useEffect(() => { firebaseObserver.subscribe('authStateChanged', data => { setAuthenticated(data); }); return () => { firebaseObserver.unsubscribe('authStateChanged'); } }, []); return <BrowserRouter> <Route exact path="/" render={() => (authenticated ? <Home/> : <Login/>)} /> </BrowserRouter>; } My firebase.js: import firebase from "firebase/app"; import "firebase/auth"; import "firebase/firestore"; import ReactObserver from 'react-event-observer'; const firebaseConfig = { apiKey: ..., authDomain: ..., projectId: ..., storageBucket: ..., messagingSenderId: ..., appId: ... }; firebase.initializeApp(firebaseConfig); export const auth = firebase.auth(); export const firestore = firebase.firestore(); export const firebaseObserver = ReactObserver(); auth.onAuthStateChanged(function(user) { firebaseObserver.publish("authStateChanged", loggedIn()) }); export function loggedIn() { return !!auth.currentUser; } A: To whom it may concern, adding a simple flag for when the authentication actually loaded solved the glitch for me. I also added protected routes (inspired by this article and I think I can continue on with my project nicely now. App.js: import {BrowserRouter, Redirect, Route, Switch} from "react-router-dom"; import Home from "./Home"; import Login from "./Login"; import {PrivateRoute} from "./PrivateRoute"; import {loggedIn, firebaseObserver} from "../firebase"; import {useEffect, useState} from "react"; export default function App() { const [authenticated, setAuthenticated] = useState(loggedIn()); const [isLoading, setIsLoading] = useState(true); useEffect(() => { firebaseObserver.subscribe('authStateChanged', data => { setAuthenticated(data); setIsLoading(false); }); return () => { firebaseObserver.unsubscribe('authStateChanged'); } }, []); return isLoading ? <div/> : <BrowserRouter> <Switch> <Route path="/" exact> <Redirect to={authenticated ? "/home" : "/login"} /> </Route> <PrivateRoute path="/home" exact component={Home} hasAccess={authenticated} /> <PrivateRoute path="/login" exact component={Login} hasAccess={!authenticated} /> <Route path="*"> <Redirect to={authenticated ? "/home" : "/login"} /> </Route> </Switch> </BrowserRouter>; } A: Simplified version; You can use a logged in condition to load data; /** * loggedIn = undefined when loading * loggedIn = true if loading is finished and there is a user * loggedIn = flase if loading is finished and there is no user */ const [loggedIn, setLoggedIn] = useState<boolean>(); auth.onAuthStateChanged((user) => { if (user) { setLoggedIn(true); } else { setLoggedIn(false); } }); useEffect(() => { if (loggedIn != undefined) { //do loggedIn stuff } }, [loggedIn]);
How to handle Firebase onAuthStateChanged in a React app and route users accordingly?
I'm working on a React web app that is integrated with Firebase and I'm trying to authenticate my users. I have setup my route to display Home component if the user is authenticated and the Login page otherwise. But when my app first loads, it shows the Login page and it takes a second or two for it to recognize the user has actually been authenticated and then it switches to the Home page. It just seems messy and I'm guessing I'm not handling onAuthStateChanged quite well or fast enough. In my App component, I am subscribed to a ReactObserver that signals when auth state has changed. What can I do to avoid this weird behaviour? My App.js: import {BrowserRouter, Route} from "react-router-dom"; import Home from "./Home"; import Login from "./Login"; import {loggedIn, firebaseObserver} from "../firebase"; import {useEffect, useState} from "react"; export default function App() { const [authenticated, setAuthenticated] = useState(loggedIn()) useEffect(() => { firebaseObserver.subscribe('authStateChanged', data => { setAuthenticated(data); }); return () => { firebaseObserver.unsubscribe('authStateChanged'); } }, []); return <BrowserRouter> <Route exact path="/" render={() => (authenticated ? <Home/> : <Login/>)} /> </BrowserRouter>; } My firebase.js: import firebase from "firebase/app"; import "firebase/auth"; import "firebase/firestore"; import ReactObserver from 'react-event-observer'; const firebaseConfig = { apiKey: ..., authDomain: ..., projectId: ..., storageBucket: ..., messagingSenderId: ..., appId: ... }; firebase.initializeApp(firebaseConfig); export const auth = firebase.auth(); export const firestore = firebase.firestore(); export const firebaseObserver = ReactObserver(); auth.onAuthStateChanged(function(user) { firebaseObserver.publish("authStateChanged", loggedIn()) }); export function loggedIn() { return !!auth.currentUser; }
[ "To whom it may concern, adding a simple flag for when the authentication actually loaded solved the glitch for me. I also added protected routes (inspired by this article and I think I can continue on with my project nicely now.\nApp.js:\nimport {BrowserRouter, Redirect, Route, Switch} from \"react-router-dom\";\nimport Home from \"./Home\";\nimport Login from \"./Login\";\nimport {PrivateRoute} from \"./PrivateRoute\";\nimport {loggedIn, firebaseObserver} from \"../firebase\";\nimport {useEffect, useState} from \"react\";\n\nexport default function App() {\n const [authenticated, setAuthenticated] = useState(loggedIn());\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n firebaseObserver.subscribe('authStateChanged', data => {\n setAuthenticated(data);\n setIsLoading(false);\n });\n return () => { firebaseObserver.unsubscribe('authStateChanged'); }\n }, []);\n\n return isLoading ? <div/> :\n <BrowserRouter>\n <Switch>\n <Route path=\"/\" exact>\n <Redirect to={authenticated ? \"/home\" : \"/login\"} />\n </Route>\n <PrivateRoute path=\"/home\" exact\n component={Home}\n hasAccess={authenticated} />\n <PrivateRoute path=\"/login\" exact\n component={Login}\n hasAccess={!authenticated} />\n <Route path=\"*\">\n <Redirect to={authenticated ? \"/home\" : \"/login\"} />\n </Route>\n </Switch>\n </BrowserRouter>;\n}\n\n", "Simplified version; You can use a logged in condition to load data;\n /**\n * loggedIn = undefined when loading\n * loggedIn = true if loading is finished and there is a user\n * loggedIn = flase if loading is finished and there is no user\n */\n const [loggedIn, setLoggedIn] = useState<boolean>();\n auth.onAuthStateChanged((user) => {\n if (user) {\n setLoggedIn(true);\n } else {\n setLoggedIn(false);\n }\n });\n\n useEffect(() => {\n if (loggedIn != undefined) {\n //do loggedIn stuff\n }\n }, [loggedIn]);\n\n" ]
[ 4, 1 ]
[]
[]
[ "authentication", "firebase", "observer_pattern", "react_router_dom", "reactjs" ]
stackoverflow_0066943220_authentication_firebase_observer_pattern_react_router_dom_reactjs.txt
Q: MainActivity cannot be cast to interface error when implementing interface from child fragment in parent fragment I have this app in which I have a parent fragment, which has 2 child fragments in a ViewPager2 object. One of the child fragments has an interface to communicate changes on its menu to the parent fragment. The child fragment in question is TasksListFragment.kt and the parent fragment is TodayFragment.kt When I try to initialize the interface in the child fragment onAttach() function, I get FATAL EXCEPTION: main Process: com.rajchenbergstudios.hoygenda, PID: java.lang.ClassCastException: com.rajchenbergstudios.hoygenda.ui.activity.MainActivity cannot be cast to com.rajchenbergstudios.hoygenda.ui.todaylists.taskslist.TasksListFragment$ChildFragmentListener I don't understand why I get this error, and it says MainActivity, when the parent is a fragment which is the one implementing the interface in the first place, not the MainActivity. I have everything set up correctly: I have an interface in the child fragment The interface is used on the child fragment onCreateMenu to pass the menu object to its interface function onFragmentMenuChanged(menu: Menu) I override the child fragment's onAttach() and initialize the interface: override fun onAttach(context: Context) { super.onAttach(context) childFragmentListener = context as ChildFragmentListener } I write a function called setListener() which is called from the parent fragment to pass its context this to the function parameter which assigns it to the childFragment listener fun setListener(listener: ChildFragmentListener) { this.childFragmentListener = listener } The parent fragment implements the child fragment listener as seen in the TodayFragment.kt file Can you tell me what am I doing wrong or how to implement an interface to effectively communicate from child fragment back to its parent fragment? TasksListFragment.kt @ExperimentalCoroutinesApi @AndroidEntryPoint class TasksListFragment : Fragment(R.layout.fragment_child_tasks_list), TasksListAdapter.OnItemClickListener { private val viewModel: TasksListViewModel by viewModels() private lateinit var searchView: SearchView private lateinit var childFragmentListener: ChildFragmentListener override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = FragmentChildTasksListBinding.bind(view) val tasksListAdapter = TasksListAdapter(this) binding.apply { tasksListRecyclerview.layoutTasksListRecyclerview.apply { adapter = tasksListAdapter layoutManager = LinearLayoutManager(requireContext()) setHasFixedSize(true) } ItemTouchHelper(object: ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT){ override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val task = tasksListAdapter.currentList[viewHolder.adapterPosition] viewModel.onTaskSwiped(task) } }).attachToRecyclerView(tasksListRecyclerview.layoutTasksListRecyclerview) } loadObservable(binding, tasksListAdapter) loadTasksEventCollector() loadMenu() } private fun loadObservable(binding: FragmentChildTasksListBinding, tasksListAdapter: TasksListAdapter) { viewModel.tasks.observe(viewLifecycleOwner){ tasksList -> binding.apply { HGDAViewStateUtils.apply { if (tasksList.isEmpty()) { setViewVisibility(tasksListRecyclerview.layoutTasksListRecyclerview, visibility = View.INVISIBLE) setViewVisibility(tasksListLayoutNoData.layoutNoDataLinearlayout, visibility = View.VISIBLE) } else { setViewVisibility(tasksListRecyclerview.layoutTasksListRecyclerview, visibility = View.VISIBLE) setViewVisibility(tasksListLayoutNoData.layoutNoDataLinearlayout, visibility = View.INVISIBLE) tasksListAdapter.submitList(tasksList) } } } } } /** * TasksListViewModel.TaskEvent.ShowUndoDeleteTaskMessage: Stays in this class. It asks for components relevant to this class. * TasksListViewModel.TaskEvent.NavigateToEditTaskScreen: Stays in this class. The method it overrides comes from task list adapter. * TasksListViewModel.TaskEvent.NavigateToDeleteAllCompletedScreen: Stays in this class. Relevant to menu which is in this class. * TasksListViewModel.TaskEvent.NavigateToDeleteAllScreen: Stays in this class. Relevant to menu which is in this class. */ private fun loadTasksEventCollector() { viewLifecycleOwner.lifecycleScope.launchWhenStarted { viewModel.tasksEvent.collect { event -> when (event) { is TasksListViewModel.TaskEvent.ShowUndoDeleteTaskMessage -> { Snackbar .make(requireView(), "Task deleted", Snackbar.LENGTH_LONG) .setAction("UNDO"){ viewModel.onUndoDeleteClick(event.task) } .show() } is TasksListViewModel.TaskEvent.NavigateToEditTaskScreen -> { val action = TodayFragmentDirections .actionTodayFragmentToTaskAddEditFragment(task = event.task, title = "Edit task", taskinset = null, origin = 1) findNavController().navigate(action) } is TasksListViewModel.TaskEvent.NavigateToAddTaskToSetBottomSheet -> { val action = TasksListFragmentDirections.actionGlobalSetBottomSheetDialogFragment(task = event.task, origin = 1) findNavController().navigate(action) } is TasksListViewModel.TaskEvent.NavigateToDeleteAllCompletedScreen -> { val action = TasksListFragmentDirections .actionGlobalTasksDeleteAllDialogFragment(origin = 1) findNavController().navigate(action) } is TasksListViewModel.TaskEvent.NavigateToDeleteAllScreen -> { val action = TasksListFragmentDirections .actionGlobalTasksDeleteAllDialogFragment(origin = 3) findNavController().navigate(action) } }.exhaustive } } } private fun loadMenu(){ val menuHost: MenuHost = requireActivity() menuHost.addMenuProvider(object: MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { childFragmentListener.onFragmentChanged(menu) menuInflater.inflate(R.menu.menu_tasks_list_fragment, menu) val searchItem = menu.findItem(R.id.tasks_list_menu_search) searchView = searchItem.actionView as SearchView val pendingQuery = viewModel.searchQuery.value if (pendingQuery != null && pendingQuery.isNotEmpty()) { searchItem.expandActionView() searchView.setQuery(pendingQuery, false) } searchView.OnQueryTextChanged{ searchQuery -> viewModel.searchQuery.value = searchQuery } viewLifecycleOwner.lifecycleScope.launchWhenStarted { menu.findItem(R.id.tasks_list_menu_hide_completed).isChecked = viewModel.preferencesFlow.first().hideCompleted } } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.tasks_list_menu_sort_by_date -> { viewModel.onSortOrderSelected(SortOrder.BY_DATE) true } R.id.tasks_list_menu_sort_by_name -> { viewModel.onSortOrderSelected(SortOrder.BY_NAME) true } R.id.tasks_list_menu_hide_completed -> { menuItem.isChecked = !menuItem.isChecked viewModel.onHideCompletedSelected(menuItem.isChecked) true } R.id.tasks_list_menu_delete_completed -> { viewModel.onDeleteAllCompletedClick() true } R.id.tasks_list_menu_delete_all -> { viewModel.onDeleteAllClick() true } else -> false } } }, viewLifecycleOwner, Lifecycle.State.RESUMED) } interface ChildFragmentListener { fun onFragmentChanged(menu: Menu) } fun setListener(listener: ChildFragmentListener) { this.childFragmentListener = listener } override fun onItemClick(task: Task) { viewModel.onTaskSelected(task) } override fun onItemLongClick(task: Task) { viewModel.onTaskLongSelected(task) } override fun onCheckboxClick(task: Task, isChecked: Boolean) { viewModel.onTaskCheckedChanged(task, isChecked) } override fun onAttach(context: Context) { super.onAttach(context) childFragmentListener = context as ChildFragmentListener } override fun onPause() { super.onPause() Logger.i(TAG, "onPause", "TasksListFragment paused") } override fun onDestroyView() { super.onDestroyView() searchView.setOnQueryTextListener(null) } } TodayFragment.kt @ExperimentalCoroutinesApi @AndroidEntryPoint class TodayFragment : Fragment(R.layout.fragment_parent_today), TasksListFragment.ChildFragmentListener { private val viewModel: TodayViewModel by viewModels() private lateinit var binding: FragmentParentTodayBinding private var fabClicked: Boolean = false private lateinit var tasksListMenu: Menu private lateinit var viewPager: ViewPager2 private val rotateOpen: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.rotate_open_anim) } private val rotateClose: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.rotate_close_anim) } private val fromBottom: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.from_bottom_anim) } private val toBottom: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.to_bottom_anim) } private val fadeIn: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.fade_in) } private val fadeOut: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.fade_out) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentParentTodayBinding.bind(view) binding.apply { tasksListTransparentWhiteScreen.setOnClickListener { fabAnimationsRollBack(binding) fabClicked = !fabClicked } } setChildFragmentMenus() initViewPagerWithTabLayout(binding) todayDateDisplay(binding) initFabs(binding) loadTodayEventCollector() getFragmentResultListeners() } private fun setChildFragmentMenus(){ val tasksListFragment = TasksListFragment() tasksListFragment.setListener(this) Logger.i(TAG, "setChildFragmentMenus", "TasksListFragment menu set") } private fun getFragmentResultListeners() { setFragmentResultListener("add_edit_request"){_, bundle -> val result = bundle.getInt("add_edit_result") onFragmentResult(result) } setFragmentResultListener("create_set_request_2"){_, bundle -> val result = bundle.getInt("create_set_result_2") onFragmentResult(result) } setFragmentResultListener("task_added_to_set_request"){_, bundle -> val result = bundle.getInt("task_added_to_set_result") val message = bundle.getString("task_added_to_set_message") onFragmentResult(result, message) } setFragmentResultListener("task_added_from_set_request"){_, bundle -> val result = bundle.getInt("task_added_from_set_result") val message = bundle.getString("task_added_from_set_message") onFragmentResult(result, message) } } private fun onFragmentResult(result: Int, message: String? = ""){ viewModel.onFragmentResult(result, message) } /** * TodayViewModel.TodayEvent.NavigateToAddTaskScreen: Relevant to this class. Belongs to Fab which are all in this class. * TodayViewModel.TodayEvent.ShowTaskSavedConfirmationMessage: Relevant to this class. Belongs to onFragmentResultListener which is here. * TodayViewModel.TodayEvent.ShowTaskSavedInNewOrOldSetConfirmationMessage: Relevant to this class. Belongs to onFragmentResultListener which is here. * TodayViewModel.TodayEvent.ShowTaskAddedFromSetConfirmationMessage: Relevant to this class. Belongs to onFragmentResultListener which is here. * TodayViewModel.TodayEvent.NavigateToAddTasksFromSetBottomSheet: Relevant to this class. Belongs to Fab which are all in this class. */ private fun loadTodayEventCollector() { viewLifecycleOwner.lifecycleScope.launchWhenStarted { viewModel.todayEvent.collect { event -> when (event) { is TodayViewModel.TodayEvent.NavigateToAddTaskScreen -> { val action = TodayFragmentDirections .actionTodayFragmentToTaskAddEditFragment(task = null, title = "Add task" , taskinset = null, origin = 1) findNavController().navigate(action) } is TodayViewModel.TodayEvent.ShowTaskSavedConfirmationMessage -> { Snackbar.make(requireView(), event.msg, Snackbar.LENGTH_LONG).show() setViewPagerPage(0) } is TodayViewModel.TodayEvent.ShowTaskSavedInNewOrOldSetConfirmationMessage -> { Snackbar.make(requireView(), event.msg.toString(), Snackbar.LENGTH_LONG).show() } is TodayViewModel.TodayEvent.ShowTaskAddedFromSetConfirmationMessage -> { Snackbar.make(requireView(), event.msg.toString(), Snackbar.LENGTH_LONG).show() fabClicked = true setFabAnimationsAndViewStates(binding) setViewPagerPage(0) } is TodayViewModel.TodayEvent.NavigateToAddTasksFromSetBottomSheet -> { val action = TasksListFragmentDirections .actionGlobalSetBottomSheetDialogFragment(task = null, origin = 2) findNavController().navigate(action) } }.exhaustive } } } // This will soon be used to be 1 private fun setViewPagerPage(index: Int){ viewModel.postActionWithDelay(300, object: TodayViewModel.PostActionListener{ override fun onDelayFinished() { viewPager.setCurrentItem(index, true) } }) } private fun todayDateDisplay(binding: FragmentParentTodayBinding) { binding.apply { tasksListDateheader.apply { dateHeaderDayofmonth.text = viewModel.getCurrentDayOfMonth() dateHeaderMonth.text = viewModel.getCurrentMonth() dateHeaderYear.text = viewModel.getCurrentYear() dateHeaderDayofweek.text = viewModel.getCurrentDayOfWeek() } } } private fun initViewPagerWithTabLayout(binding: FragmentParentTodayBinding) { viewPager = binding.todayViewpager val tabLayout: TabLayout = binding.todayTablayout viewPager.adapter = activity?.let { TodayPagerAdapter(it) } Logger.i(TAG, "initViewPagerWithTabLayout", "viewPager is not null") TabLayoutMediator(tabLayout, viewPager) { tab, index -> tab.text = when (index) { 0 -> "Tasks" 1 -> "Journal" else -> throw Resources.NotFoundException("Tab not found at position") }.exhaustive when (index) { 0 -> { } 1 -> { fabClicked = false } } }.attach() } private fun initFabs(binding: FragmentParentTodayBinding) { binding.apply { tasksListFab.setOnClickListener { onMainFabClick(binding) } tasksListSubFab1.setOnClickListener { Logger.i(TAG, "initFabs", "Coming soon") } tasksListSubFab2.setOnClickListener { viewModel.onAddTasksFromSetClick() } tasksListSubFab3.setOnClickListener { viewModel.onAddNewTaskClick() } } } private fun onMainFabClick(binding: FragmentParentTodayBinding) { setFabAnimationsAndViewStates(binding) } private fun setFabAnimationsAndViewStates(binding: FragmentParentTodayBinding) { setFabAnimationVisibilityAndClickability(binding, fabClicked) fabClicked = !fabClicked } private fun setFabAnimationVisibilityAndClickability(binding: FragmentParentTodayBinding, clicked: Boolean) { if (!clicked) fabAnimationsRollIn(binding) else fabAnimationsRollBack(binding) } private fun fabAnimationsRollIn(binding: FragmentParentTodayBinding) { binding.apply { HGDAAnimationUtils.apply { HGDAViewStateUtils.apply { setViewAnimation(v1 = tasksListFab, a = rotateOpen) setViewAnimation(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3, a = fromBottom) setViewAnimation(v1 = tasksListSubFab1Tv, v2 = tasksListSubFab2Tv, v3 = tasksListSubFab3Tv, a = fromBottom) setViewAnimation(v1 = tasksListTransparentWhiteScreen, a = fadeIn) setViewVisibility(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3 , v4 = tasksListSubFab1Tv, v5 = tasksListSubFab2Tv, v6 = tasksListSubFab3Tv, visibility = View.VISIBLE) setViewVisibility(v1 = tasksListTransparentWhiteScreen, visibility = View.VISIBLE) setViewClickState(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3, clickable = true) setViewClickState(v1 = tasksListTransparentWhiteScreen, clickable = true) } } } } private fun fabAnimationsRollBack(binding: FragmentParentTodayBinding) { binding.apply { HGDAAnimationUtils.apply { HGDAViewStateUtils.apply { setViewAnimation(v1 = tasksListFab, a = rotateClose) setViewAnimation(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3, a = toBottom) setViewAnimation(v1 = tasksListSubFab1Tv, v2 = tasksListSubFab2Tv, v3 = tasksListSubFab3Tv, a = toBottom) setViewAnimation(v1 = tasksListTransparentWhiteScreen, a = fadeOut) setViewVisibility(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3 , v4 = tasksListSubFab1Tv, v5 = tasksListSubFab2Tv, v6 = tasksListSubFab3Tv, visibility = View.INVISIBLE) setViewVisibility(v1 = tasksListTransparentWhiteScreen, visibility = View.INVISIBLE) setViewClickState(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3, clickable = false) setViewClickState(v1 = tasksListTransparentWhiteScreen, clickable = false) } } } } override fun onFragmentChanged(menu: Menu) { tasksListMenu = menu } override fun onPause() { super.onPause() tasksListMenu.clear() } } A: Fragment is not a Context i.e fragment is not a child of context . So when you try to cast context as ChildFragmentListener you are actually casting your Activity to ChildFragmentListener which is giving you this RuntimeException . to make it work you can use childFragmentListener = parentFragment as ChildFragmentListener Also if your Doing this you do not setListener method anymore. On other hand i would suggest you do not use listeners to communicate b/w fragments . I see you already using viewModel so just use a shared one to communicate . You can get a shared ViewModel inside child by creating it with parentFragment.
MainActivity cannot be cast to interface error when implementing interface from child fragment in parent fragment
I have this app in which I have a parent fragment, which has 2 child fragments in a ViewPager2 object. One of the child fragments has an interface to communicate changes on its menu to the parent fragment. The child fragment in question is TasksListFragment.kt and the parent fragment is TodayFragment.kt When I try to initialize the interface in the child fragment onAttach() function, I get FATAL EXCEPTION: main Process: com.rajchenbergstudios.hoygenda, PID: java.lang.ClassCastException: com.rajchenbergstudios.hoygenda.ui.activity.MainActivity cannot be cast to com.rajchenbergstudios.hoygenda.ui.todaylists.taskslist.TasksListFragment$ChildFragmentListener I don't understand why I get this error, and it says MainActivity, when the parent is a fragment which is the one implementing the interface in the first place, not the MainActivity. I have everything set up correctly: I have an interface in the child fragment The interface is used on the child fragment onCreateMenu to pass the menu object to its interface function onFragmentMenuChanged(menu: Menu) I override the child fragment's onAttach() and initialize the interface: override fun onAttach(context: Context) { super.onAttach(context) childFragmentListener = context as ChildFragmentListener } I write a function called setListener() which is called from the parent fragment to pass its context this to the function parameter which assigns it to the childFragment listener fun setListener(listener: ChildFragmentListener) { this.childFragmentListener = listener } The parent fragment implements the child fragment listener as seen in the TodayFragment.kt file Can you tell me what am I doing wrong or how to implement an interface to effectively communicate from child fragment back to its parent fragment? TasksListFragment.kt @ExperimentalCoroutinesApi @AndroidEntryPoint class TasksListFragment : Fragment(R.layout.fragment_child_tasks_list), TasksListAdapter.OnItemClickListener { private val viewModel: TasksListViewModel by viewModels() private lateinit var searchView: SearchView private lateinit var childFragmentListener: ChildFragmentListener override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = FragmentChildTasksListBinding.bind(view) val tasksListAdapter = TasksListAdapter(this) binding.apply { tasksListRecyclerview.layoutTasksListRecyclerview.apply { adapter = tasksListAdapter layoutManager = LinearLayoutManager(requireContext()) setHasFixedSize(true) } ItemTouchHelper(object: ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT){ override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val task = tasksListAdapter.currentList[viewHolder.adapterPosition] viewModel.onTaskSwiped(task) } }).attachToRecyclerView(tasksListRecyclerview.layoutTasksListRecyclerview) } loadObservable(binding, tasksListAdapter) loadTasksEventCollector() loadMenu() } private fun loadObservable(binding: FragmentChildTasksListBinding, tasksListAdapter: TasksListAdapter) { viewModel.tasks.observe(viewLifecycleOwner){ tasksList -> binding.apply { HGDAViewStateUtils.apply { if (tasksList.isEmpty()) { setViewVisibility(tasksListRecyclerview.layoutTasksListRecyclerview, visibility = View.INVISIBLE) setViewVisibility(tasksListLayoutNoData.layoutNoDataLinearlayout, visibility = View.VISIBLE) } else { setViewVisibility(tasksListRecyclerview.layoutTasksListRecyclerview, visibility = View.VISIBLE) setViewVisibility(tasksListLayoutNoData.layoutNoDataLinearlayout, visibility = View.INVISIBLE) tasksListAdapter.submitList(tasksList) } } } } } /** * TasksListViewModel.TaskEvent.ShowUndoDeleteTaskMessage: Stays in this class. It asks for components relevant to this class. * TasksListViewModel.TaskEvent.NavigateToEditTaskScreen: Stays in this class. The method it overrides comes from task list adapter. * TasksListViewModel.TaskEvent.NavigateToDeleteAllCompletedScreen: Stays in this class. Relevant to menu which is in this class. * TasksListViewModel.TaskEvent.NavigateToDeleteAllScreen: Stays in this class. Relevant to menu which is in this class. */ private fun loadTasksEventCollector() { viewLifecycleOwner.lifecycleScope.launchWhenStarted { viewModel.tasksEvent.collect { event -> when (event) { is TasksListViewModel.TaskEvent.ShowUndoDeleteTaskMessage -> { Snackbar .make(requireView(), "Task deleted", Snackbar.LENGTH_LONG) .setAction("UNDO"){ viewModel.onUndoDeleteClick(event.task) } .show() } is TasksListViewModel.TaskEvent.NavigateToEditTaskScreen -> { val action = TodayFragmentDirections .actionTodayFragmentToTaskAddEditFragment(task = event.task, title = "Edit task", taskinset = null, origin = 1) findNavController().navigate(action) } is TasksListViewModel.TaskEvent.NavigateToAddTaskToSetBottomSheet -> { val action = TasksListFragmentDirections.actionGlobalSetBottomSheetDialogFragment(task = event.task, origin = 1) findNavController().navigate(action) } is TasksListViewModel.TaskEvent.NavigateToDeleteAllCompletedScreen -> { val action = TasksListFragmentDirections .actionGlobalTasksDeleteAllDialogFragment(origin = 1) findNavController().navigate(action) } is TasksListViewModel.TaskEvent.NavigateToDeleteAllScreen -> { val action = TasksListFragmentDirections .actionGlobalTasksDeleteAllDialogFragment(origin = 3) findNavController().navigate(action) } }.exhaustive } } } private fun loadMenu(){ val menuHost: MenuHost = requireActivity() menuHost.addMenuProvider(object: MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { childFragmentListener.onFragmentChanged(menu) menuInflater.inflate(R.menu.menu_tasks_list_fragment, menu) val searchItem = menu.findItem(R.id.tasks_list_menu_search) searchView = searchItem.actionView as SearchView val pendingQuery = viewModel.searchQuery.value if (pendingQuery != null && pendingQuery.isNotEmpty()) { searchItem.expandActionView() searchView.setQuery(pendingQuery, false) } searchView.OnQueryTextChanged{ searchQuery -> viewModel.searchQuery.value = searchQuery } viewLifecycleOwner.lifecycleScope.launchWhenStarted { menu.findItem(R.id.tasks_list_menu_hide_completed).isChecked = viewModel.preferencesFlow.first().hideCompleted } } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.tasks_list_menu_sort_by_date -> { viewModel.onSortOrderSelected(SortOrder.BY_DATE) true } R.id.tasks_list_menu_sort_by_name -> { viewModel.onSortOrderSelected(SortOrder.BY_NAME) true } R.id.tasks_list_menu_hide_completed -> { menuItem.isChecked = !menuItem.isChecked viewModel.onHideCompletedSelected(menuItem.isChecked) true } R.id.tasks_list_menu_delete_completed -> { viewModel.onDeleteAllCompletedClick() true } R.id.tasks_list_menu_delete_all -> { viewModel.onDeleteAllClick() true } else -> false } } }, viewLifecycleOwner, Lifecycle.State.RESUMED) } interface ChildFragmentListener { fun onFragmentChanged(menu: Menu) } fun setListener(listener: ChildFragmentListener) { this.childFragmentListener = listener } override fun onItemClick(task: Task) { viewModel.onTaskSelected(task) } override fun onItemLongClick(task: Task) { viewModel.onTaskLongSelected(task) } override fun onCheckboxClick(task: Task, isChecked: Boolean) { viewModel.onTaskCheckedChanged(task, isChecked) } override fun onAttach(context: Context) { super.onAttach(context) childFragmentListener = context as ChildFragmentListener } override fun onPause() { super.onPause() Logger.i(TAG, "onPause", "TasksListFragment paused") } override fun onDestroyView() { super.onDestroyView() searchView.setOnQueryTextListener(null) } } TodayFragment.kt @ExperimentalCoroutinesApi @AndroidEntryPoint class TodayFragment : Fragment(R.layout.fragment_parent_today), TasksListFragment.ChildFragmentListener { private val viewModel: TodayViewModel by viewModels() private lateinit var binding: FragmentParentTodayBinding private var fabClicked: Boolean = false private lateinit var tasksListMenu: Menu private lateinit var viewPager: ViewPager2 private val rotateOpen: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.rotate_open_anim) } private val rotateClose: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.rotate_close_anim) } private val fromBottom: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.from_bottom_anim) } private val toBottom: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.to_bottom_anim) } private val fadeIn: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.fade_in) } private val fadeOut: Animation by lazy { AnimationUtils.loadAnimation(requireContext(), R.anim.fade_out) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentParentTodayBinding.bind(view) binding.apply { tasksListTransparentWhiteScreen.setOnClickListener { fabAnimationsRollBack(binding) fabClicked = !fabClicked } } setChildFragmentMenus() initViewPagerWithTabLayout(binding) todayDateDisplay(binding) initFabs(binding) loadTodayEventCollector() getFragmentResultListeners() } private fun setChildFragmentMenus(){ val tasksListFragment = TasksListFragment() tasksListFragment.setListener(this) Logger.i(TAG, "setChildFragmentMenus", "TasksListFragment menu set") } private fun getFragmentResultListeners() { setFragmentResultListener("add_edit_request"){_, bundle -> val result = bundle.getInt("add_edit_result") onFragmentResult(result) } setFragmentResultListener("create_set_request_2"){_, bundle -> val result = bundle.getInt("create_set_result_2") onFragmentResult(result) } setFragmentResultListener("task_added_to_set_request"){_, bundle -> val result = bundle.getInt("task_added_to_set_result") val message = bundle.getString("task_added_to_set_message") onFragmentResult(result, message) } setFragmentResultListener("task_added_from_set_request"){_, bundle -> val result = bundle.getInt("task_added_from_set_result") val message = bundle.getString("task_added_from_set_message") onFragmentResult(result, message) } } private fun onFragmentResult(result: Int, message: String? = ""){ viewModel.onFragmentResult(result, message) } /** * TodayViewModel.TodayEvent.NavigateToAddTaskScreen: Relevant to this class. Belongs to Fab which are all in this class. * TodayViewModel.TodayEvent.ShowTaskSavedConfirmationMessage: Relevant to this class. Belongs to onFragmentResultListener which is here. * TodayViewModel.TodayEvent.ShowTaskSavedInNewOrOldSetConfirmationMessage: Relevant to this class. Belongs to onFragmentResultListener which is here. * TodayViewModel.TodayEvent.ShowTaskAddedFromSetConfirmationMessage: Relevant to this class. Belongs to onFragmentResultListener which is here. * TodayViewModel.TodayEvent.NavigateToAddTasksFromSetBottomSheet: Relevant to this class. Belongs to Fab which are all in this class. */ private fun loadTodayEventCollector() { viewLifecycleOwner.lifecycleScope.launchWhenStarted { viewModel.todayEvent.collect { event -> when (event) { is TodayViewModel.TodayEvent.NavigateToAddTaskScreen -> { val action = TodayFragmentDirections .actionTodayFragmentToTaskAddEditFragment(task = null, title = "Add task" , taskinset = null, origin = 1) findNavController().navigate(action) } is TodayViewModel.TodayEvent.ShowTaskSavedConfirmationMessage -> { Snackbar.make(requireView(), event.msg, Snackbar.LENGTH_LONG).show() setViewPagerPage(0) } is TodayViewModel.TodayEvent.ShowTaskSavedInNewOrOldSetConfirmationMessage -> { Snackbar.make(requireView(), event.msg.toString(), Snackbar.LENGTH_LONG).show() } is TodayViewModel.TodayEvent.ShowTaskAddedFromSetConfirmationMessage -> { Snackbar.make(requireView(), event.msg.toString(), Snackbar.LENGTH_LONG).show() fabClicked = true setFabAnimationsAndViewStates(binding) setViewPagerPage(0) } is TodayViewModel.TodayEvent.NavigateToAddTasksFromSetBottomSheet -> { val action = TasksListFragmentDirections .actionGlobalSetBottomSheetDialogFragment(task = null, origin = 2) findNavController().navigate(action) } }.exhaustive } } } // This will soon be used to be 1 private fun setViewPagerPage(index: Int){ viewModel.postActionWithDelay(300, object: TodayViewModel.PostActionListener{ override fun onDelayFinished() { viewPager.setCurrentItem(index, true) } }) } private fun todayDateDisplay(binding: FragmentParentTodayBinding) { binding.apply { tasksListDateheader.apply { dateHeaderDayofmonth.text = viewModel.getCurrentDayOfMonth() dateHeaderMonth.text = viewModel.getCurrentMonth() dateHeaderYear.text = viewModel.getCurrentYear() dateHeaderDayofweek.text = viewModel.getCurrentDayOfWeek() } } } private fun initViewPagerWithTabLayout(binding: FragmentParentTodayBinding) { viewPager = binding.todayViewpager val tabLayout: TabLayout = binding.todayTablayout viewPager.adapter = activity?.let { TodayPagerAdapter(it) } Logger.i(TAG, "initViewPagerWithTabLayout", "viewPager is not null") TabLayoutMediator(tabLayout, viewPager) { tab, index -> tab.text = when (index) { 0 -> "Tasks" 1 -> "Journal" else -> throw Resources.NotFoundException("Tab not found at position") }.exhaustive when (index) { 0 -> { } 1 -> { fabClicked = false } } }.attach() } private fun initFabs(binding: FragmentParentTodayBinding) { binding.apply { tasksListFab.setOnClickListener { onMainFabClick(binding) } tasksListSubFab1.setOnClickListener { Logger.i(TAG, "initFabs", "Coming soon") } tasksListSubFab2.setOnClickListener { viewModel.onAddTasksFromSetClick() } tasksListSubFab3.setOnClickListener { viewModel.onAddNewTaskClick() } } } private fun onMainFabClick(binding: FragmentParentTodayBinding) { setFabAnimationsAndViewStates(binding) } private fun setFabAnimationsAndViewStates(binding: FragmentParentTodayBinding) { setFabAnimationVisibilityAndClickability(binding, fabClicked) fabClicked = !fabClicked } private fun setFabAnimationVisibilityAndClickability(binding: FragmentParentTodayBinding, clicked: Boolean) { if (!clicked) fabAnimationsRollIn(binding) else fabAnimationsRollBack(binding) } private fun fabAnimationsRollIn(binding: FragmentParentTodayBinding) { binding.apply { HGDAAnimationUtils.apply { HGDAViewStateUtils.apply { setViewAnimation(v1 = tasksListFab, a = rotateOpen) setViewAnimation(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3, a = fromBottom) setViewAnimation(v1 = tasksListSubFab1Tv, v2 = tasksListSubFab2Tv, v3 = tasksListSubFab3Tv, a = fromBottom) setViewAnimation(v1 = tasksListTransparentWhiteScreen, a = fadeIn) setViewVisibility(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3 , v4 = tasksListSubFab1Tv, v5 = tasksListSubFab2Tv, v6 = tasksListSubFab3Tv, visibility = View.VISIBLE) setViewVisibility(v1 = tasksListTransparentWhiteScreen, visibility = View.VISIBLE) setViewClickState(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3, clickable = true) setViewClickState(v1 = tasksListTransparentWhiteScreen, clickable = true) } } } } private fun fabAnimationsRollBack(binding: FragmentParentTodayBinding) { binding.apply { HGDAAnimationUtils.apply { HGDAViewStateUtils.apply { setViewAnimation(v1 = tasksListFab, a = rotateClose) setViewAnimation(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3, a = toBottom) setViewAnimation(v1 = tasksListSubFab1Tv, v2 = tasksListSubFab2Tv, v3 = tasksListSubFab3Tv, a = toBottom) setViewAnimation(v1 = tasksListTransparentWhiteScreen, a = fadeOut) setViewVisibility(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3 , v4 = tasksListSubFab1Tv, v5 = tasksListSubFab2Tv, v6 = tasksListSubFab3Tv, visibility = View.INVISIBLE) setViewVisibility(v1 = tasksListTransparentWhiteScreen, visibility = View.INVISIBLE) setViewClickState(v1 = tasksListSubFab1, v2 = tasksListSubFab2, v3 = tasksListSubFab3, clickable = false) setViewClickState(v1 = tasksListTransparentWhiteScreen, clickable = false) } } } } override fun onFragmentChanged(menu: Menu) { tasksListMenu = menu } override fun onPause() { super.onPause() tasksListMenu.clear() } }
[ "Fragment is not a Context i.e fragment is not a child of context .\nSo when you try to cast context as ChildFragmentListener you are actually casting your Activity to ChildFragmentListener which is giving you this RuntimeException . to make it work you can use childFragmentListener = parentFragment as ChildFragmentListener\nAlso if your Doing this you do not setListener method anymore.\nOn other hand i would suggest you do not use listeners to communicate b/w fragments . I see you already using viewModel so just use a shared one to communicate . You can get a shared ViewModel inside child by creating it with parentFragment.\n" ]
[ 1 ]
[]
[]
[ "android", "android_fragments", "interface", "kotlin" ]
stackoverflow_0074673512_android_android_fragments_interface_kotlin.txt
Q: Close menù when I click on navlink I have this problem. When I click on menù link, the page scroll but the menù remain open. This is my code-pen link (For some reason, codepen don't read che css color link, but don't worry about it) Js suggestions? I have just tried with on click function, but don't work. Thank you every body can help me! [Link Codepen][MyCodepen] .nav-link{ font-weight: 300; } .text-menu{ font-weight: 200; } .navbar-toggler{ border: none; } .offcanvas-header{ background-color: #0c0c0c; padding-left: 2.5rem; color: #eab736; } .offcanvas-body{ background-color: #0c0c0c; } .nav-link{ font-size: 1.3rem; color: white; padding-left: 2rem; } .nav-link:hover{ font-size: 1.3rem; color: rgba(255, 255, 255, 0.20); padding-left: 2rem; } .text-menu{ font-size: 0.7rem; color: rgba(255, 255, 255, 0.20); padding-left: 2rem; } .icon-white{ color: white; font-size: 2rem; } .header-nav__social { padding-top: 3rem; list-style: none; display: inline-block; margin: 0; font-size: 1.2rem; } .header-nav__social li { margin-right: 12px; padding-left: 0; display: inline-block; } .header-nav__social li a { color: rgba(255, 255, 255, 0.20); } .header-nav__social li a:hover, .header-nav__social li a:focus { color: white; transition: all 0.5s; } .header-nav__social li:last-child { margin: 0; } <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Example</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> </head> <body> <nav class="navbar fixed-top" id="mainNav"> <div class="container-fluid"> <a class="navbar-brand text-black js-scroll-trigger" href="#home">Brand name</a> <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar"> <i class="bi bi-list icon-black"></i> </button> <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNavbar" aria-labelledby="offcanvasNavbarLabel"> <div class="offcanvas-header"> <p class="offcanvas-title" id="offcanvasNavbarLabel">Menù</p> <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close" ></button> </div> <div class="offcanvas-body"> <ul class="navbar-nav justify-content-end flex-grow-1 pe-3 text-white"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#home">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#about">About</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#works">Gallery</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#contacts">Contacts</a> </li> <p class="text-menu mt-5">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam minima beatae, repudiandae voluptatibus in suscipit dicta, facere consequuntur.</p> </ul> <ul class="header-nav__social"> <li> <a href="#"><i class="bi bi-facebook"></i></a> </li> <li> <a href="#"><i class="bi bi-twitter"></i></a> </li> <li> <a href="#"><i class="bi bi-instagram"></i></a> </li> <li> <a href="#"><i class="bi bi-behance"></i></a> </li> </ul> </div> </div> </div> </nav> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script> </body> </html> ]1 A: .nav-link{ font-weight: 300; } .text-menu{ font-weight: 200; } .navbar-toggler{ border: none; } .offcanvas-header{ background-color: #0c0c0c; padding-left: 2.5rem; color: #eab736; } .offcanvas-body{ background-color: #0c0c0c; } .nav-link{ font-size: 1.3rem; color: white; padding-left: 2rem; } .nav-link:hover{ font-size: 1.3rem; color: rgba(255, 255, 255, 0.20); padding-left: 2rem; } .text-menu{ font-size: 0.7rem; color: rgba(255, 255, 255, 0.20); padding-left: 2rem; } .icon-white{ color: white; font-size: 2rem; } .header-nav__social { padding-top: 3rem; list-style: none; display: inline-block; margin: 0; font-size: 1.2rem; } .header-nav__social li { margin-right: 12px; padding-left: 0; display: inline-block; } .header-nav__social li a { color: rgba(255, 255, 255, 0.20); } .header-nav__social li a:hover, .header-nav__social li a:focus { color: white; transition: all 0.5s; } .header-nav__social li:last-child { margin: 0; } <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Example</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> </head> <body> <nav class="navbar fixed-top" id="mainNav"> <div class="container-fluid"> <a class="navbar-brand text-black js-scroll-trigger" href="#home">Brand name</a> <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar"> <i class="bi bi-list icon-black"></i> </button> <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNavbar" aria-labelledby="offcanvasNavbarLabel"> <div class="offcanvas-header"> <p class="offcanvas-title" id="offcanvasNavbarLabel">Menù</p> <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close" ></button> </div> <div class="offcanvas-body"> <ul class="navbar-nav justify-content-end flex-grow-1 pe-3 text-white"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#home" data-bs-dismiss="offcanvas" aria-label="Close" data-bs-dismiss="offcanvas" aria-label="Close">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#about" data-bs-dismiss="offcanvas" aria-label="Close">About</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#works" data-bs-dismiss="offcanvas" aria-label="Close">Gallery</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#contacts" data-bs-dismiss="offcanvas" aria-label="Close">Contacts</a> </li> <p class="text-menu mt-5">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam minima beatae, repudiandae voluptatibus in suscipit dicta, facere consequuntur.</p> </ul> <ul class="header-nav__social"> <li> <a href="#"><i class="bi bi-facebook"></i></a> </li> <li> <a href="#"><i class="bi bi-twitter"></i></a> </li> <li> <a href="#"><i class="bi bi-instagram"></i></a> </li> <li> <a href="#"><i class="bi bi-behance"></i></a> </li> </ul> </div> </div> </div> </nav> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script> </body> </html> A: Please add this js $(document).ready(function(){ $('a.nav-link').click(function(){ $('#offcanvasNavbar').removeClass('show'); $('.offcanvas-backdrop').removeClass('show'); }); });
Close menù when I click on navlink
I have this problem. When I click on menù link, the page scroll but the menù remain open. This is my code-pen link (For some reason, codepen don't read che css color link, but don't worry about it) Js suggestions? I have just tried with on click function, but don't work. Thank you every body can help me! [Link Codepen][MyCodepen] .nav-link{ font-weight: 300; } .text-menu{ font-weight: 200; } .navbar-toggler{ border: none; } .offcanvas-header{ background-color: #0c0c0c; padding-left: 2.5rem; color: #eab736; } .offcanvas-body{ background-color: #0c0c0c; } .nav-link{ font-size: 1.3rem; color: white; padding-left: 2rem; } .nav-link:hover{ font-size: 1.3rem; color: rgba(255, 255, 255, 0.20); padding-left: 2rem; } .text-menu{ font-size: 0.7rem; color: rgba(255, 255, 255, 0.20); padding-left: 2rem; } .icon-white{ color: white; font-size: 2rem; } .header-nav__social { padding-top: 3rem; list-style: none; display: inline-block; margin: 0; font-size: 1.2rem; } .header-nav__social li { margin-right: 12px; padding-left: 0; display: inline-block; } .header-nav__social li a { color: rgba(255, 255, 255, 0.20); } .header-nav__social li a:hover, .header-nav__social li a:focus { color: white; transition: all 0.5s; } .header-nav__social li:last-child { margin: 0; } <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Example</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> </head> <body> <nav class="navbar fixed-top" id="mainNav"> <div class="container-fluid"> <a class="navbar-brand text-black js-scroll-trigger" href="#home">Brand name</a> <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar"> <i class="bi bi-list icon-black"></i> </button> <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNavbar" aria-labelledby="offcanvasNavbarLabel"> <div class="offcanvas-header"> <p class="offcanvas-title" id="offcanvasNavbarLabel">Menù</p> <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close" ></button> </div> <div class="offcanvas-body"> <ul class="navbar-nav justify-content-end flex-grow-1 pe-3 text-white"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#home">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#about">About</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#works">Gallery</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#contacts">Contacts</a> </li> <p class="text-menu mt-5">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam minima beatae, repudiandae voluptatibus in suscipit dicta, facere consequuntur.</p> </ul> <ul class="header-nav__social"> <li> <a href="#"><i class="bi bi-facebook"></i></a> </li> <li> <a href="#"><i class="bi bi-twitter"></i></a> </li> <li> <a href="#"><i class="bi bi-instagram"></i></a> </li> <li> <a href="#"><i class="bi bi-behance"></i></a> </li> </ul> </div> </div> </div> </nav> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script> </body> </html> ]1
[ "\n\n.nav-link{\n font-weight: 300;\n}\n.text-menu{\n font-weight: 200;\n}\n.navbar-toggler{\n border: none;\n}\n\n.offcanvas-header{\n background-color: #0c0c0c;\n padding-left: 2.5rem;\n color: #eab736;\n \n}\n.offcanvas-body{\n background-color: #0c0c0c;\n}\n.nav-link{\n font-size: 1.3rem;\n color: white;\n padding-left: 2rem;\n}\n.nav-link:hover{\n font-size: 1.3rem;\n color: rgba(255, 255, 255, 0.20);\n padding-left: 2rem;\n}\n.text-menu{\n font-size: 0.7rem;\n color: rgba(255, 255, 255, 0.20);\n padding-left: 2rem;\n}\n.icon-white{\n color: white;\n font-size: 2rem;\n}\n.header-nav__social {\n padding-top: 3rem;\n list-style: none;\n display: inline-block;\n margin: 0;\n font-size: 1.2rem;\n}\n\n.header-nav__social li {\n margin-right: 12px;\n padding-left: 0;\n display: inline-block;\n}\n\n.header-nav__social li a {\n color: rgba(255, 255, 255, 0.20);\n}\n\n.header-nav__social li a:hover,\n.header-nav__social li a:focus {\n color: white;\n transition: all 0.5s;\n}\n\n.header-nav__social li:last-child {\n margin: 0;\n}\n<html>\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n<title>Example</title>\n\n\n <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\">\n\n <link href=\"https://getbootstrap.com/docs/5.2/assets/css/docs.css\" rel=\"stylesheet\">\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css\">\n</head>\n\n<body>\n<nav class=\"navbar fixed-top\" id=\"mainNav\">\n <div class=\"container-fluid\">\n <a class=\"navbar-brand text-black js-scroll-trigger\" href=\"#home\">Brand name</a>\n <button class=\"navbar-toggler\" type=\"button\" data-bs-toggle=\"offcanvas\" data-bs-target=\"#offcanvasNavbar\" aria-controls=\"offcanvasNavbar\">\n <i class=\"bi bi-list icon-black\"></i>\n </button>\n <div class=\"offcanvas offcanvas-end\" tabindex=\"-1\" id=\"offcanvasNavbar\" aria-labelledby=\"offcanvasNavbarLabel\">\n <div class=\"offcanvas-header\">\n <p class=\"offcanvas-title\" id=\"offcanvasNavbarLabel\">Menù</p>\n <button type=\"button\" class=\"btn-close btn-close-white\" data-bs-dismiss=\"offcanvas\" aria-label=\"Close\" ></button>\n </div>\n <div class=\"offcanvas-body\">\n \n <ul class=\"navbar-nav justify-content-end flex-grow-1 pe-3 text-white\">\n <li class=\"nav-item\">\n <a class=\"nav-link js-scroll-trigger\" href=\"#home\" data-bs-dismiss=\"offcanvas\" aria-label=\"Close\" data-bs-dismiss=\"offcanvas\" aria-label=\"Close\">Home</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link js-scroll-trigger\" href=\"#about\" data-bs-dismiss=\"offcanvas\" aria-label=\"Close\">About</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link js-scroll-trigger\" href=\"#works\" data-bs-dismiss=\"offcanvas\" aria-label=\"Close\">Gallery</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link js-scroll-trigger\" href=\"#contacts\" data-bs-dismiss=\"offcanvas\" aria-label=\"Close\">Contacts</a>\n </li>\n \n <p class=\"text-menu mt-5\">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam minima beatae, repudiandae voluptatibus in suscipit dicta, facere consequuntur.</p>\n \n \n </ul>\n \n <ul class=\"header-nav__social\">\n <li>\n <a href=\"#\"><i class=\"bi bi-facebook\"></i></a>\n </li>\n <li>\n <a href=\"#\"><i class=\"bi bi-twitter\"></i></a>\n </li>\n <li>\n <a href=\"#\"><i class=\"bi bi-instagram\"></i></a>\n </li>\n <li>\n <a href=\"#\"><i class=\"bi bi-behance\"></i></a>\n </li>\n </ul>\n </div>\n </div>\n </div>\n</nav>\n \n \n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js\"></script> \n </body>\n</html>\n\n\n\n", "Please add this js\n$(document).ready(function(){\n $('a.nav-link').click(function(){\n $('#offcanvasNavbar').removeClass('show');\n $('.offcanvas-backdrop').removeClass('show');\n });\n});\n\n" ]
[ 0, 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074668687_javascript.txt
Q: In the same function separating code into y/n from the user and taking steps based on that without if/else? I made a sample below to help explain. The problem with an if/else clause is that it makes the variables local so i can't assign a returned value under if: when the user enters 'y' and use it across the bounds of else: -See the value return_from_add and the two places I want to use it. I want to obey running my code sequentially and simply have the user enter a 'n' instead of a 'y' to run a further down piece of code. I don't know how without an if/else statement maybe somebody else has figured out something similar before and then you would understand my frustration in even wording the question appropriately. Because what else comes to mind other than **if **i want to do this **else ** do this for a yes no question. def run_main_prgm_2(): while True: other = 'Invalid Response' no = 'n' yes = 'y' y_n = input('Would you like to add a new person to the address book? y/n \n - ') if y_n == 'y': return_from_add = add_person() return yes elif y_n = 'n': search_full_name1 = input("Type in a fullname for indexing\n- ") index_person(return_from_add,search_full_name1) return no else: return other If you're having trouble understanding my question look at where return_from_add is being used in two places where it's not possible because the if elif makes it local even under the same function. Which is why I included a def at the top to illustrate that this is all under the same function. Now how can i pull this off with local variables under the same function I've tried messing with while loops. Basically it would be cool in programming if there was something that said skip x number of lines and run this instead when the user enters a specific key. A: There is a syntax error in the code. In the second if statement, the 'y_n' variable is compared to the string 'y' using a single equal sign '=' instead of a double equal sign '=='. This will cause a syntax error, as the single equal sign is used to assign a value to a variable, while the double equal sign is used to compare two values.
In the same function separating code into y/n from the user and taking steps based on that without if/else?
I made a sample below to help explain. The problem with an if/else clause is that it makes the variables local so i can't assign a returned value under if: when the user enters 'y' and use it across the bounds of else: -See the value return_from_add and the two places I want to use it. I want to obey running my code sequentially and simply have the user enter a 'n' instead of a 'y' to run a further down piece of code. I don't know how without an if/else statement maybe somebody else has figured out something similar before and then you would understand my frustration in even wording the question appropriately. Because what else comes to mind other than **if **i want to do this **else ** do this for a yes no question. def run_main_prgm_2(): while True: other = 'Invalid Response' no = 'n' yes = 'y' y_n = input('Would you like to add a new person to the address book? y/n \n - ') if y_n == 'y': return_from_add = add_person() return yes elif y_n = 'n': search_full_name1 = input("Type in a fullname for indexing\n- ") index_person(return_from_add,search_full_name1) return no else: return other If you're having trouble understanding my question look at where return_from_add is being used in two places where it's not possible because the if elif makes it local even under the same function. Which is why I included a def at the top to illustrate that this is all under the same function. Now how can i pull this off with local variables under the same function I've tried messing with while loops. Basically it would be cool in programming if there was something that said skip x number of lines and run this instead when the user enters a specific key.
[ "There is a syntax error in the code. In the second if statement, the 'y_n' variable is compared to the string 'y' using a single equal sign '=' instead of a double equal sign '=='. This will cause a syntax error, as the single equal sign is used to assign a value to a variable, while the double equal sign is used to compare two values.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074673507_python_python_3.x.txt
Q: How to count len of strings in a list without built-in function? How can I create a function count_word in order to get the result like this: x = ['Hello', 'Bye'] print(count_word(x)) # Result must be [5, 3] without using len(x[index]) or any built-in function? A: Since you're not allowed to use built-in functions, you have to iterate over each string in the list and over all characters of each word as well. Also you have to memorize the current length of each word and reset the counter if the next word is taken. This is done by re-assigning the counter value to 0 (length = 0) before the next inner iteration will be started: def count_word(x): result = [] for word in x: length = 0 for char in word: length += 1 result.append(length) return result Please note that this is probably the no-brainer par excellence. However, Python offers some interesting other approaches to solve this problem. Here are some other interesting examples, which of course need to be adapted. While this should answer your questions, I would like to add some notes about performance and why it is better to use built-in functions: Generally spoken, built-in functions are doing the iteration under the hood for you or are even faster by e.g. simply getting the array’s length from the CPython list head structure (emphasis mine): How are lists implemented in CPython? CPython’s lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array’s length in a list head structure. This makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index. When items are appended or inserted, the array of references is resized. Some cleverness is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don’t require an actual resize. (Credits also to Ken Y-N, see How does len(array) work under the hood) Generally, it is better to use built-in functions whenever you can, because you seldom can beat the performance of the underlying implementation (e.g. for C-based Python installations): def count_word_2(x): return [len(word) for word in x] You can see that if you time the two given functions: In [1]: from timeit import timeit In [2]: statement = 'count_word(["Hello", "Bye"])' In [3]: count_word_1 = """ ...: def count_word(x): ...: result = [] ...: for word in x: ...: length = 0 ...: for char in word: ...: length += 1 ...: result.append(length) ...: return result ...: """ In [4]: count_word_2 = """ ...: def count_word(x): ...: return [len(word) for word in x] ...: """ In [5]: timeit(stmt=statement, setup=count_word_1, number=10000000) Out[5]: 4.744415309000033 In [6]: timeit(stmt=statement, setup=count_word_2, number=10000000) Out[6]: 2.7576589090022026 If also a little bit of cheating is allowed (using string dunder method __len()__ instead of built-in function len()), you can get some performance back (credits to HeapOverflow): In [7]: count_word_3 = """ ...: def count_word(x): ...: return [word.__len__() for word in x] ...: """ In [8]: timeit(stmt=statement, setup=count_word_3, number=10000000) Out[8]: 3.313732603997778 So a good rule of thumb is: Do whatever you can with built-in functions. They are more readable and faster. A: x = ['Hello', 'Bye'] results = [] for single_string in x: string_length = 0 for i in single_string: string_length += 1 results.append(string_length) print(results) A: x = ['Hello', 'Bye'] def count(x): i=0 for j in x:i+=1 return i print(list(map(count, x))) A: Another possibility using inline assignment (Python >= 3.8) def count(word): c = 0 return [[_ for _ in word if (c := c+1)], c][1] words = ['Hello', 'How are you', 'Bye!'] >>> [count(w) for w in words] [5, 11, 4] Or even passing c as an input argument (defaulted to 0) could be used as an accumulated result from previous counts: def count(word, c=0): return [[_ for _ in word if (c := c+1)], c][1] ctot = [0] [ctot.append(count(w, ctot[-1])) for w in words] # sort of equivalent to built-in 'reduce' >>> ctot # or ctot[1:] to ignore the first zero [0, 5, 16, 20]
How to count len of strings in a list without built-in function?
How can I create a function count_word in order to get the result like this: x = ['Hello', 'Bye'] print(count_word(x)) # Result must be [5, 3] without using len(x[index]) or any built-in function?
[ "Since you're not allowed to use built-in functions, you have to iterate over each string in the list and over all characters of each word as well. Also you have to memorize the current length of each word and reset the counter if the next word is taken. This is done by re-assigning the counter value to 0 (length = 0) before the next inner iteration will be started:\ndef count_word(x):\n result = []\n for word in x:\n length = 0\n for char in word:\n length += 1\n result.append(length)\n return result\n\nPlease note that this is probably the no-brainer par excellence. However, Python offers some interesting other approaches to solve this problem. Here are some other interesting examples, which of course need to be adapted.\n\nWhile this should answer your questions, I would like to add some notes about performance and why it is better to use built-in functions:\nGenerally spoken, built-in functions are doing the iteration under the hood for you or are even faster by e.g. simply getting the array’s length from the CPython list head structure (emphasis mine):\n\nHow are lists implemented in CPython?\nCPython’s lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array’s length in a list head structure.\nThis makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index.\nWhen items are appended or inserted, the array of references is resized. Some cleverness is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don’t require an actual resize.\n\n(Credits also to Ken Y-N, see How does len(array) work under the hood)\nGenerally, it is better to use built-in functions whenever you can, because you seldom can beat the performance of the underlying implementation (e.g. for C-based Python installations):\ndef count_word_2(x):\n return [len(word) for word in x]\n\nYou can see that if you time the two given functions:\nIn [1]: from timeit import timeit\n\nIn [2]: statement = 'count_word([\"Hello\", \"Bye\"])'\n\nIn [3]: count_word_1 = \"\"\"\n ...: def count_word(x):\n ...: result = []\n ...: for word in x:\n ...: length = 0\n ...: for char in word:\n ...: length += 1\n ...: result.append(length)\n ...: return result\n ...: \"\"\"\n\nIn [4]: count_word_2 = \"\"\"\n ...: def count_word(x):\n ...: return [len(word) for word in x]\n ...: \"\"\"\n\nIn [5]: timeit(stmt=statement, setup=count_word_1, number=10000000)\nOut[5]: 4.744415309000033\n\nIn [6]: timeit(stmt=statement, setup=count_word_2, number=10000000)\nOut[6]: 2.7576589090022026\n\nIf also a little bit of cheating is allowed (using string dunder method __len()__ instead of built-in function len()), you can get some performance back (credits to HeapOverflow):\nIn [7]: count_word_3 = \"\"\"\n...: def count_word(x):\n...: return [word.__len__() for word in x]\n...: \"\"\"\n\nIn [8]: timeit(stmt=statement, setup=count_word_3, number=10000000)\nOut[8]: 3.313732603997778\n\nSo a good rule of thumb is: Do whatever you can with built-in functions. They are more readable and faster.\n", "x = ['Hello', 'Bye']\nresults = []\nfor single_string in x:\n string_length = 0\n for i in single_string: string_length += 1\n results.append(string_length)\nprint(results)\n\n", "x = ['Hello', 'Bye']\ndef count(x):\n i=0\n for j in x:i+=1\n return i\nprint(list(map(count, x)))\n\n", "Another possibility using inline assignment (Python >= 3.8)\ndef count(word):\n c = 0\n return [[_ for _ in word if (c := c+1)], c][1]\n\nwords = ['Hello', 'How are you', 'Bye!']\n\n>>> [count(w) for w in words]\n[5, 11, 4]\n\nOr even passing c as an input argument (defaulted to 0) could be used as an accumulated result from previous counts:\ndef count(word, c=0):\n return [[_ for _ in word if (c := c+1)], c][1]\n\nctot = [0]\n[ctot.append(count(w, ctot[-1])) for w in words] # sort of equivalent to built-in 'reduce'\n\n>>> ctot # or ctot[1:] to ignore the first zero\n[0, 5, 16, 20]\n\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0060767809_python.txt
Q: Use leaflet with VueJS3 leads to an error I'm trying to display interactive maps in my VueJS3 app. I found a code that works: <template> <div id="mapContainer"></div> </template> <script> import 'leaflet/dist/leaflet.css'; import L from 'leaflet'; export default { name: 'LeafletMap', data() { return { map: null, }; }, mounted() { this.map = L.map('mapContainer').setView([46.05, 11.05], 5); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors', }).addTo(this.map); //use a mix of renderers var customPane = this.map.createPane('customPane'); var canvasRenderer = L.canvas({ pane: 'customPane' }); customPane.style.zIndex = 399; // put just behind the standard overlay pane which is at 400 L.marker([50, 14]).addTo(this.map); L.marker([53, 20]).addTo(this.map); L.marker([49.5, 19.5]).addTo(this.map); L.marker([49, 25]).addTo(this.map); L.marker([-10, 25]).addTo(this.map); L.marker([10, -25]).addTo(this.map); L.marker([0, 0]).addTo(this.map); }, onBeforeUnmount() { if (this.map) { this.map.remove(); } }, }; </script> <style scoped> #mapContainer { width: 100vw; height: 100vh; } </style> But as soon as I import a custom geoJSON, like this: import France from '@/assets/carto/France.geojson'; I have this in my console: [Vue Router warn]: uncaught error during route navigation: vue-router.mjs:35:17 SyntaxError: unexpected token: ':' vue-router.mjs:3451:20 [Vue Router warn]: Unexpected error when starting the router: SyntaxError: unexpected token: ':' Uncaught (in promise) SyntaxError: unexpected token: ':'France.geojson:2:8 What is wrong? By the way, France.geoJSON is a classic geoJSON file: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [5.829184048326689, 45.93827339383888], ... ] ] }, "properties": { "dep": "01", "reg": "84", "libgeo": "Ain" } }, ... A: Actually if I write import France from '@/assets/carto/france.json'; After having changed the name of the file, it works. I still don't know why the extension matters.
Use leaflet with VueJS3 leads to an error
I'm trying to display interactive maps in my VueJS3 app. I found a code that works: <template> <div id="mapContainer"></div> </template> <script> import 'leaflet/dist/leaflet.css'; import L from 'leaflet'; export default { name: 'LeafletMap', data() { return { map: null, }; }, mounted() { this.map = L.map('mapContainer').setView([46.05, 11.05], 5); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors', }).addTo(this.map); //use a mix of renderers var customPane = this.map.createPane('customPane'); var canvasRenderer = L.canvas({ pane: 'customPane' }); customPane.style.zIndex = 399; // put just behind the standard overlay pane which is at 400 L.marker([50, 14]).addTo(this.map); L.marker([53, 20]).addTo(this.map); L.marker([49.5, 19.5]).addTo(this.map); L.marker([49, 25]).addTo(this.map); L.marker([-10, 25]).addTo(this.map); L.marker([10, -25]).addTo(this.map); L.marker([0, 0]).addTo(this.map); }, onBeforeUnmount() { if (this.map) { this.map.remove(); } }, }; </script> <style scoped> #mapContainer { width: 100vw; height: 100vh; } </style> But as soon as I import a custom geoJSON, like this: import France from '@/assets/carto/France.geojson'; I have this in my console: [Vue Router warn]: uncaught error during route navigation: vue-router.mjs:35:17 SyntaxError: unexpected token: ':' vue-router.mjs:3451:20 [Vue Router warn]: Unexpected error when starting the router: SyntaxError: unexpected token: ':' Uncaught (in promise) SyntaxError: unexpected token: ':'France.geojson:2:8 What is wrong? By the way, France.geoJSON is a classic geoJSON file: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [5.829184048326689, 45.93827339383888], ... ] ] }, "properties": { "dep": "01", "reg": "84", "libgeo": "Ain" } }, ...
[ "Actually if I write\nimport France from '@/assets/carto/france.json';\n\nAfter having changed the name of the file, it works.\nI still don't know why the extension matters.\n" ]
[ 0 ]
[]
[]
[ "leaflet", "vue.js", "vuejs3" ]
stackoverflow_0074671315_leaflet_vue.js_vuejs3.txt
Q: Gradle Shadow Plugin .jar not running on Docker container, no main manifest attribute I built a fat jar using the Gradle Shadow Plugin like so: tasks { "build" { dependsOn(shadowJar) } shadowJar { mergeServiceFiles { var path = "META-INF/" } manifest.inheritFrom(jar.get().manifest) manifest.attributes["Main-Class"] = "some.main.class.Main" manifest.attributes["Implementation-Version"] = version } } This works with no problem when I do gradle build and then java -jar fat_jar_name.jar, I have tested in MacOS, Windows and Ubuntu (WSL). The same command works exactly the same on all those platforms, even if the .jar was not locally built, but for some reason it is not working in Docker with eclipse-temurin. I am trying to run a .jar file within Docker using: FROM eclipse-temurin:17 ARG JAR_FILE=build/libs/*jar COPY ${JAR_FILE} fat_jar_name-all.jar ENTRYPOINT java -jar fat_jar_name.jar I build the image using docker image build -t image_name ., and then I am trying to run it using docker run -d -p 8080:8080 image_name. I get this error when running: no main manifest attribute, in fat_jar_name-all.jar I found that this issue is related to not having a META-INF\MANIFEST.MF file in the exported .jar. However, the fat_jar_name.jar does contain a manifest file with these contents: Manifest-Version: 1.0 Main-Class: some.main.class.Main Implementation-Version: 3.9.1-SNAPSHOT Is there something I'm missing at the Docker, Gradle or Shadow Plugin level to make this work? I found this resource for the Shadow Plugin about configuring the manifest, but it makes no mention of a main manifest attribute. A: I found that the COPY command I was using was broken. I used this one instead: FROM eclipse-temurin:17 COPY build/libs/fat_jar_name-all.jar / ENTRYPOINT java -jar fat_jar_name-all.jar
Gradle Shadow Plugin .jar not running on Docker container, no main manifest attribute
I built a fat jar using the Gradle Shadow Plugin like so: tasks { "build" { dependsOn(shadowJar) } shadowJar { mergeServiceFiles { var path = "META-INF/" } manifest.inheritFrom(jar.get().manifest) manifest.attributes["Main-Class"] = "some.main.class.Main" manifest.attributes["Implementation-Version"] = version } } This works with no problem when I do gradle build and then java -jar fat_jar_name.jar, I have tested in MacOS, Windows and Ubuntu (WSL). The same command works exactly the same on all those platforms, even if the .jar was not locally built, but for some reason it is not working in Docker with eclipse-temurin. I am trying to run a .jar file within Docker using: FROM eclipse-temurin:17 ARG JAR_FILE=build/libs/*jar COPY ${JAR_FILE} fat_jar_name-all.jar ENTRYPOINT java -jar fat_jar_name.jar I build the image using docker image build -t image_name ., and then I am trying to run it using docker run -d -p 8080:8080 image_name. I get this error when running: no main manifest attribute, in fat_jar_name-all.jar I found that this issue is related to not having a META-INF\MANIFEST.MF file in the exported .jar. However, the fat_jar_name.jar does contain a manifest file with these contents: Manifest-Version: 1.0 Main-Class: some.main.class.Main Implementation-Version: 3.9.1-SNAPSHOT Is there something I'm missing at the Docker, Gradle or Shadow Plugin level to make this work? I found this resource for the Shadow Plugin about configuring the manifest, but it makes no mention of a main manifest attribute.
[ "I found that the COPY command I was using was broken. I used this one instead:\nFROM eclipse-temurin:17\nCOPY build/libs/fat_jar_name-all.jar /\nENTRYPOINT java -jar fat_jar_name-all.jar\n\n" ]
[ 0 ]
[]
[]
[ "docker", "fatjar", "gradle", "java" ]
stackoverflow_0074673460_docker_fatjar_gradle_java.txt
Q: Accessing a Pandas index like a regular column I have a Pandas DataFrame with a named index. I want to pass it off to a piece off code that takes a DataFrame, a column name, and some other stuff, and does a bunch of work involving that column. Only in this case the column I want to highlight is the index, but giving the index's label to this piece of code doesn't work because you can't extract an index like you can a regular column. For example, I can construct a DataFrame like this: import pandas as pd, numpy as np df=pd.DataFrame({'name':map(chr, range(97, 102)), 'id':range(10000,10005), 'value':np.random.randn(5)}) df.set_index('name', inplace=True) Here's the result: id value name a 10000 0.659710 b 10001 1.001821 c 10002 -0.197576 d 10003 -0.569181 e 10004 -0.882097 Now how am I allowed to go about accessing the name column? print(df.index) # No problem print(df['name']) # KeyError: u'name' I know there are workaround like duplicating the column or changing the index to something else. But is there something cleaner, like some form of column access that treats the index the same way as everything else? A: Index has a special meaning in Pandas. It's used to optimise specific operations and can be used in various methods such as merging / joining data. Therefore, make a choice: If it's "just another column", use reset_index and treat it as another column. If it's genuinely used for indexing, keep it as an index and use df.index. We can't make this choice for you. It should be dependent on the structure of your underlying data and on how you intend to analyse your data. For more information on use of a dataframe index, see: What is the performance impact of non-unique indexes in pandas? What is the point of indexing in pandas? A: You could also use df.index.get_level_values if you need to access a (index) column by name. It also works with hierarchical indices (MultiIndex). >>> df.index.get_level_values('name') Index(['a', 'b', 'c', 'd', 'e'], dtype='object', name='name') A: Instead of using reset_index, you could just copy the index to a normal column, do some work and then drop the column, for example: df['tmp'] = df.index # do stuff based on df['tmp'] del df['tmp'] A: df.reset_index(inplace=True) print(df.head()) Try this
Accessing a Pandas index like a regular column
I have a Pandas DataFrame with a named index. I want to pass it off to a piece off code that takes a DataFrame, a column name, and some other stuff, and does a bunch of work involving that column. Only in this case the column I want to highlight is the index, but giving the index's label to this piece of code doesn't work because you can't extract an index like you can a regular column. For example, I can construct a DataFrame like this: import pandas as pd, numpy as np df=pd.DataFrame({'name':map(chr, range(97, 102)), 'id':range(10000,10005), 'value':np.random.randn(5)}) df.set_index('name', inplace=True) Here's the result: id value name a 10000 0.659710 b 10001 1.001821 c 10002 -0.197576 d 10003 -0.569181 e 10004 -0.882097 Now how am I allowed to go about accessing the name column? print(df.index) # No problem print(df['name']) # KeyError: u'name' I know there are workaround like duplicating the column or changing the index to something else. But is there something cleaner, like some form of column access that treats the index the same way as everything else?
[ "Index has a special meaning in Pandas. It's used to optimise specific operations and can be used in various methods such as merging / joining data. Therefore, make a choice:\n\nIf it's \"just another column\", use reset_index and treat it as another column.\nIf it's genuinely used for indexing, keep it as an index and use df.index.\n\nWe can't make this choice for you. It should be dependent on the structure of your underlying data and on how you intend to analyse your data.\nFor more information on use of a dataframe index, see:\n\nWhat is the performance impact of non-unique indexes in pandas?\nWhat is the point of indexing in pandas?\n\n", "You could also use df.index.get_level_values if you need to access a (index) column by name. It also works with hierarchical indices (MultiIndex).\n>>> df.index.get_level_values('name')\nIndex(['a', 'b', 'c', 'd', 'e'], dtype='object', name='name')\n\n", "Instead of using reset_index, you could just copy the index to a normal column, do some work and then drop the column, for example:\ndf['tmp'] = df.index\n# do stuff based on df['tmp']\ndel df['tmp']\n\n", "df.reset_index(inplace=True)\nprint(df.head())\nTry this\n" ]
[ 23, 13, 6, 0 ]
[]
[]
[ "dataframe", "indexing", "pandas", "python", "series" ]
stackoverflow_0052139506_dataframe_indexing_pandas_python_series.txt
Q: configtxgen is not finding organization with -printOrg option fabric & fabric-ca version 2.4.7 1.5.5 In /root/demo/fabric-samples/test-network/configtx/configtx.yaml - &Org1 # DefaultOrg defines the organization which is used in the sampleconfig # of the fabric.git development environment Name: Org1MSP # ID to load the MSP definition as ID: Org1MSP MSPDir: ../organizations/peerOrganizations/org1.example.com/msp # Policies defines the set of policies at this level of the config tree # For organization policies, their canonical path is usually # /Channel/<Application|Orderer>/<OrgName>/<PolicyName> Policies: Readers: Type: Signature Rule: "OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')" Writers: Type: Signature Rule: "OR('Org1MSP.admin', 'Org1MSP.client')" Admins: Type: Signature Rule: "OR('Org1MSP.admin')" Endorsement: Type: Signature Rule: "OR('Org1MSP.peer')" run configtxgen -printOrg Org1 root@BCN1N108450:~/demo/fabric-samples# export FABRIC_CFG_PATH=$PWD/test-network/configtx/ root@BCN1N108450:~/demo/fabric-samples# configtxgen -printOrg Org1 2022-12-02 14:22:14.071 CET 0001 INFO [common.tools.configtxgen] main -> Loading configuration 2022-12-02 14:22:14.086 CET 0002 INFO [common.tools.configtxgen.localconfig] completeInitialization -> orderer type: etcdraft 2022-12-02 14:22:14.086 CET 0003 INFO [common.tools.configtxgen.localconfig] completeInitialization -> Orderer.EtcdRaft.Options unset, setting to tick_interval:"500ms" election_tick:10 heartbeat_tick:1 max_inflight_blocks:5 snapshot_interval_size:16777216 2022-12-02 14:22:14.086 CET 0004 INFO [common.tools.configtxgen.localconfig] LoadTopLevel -> Loaded configuration: /root/demo/fabric-samples/test-network/configtx/configtx.yaml 2022-12-02 14:22:14.086 CET 0005 FATA [common.tools.configtxgen] main -> Error on printOrg: organization Org1 not found root@BCN1N108450:~/demo/fabric-samples# I keep finding errors. what am I doing wrong? A: - &Org1 # DefaultOrg defines the organization which is used in the sampleconfig # of the fabric.git development environment Name: Org1MSP # ID to load the MSP definition as ID: Org1MSP MSPDir: ../organizations/peerOrganizations/org1.example.com/msp # Policies defines the set of policies at this level of the config tree # For organization policies, their canonical path is usually # /Channel/<Application|Orderer>/<OrgName>/<PolicyName> Policies: Readers: Type: Signature Rule: "OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')" Writers: Type: Signature Rule: "OR('Org1MSP.admin', 'Org1MSP.client')" Admins: Type: Signature Rule: "OR('Org1MSP.admin')" Endorsement: Type: Signature Rule: "OR('Org1MSP.peer')" The Org1 is a reference name of the configuration section related to the definition of the organization, while running confitxgen you need to reference it by actual organization ID, which in your case is Org1MSP: configtxgen -printOrg Org1MSP
configtxgen is not finding organization with -printOrg option
fabric & fabric-ca version 2.4.7 1.5.5 In /root/demo/fabric-samples/test-network/configtx/configtx.yaml - &Org1 # DefaultOrg defines the organization which is used in the sampleconfig # of the fabric.git development environment Name: Org1MSP # ID to load the MSP definition as ID: Org1MSP MSPDir: ../organizations/peerOrganizations/org1.example.com/msp # Policies defines the set of policies at this level of the config tree # For organization policies, their canonical path is usually # /Channel/<Application|Orderer>/<OrgName>/<PolicyName> Policies: Readers: Type: Signature Rule: "OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')" Writers: Type: Signature Rule: "OR('Org1MSP.admin', 'Org1MSP.client')" Admins: Type: Signature Rule: "OR('Org1MSP.admin')" Endorsement: Type: Signature Rule: "OR('Org1MSP.peer')" run configtxgen -printOrg Org1 root@BCN1N108450:~/demo/fabric-samples# export FABRIC_CFG_PATH=$PWD/test-network/configtx/ root@BCN1N108450:~/demo/fabric-samples# configtxgen -printOrg Org1 2022-12-02 14:22:14.071 CET 0001 INFO [common.tools.configtxgen] main -> Loading configuration 2022-12-02 14:22:14.086 CET 0002 INFO [common.tools.configtxgen.localconfig] completeInitialization -> orderer type: etcdraft 2022-12-02 14:22:14.086 CET 0003 INFO [common.tools.configtxgen.localconfig] completeInitialization -> Orderer.EtcdRaft.Options unset, setting to tick_interval:"500ms" election_tick:10 heartbeat_tick:1 max_inflight_blocks:5 snapshot_interval_size:16777216 2022-12-02 14:22:14.086 CET 0004 INFO [common.tools.configtxgen.localconfig] LoadTopLevel -> Loaded configuration: /root/demo/fabric-samples/test-network/configtx/configtx.yaml 2022-12-02 14:22:14.086 CET 0005 FATA [common.tools.configtxgen] main -> Error on printOrg: organization Org1 not found root@BCN1N108450:~/demo/fabric-samples# I keep finding errors. what am I doing wrong?
[ "- &Org1\n # DefaultOrg defines the organization which is used in the sampleconfig\n # of the fabric.git development environment\n Name: Org1MSP\n\n # ID to load the MSP definition as\n ID: Org1MSP\n\n MSPDir: ../organizations/peerOrganizations/org1.example.com/msp\n\n # Policies defines the set of policies at this level of the config tree\n # For organization policies, their canonical path is usually\n # /Channel/<Application|Orderer>/<OrgName>/<PolicyName>\n Policies:\n Readers:\n Type: Signature\n Rule: \"OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')\"\n Writers:\n Type: Signature\n Rule: \"OR('Org1MSP.admin', 'Org1MSP.client')\"\n Admins:\n Type: Signature\n Rule: \"OR('Org1MSP.admin')\"\n Endorsement:\n Type: Signature\n Rule: \"OR('Org1MSP.peer')\"\n\nThe Org1 is a reference name of the configuration section related to the definition of the organization, while running confitxgen you need to reference it by actual organization ID, which in your case is Org1MSP:\nconfigtxgen -printOrg Org1MSP\n\n" ]
[ 0 ]
[]
[]
[ "hyperledger", "hyperledger_fabric" ]
stackoverflow_0074656628_hyperledger_hyperledger_fabric.txt
Q: Create Object model with Dynamic Name and Properties JavaScript I am new in javascript/typescript & figuring out a way to create a dynamic named object & obj properties in typescript based on the filter type like below Number type Filter Properties : { "filterType": "", "type": "", "filter":'', "filterTo":'' } Text type Filter Properties : { "filterType": "", "type": "", "filter": "" } Date type Filter Properties : { "dateFrom": "", "dateTo": "", "filterType": "", "type": "" } Based on the filter type selected I want to create object with particular filter type properties like below "filterModel": { "OriginDate": { <--------------- this column name I will be getting at runtime which i want to be the object name "dateFrom": "2022-09-21 00:00:00", > "dateTo": "2022-09-21 00:00:00", > "filterType": "date", > properties i want to set based on filter type "type": "inRange" > }, "Score": { <--------------- this column name I will be getting at runtime which i want to be the object name "filterType": "number", > "type": "inRange", > "filter": 0, > properties i want to set based on filter type "filterTo": 90 > }, "Title": { <--------------- this column name I will be getting at runtime which i want to be the object name "filterType": "text", > "type": "contains", > properties i want to set based on filter type "filter": "wire" > } } Assuming the Inputs I will be getting for generating this object will be generateFilterModel(columnName : string ,filterType : any ,filtervalues: any[]) { // logic -> generating the object and adding it to filterModel {} } For Removing all the filters I will be having a button to set filterModel {} as empty Final Expected Output : For Input -> this.generateFilterModel('OriginDate','Date',filtervalues[]) // (columnName, Filtertype , filtervalues) Output : "OriginDate": { "dateFrom": "2022-09-21 00:00:00", "dateTo": "2022-09-21 00:00:00", "filterType": "date", "type": "inRange" } For Input -> this.generateFilterModel('Score','number',filtervalues[]) // (columnName, Filtertype , filtervalues) Output : "Score": { "filterType": "number", "type": "inRange", "filter": 0, "filterTo": 90 } For Input -> this.generateFilterModel('Title','text',filtervalues[]) // (columnName, Filtertype ,filtervalues) Output : "Title": { "filterType": "text", "type": "contains", "filter": "wire" } A: Basic way: You should defined the interfaces of the filters first: type FilterType = "number" | "text" | "date" interface FilterBase { filterType: FilterType type: string } interface NumberFilter extends FilterBase { filterType: "number" filter: string filterTo: string } interface TextFilter extends FilterBase { filterType: "text" filter: string } interface DateFilter extends FilterBase { filterType: "date" dateFrom: "" dateTo: "" } type Filter = NumberFilter | TextFilter | DateFilter then apply to your function function generateFilterModel(columnName: string, filterType: FilterType, filtervalues: any[]): Record<string, Filter> { // do what you want here } in this case, the return type will become Record<string, Filter> which is wide but fit most of the usage already. Some advanced ways: if the type need to be more correct like columnName must be known in the type, it can be: function generateFilterModel<T extends string>(columnName: T, filterType: FilterType, filtervalues: any[]): Record<T, Filter> { // do what you want here } moreover, if the type of Filter must be more accurate, you will need do defined a map first: interface FilterMap { number: NumberFilter text: TextFilter date: DateFilter } and the function will be: function generateFilterModel<T extends string, U extends FilterType>(columnName: T, filterType: U, filtervalues: any[]): Record<T, FilterMap[U]> { // do what you want here }
Create Object model with Dynamic Name and Properties JavaScript
I am new in javascript/typescript & figuring out a way to create a dynamic named object & obj properties in typescript based on the filter type like below Number type Filter Properties : { "filterType": "", "type": "", "filter":'', "filterTo":'' } Text type Filter Properties : { "filterType": "", "type": "", "filter": "" } Date type Filter Properties : { "dateFrom": "", "dateTo": "", "filterType": "", "type": "" } Based on the filter type selected I want to create object with particular filter type properties like below "filterModel": { "OriginDate": { <--------------- this column name I will be getting at runtime which i want to be the object name "dateFrom": "2022-09-21 00:00:00", > "dateTo": "2022-09-21 00:00:00", > "filterType": "date", > properties i want to set based on filter type "type": "inRange" > }, "Score": { <--------------- this column name I will be getting at runtime which i want to be the object name "filterType": "number", > "type": "inRange", > "filter": 0, > properties i want to set based on filter type "filterTo": 90 > }, "Title": { <--------------- this column name I will be getting at runtime which i want to be the object name "filterType": "text", > "type": "contains", > properties i want to set based on filter type "filter": "wire" > } } Assuming the Inputs I will be getting for generating this object will be generateFilterModel(columnName : string ,filterType : any ,filtervalues: any[]) { // logic -> generating the object and adding it to filterModel {} } For Removing all the filters I will be having a button to set filterModel {} as empty Final Expected Output : For Input -> this.generateFilterModel('OriginDate','Date',filtervalues[]) // (columnName, Filtertype , filtervalues) Output : "OriginDate": { "dateFrom": "2022-09-21 00:00:00", "dateTo": "2022-09-21 00:00:00", "filterType": "date", "type": "inRange" } For Input -> this.generateFilterModel('Score','number',filtervalues[]) // (columnName, Filtertype , filtervalues) Output : "Score": { "filterType": "number", "type": "inRange", "filter": 0, "filterTo": 90 } For Input -> this.generateFilterModel('Title','text',filtervalues[]) // (columnName, Filtertype ,filtervalues) Output : "Title": { "filterType": "text", "type": "contains", "filter": "wire" }
[ "Basic way:\nYou should defined the interfaces of the filters first:\ntype FilterType = \"number\" | \"text\" | \"date\"\n\ninterface FilterBase {\n filterType: FilterType\n type: string\n}\n\ninterface NumberFilter extends FilterBase {\n filterType: \"number\"\n filter: string\n filterTo: string\n}\n\ninterface TextFilter extends FilterBase {\n filterType: \"text\"\n filter: string\n}\n\ninterface DateFilter extends FilterBase {\n filterType: \"date\"\n dateFrom: \"\"\n dateTo: \"\"\n}\n\ntype Filter = NumberFilter | TextFilter | DateFilter\n\nthen apply to your function\nfunction generateFilterModel(columnName: string, filterType: FilterType, filtervalues: any[]): Record<string, Filter> {\n // do what you want here\n}\n\nin this case, the return type will become Record<string, Filter> which is wide but fit most of the usage already.\nSome advanced ways:\nif the type need to be more correct like columnName must be known in the type, it can be:\nfunction generateFilterModel<T extends string>(columnName: T, filterType: FilterType, filtervalues: any[]): Record<T, Filter> {\n // do what you want here\n}\n\nmoreover, if the type of Filter must be more accurate, you will need do defined a map first:\ninterface FilterMap {\n number: NumberFilter\n text: TextFilter\n date: DateFilter\n}\n\nand the function will be:\nfunction generateFilterModel<T extends string, U extends FilterType>(columnName: T, filterType: U, filtervalues: any[]): Record<T, FilterMap[U]> {\n // do what you want here\n}\n\n" ]
[ 0 ]
[]
[]
[ "angular", "javascript", "javascript_objects", "reactjs", "typescript" ]
stackoverflow_0074632247_angular_javascript_javascript_objects_reactjs_typescript.txt
Q: Flutter: Widget state not changing base on constructor variable after first build My goal is to have a list of checkbox cards on my PageView.builder. For that, I make a stateful widget that I can call on the PageView and loop it to make a list and change the state of the checkbox to be checked or not checked based on the constructor that it has, cause it will be checked based on data that I gave later on. My expectation I just need to call the checkbox cards widget on the PageView builder, loop it based on the data that I give, and it will change the state base on data in the constructor and I change the state with the gesture detector. It works well, but only on the first PageView that got loaded first, and the state of checkbox cards somehow got dragged to every page that PageView.builder has. To put it simply every checkbox card on every page of PageView.builder has the same state as the first page after it gets built. I have tried using after layout and widget binding in initstate, but it seems my implementation doesn't work. Then, I tried to move the variable that determined whether the checkbox is checked or not checked to build method based on the constructor value and now I have different checked items on every pageview, but I can't update the UI. Here is the code for checkbox card import 'package:flutter/material.dart'; class MakananCard extends StatefulWidget { final int status; final String name; const MakananCard({ Key? key, this.status = 2, this.name = '', }) : super(key: key); @override State<MakananCard> createState() => _MakananCardState(); } class _MakananCardState extends State<MakananCard> { // Variable state Color? _checkColor; IconData? _checkIcon; bool? checked; void createState() { if (widget.status == 2) { _checkColor = Colors.blue; _checkIcon = Icons.crop_square_outlined; checked = false; } else { _checkColor = Colors.green; _checkIcon = Icons.check_circle; checked = true; } } @override void initState() { super.initState(); createState(); // <= Can use setstate, but doesn't change on every page } @override Widget build(BuildContext context) { // createState(); <= Change on every page, but can't use setstate return Container( decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular(9), ), ), child: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ const Text(${widget.name}), GestureDetector( child: Padding( padding: const EdgeInsets.all(8.0), child: Icon( _checkIcon, color: _checkColor, size: 30, ), ), onTap: () async { setState(() => checked = !checked!); if (checked!) { setState(() { _checkColor = Colors.green; _checkIcon = Icons.check_circle; }); } else { setState(() { _checkColor = Colors.blue; _checkIcon = Icons.crop_square_outlined; }); } }, ), ], ), ), ); } } What I know in debugging: The constructor variable still gets call, cause widget.name change base on current data Initstate still runs on every page change Best regards. ======== Edit 1 Found the root cause of the problem. Actually, the problem is coming from how I implement PageView.builder and onpagechange. onpagechange for some reason gets called multiple times and calls old data (again) before the new data. Because of the behavior of initstate that runs only one time after build, my checkbox card has the state of old data, and at the same time displays the new data. here is the article that I found: in pageview:- sometime itemBuilder called 2-3 times when swipe PageView.builder itemBuilder being called 3 times for every page change All that article above unfortunately doesn't have a solid answer. I will just stop here for self-debugging and cut my app feature until I find the solution. A: You need to update your view after updating status like this: void createState() { if (widget.status == 2) { _checkColor = Colors.blue; _checkIcon = Icons.crop_square_outlined; checked = false; } else { _checkColor = Colors.green; _checkIcon = Icons.check_circle; checked = true; } setState(() {}); } then call it in initState, also remember don't call it inside build method, because its gonna change your checked to default value every time you rebuild the view. also change your onTap to this: onTap: () async { checked = !checked!; if (checked!) { _checkColor = Colors.green; _checkIcon = Icons.check_circle; } else { _checkColor = Colors.blue; _checkIcon = Icons.crop_square_outlined; } setState(() {); },
Flutter: Widget state not changing base on constructor variable after first build
My goal is to have a list of checkbox cards on my PageView.builder. For that, I make a stateful widget that I can call on the PageView and loop it to make a list and change the state of the checkbox to be checked or not checked based on the constructor that it has, cause it will be checked based on data that I gave later on. My expectation I just need to call the checkbox cards widget on the PageView builder, loop it based on the data that I give, and it will change the state base on data in the constructor and I change the state with the gesture detector. It works well, but only on the first PageView that got loaded first, and the state of checkbox cards somehow got dragged to every page that PageView.builder has. To put it simply every checkbox card on every page of PageView.builder has the same state as the first page after it gets built. I have tried using after layout and widget binding in initstate, but it seems my implementation doesn't work. Then, I tried to move the variable that determined whether the checkbox is checked or not checked to build method based on the constructor value and now I have different checked items on every pageview, but I can't update the UI. Here is the code for checkbox card import 'package:flutter/material.dart'; class MakananCard extends StatefulWidget { final int status; final String name; const MakananCard({ Key? key, this.status = 2, this.name = '', }) : super(key: key); @override State<MakananCard> createState() => _MakananCardState(); } class _MakananCardState extends State<MakananCard> { // Variable state Color? _checkColor; IconData? _checkIcon; bool? checked; void createState() { if (widget.status == 2) { _checkColor = Colors.blue; _checkIcon = Icons.crop_square_outlined; checked = false; } else { _checkColor = Colors.green; _checkIcon = Icons.check_circle; checked = true; } } @override void initState() { super.initState(); createState(); // <= Can use setstate, but doesn't change on every page } @override Widget build(BuildContext context) { // createState(); <= Change on every page, but can't use setstate return Container( decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular(9), ), ), child: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ const Text(${widget.name}), GestureDetector( child: Padding( padding: const EdgeInsets.all(8.0), child: Icon( _checkIcon, color: _checkColor, size: 30, ), ), onTap: () async { setState(() => checked = !checked!); if (checked!) { setState(() { _checkColor = Colors.green; _checkIcon = Icons.check_circle; }); } else { setState(() { _checkColor = Colors.blue; _checkIcon = Icons.crop_square_outlined; }); } }, ), ], ), ), ); } } What I know in debugging: The constructor variable still gets call, cause widget.name change base on current data Initstate still runs on every page change Best regards. ======== Edit 1 Found the root cause of the problem. Actually, the problem is coming from how I implement PageView.builder and onpagechange. onpagechange for some reason gets called multiple times and calls old data (again) before the new data. Because of the behavior of initstate that runs only one time after build, my checkbox card has the state of old data, and at the same time displays the new data. here is the article that I found: in pageview:- sometime itemBuilder called 2-3 times when swipe PageView.builder itemBuilder being called 3 times for every page change All that article above unfortunately doesn't have a solid answer. I will just stop here for self-debugging and cut my app feature until I find the solution.
[ "You need to update your view after updating status like this:\nvoid createState() {\n if (widget.status == 2) {\n _checkColor = Colors.blue;\n _checkIcon = Icons.crop_square_outlined;\n checked = false;\n } else {\n _checkColor = Colors.green;\n _checkIcon = Icons.check_circle;\n checked = true;\n }\n setState(() {});\n }\n\nthen call it in initState, also remember don't call it inside build method, because its gonna change your checked to default value every time you rebuild the view.\nalso change your onTap to this:\nonTap: () async {\n checked = !checked!;\n \n if (checked!) {\n _checkColor = Colors.green;\n _checkIcon = Icons.check_circle;\n } else {\n _checkColor = Colors.blue;\n _checkIcon = Icons.crop_square_outlined;\n }\n setState(() {);\n },\n\n" ]
[ 0 ]
[]
[]
[ "flutter", "flutter_futurebuilder", "flutter_pageview", "flutter_state" ]
stackoverflow_0074673531_flutter_flutter_futurebuilder_flutter_pageview_flutter_state.txt
Q: List of integers to pairs of tuples I have a list of integers like this numbers = [1, 5, 7, 19, 22, 55] I want to have a function that takes this as input and gives me a list of paired tuples that should contain the numbers as (1,5), (5,7), (7,19) and so on. Kindly suggest. I have tried using for loops. Didn't get expected output. A: From Python 3.10 you can use itertools.pairwise from itertools import pairwise numbers = [1, 5, 7, 19, 22, 55] list(pairwise(numbers)) # [(1, 5), (5, 7), (7, 19), (19, 22), (22, 55)] A: lst = [(numbers[i],numbers[i+1]) for i in range(0,len(numbers)-1)] This should do the trick: loop over all elements in the list numbers. You loop until the one to last element, since otherwise you would walk out of the array (get an index error).
List of integers to pairs of tuples
I have a list of integers like this numbers = [1, 5, 7, 19, 22, 55] I want to have a function that takes this as input and gives me a list of paired tuples that should contain the numbers as (1,5), (5,7), (7,19) and so on. Kindly suggest. I have tried using for loops. Didn't get expected output.
[ "From Python 3.10 you can use itertools.pairwise\nfrom itertools import pairwise\n\nnumbers = [1, 5, 7, 19, 22, 55]\nlist(pairwise(numbers)) # [(1, 5), (5, 7), (7, 19), (19, 22), (22, 55)]\n\n", "lst = [(numbers[i],numbers[i+1]) for i in range(0,len(numbers)-1)]\n\nThis should do the trick: loop over all elements in the list numbers. You loop until the one to last element, since otherwise you would walk out of the array (get an index error).\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074673571_python.txt
Q: How to conditionally set ::after sass rule in a react app hope your weekends are going great! I am just trying to figure out how I can conditionally set the &::after {} rule. Please see below to what I mean: @import "../global/parts"; .nav__item { position: relative; @include _minWidthMedium { text-transform: uppercase; } &::after { content: ""; position: absolute; background-color: $orange; bottom: -3px; transform: scaleX(0); transition: transform 460ms ease-out; transform-origin: right; perspective: 1000px; backface-visibility: hidden; pointer-events: none; z-index: 70; } &:hover, &.nav__item_active { &::after { transform: scaleX(1); transform-origin: left; } } } As you can see, in the first &::after rule, I am setting the background color to orange that renders an orange underline after hover. However, there are multiple places where this nav__item is being used and I would like to keep the code dry. What I am trying to do is have background-color set to 'none' if the link is a main CTA, rather than just a regular nav item. Is there any way to do this? I have tried to search relevant topics on this but couldn't find anything. A: To conditionally set the background-color property for the ::after pseudo-element, you can use the @if or @else directives provided by Sass. Here is an example of how you could use these directives to set the background-color based on whether the nav__item is a main CTA or not: @import "../global/parts"; .nav__item { position: relative; @include _minWidthMedium { text-transform: uppercase; } &::after { content: ""; position: absolute; @if $main-cta { background-color: none; } @else { background-color: $orange; } bottom: -3px; transform: scaleX(0); transition: transform 460ms ease-out; transform-origin: right; perspective: 1000px; backface-visibility: hidden; pointer-events: none; z-index: 70; } &:hover, &.nav__item_active { &::after { transform: scaleX(1); transform-origin: left; } } } In this example, the background-color will be set to none if the $main-cta variable is true, and to $orange if the $main-cta variable is false. You can set the value of the $main-cta variable when you include the nav__item class in your HTML code, for example: <div class="nav__item" $main-cta: true>...</div>
How to conditionally set ::after sass rule in a react app
hope your weekends are going great! I am just trying to figure out how I can conditionally set the &::after {} rule. Please see below to what I mean: @import "../global/parts"; .nav__item { position: relative; @include _minWidthMedium { text-transform: uppercase; } &::after { content: ""; position: absolute; background-color: $orange; bottom: -3px; transform: scaleX(0); transition: transform 460ms ease-out; transform-origin: right; perspective: 1000px; backface-visibility: hidden; pointer-events: none; z-index: 70; } &:hover, &.nav__item_active { &::after { transform: scaleX(1); transform-origin: left; } } } As you can see, in the first &::after rule, I am setting the background color to orange that renders an orange underline after hover. However, there are multiple places where this nav__item is being used and I would like to keep the code dry. What I am trying to do is have background-color set to 'none' if the link is a main CTA, rather than just a regular nav item. Is there any way to do this? I have tried to search relevant topics on this but couldn't find anything.
[ "To conditionally set the background-color property for the ::after pseudo-element, you can use the @if or @else directives provided by Sass.\nHere is an example of how you could use these directives to set the background-color based on whether the nav__item is a main CTA or not:\n@import \"../global/parts\";\n.nav__item {\n position: relative;\n @include _minWidthMedium {\n text-transform: uppercase;\n }\n &::after {\n content: \"\";\n position: absolute;\n @if $main-cta {\n background-color: none;\n } @else {\n background-color: $orange;\n }\n bottom: -3px;\n transform: scaleX(0);\n transition: transform 460ms ease-out;\n transform-origin: right;\n perspective: 1000px;\n backface-visibility: hidden;\n pointer-events: none;\n z-index: 70;\n }\n &:hover,\n &.nav__item_active {\n &::after {\n transform: scaleX(1);\n transform-origin: left;\n }\n }\n}\n\nIn this example, the background-color will be set to none if the $main-cta variable is true, and to $orange if the $main-cta variable is false. You can set the value of the $main-cta variable when you include the nav__item class in your HTML code, for example:\n<div class=\"nav__item\" $main-cta: true>...</div>\n\n\n" ]
[ 0 ]
[]
[]
[ "css", "javascript", "reactjs", "sass" ]
stackoverflow_0074672794_css_javascript_reactjs_sass.txt
Q: Get Decile of Values and # of records between deciles Presto SQL I have a table that looks like this User ID Income 1 4.00 2 5.00 1 7.00 3 10.00 4 80.00 1 40.00 5 7.00 6 4.00 I need a Presto SQL query that breaks the range of "Income" {eg.4.00-80.00} up into deciles irrespective of frequency of that "Income" value. I also need the # of unique "User ID" that falls beneath that decile (eg. 10th percentile -> X users, 20th percentile Y users). A: You can calculate the decile for each user-income, and then join the cte with itself (to account for the repeated users, since count distinct over() is not allowed in Presto). WITH user_deciles_cte AS( SELECT user_id, NTILE(10) OVER (ORDER BY income) AS deciles FROM table ), join_users_and_deciles_cte AS( SELECT DISTINCT dec.deciles, users.user_id FROM user_deciles_cte dec LEFT JOIN user_deciles_cte users ON users.deciles <= dec.deciles ) SELECT deciles, COUNT(DISTINCT user_id) AS users FROM join_users_and_deciles_cte GROUP BY 1 ORDER BY 1 ASC
Get Decile of Values and # of records between deciles Presto SQL
I have a table that looks like this User ID Income 1 4.00 2 5.00 1 7.00 3 10.00 4 80.00 1 40.00 5 7.00 6 4.00 I need a Presto SQL query that breaks the range of "Income" {eg.4.00-80.00} up into deciles irrespective of frequency of that "Income" value. I also need the # of unique "User ID" that falls beneath that decile (eg. 10th percentile -> X users, 20th percentile Y users).
[ "You can calculate the decile for each user-income, and then join the cte with itself (to account for the repeated users, since count distinct over() is not allowed in Presto).\nWITH user_deciles_cte AS(\n SELECT user_id,\n NTILE(10) OVER (ORDER BY income) AS deciles\n FROM table\n),\njoin_users_and_deciles_cte AS(\n SELECT DISTINCT dec.deciles,\n users.user_id\n FROM user_deciles_cte dec\n LEFT JOIN user_deciles_cte users\n ON users.deciles <= dec.deciles\n)\nSELECT deciles,\n COUNT(DISTINCT user_id) AS users\nFROM join_users_and_deciles_cte\nGROUP BY 1\nORDER BY 1 ASC\n\n" ]
[ 0 ]
[]
[]
[ "presto", "sql" ]
stackoverflow_0074672415_presto_sql.txt
Q: I can't print hello world in visual studio code I created a folder named " Python Trial ", and a folder within it named test and within that folder i created a file named test.py I installed the python extension and tried to print " Hello World! " however it keeps on giving me this command: C:/Users/saram/AppData/Local/Microsoft/WindowsApps/python3.10.exe "c:/Users/saram/Documents/Python Trial/test/test.py" -bash: C:/Users/saram/AppData/Local/Microsoft/WindowsApps/python3.10.exe: No such file or directory I don't know what to do I tried reinstalling visual studio code and the python extension but it kept on giving me the same error message A: The error message you're seeing indicates that the interpreter can't find the Python file that you're trying to run. This could be because the path to the interpreter is incorrect, or because the Python interpreter is not installed on your system. The Python extension in VSCode isn't sufficient for running Python code. In the bottom right corner of VSCode, you can see the version of Python you are currently using. You can click it to change the interpreter path once you install Python.
I can't print hello world in visual studio code
I created a folder named " Python Trial ", and a folder within it named test and within that folder i created a file named test.py I installed the python extension and tried to print " Hello World! " however it keeps on giving me this command: C:/Users/saram/AppData/Local/Microsoft/WindowsApps/python3.10.exe "c:/Users/saram/Documents/Python Trial/test/test.py" -bash: C:/Users/saram/AppData/Local/Microsoft/WindowsApps/python3.10.exe: No such file or directory I don't know what to do I tried reinstalling visual studio code and the python extension but it kept on giving me the same error message
[ "The error message you're seeing indicates that the interpreter can't find the Python file that you're trying to run. This could be because the path to the interpreter is incorrect, or because the Python interpreter is not installed on your system.\nThe Python extension in VSCode isn't sufficient for running Python code. In the bottom right corner of VSCode, you can see the version of Python you are currently using. You can click it to change the interpreter path once you install Python.\n" ]
[ 1 ]
[]
[]
[ "python", "terminal", "visual_studio_code" ]
stackoverflow_0074672914_python_terminal_visual_studio_code.txt
Q: Browser-based debugging and performance testing software for react application I am knee on learning how to do Browser-based debugging and performance testing software for react application what all the tools to use and also what are the metrics to consider for effective react application Any article or pointers will be to explore more A: From my information You can use Chrome lighthouse or GTmetrix website for performance and for debugging you use react-devtools extension and if you are using webstorm you can use its built-in tools or webpack devTool with source map to see and edit react components in the browser
Browser-based debugging and performance testing software for react application
I am knee on learning how to do Browser-based debugging and performance testing software for react application what all the tools to use and also what are the metrics to consider for effective react application Any article or pointers will be to explore more
[ "From my information You can use Chrome lighthouse or GTmetrix website for performance\nand for debugging you use react-devtools extension and if you are using webstorm you can use its built-in tools\nor webpack devTool with source map to see and edit react components in the browser\n" ]
[ 0 ]
[]
[]
[ "google_chrome_devtools", "performance", "profiling", "reactjs" ]
stackoverflow_0074673557_google_chrome_devtools_performance_profiling_reactjs.txt
Q: The propriety 'setEstado' doesnt exist on type 'number | IContexto'.ts(2339) This is MyContext file. import React, { useState , createContext, SetStateAction } from 'react' type StateType = { state: number } interface IContexto { state?: StateType | null; setState?: React.Dispatch<SetStateAction<StateType | null>>; } export const PathContext = createContext<IContexto| number>( 0 ) // CRIA CONTEXTO interface IProps{ children?: JSX.Element|JSX.Element[]; } const MyContext: React.FC<IProps> = ({ children }:IProps ) => { // Envolve componentes no app const [ state, setState ] = useState<StateType | null >(null); return ( <PathContext.Provider // CRIA PROVIDER com value do state global value={{ state, setState } } > {children} </PathContext.Provider> ); }; export default MyContext; This is Percentual file import React, { useContext, useState } from "react"; import { PathContext } from '../contexto/MyContext' type Tipo = { comissao?: number; } const Percentual: React.FC<Tipo> = ( props: Tipo ) => { // componente usa o contexto criado const { state, setState } = useContext(PathContext) function AplicaPercentual(valor: number | undefined){ setState(valor) } return ( <> { state } <button onClick={ ()=>{ AplicaPercentual(props.comissao) } }> { props.comissao } </button> </> ) } export default Percentual In the percentual file the state e setState which were typed on MyContext file are not reconized. It says Property state/setState does not exist on type 'number | IContexto'.ts(2339) although typed before. In the mycontext file i tried to type state and setState with interface and type. Later i desestructured it in the percentual file as usual. Maybe i'm not typing the right way becouse there is no specific material on google to my case to help me out. A: The IContext type has only state and setState, there's no a "setEstado" there. If you wanted to access this method, then I think you should try create this method within IContext or try another type which contains setEstado ex: interface IContext { setEstado: () => void }
The propriety 'setEstado' doesnt exist on type 'number | IContexto'.ts(2339)
This is MyContext file. import React, { useState , createContext, SetStateAction } from 'react' type StateType = { state: number } interface IContexto { state?: StateType | null; setState?: React.Dispatch<SetStateAction<StateType | null>>; } export const PathContext = createContext<IContexto| number>( 0 ) // CRIA CONTEXTO interface IProps{ children?: JSX.Element|JSX.Element[]; } const MyContext: React.FC<IProps> = ({ children }:IProps ) => { // Envolve componentes no app const [ state, setState ] = useState<StateType | null >(null); return ( <PathContext.Provider // CRIA PROVIDER com value do state global value={{ state, setState } } > {children} </PathContext.Provider> ); }; export default MyContext; This is Percentual file import React, { useContext, useState } from "react"; import { PathContext } from '../contexto/MyContext' type Tipo = { comissao?: number; } const Percentual: React.FC<Tipo> = ( props: Tipo ) => { // componente usa o contexto criado const { state, setState } = useContext(PathContext) function AplicaPercentual(valor: number | undefined){ setState(valor) } return ( <> { state } <button onClick={ ()=>{ AplicaPercentual(props.comissao) } }> { props.comissao } </button> </> ) } export default Percentual In the percentual file the state e setState which were typed on MyContext file are not reconized. It says Property state/setState does not exist on type 'number | IContexto'.ts(2339) although typed before. In the mycontext file i tried to type state and setState with interface and type. Later i desestructured it in the percentual file as usual. Maybe i'm not typing the right way becouse there is no specific material on google to my case to help me out.
[ "The IContext type has only state and setState, there's no a \"setEstado\" there.\nIf you wanted to access this method, then I think you should try create this method within IContext or try another type which contains setEstado ex:\ninterface IContext {\n setEstado: () => void\n}\n\n" ]
[ 0 ]
[]
[]
[ "react_typescript", "reactjs", "typescript" ]
stackoverflow_0074508169_react_typescript_reactjs_typescript.txt
Q: Swift Package Manager - Type 'Bundle' has no member “module” error Working on implementing SPM for a framework, and got stuck on the Type 'Bundle' has no member “module” error. I have seen two other recent posts about this here and here, but following all the steps, it is still not working for me, no resource_bundle_accessor file is generated. I asked about my Package.swift file here, and that has been answered and resolved. For completeness here's the file: // swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "BioSwift", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "BioSwift", targets: ["BioSwift"] ) ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "BioSwift", dependencies: [], resources: [ .process("Resources") ] ), .testTarget( name: "BioSwiftTests", dependencies: ["BioSwift"] ) ] ) I get the Type 'Bundle' has no member “module” error when trying to access one of the resources in the bundle: public let unimodURL = Bundle.module?.url(forResource: "unimod", withExtension: "xml") The project is on GitHub here A: Besides all errors in the test file, the only issue remains is that module is not an optional. To fix that, just change this: public let unimodURL = Bundle.module?.url(forResource: "unimod", withExtension: "XML") to: public let unimodURL = Bundle.module.url(forResource: "unimod", withExtension: "xml") Update: If you use .xcodeproj file, you will continue seeing this error. You should consider opening it with the package.swift or import it as a package (instead of converting it to a project)! by the way, here is the generated file, so you can add it as a development asset when you are working with the xcodeproject: import class Foundation.Bundle private class BundleFinder {} extension Foundation.Bundle { /// Returns the resource bundle associated with the current Swift module. static var module: Bundle = { let bundleName = "BioSwift_BioSwift" let candidates = [ // Bundle should be present here when the package is linked into an App. Bundle.main.resourceURL, // Bundle should be present here when the package is linked into a framework. Bundle(for: BundleFinder.self).resourceURL, // For command-line tools. Bundle.main.bundleURL, ] for candidate in candidates { let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle") if let bundle = bundlePath.flatMap(Bundle.init(url:)) { return bundle } } fatalError("unable to find bundle named BioSwift_BioSwift") }() } A: If you follow the instructions on this video you will see that you need to define how you would like to include non-clear purpose files in a package. In this case your package manifest should be something like: // swift-tools-version:5.3 import PackageDescription let package = Package( name: "BioSwift", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "BioSwift", targets: ["BioSwift"]), ], dependencies: [], targets: [ .target( name: "BioSwift", dependencies: [], resources: [ .copy("Resources") ]), .testTarget( name: "BioSwiftTests", dependencies: ["BioSwift"]), ] ) Please pay attention on using Swift 5.3 tools and that you need to declare the resources for the respective target. The copy action on resources will leave them unprocessed when they are added in the compiled bundle. A: I had same issue (when i created fresh new package) ,what i did was i added new View file inside my package . And the error was gone . A: I had the same problem and I could solve it with the good ol' "did you try to turn it off and back on again?". No seriously, I simply used Bundle.module in my code (could also just be a one liner like print(Bundle.module)), closed Xcode completly and reopened the package via the Package.swift file and it worked. A: Please check your Resources folder path. It should be kept inside the Sources/PackageNameFolder/{Resources}.
Swift Package Manager - Type 'Bundle' has no member “module” error
Working on implementing SPM for a framework, and got stuck on the Type 'Bundle' has no member “module” error. I have seen two other recent posts about this here and here, but following all the steps, it is still not working for me, no resource_bundle_accessor file is generated. I asked about my Package.swift file here, and that has been answered and resolved. For completeness here's the file: // swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "BioSwift", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "BioSwift", targets: ["BioSwift"] ) ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "BioSwift", dependencies: [], resources: [ .process("Resources") ] ), .testTarget( name: "BioSwiftTests", dependencies: ["BioSwift"] ) ] ) I get the Type 'Bundle' has no member “module” error when trying to access one of the resources in the bundle: public let unimodURL = Bundle.module?.url(forResource: "unimod", withExtension: "xml") The project is on GitHub here
[ "Besides all errors in the test file, the only issue remains is that module is not an optional. To fix that, just change this:\npublic let unimodURL = Bundle.module?.url(forResource: \"unimod\", withExtension: \"XML\")\n\nto:\npublic let unimodURL = Bundle.module.url(forResource: \"unimod\", withExtension: \"xml\")\n\n\nUpdate:\nIf you use .xcodeproj file, you will continue seeing this error. You should consider opening it with the package.swift or import it as a package (instead of converting it to a project)!\nby the way, here is the generated file, so you can add it as a development asset when you are working with the xcodeproject:\nimport class Foundation.Bundle\n\nprivate class BundleFinder {}\n\nextension Foundation.Bundle {\n /// Returns the resource bundle associated with the current Swift module.\n static var module: Bundle = {\n let bundleName = \"BioSwift_BioSwift\"\n\n let candidates = [\n // Bundle should be present here when the package is linked into an App.\n Bundle.main.resourceURL,\n\n // Bundle should be present here when the package is linked into a framework.\n Bundle(for: BundleFinder.self).resourceURL,\n\n // For command-line tools.\n Bundle.main.bundleURL,\n ]\n\n for candidate in candidates {\n let bundlePath = candidate?.appendingPathComponent(bundleName + \".bundle\")\n if let bundle = bundlePath.flatMap(Bundle.init(url:)) {\n return bundle\n }\n }\n fatalError(\"unable to find bundle named BioSwift_BioSwift\")\n }()\n}\n\n", "If you follow the instructions on this video you will see that you need to define how you would like to include non-clear purpose files in a package. In this case your package manifest should be something like:\n// swift-tools-version:5.3\n\nimport PackageDescription\n\nlet package = Package(\n name: \"BioSwift\",\n products: [\n // Products define the executables and libraries produced by a package, and make them visible to other packages.\n .library(\n name: \"BioSwift\",\n targets: [\"BioSwift\"]),\n ],\n dependencies: [],\n targets: [\n .target(\n name: \"BioSwift\",\n dependencies: [],\n resources: [\n .copy(\"Resources\")\n ]),\n .testTarget(\n name: \"BioSwiftTests\",\n dependencies: [\"BioSwift\"]),\n ]\n)\n\nPlease pay attention on using Swift 5.3 tools and that you need to declare the resources for the respective target. The copy action on resources will leave them unprocessed when they are added in the compiled bundle.\n", "I had same issue (when i created fresh new package) ,what i did was i added new View file inside my package . And the error was gone .\n", "I had the same problem and I could solve it with the good ol' \"did you try to turn it off and back on again?\".\nNo seriously, I simply used Bundle.module in my code (could also just be a one liner like print(Bundle.module)), closed Xcode completly and reopened the package via the Package.swift file and it worked.\n", "Please check your Resources folder path. It should be kept inside the Sources/PackageNameFolder/{Resources}. \n" ]
[ 11, 1, 0, 0, 0 ]
[]
[]
[ "swift", "swift_package_manager", "xcode" ]
stackoverflow_0064407950_swift_swift_package_manager_xcode.txt
Q: How does verilog concatenation work when used as both sides of a non-blocking assignement? I am a beginner when it comes to verilog or any HDL. While working on a project I found a post where someone uses concatenation in both sides of the non-blocking assignment. Like so: {tf0, th0,tl0} <= {1'b0, th0, tl0}+ 1'b1; I don't really understand how this works. This is part of an implementation of a timer module in a Intel 8051 micro-controller implementation . This is the whole relevant code part for this problem: module oc8051_tc (clk, rst, data_in, wr_addr, wr, wr_bit, ie0, ie1, tr0, tr1, t0, t1, tf0, tf1, pres_ow, //registers tmod, tl0, th0, tl1, th1); input [7:0] wr_addr, data_in; input clk, rst, wr, wr_bit, ie0, ie1, tr0, tr1, t0, t1, pres_ow; output [7:0] tmod, tl0, th0, tl1, th1; output tf0, tf1; reg [7:0] tmod, tl0, th0, tl1, th1; reg tf0, tf1_0, tf1_1, t0_buff, t1_buff; wire tc0_add, tc1_add; assign tc0_add = (tr0 & (!tmod[3] | !ie0) & ((!tmod[2] & pres_ow) | (tmod[2] & !t0 & t0_buff))); assign tc1_add = (tr1 & (!tmod[7] | !ie1) & ((!tmod[6] & pres_ow) | (tmod[6] & !t1 & t1_buff))); assign tf1= tf1_0 | tf1_1; // // read or write from one of the addresses in tmod // always @(posedge clk or posedge rst) begin if (rst) begin tmod <=#1 `OC8051_RST_TMOD; end else if ((wr) & !(wr_bit) & (wr_addr==`OC8051_SFR_TMOD)) tmod <= #1 data_in; end // // TIMER COUNTER 0 // always @(posedge clk or posedge rst) begin if (rst) begin tl0 <=#1 `OC8051_RST_TL0; th0 <=#1 `OC8051_RST_TH0; tf0 <= #1 1'b0; tf1_0 <= #1 1'b0; end else if ((wr) & !(wr_bit) & (wr_addr==`OC8051_SFR_TL0)) begin tl0 <= #1 data_in; tf0 <= #1 1'b0; tf1_0 <= #1 1'b0; end else if ((wr) & !(wr_bit) & (wr_addr==`OC8051_SFR_TH0)) begin th0 <= #1 data_in; tf0 <= #1 1'b0; tf1_0 <= #1 1'b0; end else begin case (tmod[1:0]) /* synopsys full_case parallel_case */ `OC8051_MODE0: begin // mode 0 tf1_0 <= #1 1'b0; if (tc0_add) {tf0, th0,tl0[4:0]} <= #1 {1'b0, th0, tl0[4:0]}+ 1'b1; end `OC8051_MODE1: begin // mode 1 tf1_0 <= #1 1'b0; if (tc0_add) {tf0, th0,tl0} <= #1 {1'b0, th0, tl0}+ 1'b1; end `OC8051_MODE2: begin // mode 2 tf1_0 <= #1 1'b0; if (tc0_add) begin if (tl0 == 8'b1111_1111) begin tf0 <=#1 1'b1; tl0 <=#1 th0; end else begin tl0 <=#1 tl0 + 8'h1; tf0 <= #1 1'b0; end end end `OC8051_MODE3: begin // mode 3 if (tc0_add) {tf0, tl0} <= #1 {1'b0, tl0} +1'b1; if (tr1 & pres_ow) {tf1_0, th0} <= #1 {1'b0, th0} +1'b1; end /* default:begin tf0 <= #1 1'b0; tf1_0 <= #1 1'b0; end*/ endcase end end A: A concatenation on the RHS of the assignment is a packing operation. It is going to take its 3 operands and pack them into a 17-bit value. The first operand (1'b0) becomes the most significant bit(MSB) and the last operand (tl0) becomes the least significant bits(LSBs). That value then gets incremented by one, and the result gets scheduled for assignment to the LHS. A concatenation on the LHS of the assignment is an unpacking operation. The first operand (tf0) gets the MSB of the result and the last operand (tl0) gets the LSBs. Note that a packing concatenation may contain read-only literals and constants, but an unpacking concatenation must be all writable variables.
How does verilog concatenation work when used as both sides of a non-blocking assignement?
I am a beginner when it comes to verilog or any HDL. While working on a project I found a post where someone uses concatenation in both sides of the non-blocking assignment. Like so: {tf0, th0,tl0} <= {1'b0, th0, tl0}+ 1'b1; I don't really understand how this works. This is part of an implementation of a timer module in a Intel 8051 micro-controller implementation . This is the whole relevant code part for this problem: module oc8051_tc (clk, rst, data_in, wr_addr, wr, wr_bit, ie0, ie1, tr0, tr1, t0, t1, tf0, tf1, pres_ow, //registers tmod, tl0, th0, tl1, th1); input [7:0] wr_addr, data_in; input clk, rst, wr, wr_bit, ie0, ie1, tr0, tr1, t0, t1, pres_ow; output [7:0] tmod, tl0, th0, tl1, th1; output tf0, tf1; reg [7:0] tmod, tl0, th0, tl1, th1; reg tf0, tf1_0, tf1_1, t0_buff, t1_buff; wire tc0_add, tc1_add; assign tc0_add = (tr0 & (!tmod[3] | !ie0) & ((!tmod[2] & pres_ow) | (tmod[2] & !t0 & t0_buff))); assign tc1_add = (tr1 & (!tmod[7] | !ie1) & ((!tmod[6] & pres_ow) | (tmod[6] & !t1 & t1_buff))); assign tf1= tf1_0 | tf1_1; // // read or write from one of the addresses in tmod // always @(posedge clk or posedge rst) begin if (rst) begin tmod <=#1 `OC8051_RST_TMOD; end else if ((wr) & !(wr_bit) & (wr_addr==`OC8051_SFR_TMOD)) tmod <= #1 data_in; end // // TIMER COUNTER 0 // always @(posedge clk or posedge rst) begin if (rst) begin tl0 <=#1 `OC8051_RST_TL0; th0 <=#1 `OC8051_RST_TH0; tf0 <= #1 1'b0; tf1_0 <= #1 1'b0; end else if ((wr) & !(wr_bit) & (wr_addr==`OC8051_SFR_TL0)) begin tl0 <= #1 data_in; tf0 <= #1 1'b0; tf1_0 <= #1 1'b0; end else if ((wr) & !(wr_bit) & (wr_addr==`OC8051_SFR_TH0)) begin th0 <= #1 data_in; tf0 <= #1 1'b0; tf1_0 <= #1 1'b0; end else begin case (tmod[1:0]) /* synopsys full_case parallel_case */ `OC8051_MODE0: begin // mode 0 tf1_0 <= #1 1'b0; if (tc0_add) {tf0, th0,tl0[4:0]} <= #1 {1'b0, th0, tl0[4:0]}+ 1'b1; end `OC8051_MODE1: begin // mode 1 tf1_0 <= #1 1'b0; if (tc0_add) {tf0, th0,tl0} <= #1 {1'b0, th0, tl0}+ 1'b1; end `OC8051_MODE2: begin // mode 2 tf1_0 <= #1 1'b0; if (tc0_add) begin if (tl0 == 8'b1111_1111) begin tf0 <=#1 1'b1; tl0 <=#1 th0; end else begin tl0 <=#1 tl0 + 8'h1; tf0 <= #1 1'b0; end end end `OC8051_MODE3: begin // mode 3 if (tc0_add) {tf0, tl0} <= #1 {1'b0, tl0} +1'b1; if (tr1 & pres_ow) {tf1_0, th0} <= #1 {1'b0, th0} +1'b1; end /* default:begin tf0 <= #1 1'b0; tf1_0 <= #1 1'b0; end*/ endcase end end
[ "A concatenation on the RHS of the assignment is a packing operation. It is going to take its 3 operands and pack them into a 17-bit value. The first operand (1'b0) becomes the most significant bit(MSB) and the last operand (tl0) becomes the least significant bits(LSBs). That value then gets incremented by one, and the result gets scheduled for assignment to the LHS.\nA concatenation on the LHS of the assignment is an unpacking operation. The first operand (tf0) gets the MSB of the result and the last operand (tl0) gets the LSBs.\nNote that a packing concatenation may contain read-only literals and constants, but an unpacking concatenation must be all writable variables.\n" ]
[ 0 ]
[]
[]
[ "8051", "hdl", "verilog" ]
stackoverflow_0074670460_8051_hdl_verilog.txt
Q: Use multiple style tags in the A tag Just so you know, I'm still learning HTML, and I'm not very knowledgeable. So I'm trying to figure out how to add multiple styles to one of my buttons on my navbar <div id="navbar"> <a href="#home">Home</a> <a href="#skills">Skills</a> <a href="#interests">Interests</a> <a style="float:right" href="#about">About</a> </div> On the bottom line I want to include: (You will need to use the style sheet below for the HTML to format correctly its just above the last sentence.) style="background-color: #04AA6D" Into the the code so that the background is turned green I have this working on the other buttons that aren't floating right here's my main pages one, the button named "home" is green on the back and that's how I want the About pages one to be. <div id="navbar"> <a style="background-color: #04AA6D" href="#home">Home</a> <a href="#skilss">Skills</a> <a href="#interests">Interests</a> <a style="float:right" href="#about">About</a> </div> I'm using this style sheet (Needed for the page to format correctly.) <style> body { margin: 0; background-color: #f1f1f1; font-family: Arial, Helvetica, sans-serif; } #navbar { background-color: #333; position: fixed; top: 0; width: 100%; display: block; transition: top 0.3s; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 15px; text-decoration: none; font-size: 17px; } #navbar a:hover { background-color: #ddd; color: black; } li a:hover:not(.active) { background-color: #111; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } </style> I hope you understand what I mean, I'm horrible at explaining things . Any Questions you need me to answer so that you can help please let me know I tried connecting the two together like this <a style="float:right" style="background-color: #04AA6D" href="#contact">Interests</a> But that didn't work A: body { margin: 0; background-color: #f1f1f1; font-family: Arial, Helvetica, sans-serif; } #navbar { background-color: #333; position: fixed; top: 0; width: 100%; display: block; transition: top 0.3s; } .style1{ float:right !important; } .style2{ background: #04AA6D; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 15px; text-decoration: none; font-size: 17px; } #navbar a:hover { background-color: #ddd; color: black; } li a:hover:not(.active) { background-color: #111; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } <div id="navbar"> <a style="background-color: #04AA6D" href="#home">Home</a> <a href="#skilss">Skills</a> <a href="#interests">Interests</a> <a class="style1 style2" href="#about">About</a> </div> You can implement the following approach: Create classes for different CSS: .style1{ float:right !important; //i used '!important' because you are overriding other class } .style2{ background-color: #04AA6D } .style3{ //your 3rd extra css here } Then you can implement multiple css in following way: <a class="style1 style2 style3">Example</a>
Use multiple style tags in the A tag
Just so you know, I'm still learning HTML, and I'm not very knowledgeable. So I'm trying to figure out how to add multiple styles to one of my buttons on my navbar <div id="navbar"> <a href="#home">Home</a> <a href="#skills">Skills</a> <a href="#interests">Interests</a> <a style="float:right" href="#about">About</a> </div> On the bottom line I want to include: (You will need to use the style sheet below for the HTML to format correctly its just above the last sentence.) style="background-color: #04AA6D" Into the the code so that the background is turned green I have this working on the other buttons that aren't floating right here's my main pages one, the button named "home" is green on the back and that's how I want the About pages one to be. <div id="navbar"> <a style="background-color: #04AA6D" href="#home">Home</a> <a href="#skilss">Skills</a> <a href="#interests">Interests</a> <a style="float:right" href="#about">About</a> </div> I'm using this style sheet (Needed for the page to format correctly.) <style> body { margin: 0; background-color: #f1f1f1; font-family: Arial, Helvetica, sans-serif; } #navbar { background-color: #333; position: fixed; top: 0; width: 100%; display: block; transition: top 0.3s; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 15px; text-decoration: none; font-size: 17px; } #navbar a:hover { background-color: #ddd; color: black; } li a:hover:not(.active) { background-color: #111; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } </style> I hope you understand what I mean, I'm horrible at explaining things . Any Questions you need me to answer so that you can help please let me know I tried connecting the two together like this <a style="float:right" style="background-color: #04AA6D" href="#contact">Interests</a> But that didn't work
[ "\n\nbody {\n margin: 0;\n background-color: #f1f1f1;\n font-family: Arial, Helvetica, sans-serif;\n }\n \n #navbar {\n background-color: #333;\n position: fixed;\n top: 0;\n width: 100%;\n display: block;\n transition: top 0.3s;\n }\n\n.style1{\n float:right !important;\n}\n\n.style2{\n background: #04AA6D;\n}\n \n #navbar a {\n float: left;\n display: block;\n color: #f2f2f2;\n text-align: center;\n padding: 15px;\n text-decoration: none;\n font-size: 17px;\n }\n \n #navbar a:hover {\n background-color: #ddd;\n color: black;\n }\n li a:hover:not(.active) {\n background-color: #111;\n }\n li {\n float: left;\n }\n li a {\n display: block;\n color: white;\n text-align: center;\n padding: 14px 16px;\n text-decoration: none;\n }\n<div id=\"navbar\">\n <a style=\"background-color: #04AA6D\" href=\"#home\">Home</a>\n <a href=\"#skilss\">Skills</a>\n <a href=\"#interests\">Interests</a>\n <a class=\"style1 style2\" href=\"#about\">About</a>\n </div>\n\n\n\nYou can implement the following approach:\nCreate classes for different CSS:\n.style1{\n float:right !important;\n//i used '!important' because you are overriding other class\n}\n\n.style2{\n background-color: #04AA6D\n}\n\n.style3{\n //your 3rd extra css here\n}\n\nThen you can implement multiple css in following way:\n<a class=\"style1 style2 style3\">Example</a>\n\n" ]
[ 0 ]
[]
[]
[ "html", "styles" ]
stackoverflow_0074672916_html_styles.txt
Q: LinQ To group files by extension and get File sizes I am trying to write a C# LinQ code to group the files by extension and compute the sizes and the total number of each extension. For example, I have files = [a.txt, b.xml, c.html, d.doc, e.txt, f.pdf, g.docx]; I want to get: |Extension| Count| Size| txt | 2 | 24kb doc | 2 | 16kb html | 1 | 10b xml | 1 | 8b Here is my current code var group = files.Select(file => Path.GetExtension(file) .TrimStart('.').ToLower()) .GroupBy(y => y, (type, typecount) => new { Type = type, Count = typecount.Count(), Size = new FileInfo(type).Length }) .OrderBy(e=>e.Type); It is not working as expected. Any help will be appreciated. A: To be able to sum the sizes, you must not select for the extension too early as you need the individual file names later to determine the size. I suggest the following: var group = files .GroupBy(file => Path.GetExtension(file).ToLower().TrimStart('.')) .Select(g => new { Type = g.Key, Count = g.Count(), Size = g.Sum(file => new FileInfo(file).Length)}) .OrderBy(e => e.Type); The first line groups the file names by extension. The second line constructs the desired data.
LinQ To group files by extension and get File sizes
I am trying to write a C# LinQ code to group the files by extension and compute the sizes and the total number of each extension. For example, I have files = [a.txt, b.xml, c.html, d.doc, e.txt, f.pdf, g.docx]; I want to get: |Extension| Count| Size| txt | 2 | 24kb doc | 2 | 16kb html | 1 | 10b xml | 1 | 8b Here is my current code var group = files.Select(file => Path.GetExtension(file) .TrimStart('.').ToLower()) .GroupBy(y => y, (type, typecount) => new { Type = type, Count = typecount.Count(), Size = new FileInfo(type).Length }) .OrderBy(e=>e.Type); It is not working as expected. Any help will be appreciated.
[ "To be able to sum the sizes, you must not select for the extension too early as you need the individual file names later to determine the size.\nI suggest the following:\nvar group = files\n .GroupBy(file => Path.GetExtension(file).ToLower().TrimStart('.'))\n .Select(g => new { Type = g.Key, Count = g.Count(), Size = g.Sum(file => new FileInfo(file).Length)})\n .OrderBy(e => e.Type);\n\nThe first line groups the file names by extension. The second line constructs the desired data.\n" ]
[ 0 ]
[]
[]
[ "c#", "linq" ]
stackoverflow_0074673576_c#_linq.txt
Q: Photon Unity Turn based Multiplayer game I am trying to create a simple 2D Turn based multiplayer game using Photon Unity Networking. It is just a simple turn based game where a player 1 (host) presses his button and it adds his score and changes its turn to player 2 (client) who presses his button to add score and change turn to player 1. It continues to infinite. I was able to connect two players in the game using the basic Photon documentation. Now I need to add the networking logic of taking turns and changing them. I searched the internet but I can't understand the RPC and SerializeView of Photon. I am really confused with that. Please Help me. Thank you in future. Here is my GameManager Script using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameManager : Photon.PunBehaviour { public Text roomName; public Text player1Name,player2Name; public List<string> playersConnected = new List<string>(); int scoreP1 = 0, scoreP2 = 0; public Text scoreTextP1, scoreTextP2; public Button p1Btn, p2Btn; int playerTurn = 1; void Start() { roomName.text = SceneManager.GetActiveScene().name; p2Btn.gameObject.SetActive(false); p1Btn.gameObject.SetActive(true); } public void AddScoreP1() { scoreP1++; scoreTextP1.text = scoreP1.ToString(); ChangePlayerTurn(); } public void AddScoreP2() { scoreP2++; scoreTextP2.text = scoreP2.ToString(); ChangePlayerTurn(); } void ChangePlayerTurn() { if (playerTurn == 1) { playerTurn = 2; p2Btn.gameObject.SetActive(true); p1Btn.gameObject.SetActive(false); } else { playerTurn = 1; p1Btn.gameObject.SetActive(true); p2Btn.gameObject.SetActive(false); } print("Player Turn: P" + playerTurn); } void LoadArena() { if (!PhotonNetwork.isMasterClient) { Debug.LogError("PhotonNetwork : Trying to Load a level but we are not the master Client"); } Debug.Log("PhotonNetwork : Loading Level : " + PhotonNetwork.room.PlayerCount); PhotonNetwork.LoadLevel("Room for " + PhotonNetwork.room.PlayerCount); } public override void OnLeftRoom() { SceneManager.LoadScene(0); } public void LeaveRoom() { PhotonNetwork.LeaveRoom(); } public override void OnPhotonPlayerConnected(PhotonPlayer other) { Debug.Log("OnPhotonPlayerConnected() " + other.NickName); // not seen if you're the player connecting foreach (PhotonPlayer _player in PhotonNetwork.playerList) { playersConnected.Add(other.NickName); } if (PhotonNetwork.isMasterClient) { Debug.Log("OnPhotonPlayerConnected isMasterClient " + PhotonNetwork.isMasterClient); // called before OnPhotonPlayerDisconnected LoadArena(); } } public override void OnPhotonPlayerDisconnected(PhotonPlayer other) { Debug.Log("OnPhotonPlayerDisconnected() " + other.NickName); // seen when other disconnects foreach (PhotonPlayer _player in PhotonNetwork.playerList) { playersConnected.Remove(other.NickName); } if (PhotonNetwork.isMasterClient) { Debug.Log("OnPhotonPlayerDisonnected isMasterClient " + PhotonNetwork.isMasterClient); // called before OnPhotonPlayerDisconnected LoadArena(); } } } A: RPC is basically a way of invoking a function on a remote client. Usually in a multiplayer setup you'd want your MasterClient to control the flow of the game. So, when two players join a room, what you need to do is from your MasterClient, decide which player goes first and then call a RPC function from MasterClient telling both client whose the first turn is. Then whichever player's turn it is, just activate its button and let them add score (Send RPC to MasterClient as well for that, so that everyone can stay in sync.) and the update turn and tell everyone via another RPC and so on. though you can also use Events for such cases, they need less preparation to be used. A: Both in a nutshell: RPC, Remote Procedural calls, is used to call a certain method to all or certain clients/users in the same room/level. Example like this, you might want to use RCP to update the teams score if a team scored a goal. SerializeView is used by PUN to synchronize and read data a few times per second, depending on the serialization rate. Example like this, you will use this to get and read to see each other's data like how much points another player have in realtime. both of these functions are practically similar, but their use is entirely different. There is more information about RCP and SerializeView on the Photon Website Link
Photon Unity Turn based Multiplayer game
I am trying to create a simple 2D Turn based multiplayer game using Photon Unity Networking. It is just a simple turn based game where a player 1 (host) presses his button and it adds his score and changes its turn to player 2 (client) who presses his button to add score and change turn to player 1. It continues to infinite. I was able to connect two players in the game using the basic Photon documentation. Now I need to add the networking logic of taking turns and changing them. I searched the internet but I can't understand the RPC and SerializeView of Photon. I am really confused with that. Please Help me. Thank you in future. Here is my GameManager Script using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameManager : Photon.PunBehaviour { public Text roomName; public Text player1Name,player2Name; public List<string> playersConnected = new List<string>(); int scoreP1 = 0, scoreP2 = 0; public Text scoreTextP1, scoreTextP2; public Button p1Btn, p2Btn; int playerTurn = 1; void Start() { roomName.text = SceneManager.GetActiveScene().name; p2Btn.gameObject.SetActive(false); p1Btn.gameObject.SetActive(true); } public void AddScoreP1() { scoreP1++; scoreTextP1.text = scoreP1.ToString(); ChangePlayerTurn(); } public void AddScoreP2() { scoreP2++; scoreTextP2.text = scoreP2.ToString(); ChangePlayerTurn(); } void ChangePlayerTurn() { if (playerTurn == 1) { playerTurn = 2; p2Btn.gameObject.SetActive(true); p1Btn.gameObject.SetActive(false); } else { playerTurn = 1; p1Btn.gameObject.SetActive(true); p2Btn.gameObject.SetActive(false); } print("Player Turn: P" + playerTurn); } void LoadArena() { if (!PhotonNetwork.isMasterClient) { Debug.LogError("PhotonNetwork : Trying to Load a level but we are not the master Client"); } Debug.Log("PhotonNetwork : Loading Level : " + PhotonNetwork.room.PlayerCount); PhotonNetwork.LoadLevel("Room for " + PhotonNetwork.room.PlayerCount); } public override void OnLeftRoom() { SceneManager.LoadScene(0); } public void LeaveRoom() { PhotonNetwork.LeaveRoom(); } public override void OnPhotonPlayerConnected(PhotonPlayer other) { Debug.Log("OnPhotonPlayerConnected() " + other.NickName); // not seen if you're the player connecting foreach (PhotonPlayer _player in PhotonNetwork.playerList) { playersConnected.Add(other.NickName); } if (PhotonNetwork.isMasterClient) { Debug.Log("OnPhotonPlayerConnected isMasterClient " + PhotonNetwork.isMasterClient); // called before OnPhotonPlayerDisconnected LoadArena(); } } public override void OnPhotonPlayerDisconnected(PhotonPlayer other) { Debug.Log("OnPhotonPlayerDisconnected() " + other.NickName); // seen when other disconnects foreach (PhotonPlayer _player in PhotonNetwork.playerList) { playersConnected.Remove(other.NickName); } if (PhotonNetwork.isMasterClient) { Debug.Log("OnPhotonPlayerDisonnected isMasterClient " + PhotonNetwork.isMasterClient); // called before OnPhotonPlayerDisconnected LoadArena(); } } }
[ "RPC is basically a way of invoking a function on a remote client.\nUsually in a multiplayer setup you'd want your MasterClient to control the flow of the game. So, when two players join a room, what you need to do is from your MasterClient, decide which player goes first and then call a RPC function from MasterClient telling both client whose the first turn is. Then whichever player's turn it is, just activate its button and let them add score (Send RPC to MasterClient as well for that, so that everyone can stay in sync.) and the update turn and tell everyone via another RPC and so on.\nthough you can also use Events for such cases, they need less preparation to be used.\n", "Both in a nutshell:\nRPC, Remote Procedural calls, is used to call a certain method to all or certain clients/users in the same room/level. Example like this, you might want to use RCP to update the teams score if a team scored a goal.\nSerializeView is used by PUN to synchronize and read data a few times per second, depending on the serialization rate. Example like this, you will use this to get and read to see each other's data like how much points another player have in realtime.\nboth of these functions are practically similar, but their use is entirely different.\nThere is more information about RCP and SerializeView on the Photon Website Link\n" ]
[ 1, 0 ]
[]
[]
[ "multiplayer", "photon", "unity3d" ]
stackoverflow_0048505907_multiplayer_photon_unity3d.txt
Q: How to use flex-wrap inside the ScrollView in React-native I can't able to use flexWrap property inside the ScrollView container. My code looks like this function Home({ navigation }) { return ( <View style={styles.container}> <ScrollView style={styles.scrollContainer}> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> </ScrollView> <StatusBar style="auto" /> </View> ); } and styles for this is const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", alignItems: "center", justifyContent: "center", flexWrap: "wrap", }, scrollContainer: { backgroundColor: "#B7C3F3", width: "100%", flexWrap: "wrap", }, }); I don't know whether the flex works under the ScrollView or not. I am new to the native please help me with this problem and thanks in advance A: To use the flexWrap property inside a ScrollView container in React Native, you need to make sure that the ScrollView container has a fixed height. This is because ScrollView containers have a default height of "auto" which does not allow the flexWrap property to work. To fix this, you can add a height property to the styles for the ScrollView container, and set it to a fixed value. For example: const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", alignItems: "center", justifyContent: "center", flexWrap: "wrap", }, scrollContainer: { backgroundColor: "#B7C3F3", width: "100%", flexWrap: "wrap", height: "100%", // Add a height property with a fixed value }, }); A: The ScrollView component in React Native does not support the flexWrap property. This is because the ScrollView component is designed to scroll content horizontally or vertically, depending on the configuration of the horizontal and vertical props. It does not support wrapping content within its container. If you want to use the flexWrap property, you can use a different layout component that supports wrapping, such as the View component. You can nest a View component within the ScrollView component and apply the flexWrap property to the nested View component, like this: function Home({ navigation }) { return ( <View style={styles.container}> <ScrollView style={styles.scrollContainer}> <View style={styles.wrapContainer}> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> </View> </ScrollView> <StatusBar style="auto" /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", alignItems: "center", justifyContent: "center", }, scrollContainer: { backgroundColor: "#B7C3F3", width: "100%", }, wrapContainer: { flexWrap: "wrap", }, }); In this example, the View component with the wrapContainer style is nested within the ScrollView component, and the flexWrap property is applied to the View component. This allows the child elements of the View component to wrap within the container. Note that you may need to adjust the width and flex properties of the View component and its child elements to ensure that they wrap correctly within the container. You may also need to adjust the width and height properties of the ScrollView component to ensure that it is large enough to contain all of the wrapped content. A: Try to remove the flex: 1 to solve the problem
How to use flex-wrap inside the ScrollView in React-native
I can't able to use flexWrap property inside the ScrollView container. My code looks like this function Home({ navigation }) { return ( <View style={styles.container}> <ScrollView style={styles.scrollContainer}> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> <LayoutButton navigation={navigation} title={"go to setting"} path="Setting" /> </ScrollView> <StatusBar style="auto" /> </View> ); } and styles for this is const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", alignItems: "center", justifyContent: "center", flexWrap: "wrap", }, scrollContainer: { backgroundColor: "#B7C3F3", width: "100%", flexWrap: "wrap", }, }); I don't know whether the flex works under the ScrollView or not. I am new to the native please help me with this problem and thanks in advance
[ "To use the flexWrap property inside a ScrollView container in React Native, you need to make sure that the ScrollView container has a fixed height. This is because ScrollView containers have a default height of \"auto\" which does not allow the flexWrap property to work.\nTo fix this, you can add a height property to the styles for the ScrollView container, and set it to a fixed value. For example:\nconst styles = StyleSheet.create({\ncontainer: {\nflex: 1,\nbackgroundColor: \"#fff\",\nalignItems: \"center\",\njustifyContent: \"center\",\nflexWrap: \"wrap\",\n},\nscrollContainer: {\nbackgroundColor: \"#B7C3F3\",\nwidth: \"100%\",\nflexWrap: \"wrap\",\nheight: \"100%\", // Add a height property with a fixed value\n},\n});\n\n", "The ScrollView component in React Native does not support the flexWrap property. This is because the ScrollView component is designed to scroll content horizontally or vertically, depending on the configuration of the horizontal and vertical props. It does not support wrapping content within its container.\nIf you want to use the flexWrap property, you can use a different layout component that supports wrapping, such as the View component. You can nest a View component within the ScrollView component and apply the flexWrap property to the nested View component, like this:\nfunction Home({ navigation }) {\n return (\n <View style={styles.container}>\n <ScrollView style={styles.scrollContainer}>\n <View style={styles.wrapContainer}>\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n </View>\n </ScrollView>\n <StatusBar style=\"auto\" />\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: \"#fff\",\n alignItems: \"center\",\n justifyContent: \"center\",\n },\n scrollContainer: {\n backgroundColor: \"#B7C3F3\",\n width: \"100%\",\n },\n wrapContainer: {\n flexWrap: \"wrap\",\n },\n});\n\nIn this example, the View component with the wrapContainer style is nested within the ScrollView component, and the flexWrap property is applied to the View component. This allows the child elements of the View component to wrap within the container.\nNote that you may need to adjust the width and flex properties of the View component and its child elements to ensure that they wrap correctly within the container. You may also need to adjust the width and height properties of the ScrollView component to ensure that it is large enough to contain all of the wrapped content.\n", "Try to remove the flex: 1 to solve the problem\n" ]
[ 1, 1, 0 ]
[]
[]
[ "javascript", "react_native", "reactjs" ]
stackoverflow_0074673518_javascript_react_native_reactjs.txt
Q: Why to use 'defaultProvider' for useContext? I am watching his video about useContext but he is not using defaultProvider, but the template we purchased use it, why? What advantage it has? https://www.youtube.com/watch?v=5LrDIWkK_Bc const defaultProvider: AuthValuesType = { userDTO: null, handleAuth: () => Promise.resolve(), logout: () => Promise.resolve(), updateUserDTO: () => Promise.resolve(), } const AuthContext = createContext(defaultProvider) In the same file an AuthProvider is set up, and 'real' states get assigned. Then why to use the default? A: The defaultProvider value is passed to the createContext method as the default value for the context. This default value is used when a component uses the useContext hook and does not have a matching provider above it in the component tree. In other words, the defaultProvider is a fallback value that is used when the context value is not provided by a provider. The purpose of using a default value is to avoid having to check whether the context value is null or undefined every time you use it in a component. With the default value in place, you can use the context value directly in your components without having to worry about checking for its existence. In the case of the AuthContext, the default provider likely contains some default values for the context properties, such as null for the userDTO property and some empty functions for the other properties. This allows the components that use the AuthContext to assume that these properties are always defined and avoid having to check for their existence. Overall, using a default value for the context can make your code simpler and more straightforward, especially if the context is used in many different components in your application.
Why to use 'defaultProvider' for useContext?
I am watching his video about useContext but he is not using defaultProvider, but the template we purchased use it, why? What advantage it has? https://www.youtube.com/watch?v=5LrDIWkK_Bc const defaultProvider: AuthValuesType = { userDTO: null, handleAuth: () => Promise.resolve(), logout: () => Promise.resolve(), updateUserDTO: () => Promise.resolve(), } const AuthContext = createContext(defaultProvider) In the same file an AuthProvider is set up, and 'real' states get assigned. Then why to use the default?
[ "The defaultProvider value is passed to the createContext method as the default value for the context. This default value is used when a component uses the useContext hook and does not have a matching provider above it in the component tree. In other words, the defaultProvider is a fallback value that is used when the context value is not provided by a provider.\nThe purpose of using a default value is to avoid having to check whether the context value is null or undefined every time you use it in a component. With the default value in place, you can use the context value directly in your components without having to worry about checking for its existence.\nIn the case of the AuthContext, the default provider likely contains some default values for the context properties, such as null for the userDTO property and some empty functions for the other properties. This allows the components that use the AuthContext to assume that these properties are always defined and avoid having to check for their existence.\nOverall, using a default value for the context can make your code simpler and more straightforward, especially if the context is used in many different components in your application.\n" ]
[ 0 ]
[]
[]
[ "react_context", "reactjs" ]
stackoverflow_0074673581_react_context_reactjs.txt
Q: Stop loss = 100 pips Can someone help me to set stop loss = 100 pips to this strategy? I have no idea how to do it //@version=5 strategy("MovingAvg2Line Cross", overlay=true) fastLength = input(9) slowLength = input(18) price = close mafast = ta.sma(price, fastLength) maslow = ta.sma(price, slowLength) if (ta.crossover(mafast, maslow)) strategy.entry("MA2CrossLE", strategy.long, comment="MA2CrossLE") if (ta.crossunder(mafast, maslow)) strategy.entry("MA2CrossSE", strategy.short, comment="MA2CrossSE") //plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr) If someone can write for me code of stop loss i would be grateful A: To add a stop loss to this strategy, you can use the strategy.exit() function. This function takes the name of the entry order, the type of exit (in this case stop), and the stop price as arguments. Here's an example of how you can use the strategy.exit() function to add a 100 pip stop loss to the strategy: //@version=5 strategy("MovingAvg2Line Cross", overlay=true) fastLength = input(9) slowLength = input(18) price = close mafast = ta.sma(price, fastLength) maslow = ta.sma(price, slowLength) if (ta.crossover(mafast, maslow)) strategy.entry("MA2CrossLE", strategy.long, comment="MA2CrossLE") // Add a 100 pip stop loss to the long entry strategy.exit("MA2CrossLE", stop=strategy.position_avg_price * 0.99) if (ta.crossunder(mafast, maslow)) strategy.entry("MA2CrossSE", strategy.short, comment="MA2CrossSE") // Add a 100 pip stop loss to the short entry strategy.exit("MA2CrossSE", stop=strategy.position_avg_price * 1.01) //plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr) A: The loss parameter in the strategy.exit() function sets a stop loss order in measured in ticks. I've added a short function to calculate ticks vs pips and then set the value of its return as the loss argument. //@version=5 strategy("MovingAvg2Line Cross", overlay=true) fastLength = input(9) slowLength = input(18) GetPipSize(size) => syminfo.mintick * (syminfo.type == "forex" ? 10 : 1) * size price = close mafast = ta.sma(price, fastLength) maslow = ta.sma(price, slowLength) if (ta.crossover(mafast, maslow)) strategy.entry("MA2CrossLE", strategy.long, comment="MA2CrossLE") // Add a 100 pip stop loss to the long entry strategy.exit("MA2CrossXL", "MA2CrossLE", loss=GetPipSize(100)) if (ta.crossunder(mafast, maslow)) strategy.entry("MA2CrossSE", strategy.short, comment="MA2CrossSE") // Add a 100 pip stop loss to the short entry strategy.exit("MA2CrossXS", "MA2CrossSE",loss=GetPipSize(100))
Stop loss = 100 pips
Can someone help me to set stop loss = 100 pips to this strategy? I have no idea how to do it //@version=5 strategy("MovingAvg2Line Cross", overlay=true) fastLength = input(9) slowLength = input(18) price = close mafast = ta.sma(price, fastLength) maslow = ta.sma(price, slowLength) if (ta.crossover(mafast, maslow)) strategy.entry("MA2CrossLE", strategy.long, comment="MA2CrossLE") if (ta.crossunder(mafast, maslow)) strategy.entry("MA2CrossSE", strategy.short, comment="MA2CrossSE") //plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr) If someone can write for me code of stop loss i would be grateful
[ "To add a stop loss to this strategy, you can use the strategy.exit() function. This function takes the name of the entry order, the type of exit (in this case stop), and the stop price as arguments.\nHere's an example of how you can use the strategy.exit() function to add a 100 pip stop loss to the strategy:\n//@version=5\nstrategy(\"MovingAvg2Line Cross\", overlay=true)\nfastLength = input(9)\nslowLength = input(18)\nprice = close\nmafast = ta.sma(price, fastLength)\nmaslow = ta.sma(price, slowLength)\nif (ta.crossover(mafast, maslow))\n strategy.entry(\"MA2CrossLE\", strategy.long, comment=\"MA2CrossLE\")\n // Add a 100 pip stop loss to the long entry\n strategy.exit(\"MA2CrossLE\", stop=strategy.position_avg_price * 0.99)\nif (ta.crossunder(mafast, maslow))\n strategy.entry(\"MA2CrossSE\", strategy.short, comment=\"MA2CrossSE\")\n // Add a 100 pip stop loss to the short entry\n strategy.exit(\"MA2CrossSE\", stop=strategy.position_avg_price * 1.01)\n//plot(strategy.equity, title=\"equity\", color=color.red, linewidth=2, \nstyle=plot.style_areabr)\n\n", "The loss parameter in the strategy.exit() function sets a stop loss order in measured in ticks.\nI've added a short function to calculate ticks vs pips and then set the value of its return as the loss argument.\n//@version=5\nstrategy(\"MovingAvg2Line Cross\", overlay=true)\nfastLength = input(9)\nslowLength = input(18)\n\nGetPipSize(size) =>\n syminfo.mintick * (syminfo.type == \"forex\" ? 10 : 1) * size\n\nprice = close\nmafast = ta.sma(price, fastLength)\nmaslow = ta.sma(price, slowLength)\nif (ta.crossover(mafast, maslow))\n strategy.entry(\"MA2CrossLE\", strategy.long, comment=\"MA2CrossLE\")\n // Add a 100 pip stop loss to the long entry\n strategy.exit(\"MA2CrossXL\", \"MA2CrossLE\", loss=GetPipSize(100))\nif (ta.crossunder(mafast, maslow))\n strategy.entry(\"MA2CrossSE\", strategy.short, comment=\"MA2CrossSE\")\n // Add a 100 pip stop loss to the short entry\n strategy.exit(\"MA2CrossXS\", \"MA2CrossSE\",loss=GetPipSize(100))\n\n" ]
[ 0, 0 ]
[]
[]
[ "pine_script", "tradingview_api" ]
stackoverflow_0074671283_pine_script_tradingview_api.txt
Q: expo eas local build: how to avoid downloading gradle.zip? This question is about a network issue when Running Expo builds on your own infrastructure with Expo EAS CLI. I am trying to run eas build --platform android --non-interactive --local but I am facing a network error: ... [PREBUILD] [5/5] Building fresh packages... [PREBUILD] success Saved lockfile. [PREBUILD] Done in 36.84s. [PREPARE_CREDENTIALS] Writing secrets to the project's directory [PREPARE_CREDENTIALS] Injecting signing config into build.gradle [CONFIGURE_EXPO_UPDATES] Using default release channel for 'expo-updates' (default) [RUN_GRADLEW] Running 'gradlew :app:assembleRelease' in /tmp/root/eas-build-local-nodejs/f1c1ab1b-fe51-4bc9-a46a-bfab5cc8c2f7/build/01_App/frontend/android [RUN_GRADLEW] Downloading https://services.gradle.org/distributions/gradle-7.3.3-all.zip [RUN_GRADLEW] Exception in thread "main" [RUN_GRADLEW] java.io.IOException: Downloading from https://services.gradle.org/distributions/gradle-7.3.3-all.zip failed: timeout ... However, calling wget https://services.gradle.org/distributions/gradle-7.3.3-all.zip works! Therefore, this network issue only happens from within the eas build command. I am running this from a corporate network, and it is not the first time I encounter weird network issues that are hard and tiring to debug. It might be something with DNS resolution, with Docker, with firewall rules, with TLS certificates, I don't know. I've even found another machine from which it works, but I need to run this on this machine. I'd like to work around this, instead of finding the root cause of the network issue. Since I can download this zip file myself very easily, I was hoping for a way for me to give it to eas build so that it doesn't try to download it. Maybe by putting the zip file in a specific folder? Maybe by doing something with the zip file (unzipping, installing somehow)? Something else? The goal is to make eas build decide it does not need to do this. How can I achieve this? Thanks! A: Yes, You can overcome the issue easily I guess. If you can download using a normal browser, Is there any proxy configuration added to your browser so you can access external network? If yes, Then it's pretty simple. There are 3 things you can try according to my understanding of this. First, As you have downloaded the zip, It will contain Gradle-7.3.3, If you want, you can add Gradle to the system instant of using the wrapper, Once this is done. You can type Gradle wrapper command which will add gradle/wrapper folder with valid info and this should be enough to solve the issue. Second, You can manually configure, by copying the file needed into the path. This can be found in gradle/wrapper/gradle-wrapper.properties which looks like this distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists So what you have to do is, go to wrapper/dists and copy the zip file, and the build system will check that it is valid and you won't have to download it again. Third, If there is proxy configuration, Its way easier to set the rules to gradle/gradle-wrapper You can either set the rules globally, or locally by adding this to gradle.properties or gradle-wrapper.properties systemProp.https.proxyHost={PROXY IP} systemProp.https.proxyPort={PROXY PORT} systemProp.https.proxyUser={USERNAME} systemProp.https.proxyPassword={PASSWORD} This will cause either gradle or the wrapper to use the same configuration as your browser with the build, And there should be no issue downloading anymore.
expo eas local build: how to avoid downloading gradle.zip?
This question is about a network issue when Running Expo builds on your own infrastructure with Expo EAS CLI. I am trying to run eas build --platform android --non-interactive --local but I am facing a network error: ... [PREBUILD] [5/5] Building fresh packages... [PREBUILD] success Saved lockfile. [PREBUILD] Done in 36.84s. [PREPARE_CREDENTIALS] Writing secrets to the project's directory [PREPARE_CREDENTIALS] Injecting signing config into build.gradle [CONFIGURE_EXPO_UPDATES] Using default release channel for 'expo-updates' (default) [RUN_GRADLEW] Running 'gradlew :app:assembleRelease' in /tmp/root/eas-build-local-nodejs/f1c1ab1b-fe51-4bc9-a46a-bfab5cc8c2f7/build/01_App/frontend/android [RUN_GRADLEW] Downloading https://services.gradle.org/distributions/gradle-7.3.3-all.zip [RUN_GRADLEW] Exception in thread "main" [RUN_GRADLEW] java.io.IOException: Downloading from https://services.gradle.org/distributions/gradle-7.3.3-all.zip failed: timeout ... However, calling wget https://services.gradle.org/distributions/gradle-7.3.3-all.zip works! Therefore, this network issue only happens from within the eas build command. I am running this from a corporate network, and it is not the first time I encounter weird network issues that are hard and tiring to debug. It might be something with DNS resolution, with Docker, with firewall rules, with TLS certificates, I don't know. I've even found another machine from which it works, but I need to run this on this machine. I'd like to work around this, instead of finding the root cause of the network issue. Since I can download this zip file myself very easily, I was hoping for a way for me to give it to eas build so that it doesn't try to download it. Maybe by putting the zip file in a specific folder? Maybe by doing something with the zip file (unzipping, installing somehow)? Something else? The goal is to make eas build decide it does not need to do this. How can I achieve this? Thanks!
[ "Yes, You can overcome the issue easily I guess.\nIf you can download using a normal browser, Is there any proxy configuration added to your browser so you can access external network?\nIf yes, Then it's pretty simple.\nThere are 3 things you can try according to my understanding of this.\nFirst,\nAs you have downloaded the zip, It will contain Gradle-7.3.3, If you want, you can add Gradle to the system instant of using the wrapper, Once this is done. You can type Gradle wrapper command which will add gradle/wrapper folder with valid info and this should be enough to solve the issue.\nSecond,\nYou can manually configure, by copying the file needed into the path.\nThis can be found in gradle/wrapper/gradle-wrapper.properties which looks like this\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-6.9-bin.zip\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n\nSo what you have to do is, go to wrapper/dists and copy the zip file, and the build system will check that it is valid and you won't have to download it again.\nThird,\nIf there is proxy configuration, Its way easier to set the rules to gradle/gradle-wrapper\nYou can either set the rules globally, or locally by adding this to gradle.properties or gradle-wrapper.properties\nsystemProp.https.proxyHost={PROXY IP}\nsystemProp.https.proxyPort={PROXY PORT}\nsystemProp.https.proxyUser={USERNAME}\nsystemProp.https.proxyPassword={PASSWORD}\n\nThis will cause either gradle or the wrapper to use the same configuration as your browser with the build, And there should be no issue downloading anymore.\n" ]
[ 2 ]
[]
[]
[ "android", "eas", "expo", "gradle", "java" ]
stackoverflow_0074664512_android_eas_expo_gradle_java.txt
Q: python split string on multiple delimeters without regex I have a string that I need to split on multiple characters without the use of regular expressions. for example, I would need something like the following: >>>string="hello there[my]friend" >>>string.split(' []') ['hello','there','my','friend'] is there anything in python like this? A: If you need multiple delimiters, re.split is the way to go. Without using a regex, it's not possible unless you write a custom function for it. Here's such a function - it might or might not do what you want (consecutive delimiters cause empty elements): >>> def multisplit(s, delims): ... pos = 0 ... for i, c in enumerate(s): ... if c in delims: ... yield s[pos:i] ... pos = i + 1 ... yield s[pos:] ... >>> list(multisplit('hello there[my]friend', ' []')) ['hello', 'there', 'my', 'friend'] A: Solution without regexp: from itertools import groupby sep = ' []' s = 'hello there[my]friend' print [''.join(g) for k, g in groupby(s, sep.__contains__) if not k] I've just posted an explanation here https://stackoverflow.com/a/19211729/2468006 A: A recursive solution without use of regex. Uses only base python in contrast to the other answers. def split_on_multiple_chars(string_to_split, set_of_chars_as_string): # Recursive splitting # Returns a list of strings s = string_to_split chars = set_of_chars_as_string # If no more characters to split on, return input if len(chars) == 0: return([s]) # Split on the first of the delimiter characters ss = s.split(chars[0]) # Recursive call without the first splitting character bb = [] for e in ss: aa = split_on_multiple_chars(e, chars[1:]) bb.extend(aa) return(bb) Works very similarly to pythons regular string.split(...), but accepts several delimiters. Example use: print(split_on_multiple_chars('my"example_string.with:funny?delimiters', '_.:;')) Output: ['my"example', 'string', 'with', 'funny?delimiters'] A: If you're not worried about long strings, you could force all delimiters to be the same using string.replace(). The following splits a string by both - and , x.replace('-', ',').split(',') If you have many delimiters you could do the following: def split(x, delimiters): for d in delimiters: x = x.replace(d, delimiters[0]) return x.split(delimiters[0])
python split string on multiple delimeters without regex
I have a string that I need to split on multiple characters without the use of regular expressions. for example, I would need something like the following: >>>string="hello there[my]friend" >>>string.split(' []') ['hello','there','my','friend'] is there anything in python like this?
[ "If you need multiple delimiters, re.split is the way to go.\nWithout using a regex, it's not possible unless you write a custom function for it.\nHere's such a function - it might or might not do what you want (consecutive delimiters cause empty elements):\n>>> def multisplit(s, delims):\n... pos = 0\n... for i, c in enumerate(s):\n... if c in delims:\n... yield s[pos:i]\n... pos = i + 1\n... yield s[pos:]\n...\n>>> list(multisplit('hello there[my]friend', ' []'))\n['hello', 'there', 'my', 'friend']\n\n", "Solution without regexp:\nfrom itertools import groupby\nsep = ' []'\ns = 'hello there[my]friend'\nprint [''.join(g) for k, g in groupby(s, sep.__contains__) if not k]\n\nI've just posted an explanation here https://stackoverflow.com/a/19211729/2468006\n", "A recursive solution without use of regex. Uses only base python in contrast to the other answers.\ndef split_on_multiple_chars(string_to_split, set_of_chars_as_string):\n # Recursive splitting\n # Returns a list of strings\n\n s = string_to_split\n chars = set_of_chars_as_string\n\n # If no more characters to split on, return input\n if len(chars) == 0:\n return([s])\n\n # Split on the first of the delimiter characters\n ss = s.split(chars[0])\n\n # Recursive call without the first splitting character\n bb = []\n for e in ss:\n aa = split_on_multiple_chars(e, chars[1:])\n bb.extend(aa)\n return(bb)\n\nWorks very similarly to pythons regular string.split(...), but accepts several delimiters.\nExample use:\nprint(split_on_multiple_chars('my\"example_string.with:funny?delimiters', '_.:;'))\n\nOutput:\n['my\"example', 'string', 'with', 'funny?delimiters']\n\n", "If you're not worried about long strings, you could force all delimiters to be the same using string.replace(). The following splits a string by both - and ,\nx.replace('-', ',').split(',')\nIf you have many delimiters you could do the following:\ndef split(x, delimiters):\n for d in delimiters:\n x = x.replace(d, delimiters[0])\n return x.split(delimiters[0])\n\n" ]
[ 8, 1, 1, 0 ]
[ "re.split is the right tool here.\n>>> string=\"hello there[my]friend\"\n>>> import re\n>>> re.split('[] []', string)\n['hello', 'there', 'my', 'friend']\n\nIn regex, [...] defines a character class. Any characters inside the brackets will match. The way I've spaced the brackets avoids needing to escape them, but the pattern [\\[\\] ] also works.\n>>> re.split('[\\[\\] ]', string)\n['hello', 'there', 'my', 'friend']\n\nThe re.DEBUG flag to re.compile is also useful, as it prints out what the pattern will match:\n>>> re.compile('[] []', re.DEBUG)\nin \n literal 93\n literal 32\n literal 91\n<_sre.SRE_Pattern object at 0x16b0850>\n\n(Where 32, 91, 93, are the ascii values assigned to , [, ])\n" ]
[ -3 ]
[ "python", "split", "string" ]
stackoverflow_0010655850_python_split_string.txt
Q: Python multiprocessing.Process can not stop when after connecting the network When I try to crawl thesis information in multiple threads, I cannot close the process after getting the information: error And when I comment the code which function is get the information from network, these processes can end normally. normal This error is trouble me and I don't have any idea, my network connect is by requests and set the response.close() so can any handsome brother or beautiful lady help this confused person? Thanks This is whole code: my python is python 3.7 from multiprocessing import Process, Queue, Pool,Manager,Value import time, random import requests import re from bs4 import BeautifulSoup headers = { 'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36,Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", 'Connection': 'close' } ## Just get the html text def GetUrlInfo(url): response = requests.get(url=url, headers=headers) response.encoding = 'utf-8' response.close() SoupData = BeautifulSoup(response.text, 'lxml') return SoupData def GetVolumeUrlfromUrl(url:str)->str: """input is Journal's url and output is a link and a text description to each issue of the journal""" url = re.sub('http:', 'https:', url) SoupDataTemp = GetUrlInfo(url+'index.html') SoupData = SoupDataTemp.find_all('li') UrlALL = [] for i in SoupData: if i.find('a') != None: volumeUrlRule = '<a href=\"(.*?)\">(.*?)</a>' volumeUrlTemp = re.findall(volumeUrlRule,str(i),re.I) # u = i.find('a')['href'] # # print(u) for u in volumeUrlTemp: if re.findall(url, u[0]): # print(u) UrlALL.append((u[0], u[1]), ) # print(UrlALL) return UrlALL def GetPaperBaseInfoFromUrlAll(url:str)->str: """The input is the url and the output is all the paper information obtained from the web page, including, doi, title, author, and the date about this volume """ soup = GetUrlInfo(url) temp1 = soup.find_all('li',class_='entry article') temp2= soup.find_all('h2') temp2=re.sub('\\n',' ',temp2[1].text) # print(temp2) volumeYear = re.split(' ',temp2)[-1] paper = [] for i in temp1: if i.find('div',class_='head').find('a')== None: paperDoi = '' else: paperDoi = i.find('div',class_='head').find('a')['href'] title = i.find('cite').find('span',class_='title').text[:-2] paper.append([paperDoi,title]) return paper,volumeYear # test start url = 'http://dblp.uni-trier.de/db/journals/talg/' UrlALL = GetVolumeUrlfromUrl(url) UrlLen = len(UrlALL) # put the url into the query def Write(query,value,num): for count in range(num): query.put(value[count][0],True) # time.sleep(random.random()) print('write end') # from the query get the url and get the paper info with this url def Read(query,num,PaperInfo1,COUNT,i,paperNumber): while True: count = COUNT.get(True) # print("before enter" + str(i) + ' - ' + str(count)+' - '+str(num)) COUNT.put(count, True) if not query.empty(): value = query.get(True) count = COUNT.get(True) count = count + 1 COUNT.put(count,True) paper, thisYear = GetPaperBaseInfoFromUrlAll(value) # just commented print("connected " + str(i) + ' - ' + str(count) + ' - ' + str(num)) numb = paperNumber.get(True) numb = numb + len(paper) paperNumber.put(numb) # just commented # print(paper,thisYear) PaperInfo1.put((paper,thisYear),) # just commented print("the process "+str(i)+' - '+ str(count)+ ' : '+value) if not COUNT.empty(): count = COUNT.get(True) # print("after enter" + str(i) + ' - ' + str(count) + ' - ' + str(num)) COUNT.put(count,True) if int(count) == int(num): print("the process "+str(i)+" end ") break print('read end') # print the paper info def GetPaperInfo(PaperInfo1,paperNumber): for i in range(paperNumber.get(True)): value = PaperInfo1.get(True) print(value) if __name__=='__main__': r_num = 10 # th read process number w_num = 1 # th write process number w_cnt = UrlLen # the write counter q = Queue(UrlLen) # the volune url queue paperNumber = Queue(1) # the all paper number COUNT = Queue(1) # the end tag COUNT.put(int(0)) # first is zero paperNumber.put(int(0)) # first is zero PaperInfo1 = Queue() r_list = [Process( target=Read, args=(q,w_cnt,PaperInfo1,COUNT,i,paperNumber) ) for i in range(r_num)] w_list = [Process( target=Write, args=(q,UrlALL,w_cnt) )] time_start = time.time() [task.start() for task in w_list] [task.start() for task in r_list] [task.join() for task in w_list] [task.join() for task in r_list] time_used = time.time() - time_start GetPaperInfo(PaperInfo1, paperNumber) print('time_used:{}s'.format(time_used)) I have no idea, with debug the process finally enter the process.py -> row:297: try: self.run() and then enter the row:300: util._exit_function() and just a connected the debug but I dont know why the network can cause this error and how to solve this that's all Thank you! A: Hi,this is me again,I tried a concurrent implementation of threads,and global variables for threads are much more comfortable than process queue data sharing. By thread it does implement but my main function can't be stopped, previously with processes it was not possible to proceed to the next step when fetching concurrently, the fetching of data was implemented through threads and continued in the main function but the main function can't be stopped anymore. How interesting! I have designed three functions similar to the previous ones. GetUrlintoQueue is to write the fetched url UrlALL to the queue UrlQueue, UrlLen is the number of the url. import threading import queue count = 0 # Record the number of times a value is fetched from the queue paperNumber = 0 # Record the number of papers def GetUrlintoQueue(UrlQueue,UrlALL,UrlLen): for index in range(UrlLen): UrlQueue.put(UrlALL[index][0], True) print('Write End') UrlQueue.task_done() The other is GetPaperInfofromUrl. Get the url from the UrlQueue and write the information of the corresponding page to PaperInfo, index is the thread number. def GetPaperInfofromUrl(UrlQueue,PaperInfo,index,UrlLen): global count,paperNumber while True: if not UrlQueue.empty(): url = UrlQueue.get(True) count = count + 1 paper, thisYear = GetPaperBaseInfoFromUrlAll(url) # just commented print("connected " + str(index) + '-nd - ' + str(count) + ' - ' + str(UrlLen)) print(paper,thisYear) paperNumber = paperNumber + len(paper) PaperInfo.put((paper, thisYear), True) if count == UrlLen: print("the process " + str(index) + " end ") break UrlQueue.task_done() PaperInfo.task_done() print('the process ' + str(index) +' get paper info end') GetPaperInfo is to show the results about PaperInfo, and it don't change. def GetPaperInfo(PaperInfo,paperNumber): for i in range(paperNumber): value = PaperInfo.get(True) print(value) The main function first sets the corresponding variables, then writes directly first, then 10 threads crawl paper information, and finally shows the results, but after displaying the results still can not exit, I can not understand why. if __name__ == '__main__': url = 'http://dblp.uni-trier.de/db/journals/talg/' UrlALL = GetVolumeUrlfromUrl(url) UrlLen = len(UrlALL) UrlQueue = queue.Queue(UrlLen) PaperInfo = queue.Queue(1000) WriteThread = 1 ReadThread = 10 # url write GetUrlThread = [threading.Thread(target=GetUrlintoQueue, args=(UrlQueue,UrlALL,UrlLen,))] time_start = time.time() [geturl.start() for geturl in GetUrlThread] [geturl.join() for geturl in GetUrlThread] time_used = time.time() - time_start print('time_used:{}s'.format(time_used)) # url write end # paperinfo get PaperinfoGetThread = [threading.Thread(target=GetPaperInfofromUrl, args=(UrlQueue,PaperInfo,index,UrlLen,)) for index in range(ReadThread)] time_start = time.time() [getpaper.start() for getpaper in PaperinfoGetThread] [getpaper.join() for getpaper in PaperinfoGetThread] time_used = time.time() - time_start print('time_used:{}s'.format(time_used)) # paperinfo get end GetPaperInfo(PaperInfo,paperNumber) # show the results import sys # it does not work sys.exit() The debug shows: debug.gif (I dont have 10 reputation so the picture is the type of link. )
Python multiprocessing.Process can not stop when after connecting the network
When I try to crawl thesis information in multiple threads, I cannot close the process after getting the information: error And when I comment the code which function is get the information from network, these processes can end normally. normal This error is trouble me and I don't have any idea, my network connect is by requests and set the response.close() so can any handsome brother or beautiful lady help this confused person? Thanks This is whole code: my python is python 3.7 from multiprocessing import Process, Queue, Pool,Manager,Value import time, random import requests import re from bs4 import BeautifulSoup headers = { 'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36,Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", 'Connection': 'close' } ## Just get the html text def GetUrlInfo(url): response = requests.get(url=url, headers=headers) response.encoding = 'utf-8' response.close() SoupData = BeautifulSoup(response.text, 'lxml') return SoupData def GetVolumeUrlfromUrl(url:str)->str: """input is Journal's url and output is a link and a text description to each issue of the journal""" url = re.sub('http:', 'https:', url) SoupDataTemp = GetUrlInfo(url+'index.html') SoupData = SoupDataTemp.find_all('li') UrlALL = [] for i in SoupData: if i.find('a') != None: volumeUrlRule = '<a href=\"(.*?)\">(.*?)</a>' volumeUrlTemp = re.findall(volumeUrlRule,str(i),re.I) # u = i.find('a')['href'] # # print(u) for u in volumeUrlTemp: if re.findall(url, u[0]): # print(u) UrlALL.append((u[0], u[1]), ) # print(UrlALL) return UrlALL def GetPaperBaseInfoFromUrlAll(url:str)->str: """The input is the url and the output is all the paper information obtained from the web page, including, doi, title, author, and the date about this volume """ soup = GetUrlInfo(url) temp1 = soup.find_all('li',class_='entry article') temp2= soup.find_all('h2') temp2=re.sub('\\n',' ',temp2[1].text) # print(temp2) volumeYear = re.split(' ',temp2)[-1] paper = [] for i in temp1: if i.find('div',class_='head').find('a')== None: paperDoi = '' else: paperDoi = i.find('div',class_='head').find('a')['href'] title = i.find('cite').find('span',class_='title').text[:-2] paper.append([paperDoi,title]) return paper,volumeYear # test start url = 'http://dblp.uni-trier.de/db/journals/talg/' UrlALL = GetVolumeUrlfromUrl(url) UrlLen = len(UrlALL) # put the url into the query def Write(query,value,num): for count in range(num): query.put(value[count][0],True) # time.sleep(random.random()) print('write end') # from the query get the url and get the paper info with this url def Read(query,num,PaperInfo1,COUNT,i,paperNumber): while True: count = COUNT.get(True) # print("before enter" + str(i) + ' - ' + str(count)+' - '+str(num)) COUNT.put(count, True) if not query.empty(): value = query.get(True) count = COUNT.get(True) count = count + 1 COUNT.put(count,True) paper, thisYear = GetPaperBaseInfoFromUrlAll(value) # just commented print("connected " + str(i) + ' - ' + str(count) + ' - ' + str(num)) numb = paperNumber.get(True) numb = numb + len(paper) paperNumber.put(numb) # just commented # print(paper,thisYear) PaperInfo1.put((paper,thisYear),) # just commented print("the process "+str(i)+' - '+ str(count)+ ' : '+value) if not COUNT.empty(): count = COUNT.get(True) # print("after enter" + str(i) + ' - ' + str(count) + ' - ' + str(num)) COUNT.put(count,True) if int(count) == int(num): print("the process "+str(i)+" end ") break print('read end') # print the paper info def GetPaperInfo(PaperInfo1,paperNumber): for i in range(paperNumber.get(True)): value = PaperInfo1.get(True) print(value) if __name__=='__main__': r_num = 10 # th read process number w_num = 1 # th write process number w_cnt = UrlLen # the write counter q = Queue(UrlLen) # the volune url queue paperNumber = Queue(1) # the all paper number COUNT = Queue(1) # the end tag COUNT.put(int(0)) # first is zero paperNumber.put(int(0)) # first is zero PaperInfo1 = Queue() r_list = [Process( target=Read, args=(q,w_cnt,PaperInfo1,COUNT,i,paperNumber) ) for i in range(r_num)] w_list = [Process( target=Write, args=(q,UrlALL,w_cnt) )] time_start = time.time() [task.start() for task in w_list] [task.start() for task in r_list] [task.join() for task in w_list] [task.join() for task in r_list] time_used = time.time() - time_start GetPaperInfo(PaperInfo1, paperNumber) print('time_used:{}s'.format(time_used)) I have no idea, with debug the process finally enter the process.py -> row:297: try: self.run() and then enter the row:300: util._exit_function() and just a connected the debug but I dont know why the network can cause this error and how to solve this that's all Thank you!
[ "Hi,this is me again,I tried a concurrent implementation of threads,and global variables for threads are much more comfortable than process queue data sharing. By thread it does implement but my main function can't be stopped, previously with processes it was not possible to proceed to the next step when fetching concurrently, the fetching of data was implemented through threads and continued in the main function but the main function can't be stopped anymore. How interesting!\nI have designed three functions similar to the previous ones.\nGetUrlintoQueue is to write the fetched url UrlALL to the queue UrlQueue, UrlLen is the number of the url.\nimport threading\nimport queue\n\ncount = 0 # Record the number of times a value is fetched from the queue\npaperNumber = 0 # Record the number of papers\n\ndef GetUrlintoQueue(UrlQueue,UrlALL,UrlLen):\n for index in range(UrlLen):\n UrlQueue.put(UrlALL[index][0], True)\n print('Write End')\n UrlQueue.task_done()\n\nThe other is GetPaperInfofromUrl. Get the url from the UrlQueue and write the information of the corresponding page to PaperInfo, index is the thread number.\ndef GetPaperInfofromUrl(UrlQueue,PaperInfo,index,UrlLen):\n global count,paperNumber\n while True:\n if not UrlQueue.empty():\n url = UrlQueue.get(True)\n count = count + 1\n paper, thisYear = GetPaperBaseInfoFromUrlAll(url) # just commented\n print(\"connected \" + str(index) + '-nd - ' + str(count) + ' - ' + str(UrlLen))\n print(paper,thisYear)\n paperNumber = paperNumber + len(paper)\n PaperInfo.put((paper, thisYear), True)\n if count == UrlLen:\n print(\"the process \" + str(index) + \" end \")\n break\n UrlQueue.task_done()\n PaperInfo.task_done()\n print('the process ' + str(index) +' get paper info end')\n\nGetPaperInfo is to show the results about PaperInfo, and it don't change.\ndef GetPaperInfo(PaperInfo,paperNumber):\n for i in range(paperNumber):\n value = PaperInfo.get(True)\n print(value)\n\nThe main function first sets the corresponding variables, then writes directly first, then 10 threads crawl paper information, and finally shows the results, but after displaying the results still can not exit, I can not understand why.\nif __name__ == '__main__':\n url = 'http://dblp.uni-trier.de/db/journals/talg/'\n UrlALL = GetVolumeUrlfromUrl(url)\n UrlLen = len(UrlALL)\n UrlQueue = queue.Queue(UrlLen)\n PaperInfo = queue.Queue(1000)\n WriteThread = 1\n ReadThread = 10\n\n # url write\n GetUrlThread = [threading.Thread(target=GetUrlintoQueue, args=(UrlQueue,UrlALL,UrlLen,))]\n time_start = time.time()\n [geturl.start() for geturl in GetUrlThread]\n [geturl.join() for geturl in GetUrlThread]\n time_used = time.time() - time_start\n print('time_used:{}s'.format(time_used))\n # url write end\n\n # paperinfo get\n PaperinfoGetThread = [threading.Thread(target=GetPaperInfofromUrl, args=(UrlQueue,PaperInfo,index,UrlLen,)) for index in range(ReadThread)]\n time_start = time.time()\n [getpaper.start() for getpaper in PaperinfoGetThread]\n [getpaper.join() for getpaper in PaperinfoGetThread]\n time_used = time.time() - time_start\n print('time_used:{}s'.format(time_used))\n # paperinfo get end\n \n GetPaperInfo(PaperInfo,paperNumber) # show the results\n import sys # it does not work \n sys.exit()\n\nThe debug shows: debug.gif\n(I dont have 10 reputation so the picture is the type of link. )\n" ]
[ 0 ]
[]
[]
[ "multiprocessing", "python", "python_requests", "queue", "web_crawler" ]
stackoverflow_0074668048_multiprocessing_python_python_requests_queue_web_crawler.txt
Q: How to set none for border color of the phone input when using react-phone-number-input I'm using react-phone-number-input. This is the phone number field: <PhoneInput defaultCountry={"CA"} placeholder={"Phone"} value={phone} onChange={(value: string) => { setPhone(value); }} /> and the css style from: https://gitlab.com/catamphetamine/react-phone-number-input/-/blob/master/style.css I set the border and outline of PhoneInputInput to none but it not working when focus. .PhoneInputInput:focus-visible { flex: 1; min-width: 0; border: none; outline: none; } Here's the image of this field: A: It seems to be caused by the default input of reactjs. I added this to the globals.css file: .input-phone-number input:focus{ outline: none !important; border:none !important; box-shadow: none !important; } and use it in the PhoneInput field, then it worked for me: <PhoneInput defaultCountry={"CA"} placeholder={"Phone"} value={phone} onChange={(value: string) => { setPhone(value); }} className={"input-phone-number"} />
How to set none for border color of the phone input when using react-phone-number-input
I'm using react-phone-number-input. This is the phone number field: <PhoneInput defaultCountry={"CA"} placeholder={"Phone"} value={phone} onChange={(value: string) => { setPhone(value); }} /> and the css style from: https://gitlab.com/catamphetamine/react-phone-number-input/-/blob/master/style.css I set the border and outline of PhoneInputInput to none but it not working when focus. .PhoneInputInput:focus-visible { flex: 1; min-width: 0; border: none; outline: none; } Here's the image of this field:
[ "It seems to be caused by the default input of reactjs. I added this to the globals.css file:\n.input-phone-number input:focus{\n outline: none !important;\n border:none !important;\n box-shadow: none !important;\n}\n\nand use it in the PhoneInput field, then it worked for me:\n<PhoneInput\n defaultCountry={\"CA\"}\n placeholder={\"Phone\"}\n value={phone}\n onChange={(value: string) => {\n setPhone(value);\n }}\n className={\"input-phone-number\"}\n/>\n\n" ]
[ 0 ]
[]
[]
[ "input_field", "next.js", "react_phone_number_input", "reactjs", "tailwind_css" ]
stackoverflow_0074105288_input_field_next.js_react_phone_number_input_reactjs_tailwind_css.txt
Q: Create a dataframe with and specific name within a function depends on input I need to create a dataframe with and specific name within a function depends on input. Here is my code: ` def filter_season (df_teams ,season): df_teams[season]= df_teams[df_teams['SEASON']== season ] return df_teams[season] ` Error got: ValueError: Wrong number of items passed 34, placement implies 1 I expect a result where the dataframe is created with a name due to the condition said in the funcion. ex: filter_season(df_teams, 22) #(Refers to season 2022) OUTPUT: df_teams_22 A: IIUC, use varname with globals : def filter_name(df, season): sub_df = df.loc[df['SEASON'].eq(season)].copy() globals()[nameof(df) + "_" + season] = sub_df And here is an example to give you the general logic. import pandas as pd from varname import nameof df = pd.DataFrame({'character': ['cobra', 'viper', 'sidewinder'], 'max_speed': [1, 4, 7], 'shield': [2, 5, 8]}) ​ print(df) character max_speed shield 0 cobra 1 2 1 viper 4 5 2 sidewinder 7 8 Now, let's apply our function to return a new dataframe with a custom name (based on the filter). def filter_name(df, charname): sub_df = df.loc[df['character'].eq(charname)].copy() globals()[nameof(df) + "_" + charname] = sub_df filter_name(df, "viper") # Output : print(df_viper, type(df_viper)) character max_speed shield 1 viper 4 5 <class 'pandas.core.frame.DataFrame'>
Create a dataframe with and specific name within a function depends on input
I need to create a dataframe with and specific name within a function depends on input. Here is my code: ` def filter_season (df_teams ,season): df_teams[season]= df_teams[df_teams['SEASON']== season ] return df_teams[season] ` Error got: ValueError: Wrong number of items passed 34, placement implies 1 I expect a result where the dataframe is created with a name due to the condition said in the funcion. ex: filter_season(df_teams, 22) #(Refers to season 2022) OUTPUT: df_teams_22
[ "IIUC, use varname with globals :\ndef filter_name(df, season):\n sub_df = df.loc[df['SEASON'].eq(season)].copy()\n globals()[nameof(df) + \"_\" + season] = sub_df\n\nAnd here is an example to give you the general logic.\nimport pandas as pd\nfrom varname import nameof\n\ndf = pd.DataFrame({'character': ['cobra', 'viper', 'sidewinder'],\n 'max_speed': [1, 4, 7],\n 'shield': [2, 5, 8]})\n​\nprint(df)\n character max_speed shield\n0 cobra 1 2\n1 viper 4 5\n2 sidewinder 7 8\n\nNow, let's apply our function to return a new dataframe with a custom name (based on the filter).\ndef filter_name(df, charname):\n sub_df = df.loc[df['character'].eq(charname)].copy()\n globals()[nameof(df) + \"_\" + charname] = sub_df\n\nfilter_name(df, \"viper\")\n\n# Output :\nprint(df_viper, type(df_viper))\n\n character max_speed shield\n1 viper 4 5 <class 'pandas.core.frame.DataFrame'>\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "function", "python", "python_3.x" ]
stackoverflow_0074672040_dataframe_function_python_python_3.x.txt
Q: How to connect to SQL Server Analysis Services from SSMS remotely My SQL Server Analysis Services is hosted and accessed in local network. I am trying to connect to SSAS remotely from SSMS within the network. But I do not see an option to connect via userame and password. There is only option for "Windows authentication" and 2 for Azure, which we do not use. How can I overcome this and connect to the SSAS using my local username and password from the SSAS server? A: SSAS is just available through windows authentication. You can use domain user (Active Directory) for connecting to remote SSAS server.
How to connect to SQL Server Analysis Services from SSMS remotely
My SQL Server Analysis Services is hosted and accessed in local network. I am trying to connect to SSAS remotely from SSMS within the network. But I do not see an option to connect via userame and password. There is only option for "Windows authentication" and 2 for Azure, which we do not use. How can I overcome this and connect to the SSAS using my local username and password from the SSAS server?
[ "SSAS is just available through windows authentication. You can use domain user (Active Directory) for connecting to remote SSAS server.\n" ]
[ 1 ]
[]
[]
[ "sql_server", "ssas", "ssis" ]
stackoverflow_0074673637_sql_server_ssas_ssis.txt
Q: Python WebScraping - Sleep oscillate in slow websites I have a webscraping, but the site I'm using in some days is slow and sometimes not. Using the fixed SLEEP, it gives an error in a few days. How to fix this? I use SLEEP in the intervals of the tasks that I have placed, because the site is sometimes slow and does not return the result giving me an error. from bs4 import BeautifulSoup from selenium.webdriver.common.by import By from selenium.webdriver.firefox import options from selenium.webdriver.firefox.options import Options from selenium.webdriver.support.ui import Select import pandas as pd import json from time import sleep options = Options() options.headless = True navegador = webdriver.Firefox(options = options) link = '****************************' navegador.get(url = link) sleep(1) usuario = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_txtLogin') usuario.send_keys('****************************') sleep(1) senha = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_txtSenha') senha.send_keys('****************************') sleep(2.5) botaologin = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_btnEnviar') botaologin.click() sleep(40) agendamento = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_TreeView2t8') agendamento.click() sleep(2) selecdia = navegador.find_element(By.CSS_SELECTOR, "a[title='06 de dezembro']") selecdia.click() sleep(2) selecterminal = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_ddlVagasTerminalEmpresa') selecterminal.click() sleep(1) select = Select(navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_ddlVagasTerminalEmpresa')) select.select_by_index(1) sleep(10) buscalink = navegador.find_elements(by=By.XPATH, value='//*[@id="divScroll"]') for element in buscalink: teste3 = element.get_attribute('innerHTML') soup = BeautifulSoup(teste3, "html.parser") Vagas = soup.find_all(title="Vaga disponível.") print(Vagas) temp=[] for i in Vagas: on_click = i.get('onclick') temp.append(on_click) df = pd.DataFrame(temp) df.to_csv('test.csv', mode='a', header=False, index=False) It returns an error because the page does not load in time and it cannot get the data, but this time is variable A: Instead of all these hardcoded sleeps you need to use WebDriverWait expected_conditions explicit waits. With it you can set some timeout period so Selenium will poll the page periodically until the expected condition is fulfilled. For example if you need to click a button you will wait for that element clickability. Once this condition is found Selenium will return you that element and you will be able to click it. This will reduce all the redundant delays on the one hand and will keep waiting until the condition is matched on the other hand (until it is inside the defined timeout). So, your code can be modified as following: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC #----- wait = WebDriverWait(navegador, 30) navegador.get(link) wait.until(EC.element_to_be_clickable((By.ID, "ctl00_ctl00_Content_Content_txtLogin"))).send_keys('****************************') wait.until(EC.element_to_be_clickable((By.ID, "ctl00_ctl00_Content_Content_txtSenha"))).send_keys('****************************') wait.until(EC.element_to_be_clickable((By.ID, "ctl00_ctl00_Content_Content_btnEnviar"))).click() wait.until(EC.element_to_be_clickable((By.ID, "ctl00_ctl00_Content_Content_TreeView2t8"))).click() wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[title='06 de dezembro']"))).click() etc.
Python WebScraping - Sleep oscillate in slow websites
I have a webscraping, but the site I'm using in some days is slow and sometimes not. Using the fixed SLEEP, it gives an error in a few days. How to fix this? I use SLEEP in the intervals of the tasks that I have placed, because the site is sometimes slow and does not return the result giving me an error. from bs4 import BeautifulSoup from selenium.webdriver.common.by import By from selenium.webdriver.firefox import options from selenium.webdriver.firefox.options import Options from selenium.webdriver.support.ui import Select import pandas as pd import json from time import sleep options = Options() options.headless = True navegador = webdriver.Firefox(options = options) link = '****************************' navegador.get(url = link) sleep(1) usuario = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_txtLogin') usuario.send_keys('****************************') sleep(1) senha = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_txtSenha') senha.send_keys('****************************') sleep(2.5) botaologin = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_btnEnviar') botaologin.click() sleep(40) agendamento = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_TreeView2t8') agendamento.click() sleep(2) selecdia = navegador.find_element(By.CSS_SELECTOR, "a[title='06 de dezembro']") selecdia.click() sleep(2) selecterminal = navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_ddlVagasTerminalEmpresa') selecterminal.click() sleep(1) select = Select(navegador.find_element(by=By.ID, value='ctl00_ctl00_Content_Content_ddlVagasTerminalEmpresa')) select.select_by_index(1) sleep(10) buscalink = navegador.find_elements(by=By.XPATH, value='//*[@id="divScroll"]') for element in buscalink: teste3 = element.get_attribute('innerHTML') soup = BeautifulSoup(teste3, "html.parser") Vagas = soup.find_all(title="Vaga disponível.") print(Vagas) temp=[] for i in Vagas: on_click = i.get('onclick') temp.append(on_click) df = pd.DataFrame(temp) df.to_csv('test.csv', mode='a', header=False, index=False) It returns an error because the page does not load in time and it cannot get the data, but this time is variable
[ "Instead of all these hardcoded sleeps you need to use WebDriverWait expected_conditions explicit waits.\nWith it you can set some timeout period so Selenium will poll the page periodically until the expected condition is fulfilled.\nFor example if you need to click a button you will wait for that element clickability. Once this condition is found Selenium will return you that element and you will be able to click it.\nThis will reduce all the redundant delays on the one hand and will keep waiting until the condition is matched on the other hand (until it is inside the defined timeout).\nSo, your code can be modified as following:\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\n#-----\nwait = WebDriverWait(navegador, 30)\n\nnavegador.get(link)\n\nwait.until(EC.element_to_be_clickable((By.ID, \"ctl00_ctl00_Content_Content_txtLogin\"))).send_keys('****************************')\nwait.until(EC.element_to_be_clickable((By.ID, \"ctl00_ctl00_Content_Content_txtSenha\"))).send_keys('****************************')\nwait.until(EC.element_to_be_clickable((By.ID, \"ctl00_ctl00_Content_Content_btnEnviar\"))).click()\nwait.until(EC.element_to_be_clickable((By.ID, \"ctl00_ctl00_Content_Content_TreeView2t8\"))).click()\nwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"a[title='06 de dezembro']\"))).click()\n\netc.\n" ]
[ 1 ]
[]
[]
[ "python", "selenium", "sleep", "web_scraping", "webdriverwait" ]
stackoverflow_0074670711_python_selenium_sleep_web_scraping_webdriverwait.txt
Q: Get current learning rate when using ReduceLROnPlateau I am using ReduceLROnPlateau to modify the learning rate during training of a PyTorch mode. ReduceLROnPlateau does not inherit from LRScheduler and does not implement the get_last_lr method which is PyTorch's recommended way of getting the current learning rate when using a learning rate scheduler. How can I get the learning rate when using ReduceLROnPlateau? Currently I am doing the following but am not sure if this is rigorous and correct: lr = optimizer.state_dict()["param_groups"][0]["lr"] A: You can skip the state_dict of the optimizer and access the learning rate directly: optimizer.param_groups[0]["lr"]
Get current learning rate when using ReduceLROnPlateau
I am using ReduceLROnPlateau to modify the learning rate during training of a PyTorch mode. ReduceLROnPlateau does not inherit from LRScheduler and does not implement the get_last_lr method which is PyTorch's recommended way of getting the current learning rate when using a learning rate scheduler. How can I get the learning rate when using ReduceLROnPlateau? Currently I am doing the following but am not sure if this is rigorous and correct: lr = optimizer.state_dict()["param_groups"][0]["lr"]
[ "You can skip the state_dict of the optimizer and access the learning rate directly:\noptimizer.param_groups[0][\"lr\"]\n\n" ]
[ 0 ]
[]
[]
[ "learning_rate", "python", "pytorch" ]
stackoverflow_0074668086_learning_rate_python_pytorch.txt
Q: batch file to get file from last modified folder I have a batch file that compares two files and uses xcopy to copy the file if the time stamp is different. So it goes something like this: set sourcefiletime= for %%X in (%Source%) do set sourcefiletime=%%~tX set targetfiletime= for %%X in (%Local%) do set targetfiletime=%%~tX if "%sourcefiletime%" == "%targetfiletime%" goto noUpdate xcopy... The trouble I have now is that the folder structure has changed from always being a constant folder name to having different names based on date and time. And there may be multiple folders. e.g. "Build_20160411_105904" "Build_20160410_155605" "Build_20160410_021104" ... Is there any way I can get my batch file to check the "last modified" folder and grab the file from there? If it helps, the file I need will always have the same name, so can I check the parent folder's directories for the last modified file instead? Apologies if something similar has been asked before. A: Not tested @echo off set "build_dir=c:\builds" set "source_filename=build.result" for /f "tokens=* delims=" %%# in ('dir /b /a:d /o:-d /t:w "%build_dir%"') do ( set "last_build_dir=%%~f#" goto :break ) :break set "source_file=%last_build_dir%\%source_filename%" this will get the file with name %source_filename% from the last modified folder in %build_dir% . And then you can reuse your code. A: If you want to find the last modified folder name within C:\apps\test directory then you can put below code snippet in a batch script and execute it which will print the name of the last modified folder name. @echo OFF for /f "delims=" %%i in ('dir "C:\apps\test" /b /ad-h /t:c /o-d') do ( set latestModifiedFolderName=%%i goto :break ) :break echo Latest modified folder within C:\apps\test directory is %latestModifiedFolderName%
batch file to get file from last modified folder
I have a batch file that compares two files and uses xcopy to copy the file if the time stamp is different. So it goes something like this: set sourcefiletime= for %%X in (%Source%) do set sourcefiletime=%%~tX set targetfiletime= for %%X in (%Local%) do set targetfiletime=%%~tX if "%sourcefiletime%" == "%targetfiletime%" goto noUpdate xcopy... The trouble I have now is that the folder structure has changed from always being a constant folder name to having different names based on date and time. And there may be multiple folders. e.g. "Build_20160411_105904" "Build_20160410_155605" "Build_20160410_021104" ... Is there any way I can get my batch file to check the "last modified" folder and grab the file from there? If it helps, the file I need will always have the same name, so can I check the parent folder's directories for the last modified file instead? Apologies if something similar has been asked before.
[ "Not tested\n@echo off\nset \"build_dir=c:\\builds\"\nset \"source_filename=build.result\"\n\nfor /f \"tokens=* delims=\" %%# in ('dir /b /a:d /o:-d /t:w \"%build_dir%\"') do (\n set \"last_build_dir=%%~f#\"\n goto :break\n)\n:break\nset \"source_file=%last_build_dir%\\%source_filename%\"\n\nthis will get the file with name %source_filename% from the last modified folder in %build_dir% . And then you can reuse your code.\n", "If you want to find the last modified folder name within C:\\apps\\test directory then you can put below code snippet in a batch script and execute it which will print the name of the last modified folder name.\n@echo OFF\n\nfor /f \"delims=\" %%i in ('dir \"C:\\apps\\test\" /b /ad-h /t:c /o-d') do (\n set latestModifiedFolderName=%%i\n goto :break\n)\n\n:break\necho Latest modified folder within C:\\apps\\test directory is %latestModifiedFolderName%\n\n" ]
[ 2, 0 ]
[]
[]
[ "batch_file" ]
stackoverflow_0036545366_batch_file.txt
Q: Arabic keyboard in flutter I want to enter Arabic numbers in my application. How to insert an Arabic number keyboard in the flutter app? I have tried a lot but couldn't find the solution. A: I had to change the source code of the virtual_keyboard_multi_language: ^1.0.3 package to get the desired output. The package used English numbers on an Arabic keyboard so I just change the keys from English to Arabic. Step 1 Install virtual_keyboard_multi_language: ^1.0.3 package Step 2 copy and paste this demo code in main.dart import 'package:flutter/material.dart'; import 'package:virtual_keyboard_multi_language/virtual_keyboard_multi_language.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, home: HomeScreen(), ); } } class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { TextEditingController textEditingController = TextEditingController(); bool showKeyboard = false; late FocusNode focusNode; @override void initState() { super.initState(); focusNode = FocusNode(); // listen to focus changes focusNode.addListener(() { if (focusNode.hasFocus == false && showKeyboard == false) { setState(() { showKeyboard = false; }); } }); } void setFocus() { FocusScope.of(context).requestFocus(focusNode); } @override Widget build(BuildContext context) { return GestureDetector( onTap: () { if (focusNode.hasFocus == false) { setState(() { showKeyboard = false; }); } }, child: Scaffold( body: Stack( children: [ Column( children: [ Padding( padding: const EdgeInsets.all(20.0), child: TextField( focusNode: focusNode, keyboardType: TextInputType.none, controller: textEditingController, textDirection: TextDirection.rtl, onTap: () { setState(() { showKeyboard = true; }); }, decoration: InputDecoration( border: OutlineInputBorder( borderSide: const BorderSide(color: Colors.black), borderRadius: BorderRadius.circular(10), ), enabledBorder: OutlineInputBorder( borderSide: const BorderSide(color: Colors.black), borderRadius: BorderRadius.circular(10), ), focusedBorder: OutlineInputBorder( borderSide: const BorderSide(color: Colors.black), borderRadius: BorderRadius.circular(10), )), ), ), ], ), Positioned( bottom: 0, child: showKeyboard ? Container( color: Colors.black, child: VirtualKeyboard( fontSize: 20, textColor: Colors.white, textController: textEditingController, type: VirtualKeyboardType.Alphanumeric, defaultLayouts: const [ VirtualKeyboardDefaultLayouts.Arabic ], ), ) : Container(), ) ], )), ); } } Step 3 go to "flutter_windows_3.3.4-stable\flutter.pub-cache\hosted\pub.dartlang.org\virtual_keyboard_multi_language-1.0.3\lib\src\layout_keys.dart" and change in line 111 from const [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ], to const ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'], Step 4 Restart the program to see the Arabic keyboard Output Hope this helps. Happy Coding :)
Arabic keyboard in flutter
I want to enter Arabic numbers in my application. How to insert an Arabic number keyboard in the flutter app? I have tried a lot but couldn't find the solution.
[ "I had to change the source code of the virtual_keyboard_multi_language: ^1.0.3 package to get the desired output. The package used English numbers on an Arabic keyboard so I just change the keys from English to Arabic.\nStep 1\nInstall virtual_keyboard_multi_language: ^1.0.3 package\nStep 2\ncopy and paste this demo code in main.dart\nimport 'package:flutter/material.dart';\nimport 'package:virtual_keyboard_multi_language/virtual_keyboard_multi_language.dart';\n\nvoid main() => runApp(const MyApp());\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n @override\n Widget build(BuildContext context) {\n return const MaterialApp(\n debugShowCheckedModeBanner: false,\n home: HomeScreen(),\n );\n }\n}\n\nclass HomeScreen extends StatefulWidget {\n const HomeScreen({super.key});\n\n @override\n State<HomeScreen> createState() => _HomeScreenState();\n}\n\nclass _HomeScreenState extends State<HomeScreen> {\n TextEditingController textEditingController = TextEditingController();\n bool showKeyboard = false;\n late FocusNode focusNode;\n\n @override\n void initState() {\n super.initState();\n focusNode = FocusNode();\n\n // listen to focus changes\n focusNode.addListener(() {\n if (focusNode.hasFocus == false && showKeyboard == false) {\n setState(() {\n showKeyboard = false;\n });\n }\n });\n }\n\n void setFocus() {\n FocusScope.of(context).requestFocus(focusNode);\n }\n\n @override\n Widget build(BuildContext context) {\n return GestureDetector(\n onTap: () {\n if (focusNode.hasFocus == false) {\n setState(() {\n showKeyboard = false;\n });\n }\n },\n child: Scaffold(\n body: Stack(\n children: [\n Column(\n children: [\n Padding(\n padding: const EdgeInsets.all(20.0),\n child: TextField(\n focusNode: focusNode,\n keyboardType: TextInputType.none,\n controller: textEditingController,\n textDirection: TextDirection.rtl,\n onTap: () {\n setState(() {\n showKeyboard = true;\n });\n },\n decoration: InputDecoration(\n border: OutlineInputBorder(\n borderSide: const BorderSide(color: Colors.black),\n borderRadius: BorderRadius.circular(10),\n ),\n enabledBorder: OutlineInputBorder(\n borderSide: const BorderSide(color: Colors.black),\n borderRadius: BorderRadius.circular(10),\n ),\n focusedBorder: OutlineInputBorder(\n borderSide: const BorderSide(color: Colors.black),\n borderRadius: BorderRadius.circular(10),\n )),\n ),\n ),\n ],\n ),\n Positioned(\n bottom: 0,\n child: showKeyboard\n ? Container(\n color: Colors.black,\n child: VirtualKeyboard(\n fontSize: 20,\n textColor: Colors.white,\n textController: textEditingController,\n type: VirtualKeyboardType.Alphanumeric,\n defaultLayouts: const [\n VirtualKeyboardDefaultLayouts.Arabic\n ],\n ),\n )\n : Container(),\n )\n ],\n )),\n );\n }\n}\n\nStep 3\ngo to \"flutter_windows_3.3.4-stable\\flutter.pub-cache\\hosted\\pub.dartlang.org\\virtual_keyboard_multi_language-1.0.3\\lib\\src\\layout_keys.dart\"\nand change in line 111\nfrom\n const [\n'1',\n'2',\n'3',\n'4',\n'5',\n'6',\n'7',\n'8',\n'9',\n'0',\n],\n\nto\nconst ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'],\n\nStep 4\nRestart the program to see the Arabic keyboard\nOutput\n\nHope this helps. Happy Coding :)\n" ]
[ 0 ]
[]
[]
[ "arabic_support", "custom_keyboard", "flutter" ]
stackoverflow_0074672576_arabic_support_custom_keyboard_flutter.txt
Q: Cannot import ClassPathXmlApplicationContext I learning Java Spring Framework by listening to the "Spring & Hibernate for Beginners" udemy course. I struggled while trying to import org.springframework.context.support.ClassPathXmlApplicationContext; Eclipse shows me the error: ClassPathXmlApplicationContext cannot be resolved The author of the course to which I'm listening is still not involving Maven (and pom.xml) because he is concentrating on "pure" Java and Spring in his course, so please don't direct me to use Maven for organizing the project. I added all jars from spring-framework-5.0.2.RELEASE-dist to my projects buildpath. The funny thing is that when i do CTRL+Shift+O Eclipse automatically imports the org.springframework.context.support.ClassPathXmlApplicationContext package, but it shows error in import line (red line under org) and shows an error in my main function on the line where I try to use context as: ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Please help. A: I just want to share that Ш have found a solution to my problem. My execution environment JRE was set to be JAVA SE 10. After I change it to be JAVA SE 1.8 everything started working, and no errors are showing now. I do it like this: Right click on your project, then open Properties Java build path Click on Add Library Choose JRE system library Click on environments and choose JAVA SE 1.8 After that, I removed JAVA SE 10 from my build path and everything becomes right. A: I would check the following: a. right click the project -> properties -> Java Build Path -> Libraries (tab) Make sure spring-context jar is present and there is only one version of it. If that is the case, try closing and reopening the IDE. A: I solved this problem in intelliJ by doing the following: File > Project Structure Modules Dependencies Tab Click (+) button Add JARs or Directories Navigate to the correct .jar to import ClassPathXmlApplicationContext Because I have been using maven in the past, I already had the .jar file downloaded. My .jar file was at the following location on my drive: home folder Unhide hidden folders .m2 folder repository > org > springframework > spring-context > 5.2.4 RELEASE Select .jar file I also had to import the "spring-beans" and "spring-core" libraries to get the code to run in my environment. A: Delete the module-info.java file in your project, It's only used if you're using Java's built-in module system. Hope that helps:)
Cannot import ClassPathXmlApplicationContext
I learning Java Spring Framework by listening to the "Spring & Hibernate for Beginners" udemy course. I struggled while trying to import org.springframework.context.support.ClassPathXmlApplicationContext; Eclipse shows me the error: ClassPathXmlApplicationContext cannot be resolved The author of the course to which I'm listening is still not involving Maven (and pom.xml) because he is concentrating on "pure" Java and Spring in his course, so please don't direct me to use Maven for organizing the project. I added all jars from spring-framework-5.0.2.RELEASE-dist to my projects buildpath. The funny thing is that when i do CTRL+Shift+O Eclipse automatically imports the org.springframework.context.support.ClassPathXmlApplicationContext package, but it shows error in import line (red line under org) and shows an error in my main function on the line where I try to use context as: ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Please help.
[ "I just want to share that Ш have found a solution to my problem.\nMy execution environment JRE was set to be JAVA SE 10. After I change it to be JAVA SE 1.8 everything started working, and no errors are showing now.\nI do it like this:\n\nRight click on your project, then open Properties\nJava build path\nClick on Add Library\nChoose JRE system library\nClick on environments and choose JAVA SE 1.8\nAfter that, I removed JAVA SE 10 from my build path and everything becomes right.\n\n", "I would check the following:\na. right click the project -> properties -> Java Build Path -> Libraries (tab) \nMake sure spring-context jar is present and there is only one version of it. \nIf that is the case, try closing and reopening the IDE. \n", "I solved this problem in intelliJ by doing the following:\n\nFile > Project Structure\nModules\nDependencies Tab\nClick (+) button\nAdd JARs or Directories\nNavigate to the correct .jar to import ClassPathXmlApplicationContext\n\nBecause I have been using maven in the past, I already had the .jar file downloaded. My .jar file was at the following location on my drive:\n\nhome folder\nUnhide hidden folders\n.m2 folder\nrepository > org > springframework > spring-context > 5.2.4 RELEASE\nSelect .jar file\n\nI also had to import the \"spring-beans\" and \"spring-core\" libraries to get the code to run in my environment.\n", "Delete the module-info.java file in your project, It's only used if you're using Java's built-in module system.\nHope that helps:)\n" ]
[ 4, 1, 1, 1 ]
[ "Try deleting module-info.java, it worked for me!!\nHope it helps!!\n" ]
[ -1 ]
[ "eclipse", "java", "spring" ]
stackoverflow_0051543425_eclipse_java_spring.txt
Q: Swift Charts: .chartYScale only seems to work with increments of 100? Given this is a heart rate chart, I'm trying to make the chart's Y max scale 210 (bpm), e.g. .chartYScale(domain: 0 ... 210) however it only seems to scale correctly if I pass in 200 or 300, anything in between doesn't work. Is this intended or a bug? import SwiftUI import Charts import HealthKit struct TestYAxisRangeChart: View { let heartRateData = [80.0, 90.0, 120.0, 150.0, 160.0, 140.0, 125.0, 110.0, 88.0] var body: some View { Chart { ForEach(heartRateData, id: \.self) { sample in LineMark( x: .value("", heartRateData.firstIndex(of: sample)!), y: .value("HR", sample)) .foregroundStyle(Color.red) } } .chartYAxis{ AxisMarks(position: .leading) } .frame(height: 300) .padding(.horizontal) .chartYScale(domain: 0 ... 210) } } struct TestYAxisRangeChart_Previews: PreviewProvider { static var previews: some View { TestYAxisRangeChart() } } A: Maybe you just need this (Xcode 14b4 / iOS 16): let yValues = stride(from: 0, to: 220, by: 10).map { $0 } // << here !! var body: some View { Chart { ForEach(heartRateData, id: \.self) { sample in LineMark( x: .value("", heartRateData.firstIndex(of: sample)!), y: .value("HR", sample)) .foregroundStyle(Color.red) } } .chartYAxis{ AxisMarks(position: .leading, values: yValues) // << here !! } Test module on GitHub A: Use range instead of domain, and plotDimension uses the data range automatically, IIRC: .chartYScale(range: .plotDimension(padding: 20)) A: chartYScale can be passed an automatic domain excluding 0 if you just want to have the scale not start with 0 (e.g. .chartYScale(domain: .automatic(includesZero: false))), but depending on your data and the computed y stride, 0 may still be visible. To include 210 without setting an explicit domain or values, you could always just plot an invisible point mark at 210, but this will lead to a rounded max y axis value (e.g 250-300 depending on your data). The only way to make the max exactly 210 is taking full control of the axis via values or domain as suggested by others.
Swift Charts: .chartYScale only seems to work with increments of 100?
Given this is a heart rate chart, I'm trying to make the chart's Y max scale 210 (bpm), e.g. .chartYScale(domain: 0 ... 210) however it only seems to scale correctly if I pass in 200 or 300, anything in between doesn't work. Is this intended or a bug? import SwiftUI import Charts import HealthKit struct TestYAxisRangeChart: View { let heartRateData = [80.0, 90.0, 120.0, 150.0, 160.0, 140.0, 125.0, 110.0, 88.0] var body: some View { Chart { ForEach(heartRateData, id: \.self) { sample in LineMark( x: .value("", heartRateData.firstIndex(of: sample)!), y: .value("HR", sample)) .foregroundStyle(Color.red) } } .chartYAxis{ AxisMarks(position: .leading) } .frame(height: 300) .padding(.horizontal) .chartYScale(domain: 0 ... 210) } } struct TestYAxisRangeChart_Previews: PreviewProvider { static var previews: some View { TestYAxisRangeChart() } }
[ "Maybe you just need this (Xcode 14b4 / iOS 16):\nlet yValues = stride(from: 0, to: 220, by: 10).map { $0 } // << here !!\n\nvar body: some View {\n Chart {\n ForEach(heartRateData, id: \\.self) { sample in\n LineMark(\n x: .value(\"\", heartRateData.firstIndex(of: sample)!),\n y: .value(\"HR\", sample))\n .foregroundStyle(Color.red)\n \n }\n\n }\n .chartYAxis{\n AxisMarks(position: .leading, values: yValues) // << here !!\n }\n\n\nTest module on GitHub\n", "Use range instead of domain, and plotDimension uses the data range automatically, IIRC:\n.chartYScale(range: .plotDimension(padding: 20))\n\n", "chartYScale can be passed an automatic domain excluding 0 if you just want to have the scale not start with 0 (e.g. .chartYScale(domain: .automatic(includesZero: false))), but depending on your data and the computed y stride, 0 may still be visible. To include 210 without setting an explicit domain or values, you could always just plot an invisible point mark at 210, but this will lead to a rounded max y axis value (e.g 250-300 depending on your data). The only way to make the max exactly 210 is taking full control of the axis via values or domain as suggested by others.\n" ]
[ 5, 0, 0 ]
[]
[]
[ "ios", "swift", "swiftcharts", "swiftui" ]
stackoverflow_0072902333_ios_swift_swiftcharts_swiftui.txt
Q: Python http server with multiple directories Is it possible to add multiple paths from different driver in os,chdir method? like, 'd:\\folder1' , 'e:\\folder2' I tried to add two paths, but could not join them, got syntax error A: I managed to do it using symbolic links: On windows, you can create symbolic links to directories as so: mklink /D <symbolic link name> <destination directory> So in a new folder you can run: mklink /D folder1 "D:\folder1" mklink /D folder2 "E:\folder2" On linux this would be: ln -s <destination directory> <symbolic link name> ln -s /mnt/d/folder1 folder1 ln -s /mnt/e/folder2 folder2 Then by running a python HTTP server in the directory, you can access both folders as sub-folders of the server:
Python http server with multiple directories
Is it possible to add multiple paths from different driver in os,chdir method? like, 'd:\\folder1' , 'e:\\folder2' I tried to add two paths, but could not join them, got syntax error
[ "I managed to do it using symbolic links:\nOn windows, you can create symbolic links to directories as so:\nmklink /D <symbolic link name> <destination directory>\n\nSo in a new folder you can run:\nmklink /D folder1 \"D:\\folder1\"\nmklink /D folder2 \"E:\\folder2\"\n\nOn linux this would be:\nln -s <destination directory> <symbolic link name>\n\nln -s /mnt/d/folder1 folder1 \nln -s /mnt/e/folder2 folder2\n\nThen by running a python HTTP server in the directory, you can access both folders as sub-folders of the server:\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074673599_python.txt
Q: Vector field with numpy and mathplotlib I know how to generate a vector field in all plane, but know I'm trying to create the vector just in some specific line, my code is import numpy as np import matplotlib.pyplot as plt x = np.linspace(-3,3,15) y = np.linspace(-3,3,15) x,y = np.meshgrid(x,y) u = x v = (x-y) plt.quiver(x,y,u,v,color = "purple") plt.show() that create the vector field in all plane, but I want the vector field along the line x=y, how should I do that? To create a line, with x1 and y1 for example, and change x,y for x1,y1 in u,v A: For the case along the line x=y, you can define the coordinates as follows: X = np.linspace(0,9,10) Y = np.linspace(0,13.5,10) U = np.ones(10) V = np.ones(10) plt.quiver(X, Y, U, V, color='b', units='xy', scale=1) plt.xlim(-2, 15) plt.ylim(-2, 15) plt.show() Output
Vector field with numpy and mathplotlib
I know how to generate a vector field in all plane, but know I'm trying to create the vector just in some specific line, my code is import numpy as np import matplotlib.pyplot as plt x = np.linspace(-3,3,15) y = np.linspace(-3,3,15) x,y = np.meshgrid(x,y) u = x v = (x-y) plt.quiver(x,y,u,v,color = "purple") plt.show() that create the vector field in all plane, but I want the vector field along the line x=y, how should I do that? To create a line, with x1 and y1 for example, and change x,y for x1,y1 in u,v
[ "For the case along the line x=y, you can define the coordinates as follows:\nX = np.linspace(0,9,10)\nY = np.linspace(0,13.5,10) \nU = np.ones(10)\nV = np.ones(10) \n \nplt.quiver(X, Y, U, V, color='b', units='xy', scale=1)\nplt.xlim(-2, 15)\nplt.ylim(-2, 15)\nplt.show()\n\nOutput\n\n" ]
[ 0 ]
[]
[]
[ "python", "vector_graphics" ]
stackoverflow_0074672574_python_vector_graphics.txt
Q: Any clue why I cant seem to get the correct answer after pressing "play again"? As you can see from the complexity of the program I am new to this but I've heard this is the best place to ask! 'use strict' //DOM Elements declaration. const square = document.getElementById("color1") const guesses = document.getElementsByClassName("guess"); const guessArr = [...guesses] const playAgain = document.querySelector(".play-again"); const title = document.getElementById("title") var playing = true; init(); function init() { let pickedColor = createColor(); console.log(pickedColor); title.innerHTML = "GUESS THE COLOUR!" square.style.backgroundColor = pickedColor; playing = true; updateGuesses(pickedColor); guess(pickedColor); } //Setting the playing field. function createColor () { let r = Math.floor(Math.random() * 255); let g = Math.floor(Math.random() * 255); let b = Math.floor(Math.random() * 255); let color = `rgb(${r}, ${g}, ${b})` return color } function updateGuesses (pickedColor) { for (let i=0; i < 3; i++){ guesses[i].textContent = createColor() // Button[0] = rgb(random, random, random)... } //Pick a random button at runtime and make it the right guess. let correct = guesses[Math.floor(Math.random() * 3)]; correct.textContent = pickedColor } //Playing the game function guess(pickedColor){ guessArr.forEach((guess) => { guess.addEventListener("click", ()=>{ console.log(guess.textContent); if (playing){ if (guess.textContent == pickedColor){ title.innerHTML = "You Win " playing = false; document.querySelector("body").style.backgroundColor = pickedColor; } else { title.innerHTML = "YOU LOSE ❌" playing = false; } } }) }); } playAgain.addEventListener("click", init) In the code above. The game seems to work the first time around. If I select the correct colour, It will appear with "You Win!". However, unless I manually refresh the page, I can never seem to get the winning condition again regardless of if I press the correct answer. Ive uploaded the project onto codepen to help visualise what im talking about as im unsure this code will be enough. Thanks in advance. https://codepen.io/remcrw/pen/ExRObWG It works with global variables for the pickedColor but I was trying to clean up my code and see if I could minimise the use of global variables and this is where I encountered the problem. A: The issue is that when you call the init function and set playing to true, you are not resetting the value of playing back to true in the guess function when the user clicks the "Play again" button. This means that once playing is set to false, it remains false and the user can never win the game again without refreshing the page. To fix this, you can simply add a line to the guess function to reset the value of playing to true when the "Play again" button is clicked: function guess(pickedColor) { guessArr.forEach((guess) => { guess.addEventListener("click", () => { console.log(guess.textContent); if (playing) { if (guess.textContent == pickedColor) { title.innerHTML = "You Win "; playing = false; document.querySelector("body").style.backgroundColor = pickedColor; } else { title.innerHTML = "YOU LOSE ❌"; playing = false; } } }); }); // Reset the value of playing to true when the user clicks the "Play again" button playAgain.addEventListener("click", () => { playing = true; }); }
Any clue why I cant seem to get the correct answer after pressing "play again"?
As you can see from the complexity of the program I am new to this but I've heard this is the best place to ask! 'use strict' //DOM Elements declaration. const square = document.getElementById("color1") const guesses = document.getElementsByClassName("guess"); const guessArr = [...guesses] const playAgain = document.querySelector(".play-again"); const title = document.getElementById("title") var playing = true; init(); function init() { let pickedColor = createColor(); console.log(pickedColor); title.innerHTML = "GUESS THE COLOUR!" square.style.backgroundColor = pickedColor; playing = true; updateGuesses(pickedColor); guess(pickedColor); } //Setting the playing field. function createColor () { let r = Math.floor(Math.random() * 255); let g = Math.floor(Math.random() * 255); let b = Math.floor(Math.random() * 255); let color = `rgb(${r}, ${g}, ${b})` return color } function updateGuesses (pickedColor) { for (let i=0; i < 3; i++){ guesses[i].textContent = createColor() // Button[0] = rgb(random, random, random)... } //Pick a random button at runtime and make it the right guess. let correct = guesses[Math.floor(Math.random() * 3)]; correct.textContent = pickedColor } //Playing the game function guess(pickedColor){ guessArr.forEach((guess) => { guess.addEventListener("click", ()=>{ console.log(guess.textContent); if (playing){ if (guess.textContent == pickedColor){ title.innerHTML = "You Win " playing = false; document.querySelector("body").style.backgroundColor = pickedColor; } else { title.innerHTML = "YOU LOSE ❌" playing = false; } } }) }); } playAgain.addEventListener("click", init) In the code above. The game seems to work the first time around. If I select the correct colour, It will appear with "You Win!". However, unless I manually refresh the page, I can never seem to get the winning condition again regardless of if I press the correct answer. Ive uploaded the project onto codepen to help visualise what im talking about as im unsure this code will be enough. Thanks in advance. https://codepen.io/remcrw/pen/ExRObWG It works with global variables for the pickedColor but I was trying to clean up my code and see if I could minimise the use of global variables and this is where I encountered the problem.
[ "The issue is that when you call the init function and set playing to true, you are not resetting the value of playing back to true in the guess function when the user clicks the \"Play again\" button. This means that once playing is set to false, it remains false and the user can never win the game again without refreshing the page.\nTo fix this, you can simply add a line to the guess function to reset the value of playing to true when the \"Play again\" button is clicked:\nfunction guess(pickedColor) {\n guessArr.forEach((guess) => {\n guess.addEventListener(\"click\", () => {\n console.log(guess.textContent);\n if (playing) {\n if (guess.textContent == pickedColor) {\n title.innerHTML = \"You Win \";\n playing = false;\n document.querySelector(\"body\").style.backgroundColor = pickedColor;\n } else {\n title.innerHTML = \"YOU LOSE ❌\";\n playing = false;\n }\n }\n });\n });\n\n // Reset the value of playing to true when the user clicks the \"Play again\" button\n playAgain.addEventListener(\"click\", () => {\n playing = true;\n });\n}\n\n" ]
[ 0 ]
[]
[]
[ "dom", "javascript" ]
stackoverflow_0074669753_dom_javascript.txt
Q: Setting cookie in iframe - different Domain We have our site integrated as an iframe into another site that runs on a different domain. It seems that we cannot set cookies. Has anybody encountered this issue before? Any ideas? A: Since your content is being loaded into an iframe from a remote domain, it is classed as a third-party cookie. The vast majority of third-party cookies are provided by advertisers (these are usually marked as tracking cookies by anti-malware software) and many people consider them to be an invasion of privacy. Consequently, most browsers offer a facility to block third-party cookies, which is probably the cause of the issue you are encountering. A: From new update of Chromium in February 4, 2020 (Chrome 80). Cookies default to SameSite=Lax. According to this link. To fix this, you just need to mark your cookies are SameSite=None and Secure. To understand what is Samesite cookies, please see this document A: After reading through Facebook's docs on iframe canvas pages, I figured out how to set cookies in iframes with different domains. I created a proof of concept sinatra application here: https://github.com/agibralter/iframe-widget-test There is more discussion on how Facebook does it here: How does Facebook set cross-domain cookies for iFrames on canvas pages? A: IE requires you to set a P3P policy before it will allow third-party frames to set cookies, under the default privacy settings. Supposedly P3P allows the user to limit what information goes to what parties who promise to handle it in certain ways. In practice it's pretty much worthless as users can't really set any meaningful limitations on how they want information handled; in the end it's just a fairly uniform setting acting as a hoop that all third parties have to jump through, saying “I'll be nice with your personal information” even if they have no intention of doing so. A: Despite adding SameSite=None and Secure in the cookie, you might not see the cookie being sent in the request. This might be because of the browser settings. e.g, on Brave, you have to explicity disable it. As more and more people are switching to Brave or block third party cookies using browser extensions, you should not rely on this mechanism.
Setting cookie in iframe - different Domain
We have our site integrated as an iframe into another site that runs on a different domain. It seems that we cannot set cookies. Has anybody encountered this issue before? Any ideas?
[ "Since your content is being loaded into an iframe from a remote domain, it is classed as a third-party cookie.\nThe vast majority of third-party cookies are provided by advertisers (these are usually marked as tracking cookies by anti-malware software) and many people consider them to be an invasion of privacy. Consequently, most browsers offer a facility to block third-party cookies, which is probably the cause of the issue you are encountering.\n", "From new update of Chromium in February 4, 2020 (Chrome 80).\nCookies default to SameSite=Lax. According to this link.\nTo fix this, you just need to mark your cookies are SameSite=None and Secure.\nTo understand what is Samesite cookies, please see this document\n", "After reading through Facebook's docs on iframe canvas pages, I figured out how to set cookies in iframes with different domains. I created a proof of concept sinatra application here: https://github.com/agibralter/iframe-widget-test\nThere is more discussion on how Facebook does it here: How does Facebook set cross-domain cookies for iFrames on canvas pages?\n", "IE requires you to set a P3P policy before it will allow third-party frames to set cookies, under the default privacy settings.\nSupposedly P3P allows the user to limit what information goes to what parties who promise to handle it in certain ways. In practice it's pretty much worthless as users can't really set any meaningful limitations on how they want information handled; in the end it's just a fairly uniform setting acting as a hoop that all third parties have to jump through, saying “I'll be nice with your personal information” even if they have no intention of doing so.\n", "Despite adding SameSite=None and Secure in the cookie, you might not see the cookie being sent in the request. This might be because of the browser settings. e.g, on Brave, you have to explicity disable it.\n\nAs more and more people are switching to Brave or block third party cookies using browser extensions, you should not rely on this mechanism.\n" ]
[ 36, 20, 13, 9, 0 ]
[]
[]
[ "cookies", "iframe", "security" ]
stackoverflow_0002117248_cookies_iframe_security.txt
Q: How would one do minv3.1 in pinescript? In TC2000 its possible to use minv3.1 (minimum volume requirement for each of the last 3 bars) which I cannot figure out for pinescript (since its not the same a average volume). How would one create it? I've only tried V[0] > 1000 and V[1] > 1000 and V[2] > 1000 But I'm not sure if that's even correct or the best approach. A: You are not so far , you should use the volume function (from pinescript) and try : minimum_vol_requirement = 1000 if volume[2] > minimum_vol_requirement if volume[1] > minimum_vol_requirement if volume > minimum_vol_requirement // here all your conditions are ok A: The ta.lowest() function returns the lowest value for a given number of bars back. You can use this to check the lowest value of volume and then compare it to 1000: minVolume = ta.lowest(volume, 3) condition = minVolume > 1000
How would one do minv3.1 in pinescript?
In TC2000 its possible to use minv3.1 (minimum volume requirement for each of the last 3 bars) which I cannot figure out for pinescript (since its not the same a average volume). How would one create it? I've only tried V[0] > 1000 and V[1] > 1000 and V[2] > 1000 But I'm not sure if that's even correct or the best approach.
[ "You are not so far , you should use the volume function (from pinescript) and try : \nminimum_vol_requirement = 1000\nif volume[2] > minimum_vol_requirement\n if volume[1] > minimum_vol_requirement\n if volume > minimum_vol_requirement\n // here all your conditions are ok\n\n", "The ta.lowest() function returns the lowest value for a given number of bars back. You can use this to check the lowest value of volume and then compare it to 1000:\nminVolume = ta.lowest(volume, 3)\ncondition = minVolume > 1000\n\n" ]
[ 0, 0 ]
[]
[]
[ "pine_script", "pinescript_v5" ]
stackoverflow_0074671990_pine_script_pinescript_v5.txt
Q: Get most recent file in a directory on Linux Looking for a command that will return the single most recent file in a directory. Not seeing a limit parameter to ls... A: ls -Art | tail -n 1 This will return the latest modified file or directory. Not very elegant, but it works. Used flags: -A list all files except . and .. -r reverse order while sorting -t sort by time, newest first A: ls -t | head -n1 This command actually gives the latest modified file or directory in the current working directory. A: This is a recursive version (i.e. it finds the most recently updated file in a certain directory or any of its subdirectory) find /dir/path -type f -printf "%T@ %p\n" | sort -n | cut -d' ' -f 2- | tail -n 1 Brief layman explanation of command line: find /dir/path -type f finds all the files in the directory -printf "%T@ %p\n" prints a line for each file where %T@ is the float seconds since 1970 epoch and %p is the filename path and \n is the new line character for more info see man find | is a shell pipe (see man bash section on Pipelines) sort -n means to sort on the first column and to treat the token as numerical instead of lexicographic (see man sort) cut -d' ' -f 2- means to split each line using the character and then to print all tokens starting at the second token (see man cut) NOTE: -f 2 would print only the second token tail -n 1 means to print the last line (see man tail) A: A note about reliability: Since the newline character is as valid as any in a file name, any solution that relies on lines like the head/tail based ones are flawed. With GNU ls, another option is to use the --quoting-style=shell-always option and a bash array: eval "files=($(ls -t --quoting-style=shell-always))" ((${#files[@]} > 0)) && printf '%s\n' "${files[0]}" (add the -A option to ls if you also want to consider hidden files). If you want to limit to regular files (disregard directories, fifos, devices, symlinks, sockets...), you'd need to resort to GNU find. With bash 4.4 or newer (for readarray -d) and GNU coreutils 8.25 or newer (for cut -z): readarray -t -d '' files < <( LC_ALL=C find . -maxdepth 1 -type f ! -name '.*' -printf '%T@/%f\0' | sort -rzn | cut -zd/ -f2) ((${#files[@]} > 0)) && printf '%s\n' "${files[0]}" Or recursively: readarray -t -d '' files < <( LC_ALL=C find . -name . -o -name '.*' -prune -o -type f -printf '%T@%p\0' | sort -rzn | cut -zd/ -f2-) Best here would be to use zsh and its glob qualifiers instead of bash to avoid all this hassle: Newest regular file in the current directory: printf '%s\n' *(.om[1]) Including hidden ones: printf '%s\n' *(D.om[1]) Second newest: printf '%s\n' *(.om[2]) Check file age after symlink resolution: printf '%s\n' *(-.om[1]) Recursively: printf '%s\n' **/*(.om[1]) Also, with the completion system (compinit and co) enabled, Ctrl+Xm becomes a completer that expands to the newest file. So: vi Ctrl+Xm Would make you edit the newest file (you also get a chance to see which it before you press Return). vi Alt+2Ctrl+Xm For the second-newest file. vi *.cCtrl+Xm for the newest c file. vi *(.)Ctrl+Xm for the newest regular file (not directory, nor fifo/device...), and so on. A: I use: ls -ABrt1 --group-directories-first | tail -n1 It gives me just the file name, excluding folders. A: The find / sort solution works great until the number of files gets really large (like an entire file system). Use awk instead to just keep track of the most recent file: find $DIR -type f -printf "%T@ %p\n" | awk ' BEGIN { recent = 0; file = "" } { if ($1 > recent) { recent = $1; file = $0; } } END { print file; }' | sed 's/^[0-9]*\.[0-9]* //' A: ls -lAtr | tail -1 The other solutions do not include files that start with '.'. This command will also include '.' and '..', which may or may not be what you want: ls -latr | tail -1 A: I like echo *(om[1]) (zsh syntax) as that just gives the file name and doesn't invoke any other command. A: Shorted variant based on dmckee's answer: ls -t | head -1 A: If you want to get the most recent changed file also including any subdirectories you can do it with this little oneliner: find . -type f -exec stat -c '%Y %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done If you want to do the same not for changed files, but for accessed files you simple have to change the %Y parameter from the stat command to %X. And your command for most recent accessed files looks like this: find . -type f -exec stat -c '%X %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done For both commands you also can change the var="1" parameter if you want to list more than just one file. A: I personally prefer to use as few not built-in bash commands as I can (to reduce the number of expensive fork and exec syscalls). To sort by date the ls needed to be called. But using of head is not really necessary. I use the following one-liner (works only on systems supporting name pipes): read newest < <(ls -t *.log) or to get the name of the oldest file read oldest < <(ls -rt *.log) (Mind the space between the two '<' marks!) If the hidden files are also needed -A arg could be added. I hope this could help. A: With only Bash builtins, closely following BashFAQ/003: shopt -s nullglob for f in * .*; do [[ -d $f ]] && continue [[ $f -nt $latest ]] && latest=$f done printf '%s\n' "$latest" A: using R recursive option .. you may consider this as enhancement for good answers here ls -arRtlh | tail -50 A: try this simple command ls -ltq <path> | head -n 1 If you want file name - last modified, path = /ab/cd/*.log If you want directory name - last modified, path = /ab/cd/*/ A: ls -t -1 | sed '1q' Will show the last modified item in the folder. Pair with grep to find latest entries with keywords ls -t -1 | grep foo | sed '1q' A: Recursively: find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head A: All those ls/tail solutions work perfectly fine for files in a directory - ignoring subdirectories. In order to include all files in your search (recursively), find can be used. gioele suggested sorting the formatted find output. But be careful with whitespaces (his suggestion doesn't work with whitespaces). This should work with all file names: find $DIR -type f -printf "%T@ %p\n" | sort -n | sed -r 's/^[0-9.]+\s+//' | tail -n 1 | xargs -I{} ls -l "{}" This sorts by mtime, see man find: %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C `strftime' function. The possible values for k are listed below; some of them might not be available on all systems, due to differences in `strftime' between systems. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. %Ck File's last status change time in the format specified by k, which is the same as for %A. %Tk File's last modification time in the format specified by k, which is the same as for %A. So just replace %T with %C to sort by ctime. A: Finding the most current file in every directory according to a pattern, e.g. the sub directories of the working directory that have name ending with "tmp" (case insensitive): find . -iname \*tmp -type d -exec sh -c "ls -lArt {} | tail -n 1" \; A: Presuming you don't care about hidden files that start with a . ls -rt | tail -n 1 Otherwise ls -Art | tail -n 1 A: ls -Frt | grep "[^/]$" | tail -n 1 A: Find the file with prefix of shravan* and view less $(ls -Art shravan* | tail -n 1) A: If you want to find the last modified folder name within /apps/test directory then you can put below code snippet in a batch script and execute it which will print the name of the last modified folder name. #!/bin/bash -e export latestModifiedFolderName=$(ls -td /apps/test/*/ | head -n1) echo Latest modified folder within /apps/test directory is $latestModifiedFolderName
Get most recent file in a directory on Linux
Looking for a command that will return the single most recent file in a directory. Not seeing a limit parameter to ls...
[ "ls -Art | tail -n 1\n\nThis will return the latest modified file or directory. Not very elegant, but it works.\nUsed flags:\n-A list all files except . and ..\n-r reverse order while sorting\n-t sort by time, newest first\n", "ls -t | head -n1\n\nThis command actually gives the latest modified file or directory in the current working directory.\n", "This is a recursive version (i.e. it finds the most recently updated file in a certain directory or any of its subdirectory)\nfind /dir/path -type f -printf \"%T@ %p\\n\" | sort -n | cut -d' ' -f 2- | tail -n 1\n\nBrief layman explanation of command line:\n\nfind /dir/path -type f finds all the files in the directory\n\n-printf \"%T@ %p\\n\" prints a line for each file where %T@ is the float seconds since 1970 epoch and %p is the filename path and \\n is the new line character\nfor more info see man find\n\n\n| is a shell pipe (see man bash section on Pipelines)\nsort -n means to sort on the first column and to treat the token as numerical instead of lexicographic (see man sort)\ncut -d' ' -f 2- means to split each line using the character and then to print all tokens starting at the second token (see man cut)\n\nNOTE: -f 2 would print only the second token\n\n\ntail -n 1 means to print the last line (see man tail)\n\n", "A note about reliability:\nSince the newline character is as valid as any in a file name, any solution that relies on lines like the head/tail based ones are flawed.\nWith GNU ls, another option is to use the --quoting-style=shell-always option and a bash array:\neval \"files=($(ls -t --quoting-style=shell-always))\"\n((${#files[@]} > 0)) && printf '%s\\n' \"${files[0]}\"\n\n(add the -A option to ls if you also want to consider hidden files).\nIf you want to limit to regular files (disregard directories, fifos, devices, symlinks, sockets...), you'd need to resort to GNU find.\nWith bash 4.4 or newer (for readarray -d) and GNU coreutils 8.25 or newer (for cut -z):\nreadarray -t -d '' files < <(\n LC_ALL=C find . -maxdepth 1 -type f ! -name '.*' -printf '%T@/%f\\0' |\n sort -rzn | cut -zd/ -f2)\n\n((${#files[@]} > 0)) && printf '%s\\n' \"${files[0]}\"\n\nOr recursively:\nreadarray -t -d '' files < <(\n LC_ALL=C find . -name . -o -name '.*' -prune -o -type f -printf '%T@%p\\0' |\n sort -rzn | cut -zd/ -f2-)\n\nBest here would be to use zsh and its glob qualifiers instead of bash to avoid all this hassle:\nNewest regular file in the current directory:\nprintf '%s\\n' *(.om[1])\n\nIncluding hidden ones:\nprintf '%s\\n' *(D.om[1])\n\nSecond newest:\nprintf '%s\\n' *(.om[2])\n\nCheck file age after symlink resolution:\nprintf '%s\\n' *(-.om[1])\n\nRecursively:\nprintf '%s\\n' **/*(.om[1])\n\nAlso, with the completion system (compinit and co) enabled, Ctrl+Xm becomes a completer that expands to the newest file.\nSo:\nvi Ctrl+Xm\nWould make you edit the newest file (you also get a chance to see which it before you press Return).\nvi Alt+2Ctrl+Xm\nFor the second-newest file.\nvi *.cCtrl+Xm\nfor the newest c file.\nvi *(.)Ctrl+Xm\nfor the newest regular file (not directory, nor fifo/device...), and so on.\n", "I use:\nls -ABrt1 --group-directories-first | tail -n1\nIt gives me just the file name, excluding folders.\n", "The find / sort solution works great until the number of files gets really large (like an entire file system). Use awk instead to just keep track of the most recent file:\nfind $DIR -type f -printf \"%T@ %p\\n\" | \nawk '\nBEGIN { recent = 0; file = \"\" }\n{\nif ($1 > recent)\n {\n recent = $1;\n file = $0;\n }\n}\nEND { print file; }' |\nsed 's/^[0-9]*\\.[0-9]* //'\n\n", "ls -lAtr | tail -1\nThe other solutions do not include files that start with '.'.\nThis command will also include '.' and '..', which may or may not be what you want:\nls -latr | tail -1\n", "I like echo *(om[1]) (zsh syntax) as that just gives the file name and doesn't invoke any other command.\n", "Shorted variant based on dmckee's answer:\nls -t | head -1\n\n", "If you want to get the most recent changed file also including any subdirectories you can do it with this little oneliner:\nfind . -type f -exec stat -c '%Y %n' {} \\; | sort -nr | awk -v var=\"1\" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t \"+%b %d %T %Y\"); echo \"$d -- $f\"; done\n\nIf you want to do the same not for changed files, but for accessed files you simple have to change the \n%Y parameter from the stat command to %X. And your command for most recent accessed files looks like this:\nfind . -type f -exec stat -c '%X %n' {} \\; | sort -nr | awk -v var=\"1\" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t \"+%b %d %T %Y\"); echo \"$d -- $f\"; done\n\nFor both commands you also can change the var=\"1\" parameter if you want to list more than just one file.\n", "I personally prefer to use as few not built-in bash commands as I can (to reduce the number of expensive fork and exec syscalls). To sort by date the ls needed to be called. But using of head is not really necessary. I use the following one-liner (works only on systems supporting name pipes):\nread newest < <(ls -t *.log)\n\nor to get the name of the oldest file\nread oldest < <(ls -rt *.log)\n\n(Mind the space between the two '<' marks!)\nIf the hidden files are also needed -A arg could be added.\nI hope this could help.\n", "With only Bash builtins, closely following BashFAQ/003:\nshopt -s nullglob\n\nfor f in * .*; do\n [[ -d $f ]] && continue\n [[ $f -nt $latest ]] && latest=$f\ndone\n\nprintf '%s\\n' \"$latest\"\n\n", "using R recursive option .. you may consider this as enhancement for good answers here \nls -arRtlh | tail -50\n\n", "try this simple command\nls -ltq <path> | head -n 1\n\nIf you want file name - last modified, path = /ab/cd/*.log\nIf you want directory name - last modified, path = /ab/cd/*/\n", "ls -t -1 | sed '1q'\n\nWill show the last modified item in the folder. Pair with grep to find latest entries with keywords\nls -t -1 | grep foo | sed '1q'\n\n", "Recursively:\nfind $1 -type f -exec stat --format '%Y :%y %n' \"{}\" \\; | sort -nr | cut -d: -f2- | head\n\n", "All those ls/tail solutions work perfectly fine for files in a directory - ignoring subdirectories.\nIn order to include all files in your search (recursively), find can be used. gioele suggested sorting the formatted find output. But be careful with whitespaces (his suggestion doesn't work with whitespaces).\nThis should work with all file names:\nfind $DIR -type f -printf \"%T@ %p\\n\" | sort -n | sed -r 's/^[0-9.]+\\s+//' | tail -n 1 | xargs -I{} ls -l \"{}\"\n\nThis sorts by mtime, see man find:\n%Ak File's last access time in the format specified by k, which is either `@' or a directive for the C `strftime' function. The possible values for k are listed below; some of them might not be available on all systems, due to differences in `strftime' between systems.\n @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part.\n%Ck File's last status change time in the format specified by k, which is the same as for %A.\n%Tk File's last modification time in the format specified by k, which is the same as for %A.\n\nSo just replace %T with %C to sort by ctime.\n", "Finding the most current file in every directory according to a pattern, e.g. the sub directories of the working directory that have name ending with \"tmp\" (case insensitive):\nfind . -iname \\*tmp -type d -exec sh -c \"ls -lArt {} | tail -n 1\" \\;\n\n", "Presuming you don't care about hidden files that start with a .\nls -rt | tail -n 1\n\nOtherwise\nls -Art | tail -n 1\n\n", "ls -Frt | grep \"[^/]$\" | tail -n 1\n\n", "Find the file with prefix of shravan* and view\nless $(ls -Art shravan* | tail -n 1)\n\n", "If you want to find the last modified folder name within /apps/test directory then you can put below code snippet in a batch script and execute it which will print the name of the last modified folder name.\n#!/bin/bash -e\n\nexport latestModifiedFolderName=$(ls -td /apps/test/*/ | head -n1)\n\necho Latest modified folder within /apps/test directory is $latestModifiedFolderName\n\n" ]
[ 410, 240, 147, 25, 10, 9, 8, 7, 7, 6, 5, 4, 3, 2, 2, 2, 1, 1, 1, 1, 0, 0 ]
[ "I needed to do it too, and I found these commands. these work for me:\nIf you want last file by its date of creation in folder(access time) :\nls -Aru | tail -n 1 \n\nAnd if you want last file that has changes in its content (modify time) :\nls -Art | tail -n 1 \n\n" ]
[ -1 ]
[ "command_line", "linux", "shell" ]
stackoverflow_0001015678_command_line_linux_shell.txt
Q: Strapi: error when I register custom middlewares I’m creating middlewares in strapi I have three models, company, profile, people, and I’m registering three middlewares, For instance, the middleware for company is in: src/api/company/middlewares/my-middleware, which is: module.exports = (config, { strapi }) => { return (context, next) => { console.log("middleware of company”); }; }; I register each middleware in ./config/middlewares.js as (I'm following strapi v4 documentation) https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/configurations/required/middlewares.html module.exports = [ "strapi::errors", "strapi::security", "strapi::cors", "strapi::poweredBy", "strapi::logger", "strapi::query", "strapi::body", "strapi::session", "strapi::favicon", "strapi::public", { resolve: "./src/api/company/middlewares/my-middleware", }, { resolve: "./src/api/people/middlewares/my-middleware", }, { resolve: "./src/api/profile/middlewares/my-middleware", }, ]; No matter where I place these registrations, the outcome is the same But now, if I call, from postman, http://localhost:1337/api/companies?populate=*, for example, the middleware is executed but I get an error saying that this address was not found, If I comment out the middlewares registration, the error disappears but the middlewares are not executed What could I be doing wrong? Thanks in advance A: It seems like you never call the next function. module.exports = (config, { strapi }) => { return (context, next) => { console.log("middleware of company”); next() }; }; Keep in mind that if your middleware is async, you need to await next().
Strapi: error when I register custom middlewares
I’m creating middlewares in strapi I have three models, company, profile, people, and I’m registering three middlewares, For instance, the middleware for company is in: src/api/company/middlewares/my-middleware, which is: module.exports = (config, { strapi }) => { return (context, next) => { console.log("middleware of company”); }; }; I register each middleware in ./config/middlewares.js as (I'm following strapi v4 documentation) https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/configurations/required/middlewares.html module.exports = [ "strapi::errors", "strapi::security", "strapi::cors", "strapi::poweredBy", "strapi::logger", "strapi::query", "strapi::body", "strapi::session", "strapi::favicon", "strapi::public", { resolve: "./src/api/company/middlewares/my-middleware", }, { resolve: "./src/api/people/middlewares/my-middleware", }, { resolve: "./src/api/profile/middlewares/my-middleware", }, ]; No matter where I place these registrations, the outcome is the same But now, if I call, from postman, http://localhost:1337/api/companies?populate=*, for example, the middleware is executed but I get an error saying that this address was not found, If I comment out the middlewares registration, the error disappears but the middlewares are not executed What could I be doing wrong? Thanks in advance
[ "It seems like you never call the next function.\nmodule.exports = (config, { strapi }) => {\n return (context, next) => {\n console.log(\"middleware of company”);\n next()\n };\n};\n\nKeep in mind that if your middleware is async, you need to await next().\n" ]
[ 0 ]
[]
[]
[ "middleware", "strapi" ]
stackoverflow_0074670794_middleware_strapi.txt
Q: I got the remote MediaStream but it doesn't show in the video tag in Web RTC After creating the offer, setting up local and remote description, I can receive media stream from offer end, but when I put it to the answer, it doesn't show up. I use addstream event. // Handles remote MediaStream success by adding it as the remoteVideo src. function gotRemoteMediaStream(event) { console.log(event.stream); const mediaStream = event.stream; localVideo.srcObject = mediaStream; console.log('Remote peer connection received remote stream.'); } I use the console and see the event was there This is just javascript application, I haven't apply any server implementation for this. A: Update Your replace your code with this. HTML Code: <video id="localVideo" autoplay="true"></video> ScreenShare Code: function gotRemoteMediaStream(event) { console.log('Remote stream added.'); alert('Remote stream added.'); if ('srcObject' in localVideo) { localVideo.srcObject = event.streams[0]; } else { // deprecated localVideo.src = window.URL.createObjectURL(event.stream); } remoteScreenStream = event.stream}; I Hope, it will work for you.
I got the remote MediaStream but it doesn't show in the video tag in Web RTC
After creating the offer, setting up local and remote description, I can receive media stream from offer end, but when I put it to the answer, it doesn't show up. I use addstream event. // Handles remote MediaStream success by adding it as the remoteVideo src. function gotRemoteMediaStream(event) { console.log(event.stream); const mediaStream = event.stream; localVideo.srcObject = mediaStream; console.log('Remote peer connection received remote stream.'); } I use the console and see the event was there This is just javascript application, I haven't apply any server implementation for this.
[ "Update Your replace your code with this.\nHTML Code:\n<video id=\"localVideo\" autoplay=\"true\"></video>\n\nScreenShare Code:\nfunction gotRemoteMediaStream(event) {\nconsole.log('Remote stream added.');\nalert('Remote stream added.');\n if ('srcObject' in localVideo) {\nlocalVideo.srcObject = event.streams[0];\n } else {\n// deprecated\nlocalVideo.src = window.URL.createObjectURL(event.stream);\n}\n remoteScreenStream = event.stream};\n\nI Hope, it will work for you.\n" ]
[ 0 ]
[]
[]
[ "javascript", "webrtc" ]
stackoverflow_0074673543_javascript_webrtc.txt
Q: Value of the previous period according to the filter enter image description hereI want to create a measure that calculates the value of the "Objectif" measure of the previous period according to the date filter: ´ For example : if filter on Year 2021 take the value of 2020 if filter on Qt4 2021 take the value of Qt 3 2021 if filter october 2021 take the value of september 2021 Automatically in dax?, A: You can use this DAX time intelligence function: SAMEPERIODLASTYEAR
Value of the previous period according to the filter
enter image description hereI want to create a measure that calculates the value of the "Objectif" measure of the previous period according to the date filter: ´ For example : if filter on Year 2021 take the value of 2020 if filter on Qt4 2021 take the value of Qt 3 2021 if filter october 2021 take the value of september 2021 Automatically in dax?,
[ "You can use this DAX time intelligence function:\nSAMEPERIODLASTYEAR\n" ]
[ 0 ]
[]
[]
[ "dax" ]
stackoverflow_0074672024_dax.txt
Q: i am making an admin page for a project im doing and have an edit product feature but when i try to edit my product it gives me this error Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Milk',product_desc='Gallon of Reduced Fat  Milk',product_price='3...' at line 1 in C:\xampp\htdocs\Fresh-Super-Market\admin_area\edit_product.php:256 Stack trace: #0 C:\xampp\htdocs\Fresh-Super-Market\admin_area\edit_product.php(256): mysqli_query(Object(mysqli), 'update products...') #1 C:\xampp\htdocs\Fresh-Super-Market\admin_area\index.php(95): include('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\Fresh-Super-Market\admin_area\edit_product.php on line 256 CODE: `<?php if(!isset($_SESSION['admin_email'])){ echo "<script>window.open('login.php','_self')</script>"; }else{ ?> <?php if(isset($_GET['edit_product'])){ $edit_id = $_GET['edit_product']; $get_p = "select * from products where product_id='$edit_id'"; $run_edit = mysqli_query($con,$get_p); $row_edit = mysqli_fetch_array($run_edit); $p_id = $row_edit['product_id']; $p_title = $row_edit['product_title']; $p_cat = $row_edit['p_cat_id']; $cat = $row_edit['cat_id']; $p_image1 = $row_edit['product_img1']; $p_price = $row_edit['product_price']; $p_keywords = $row_edit['product_keywords']; $p_desc = $row_edit['product_desc']; } $get_p_cat = "select * from product_categories where p_cat_id='$p_cat'"; $run_p_cat = mysqli_query($con,$get_p_cat); $row_p_cat = mysqli_fetch_array($run_p_cat); $p_cat_title = $row_p_cat['p_cat_title']; $get_cat = "select * from categories where cat_id='$cat'"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> Insert Products </title> </head> <body> <div class="row"><!-- row Begin --> <div class="col-lg-12"><!-- col-lg-12 Begin --> <ol class="breadcrumb"><!-- breadcrumb Begin --> <li class="active"><!-- active Begin --> <i class="fa fa-dashboard"></i> Dashboard / Edit Products </li><!-- active Finish --> </ol><!-- breadcrumb Finish --> </div><!-- col-lg-12 Finish --> </div><!-- row Finish --> <div class="row"><!-- row Begin --> <div class="col-lg-12"><!-- col-lg-12 Begin --> <div class="panel panel-default"><!-- panel panel-default Begin --> <div class="panel-heading"><!-- panel-heading Begin --> <h3 class="panel-title"><!-- panel-title Begin --> <i class="fa fa-money fa-fw"></i> Insert Product </h3><!-- panel-title Finish --> </div> <!-- panel-heading Finish --> <div class="panel-body"><!-- panel-body Begin --> <form method="post" class="form-horizontal" enctype="multipart/form-data"><!-- form-horizontal Begin --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Title </label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="product_title" type="text" class="form-control" required value="<?php echo $p_title; ?>"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Category </label> <div class="col-md-6"><!-- col-md-6 Begin --> <select name="product_cat" class="form-control"><!-- form-control Begin --> <option value="<?php echo $p_cat; ?>"> <?php echo $p_cat_title; ?> </option> <?php $get_p_cats = "select * from product_categories"; $run_p_cats = mysqli_query($con,$get_p_cats); while ($row_p_cats=mysqli_fetch_array($run_p_cats)){ $p_cat_id = $row_p_cats['p_cat_id']; $p_cat_title = $row_p_cats['p_cat_title']; echo " <option value='$p_cat_id'> $p_cat_title </option> "; } ?> </select><!-- form-control Finish --> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Image 1 </label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="product_img1" type="file" class="form-control" required> <br> <img width="70" height="70" src="product_images/<?php echo $p_image1; ?>" alt="<?php echo $p_image1; ?>"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Price </label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="product_price" type="text" class="form-control" required value="<?php echo $p_price; ?>"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Keywords </label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="product_keywords" type="text" class="form-control" required value="<?php echo $p_keywords; ?>"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Desc </label> <div class="col-md-6"><!-- col-md-6 Begin --> <textarea name="product_desc" cols="19" rows="6" class="form-control"> <?php echo $p_desc; ?> </textarea> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"></label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="update" value="Update Product" type="submit" class="btn btn-primary form-control"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> </form><!-- form-horizontal Finish --> </div><!-- panel-body Finish --> </div><!-- canel panel-default Finish --> </div><!-- col-lg-12 Finish --> </div><!-- row Finish --> <script src="js/tinymce/tinymce.min.js"></script> <script>tinymce.init({ selector:'textarea'});</script> </body> </html> <?php if(isset($_POST['update'])){ $product_title = $_POST['product_title']; $product_cat = $_POST['product_cat']; $product_price = $_POST['product_price']; $product_keywords = $_POST['product_keywords']; $product_desc = $_POST['product_desc']; $product_img1 = $_FILES['product_img1']['name']; $temp_name1 = $_FILES['product_img1']['tmp_name']; move_uploaded_file($temp_name1,"product_images/$product_img1"); $update_product = "update products set p_cat_id='$product_cat',date=NOW(),product_title='$product_title',product_img1='$product_img1,product_keywords='$product_keywords',product_desc='$product_desc',product_price='$product_price' where product_id='$p_id'"; $run_product = mysqli_query($con,$update_product); if($run_product){ echo "<script>alert('Your product has been updated Successfully')</script>"; echo "<script>window.open('index.php?view_products','_self')</script>"; } } ?> <?php } ?> i am making an admin page for a project im doing and have an edit product feature but when i try to edit my product it gives me this error im not sure what to do.
i am making an admin page for a project im doing and have an edit product feature but when i try to edit my product it gives me this error
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Milk',product_desc='Gallon of Reduced Fat  Milk',product_price='3...' at line 1 in C:\xampp\htdocs\Fresh-Super-Market\admin_area\edit_product.php:256 Stack trace: #0 C:\xampp\htdocs\Fresh-Super-Market\admin_area\edit_product.php(256): mysqli_query(Object(mysqli), 'update products...') #1 C:\xampp\htdocs\Fresh-Super-Market\admin_area\index.php(95): include('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\Fresh-Super-Market\admin_area\edit_product.php on line 256 CODE: `<?php if(!isset($_SESSION['admin_email'])){ echo "<script>window.open('login.php','_self')</script>"; }else{ ?> <?php if(isset($_GET['edit_product'])){ $edit_id = $_GET['edit_product']; $get_p = "select * from products where product_id='$edit_id'"; $run_edit = mysqli_query($con,$get_p); $row_edit = mysqli_fetch_array($run_edit); $p_id = $row_edit['product_id']; $p_title = $row_edit['product_title']; $p_cat = $row_edit['p_cat_id']; $cat = $row_edit['cat_id']; $p_image1 = $row_edit['product_img1']; $p_price = $row_edit['product_price']; $p_keywords = $row_edit['product_keywords']; $p_desc = $row_edit['product_desc']; } $get_p_cat = "select * from product_categories where p_cat_id='$p_cat'"; $run_p_cat = mysqli_query($con,$get_p_cat); $row_p_cat = mysqli_fetch_array($run_p_cat); $p_cat_title = $row_p_cat['p_cat_title']; $get_cat = "select * from categories where cat_id='$cat'"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> Insert Products </title> </head> <body> <div class="row"><!-- row Begin --> <div class="col-lg-12"><!-- col-lg-12 Begin --> <ol class="breadcrumb"><!-- breadcrumb Begin --> <li class="active"><!-- active Begin --> <i class="fa fa-dashboard"></i> Dashboard / Edit Products </li><!-- active Finish --> </ol><!-- breadcrumb Finish --> </div><!-- col-lg-12 Finish --> </div><!-- row Finish --> <div class="row"><!-- row Begin --> <div class="col-lg-12"><!-- col-lg-12 Begin --> <div class="panel panel-default"><!-- panel panel-default Begin --> <div class="panel-heading"><!-- panel-heading Begin --> <h3 class="panel-title"><!-- panel-title Begin --> <i class="fa fa-money fa-fw"></i> Insert Product </h3><!-- panel-title Finish --> </div> <!-- panel-heading Finish --> <div class="panel-body"><!-- panel-body Begin --> <form method="post" class="form-horizontal" enctype="multipart/form-data"><!-- form-horizontal Begin --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Title </label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="product_title" type="text" class="form-control" required value="<?php echo $p_title; ?>"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Category </label> <div class="col-md-6"><!-- col-md-6 Begin --> <select name="product_cat" class="form-control"><!-- form-control Begin --> <option value="<?php echo $p_cat; ?>"> <?php echo $p_cat_title; ?> </option> <?php $get_p_cats = "select * from product_categories"; $run_p_cats = mysqli_query($con,$get_p_cats); while ($row_p_cats=mysqli_fetch_array($run_p_cats)){ $p_cat_id = $row_p_cats['p_cat_id']; $p_cat_title = $row_p_cats['p_cat_title']; echo " <option value='$p_cat_id'> $p_cat_title </option> "; } ?> </select><!-- form-control Finish --> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Image 1 </label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="product_img1" type="file" class="form-control" required> <br> <img width="70" height="70" src="product_images/<?php echo $p_image1; ?>" alt="<?php echo $p_image1; ?>"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Price </label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="product_price" type="text" class="form-control" required value="<?php echo $p_price; ?>"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Keywords </label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="product_keywords" type="text" class="form-control" required value="<?php echo $p_keywords; ?>"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"> Product Desc </label> <div class="col-md-6"><!-- col-md-6 Begin --> <textarea name="product_desc" cols="19" rows="6" class="form-control"> <?php echo $p_desc; ?> </textarea> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> <div class="form-group"><!-- form-group Begin --> <label class="col-md-3 control-label"></label> <div class="col-md-6"><!-- col-md-6 Begin --> <input name="update" value="Update Product" type="submit" class="btn btn-primary form-control"> </div><!-- col-md-6 Finish --> </div><!-- form-group Finish --> </form><!-- form-horizontal Finish --> </div><!-- panel-body Finish --> </div><!-- canel panel-default Finish --> </div><!-- col-lg-12 Finish --> </div><!-- row Finish --> <script src="js/tinymce/tinymce.min.js"></script> <script>tinymce.init({ selector:'textarea'});</script> </body> </html> <?php if(isset($_POST['update'])){ $product_title = $_POST['product_title']; $product_cat = $_POST['product_cat']; $product_price = $_POST['product_price']; $product_keywords = $_POST['product_keywords']; $product_desc = $_POST['product_desc']; $product_img1 = $_FILES['product_img1']['name']; $temp_name1 = $_FILES['product_img1']['tmp_name']; move_uploaded_file($temp_name1,"product_images/$product_img1"); $update_product = "update products set p_cat_id='$product_cat',date=NOW(),product_title='$product_title',product_img1='$product_img1,product_keywords='$product_keywords',product_desc='$product_desc',product_price='$product_price' where product_id='$p_id'"; $run_product = mysqli_query($con,$update_product); if($run_product){ echo "<script>alert('Your product has been updated Successfully')</script>"; echo "<script>window.open('index.php?view_products','_self')</script>"; } } ?> <?php } ?> i am making an admin page for a project im doing and have an edit product feature but when i try to edit my product it gives me this error im not sure what to do.
[]
[]
[ "Try this:\n$get_p = \"select * from products where product_id=\" . $edit_id;\n\nalways connect your statements with php variables using . (dot)\n" ]
[ -2 ]
[ "php", "sql" ]
stackoverflow_0074671874_php_sql.txt
Q: How to obtain the execution time of a function in Julia? I want to obtain the execution time of a function in Julia. Here is a minimum working example: function raise_to(n) for i in 1:n y = (1/7)^n end end How to obtain the time it took to execute raise_to(10) ? A: The recommended way to benchmark a function is to use BenchmarkTools: julia> function raise_to(n) y = (1/7)^n end raise_to (generic function with 1 method) julia> using BenchmarkTools julia> @btime raise_to(10) 1.815 ns (0 allocations: 0 bytes) Note that repeating the computation numerous times (like you did in your example) is a good idea to get more accurate measurements. But BenchmarTools does it for you. Also note that BenchmarkTools avoids many pitfalls of merely using @time. Most notably with @time, you're likely to measure compilation time in addition to run time. This is why the first invocation of @time often displays larger times/allocations: # First invocation: the method gets compiled # Large resource consumption julia> @time raise_to(10) 0.007901 seconds (7.70 k allocations: 475.745 KiB) 3.5401331746414338e-9 # Subsequent invocations: stable and low timings julia> @time raise_to(10) 0.000003 seconds (5 allocations: 176 bytes) 3.5401331746414338e-9 julia> @time raise_to(10) 0.000002 seconds (5 allocations: 176 bytes) 3.5401331746414338e-9 julia> @time raise_to(10) 0.000001 seconds (5 allocations: 176 bytes) 3.5401331746414338e-9 A: @time @time works as mentioned in previous answers, but it will include compile time if it is the first time you call the function in your julia session. https://docs.julialang.org/en/v1/manual/performance-tips/#Measure-performance-with-%5B%40time%5D%28%40ref%29-and-pay-attention-to-memory-allocation-1 @btime You can also use @btime if you put using BenchmarkTools in your code. https://github.com/JuliaCI/BenchmarkTools.jl This will rerun your function many times after an initial compile run, and then average the time. julia> using BenchmarkTools julia> @btime sin(x) setup=(x=rand()) 4.361 ns (0 allocations: 0 bytes) 0.49587200950472454 @timeit Another super useful library for Profiling is TimerOutputs.jl https://github.com/KristofferC/TimerOutputs.jl using TimerOutputs # Time a section code with the label "sleep" to the `TimerOutput` named "to" @timeit to "sleep" sleep(0.02) # ... several more calls to @timeit print_timer(to::TimerOutput) ────────────────────────────────────────────────────────────────────── Time Allocations ────────────────────── ─────────────────────── Tot / % measured: 5.09s / 56.0% 106MiB / 74.6% Section ncalls time %tot avg alloc %tot avg ────────────────────────────────────────────────────────────────────── sleep 101 1.17s 41.2% 11.6ms 1.48MiB 1.88% 15.0KiB nest 2 1 703ms 24.6% 703ms 2.38KiB 0.00% 2.38KiB level 2.2 1 402ms 14.1% 402ms 368B 0.00% 368.0B level 2.1 1 301ms 10.6% 301ms 368B 0.00% 368.0B throwing 1 502ms 17.6% 502ms 384B 0.00% 384.0B nest 1 1 396ms 13.9% 396ms 5.11KiB 0.01% 5.11KiB level 2.2 1 201ms 7.06% 201ms 368B 0.00% 368.0B level 2.1 3 93.5ms 3.28% 31.2ms 1.08KiB 0.00% 368.0B randoms 1 77.5ms 2.72% 77.5ms 77.3MiB 98.1% 77.3MiB funcdef 1 2.66μs 0.00% 2.66μs - 0.00% - ────────────────────────────────────────────────────────────────────── Macros can have begin ... end As seen in the docs for these functions they can cover multiple statements or functions. @my_macro begin statement1 statement2 # ... statement3 end Hope that helps. A: The @time macro can be used to tell you how long the function took to evaluate. It also gives how the memory was allocated. julia> function raise_to(n) for i in 1:n y = (1/7)^n end end raise_to (generic function with 1 method) julia> @time raise_to(10) 0.093018 seconds (26.00 k allocations: 1.461 MiB) A: It would be nice to add that if you want to find the run time of a code block, you can do as follow: @time begin # your code end
How to obtain the execution time of a function in Julia?
I want to obtain the execution time of a function in Julia. Here is a minimum working example: function raise_to(n) for i in 1:n y = (1/7)^n end end How to obtain the time it took to execute raise_to(10) ?
[ "The recommended way to benchmark a function is to use BenchmarkTools:\njulia> function raise_to(n)\n y = (1/7)^n\n end\nraise_to (generic function with 1 method)\n\njulia> using BenchmarkTools\n\njulia> @btime raise_to(10)\n 1.815 ns (0 allocations: 0 bytes)\n\nNote that repeating the computation numerous times (like you did in your example) is a good idea to get more accurate measurements. But BenchmarTools does it for you.\nAlso note that BenchmarkTools avoids many pitfalls of merely using @time. Most notably with @time, you're likely to measure compilation time in addition to run time. This is why the first invocation of @time often displays larger times/allocations:\n# First invocation: the method gets compiled\n# Large resource consumption\njulia> @time raise_to(10)\n 0.007901 seconds (7.70 k allocations: 475.745 KiB)\n3.5401331746414338e-9\n\n# Subsequent invocations: stable and low timings\njulia> @time raise_to(10)\n 0.000003 seconds (5 allocations: 176 bytes)\n3.5401331746414338e-9\n\njulia> @time raise_to(10)\n 0.000002 seconds (5 allocations: 176 bytes)\n3.5401331746414338e-9\n\njulia> @time raise_to(10)\n 0.000001 seconds (5 allocations: 176 bytes)\n3.5401331746414338e-9\n\n", "@time\n@time works as mentioned in previous answers, but it will include compile time if it is the first time you call the function in your julia session.\nhttps://docs.julialang.org/en/v1/manual/performance-tips/#Measure-performance-with-%5B%40time%5D%28%40ref%29-and-pay-attention-to-memory-allocation-1\n@btime\nYou can also use @btime if you put using BenchmarkTools in your code. \nhttps://github.com/JuliaCI/BenchmarkTools.jl\nThis will rerun your function many times after an initial compile run, and then average the time.\njulia> using BenchmarkTools\njulia> @btime sin(x) setup=(x=rand())\n 4.361 ns (0 allocations: 0 bytes)\n0.49587200950472454\n\n@timeit\nAnother super useful library for Profiling is TimerOutputs.jl\nhttps://github.com/KristofferC/TimerOutputs.jl\nusing TimerOutputs\n\n# Time a section code with the label \"sleep\" to the `TimerOutput` named \"to\"\n@timeit to \"sleep\" sleep(0.02)\n\n# ... several more calls to @timeit\n\nprint_timer(to::TimerOutput)\n\n ──────────────────────────────────────────────────────────────────────\n Time Allocations\n ────────────────────── ───────────────────────\n Tot / % measured: 5.09s / 56.0% 106MiB / 74.6%\n\n Section ncalls time %tot avg alloc %tot avg\n ──────────────────────────────────────────────────────────────────────\n sleep 101 1.17s 41.2% 11.6ms 1.48MiB 1.88% 15.0KiB\n nest 2 1 703ms 24.6% 703ms 2.38KiB 0.00% 2.38KiB\n level 2.2 1 402ms 14.1% 402ms 368B 0.00% 368.0B\n level 2.1 1 301ms 10.6% 301ms 368B 0.00% 368.0B\n throwing 1 502ms 17.6% 502ms 384B 0.00% 384.0B\n nest 1 1 396ms 13.9% 396ms 5.11KiB 0.01% 5.11KiB\n level 2.2 1 201ms 7.06% 201ms 368B 0.00% 368.0B\n level 2.1 3 93.5ms 3.28% 31.2ms 1.08KiB 0.00% 368.0B\n randoms 1 77.5ms 2.72% 77.5ms 77.3MiB 98.1% 77.3MiB\n funcdef 1 2.66μs 0.00% 2.66μs - 0.00% -\n ──────────────────────────────────────────────────────────────────────\n\nMacros can have begin ... end\nAs seen in the docs for these functions they can cover multiple statements or functions.\n@my_macro begin\n statement1\n statement2\n # ...\n statement3\nend\n\nHope that helps.\n", "The @time macro can be used to tell you how long the function took to evaluate. It also gives how the memory was allocated.\njulia> function raise_to(n)\n for i in 1:n\n y = (1/7)^n\n end\n end\nraise_to (generic function with 1 method)\njulia> @time raise_to(10)\n 0.093018 seconds (26.00 k allocations: 1.461 MiB)\n\n", "It would be nice to add that if you want to find the run time of a code block, you can do as follow:\n@time begin\n # your code \nend\n\n" ]
[ 17, 8, 1, 0 ]
[]
[]
[ "julia" ]
stackoverflow_0060867667_julia.txt
Q: How to set DB name and Collection name in Mongoose? I'm building a small program that connects to MongoDB-Atlas. I created a connection, a Schema, a Model and created a document. but somehow my DB name is "test" and Collection name is "users" without me defined it in the code or in Atlas, is that the default names? and how to create/rename a DB and a collection. the code : user.js const mongoose = require('mongoose'); const SchemaObj = mongoose.Schema; const userSchema = new SchemaObj({ name : { type:String, require:true }, email : { type:String, require:true }, password: { type:String, require:true } }); mongoose.model('User',userSchema); app.js const express = require('express'); const app = express(); const rout = express.Router(); const PORT = 8888; const {connectionString} = require('./Keys'); const mongoose = require('mongoose'); app.use(express.json()); app.use(require('./routes/auth')); app.get('/',(req,res)=>{ console.log('succesfully connected'); res.send('im in!'); }); let server = app.listen(PORT,'0.0.0.0',()=>{ let FuncPort = server.address().port let host = server.address().address console.log("Example app listening at http://%s:%s", host, FuncPort) }); const client = mongoose.connect(connectionString, { useNewUrlParser: true, useUnifiedTopology: true }); mongoose.connection.on('connected',()=>{ console.log('connected to mongodb oh hell yea'); }); mongoose.connection.on('error',()=>{ console.log('error connecting to mongodb oh hell yea'); }); auth.js const mongoose = require('mongoose'); const express = require('express'); const route = express.Router(); require('../moduls/User'); const user = mongoose.model("User"); rout.post('/sign',(req,res)=>{ const {name,password,email} = req.body; if(name && password && email) { console.log('you god damn right!'); res.json("you god damn right in response"); } else { console.log('you are god damn wrong stupid idiot!'); res.status(422); res.json("you are god damn wrong you stupid idiot in response"); } user.findOne({email:email}).then((resolve,reject)=>{ if(resolve) return res.status(422).json("user already exist yo"); const newUser = new user({ name, email, password }); newUser.save().then(() => { res.json('saved user!!!!'); }).catch(err => { console.log("there was a problem saving the user")}); }).catch(err => { console.log(err); }) }); module.exports = route; By the way, what is the difference between mongoose and MongoDB libraries? A: For naming your mongodb database, you should place it in your connection string, like: mongoose.connect('mongodb://localhost/myDatabaseName'); For naming your collection or disabling pluralization, you can find the answer here: What are Mongoose (Nodejs) pluralization rules? var schemaObj = new mongoose.Schema( { fields:Schema.Type }, { collection: 'collection_name'}); Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. Similar to Sequelize (ORM) but for documents (NoSQL). A: MONGODB_URI = mongodb+srv://name:@next.txdcl.mongodb.net/(ADD NAME DB)?retryWrites=true&w=majority You can just add name what you want ( ADD NAME ) and delete test db and reloa A: Approach 1 const url = "mongodb://127.0.0.1:27017/DatabaseName" mongoose.connect(url).then(() => { console.log("Connected to Database"); }).catch((err) => { console.log("Not Connected to Database ERROR! ", err); }); Approach 2 const url = "mongodb://127.0.0.1:27017" mongoose.connect(url,{ dbName: 'DatabaseName', }).then(() => { console.log("Connected to Database"); }).catch((err) => { console.log("Not Connected to Database ERROR! ", err); }); A: This is how I change my DB name Before mongodb+srv://username:<password>@clustername.abc.mongodb.net/?retryWrites=true&w=majority after you get your API key you can add 1 more path (/) before the query (?) and that path will be your DB name automatically the example: I add my DB name as my-new-db-name after mongodb+srv://username:<password>@clustername.abc.mongodb.net/my-new-db-name?retryWrites=true&w=majority
How to set DB name and Collection name in Mongoose?
I'm building a small program that connects to MongoDB-Atlas. I created a connection, a Schema, a Model and created a document. but somehow my DB name is "test" and Collection name is "users" without me defined it in the code or in Atlas, is that the default names? and how to create/rename a DB and a collection. the code : user.js const mongoose = require('mongoose'); const SchemaObj = mongoose.Schema; const userSchema = new SchemaObj({ name : { type:String, require:true }, email : { type:String, require:true }, password: { type:String, require:true } }); mongoose.model('User',userSchema); app.js const express = require('express'); const app = express(); const rout = express.Router(); const PORT = 8888; const {connectionString} = require('./Keys'); const mongoose = require('mongoose'); app.use(express.json()); app.use(require('./routes/auth')); app.get('/',(req,res)=>{ console.log('succesfully connected'); res.send('im in!'); }); let server = app.listen(PORT,'0.0.0.0',()=>{ let FuncPort = server.address().port let host = server.address().address console.log("Example app listening at http://%s:%s", host, FuncPort) }); const client = mongoose.connect(connectionString, { useNewUrlParser: true, useUnifiedTopology: true }); mongoose.connection.on('connected',()=>{ console.log('connected to mongodb oh hell yea'); }); mongoose.connection.on('error',()=>{ console.log('error connecting to mongodb oh hell yea'); }); auth.js const mongoose = require('mongoose'); const express = require('express'); const route = express.Router(); require('../moduls/User'); const user = mongoose.model("User"); rout.post('/sign',(req,res)=>{ const {name,password,email} = req.body; if(name && password && email) { console.log('you god damn right!'); res.json("you god damn right in response"); } else { console.log('you are god damn wrong stupid idiot!'); res.status(422); res.json("you are god damn wrong you stupid idiot in response"); } user.findOne({email:email}).then((resolve,reject)=>{ if(resolve) return res.status(422).json("user already exist yo"); const newUser = new user({ name, email, password }); newUser.save().then(() => { res.json('saved user!!!!'); }).catch(err => { console.log("there was a problem saving the user")}); }).catch(err => { console.log(err); }) }); module.exports = route; By the way, what is the difference between mongoose and MongoDB libraries?
[ "For naming your mongodb database, you should place it in your connection string, like:\nmongoose.connect('mongodb://localhost/myDatabaseName');\n\nFor naming your collection or disabling pluralization, you can find the answer here:\nWhat are Mongoose (Nodejs) pluralization rules? \nvar schemaObj = new mongoose.Schema(\n{\n fields:Schema.Type\n}, { collection: 'collection_name'});\n\nMongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. Similar to Sequelize (ORM) but for documents (NoSQL).\n", "MONGODB_URI = mongodb+srv://name:@next.txdcl.mongodb.net/(ADD NAME DB)?retryWrites=true&w=majority\nYou can just add name what you want ( ADD NAME ) and delete test db and reloa\n", "Approach 1\nconst url = \"mongodb://127.0.0.1:27017/DatabaseName\"\n\nmongoose.connect(url).then(() => {\n console.log(\"Connected to Database\");\n}).catch((err) => {\n console.log(\"Not Connected to Database ERROR! \", err);\n});\n\nApproach 2\nconst url = \"mongodb://127.0.0.1:27017\"\n\nmongoose.connect(url,{\n dbName: 'DatabaseName',\n}).then(() => {\n console.log(\"Connected to Database\");\n}).catch((err) => {\n console.log(\"Not Connected to Database ERROR! \", err);\n});\n\n", "This is how I change my DB name\nBefore\nmongodb+srv://username:<password>@clustername.abc.mongodb.net/?retryWrites=true&w=majority\n\nafter you get your API key you can add 1 more path (/) before the query (?) and that path will be your DB name automatically\nthe example: I add my DB name as\n\nmy-new-db-name\n\nafter\nmongodb+srv://username:<password>@clustername.abc.mongodb.net/my-new-db-name?retryWrites=true&w=majority\n\n" ]
[ 14, 4, 1, 0 ]
[]
[]
[ "mongodb_atlas", "mongoose", "node.js" ]
stackoverflow_0061388479_mongodb_atlas_mongoose_node.js.txt
Q: Connection working from React to NodeJS, but request-url is incorrect in Chrome Network enter image description hereenter image description hereenter image description here Assalamu ‘Alaykum my React app is running on localhost:3000 NodeJS server is running on localhost:1000 I'm sending request to server 'localhost:1000' and everything is fine, correct response is coming from server, there is no error in Console, but in Chrome Network request-url is to localhost:3000/.../... if I sent wrong data to server, it's coming correct error and bad request error in Console can someone help me, thanks A: It sounds like your React app is making requests to the wrong URL. Based on the information you provided, it appears that your React app is running on localhost:3000 and your Node.js server is running on localhost:1000, but your requests are being sent to localhost:3000. To fix this issue, you will need to update your React app to send requests to the correct URL, which should be http://localhost:1000/auth/sign/in. This can typically be done by updating the base URL or endpoint for your API requests in your React app. For example, if you are using the fetch API to make requests in your React app, you can update the base URL for your requests by setting the baseURL property in your fetch options: fetch('/auth/sign/in', { baseURL: 'http://localhost:1000', // Other fetch options }) Or, if you are using a library such as Axios to make requests in your React app, you can update the base URL for your requests by setting the baseURL property in the Axios configuration: import axios from 'axios'; axios.defaults.baseURL = 'http://localhost:1000'; After updating the base URL for your API requests, your React app should send requests to the correct URL, http://localhost:1000/auth/sign/in, and you should no longer see requests being sent to localhost:3000 in the Chrome Network tab. It's worth noting that the exact solution for updating the base URL for your API requests will depend on the specific details of your React app and how you are making requests to your server. If you are having trouble updating the base URL, you may want to consult the documentation for the specific library or API you are using.
Connection working from React to NodeJS, but request-url is incorrect in Chrome Network
enter image description hereenter image description hereenter image description here Assalamu ‘Alaykum my React app is running on localhost:3000 NodeJS server is running on localhost:1000 I'm sending request to server 'localhost:1000' and everything is fine, correct response is coming from server, there is no error in Console, but in Chrome Network request-url is to localhost:3000/.../... if I sent wrong data to server, it's coming correct error and bad request error in Console can someone help me, thanks
[ "It sounds like your React app is making requests to the wrong URL. Based on the information you provided, it appears that your React app is running on localhost:3000 and your Node.js server is running on localhost:1000, but your requests are being sent to localhost:3000.\nTo fix this issue, you will need to update your React app to send requests to the correct URL, which should be http://localhost:1000/auth/sign/in. This can typically be done by updating the base URL or endpoint for your API requests in your React app.\nFor example, if you are using the fetch API to make requests in your React app, you can update the base URL for your requests by setting the baseURL property in your fetch options:\n\n\nfetch('/auth/sign/in', {\n baseURL: 'http://localhost:1000',\n // Other fetch options\n})\n\n\n\nOr, if you are using a library such as Axios to make requests in your React app, you can update the base URL for your requests by setting the baseURL property in the Axios configuration:\n\n\nimport axios from 'axios';\n\naxios.defaults.baseURL = 'http://localhost:1000';\n\n\n\nAfter updating the base URL for your API requests, your React app should send requests to the correct URL, http://localhost:1000/auth/sign/in, and you should no longer see requests being sent to localhost:3000 in the Chrome Network tab.\nIt's worth noting that the exact solution for updating the base URL for your API requests will depend on the specific details of your React app and how you are making requests to your server. If you are having trouble updating the base URL, you may want to consult the documentation for the specific library or API you are using.\n" ]
[ 0 ]
[]
[]
[ "http_proxy", "node.js", "reactjs" ]
stackoverflow_0074673635_http_proxy_node.js_reactjs.txt
Q: Laravel Jetstream User Profile Page is Empty I have installed "laravel/jetstream": "^2.9" on "laravel/framework": "^8.75". When I accessed Profile Information page, it doesn't load necessary information into relevant form fields.Please help me with this isses. Even I have tried reinstalling Jetstream separately. Problem still exists. A: If you open your Console you probably have a console error that livewire is not working properly. Usually the following command is missing at this point php artisan livewire:publish --assets Let me know if this helps All the best! A: publish livewire config php artisan vendor:publish --tag=livewire:config verify the path to livewire in config\livewire.php 'asset_url' => '/../yourpath/public', 'app_url' => '/../yourpath/public', inspect the result web page and verify the path for livewire.js file is correct <script src="/../yourpath/public/vendor/livewire/livewire.js?id=de3fca26689cb5a39af4" data-turbo-eval="false" data-turbolinks-eval="false" ></script> i think that you production is not in the root directory ,for me it was in a subfolder so i get this problem hope it work for you
Laravel Jetstream User Profile Page is Empty
I have installed "laravel/jetstream": "^2.9" on "laravel/framework": "^8.75". When I accessed Profile Information page, it doesn't load necessary information into relevant form fields.Please help me with this isses. Even I have tried reinstalling Jetstream separately. Problem still exists.
[ "If you open your Console you probably have a console error that livewire is not working properly. Usually the following command is missing at this point\nphp artisan livewire:publish --assets\n\nLet me know if this helps\nAll the best!\n", "publish livewire config\nphp artisan vendor:publish --tag=livewire:config \n\nverify the path to livewire in config\\livewire.php\n 'asset_url' => '/../yourpath/public',\n 'app_url' => '/../yourpath/public',\n\ninspect the result web page and verify the path for livewire.js file is correct\n<script src=\"/../yourpath/public/vendor/livewire/livewire.js?id=de3fca26689cb5a39af4\" data-turbo-eval=\"false\" data-turbolinks-eval=\"false\" ></script>\n\ni think that you production is not in the root directory ,for me it was in a subfolder so i get this problem\nhope it work for you\n" ]
[ 0, 0 ]
[]
[]
[ "jetstream", "laravel", "profile" ]
stackoverflow_0074355652_jetstream_laravel_profile.txt
Q: Microsoft post_logout_redirect_uri Not working I m trying to logout Microsoft Account Like: https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=http://localhost:3000. But It's not redirecting to redirect Url.It's showing : Thank A: You should get redirected unless the post_logout_redirect_uri is not registered as a reply_url or the user is already logged out. A: Its known bug for login.microsoftonline.com/common/oauth2/logout, you can do nothing about it. A: I had the exactly same problem. I found that the post logout redirection doens't work for root accounts of the tenant, that is my personal account, which created Azure subscription. But it works for new accounts I created inside of my subscription.
Microsoft post_logout_redirect_uri Not working
I m trying to logout Microsoft Account Like: https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=http://localhost:3000. But It's not redirecting to redirect Url.It's showing : Thank
[ "You should get redirected unless the post_logout_redirect_uri is not registered as a reply_url or the user is already logged out.\n", "Its known bug for login.microsoftonline.com/common/oauth2/logout, you can do nothing about it.\n", "I had the exactly same problem. I found that the post logout redirection doens't work for root accounts of the tenant, that is my personal account, which created Azure subscription. But it works for new accounts I created inside of my subscription.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "microsoft_graph_api" ]
stackoverflow_0060145521_microsoft_graph_api.txt
Q: Lock on slider when scrolling (Swiper.js) I have a problem with locomotive scroll and swiper. I would like to stop on the slider while scrolling and then scroll the entire slider and continue scrolling the page. How can i do that with using JQuery or vanilla js. I want to know how to lock on slider when scrolling. (locomotive scroll & swiper) ` var $swiperNumbers = $(".swiper-container-numbers"); $swiperNumbers.each(function (index) { var $this = $(this); $this.addClass("swiper-slider-numbers-" + index); var dragSize = $this.data("drag-size") ? $this.data("drag-size") : 50; var freeMode = $this.data("free-mode") ? $this.data("free-mode") : false; var slidesDesktop = $this.data("slides-desktop") ? $this.data("slides-desktop") : 4; var slidesTablet = $this.data("slides-tablet") ? $this.data("slides-tablet") : 3.15; var slidesMobile = $this.data("slides-mobile") ? $this.data("slides-mobile") : 1.2; var spaceBetween = $this.data("space-between") ? $this.data("space-between") : 0; var swiperNumbers = new Swiper(".swiper-slider-numbers-" + index, { direction: "horizontal", loop: false, centeredSlides: true, spaceBetween: spaceBetween, mousewheel: { forceToAxis: true, sensitivity: 1, releaseOnEdges: true, }, breakpoints: { 1920: { slidesPerView: 3.5, spaceBetween: 90, }, 1440: { slidesPerView: 2.5, spaceBetween: 90, }, 991: { slidesPerView: 2.5, spaceBetween: 50, }, 768: { slidesPerView: 2.1, spaceBetween: 50, }, 580: { slidesPerView: 1.5, spaceBetween: 50, }, 320: { slidesPerView: 1.5, spaceBetween: 10, loop: true, centeredSlides: false, }, }, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, }); }); ` A: To lock on a slider when scrolling, you can add the allowSlideNext and allowSlidePrev options to your Swiper instance, and set them to false initially. Then, you can listen for the scroll event on the window object and check if the user has scrolled past the slider. If they have, you can set the allowSlideNext and allowSlidePrev options to true to allow the user to scroll through the slider.
Lock on slider when scrolling (Swiper.js)
I have a problem with locomotive scroll and swiper. I would like to stop on the slider while scrolling and then scroll the entire slider and continue scrolling the page. How can i do that with using JQuery or vanilla js. I want to know how to lock on slider when scrolling. (locomotive scroll & swiper) ` var $swiperNumbers = $(".swiper-container-numbers"); $swiperNumbers.each(function (index) { var $this = $(this); $this.addClass("swiper-slider-numbers-" + index); var dragSize = $this.data("drag-size") ? $this.data("drag-size") : 50; var freeMode = $this.data("free-mode") ? $this.data("free-mode") : false; var slidesDesktop = $this.data("slides-desktop") ? $this.data("slides-desktop") : 4; var slidesTablet = $this.data("slides-tablet") ? $this.data("slides-tablet") : 3.15; var slidesMobile = $this.data("slides-mobile") ? $this.data("slides-mobile") : 1.2; var spaceBetween = $this.data("space-between") ? $this.data("space-between") : 0; var swiperNumbers = new Swiper(".swiper-slider-numbers-" + index, { direction: "horizontal", loop: false, centeredSlides: true, spaceBetween: spaceBetween, mousewheel: { forceToAxis: true, sensitivity: 1, releaseOnEdges: true, }, breakpoints: { 1920: { slidesPerView: 3.5, spaceBetween: 90, }, 1440: { slidesPerView: 2.5, spaceBetween: 90, }, 991: { slidesPerView: 2.5, spaceBetween: 50, }, 768: { slidesPerView: 2.1, spaceBetween: 50, }, 580: { slidesPerView: 1.5, spaceBetween: 50, }, 320: { slidesPerView: 1.5, spaceBetween: 10, loop: true, centeredSlides: false, }, }, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, }); }); `
[ "To lock on a slider when scrolling, you can add the allowSlideNext and allowSlidePrev options to your Swiper instance, and set them to false initially. Then, you can listen for the scroll event on the window object and check if the user has scrolled past the slider. If they have, you can set the allowSlideNext and allowSlidePrev options to true to allow the user to scroll through the slider.\n" ]
[ 0 ]
[]
[]
[ "javascript", "jquery", "locomotive_scroll", "swiper.js", "wordpress" ]
stackoverflow_0074669583_javascript_jquery_locomotive_scroll_swiper.js_wordpress.txt
Q: C programming - How to print numbers with a decimal component using only loops? I'm currently taking a basic intro to C programming class, and for our current assignment I am to write a program to convert the number of kilometers to miles using loops--no if-else, switch statements, or any other construct we haven't learned yet are allowed. So basically we can only use loops and some operators. The program will generate three identical tables (starting from 1 kilometer through the input value) for one number input using the while loop for the first set of calculations, the for loop for the second, and the do loop for the third. I've written the entire program, however I'm having a bit of a problem with getting it to recognize an input with a decimal component. The code reads in and converts integers fine, but because the increment only increases by 1 it won't print a number with a decimal component (e.g. 3.2, 22.6, etc.). Can someone point me in the right direction on this? I'd really appreciate any help! :) A: It's not clear what you're trying to get as output. You use the example of starting with 3.2, so based from that, and based on your current program, your output is: KILOMETERS MILES (while loop) ========== ===== 1.000 0.620 2.000 1.240 3.000 1.860 Is the problem that your table ends without putting out a value for 3.2? A simple way to solve that (only using loop statements, per your requirement) would be to add the following code: while (count < km) { printf ("%8.3lf %14.3lf\n", km, KM_TO_MILE * km); count = km; } It's really an if statement in disguise, and I don't know if your prof would accept it, but it does provide the final line of output. Are you required to put out entries that increase by 1.0 (km) for each line? If not, perhaps a better solution is to determine an offset from one line to the next which lets you iterate between 1.0 and km, over a finite number of rows. A: A simple solution is multiplying the input (km) by 10, 100 or 1000. Then dividing the result (mi) by the same constant. But avoid printing the result in the loop, take it out of there. You may lose precision, though (that's your next exercise :) #include <stdio.h> #define KM_TO_MILE .62 #define NAMEITHOWYOULIKE 100.0 main (void) { double km, mi, count; printf ("This program converts kilometers to miles.\n"); do { printf ("\nEnter a positive non-zero number"); printf (" of kilometers of the race: "); scanf ("%lf", &km); getchar(); }while (km <= 1); km = km * NAMEITHOWYOULIKE; printf ("\n KILOMETERS MILES (while loop)\n"); printf (" ========== =====\n"); count = 1; while (count <= km) { mi = KM_TO_MILE * count; ++count; } printf ("%8.3lf %14.3lf\n", count/NAMEITHOWYOULIKE, mi/NAMEITHOWYOULIKE); getchar(); } A: If you want this for output: KILOMETERS MILES (while loop) ========== ===== 1.000 0.620 2.000 1.240 3.000 1.860 3.200 1.984 Just add the following after your while loop (for an exclusive "final result"): mi = KM_TO_MILE * km; printf("%8.3lf %14.3lf\n", km, mi); or an inclusive "final result" to prevent the last two results being the same if a whole number is used: while (km > count) { mi = KM_TO_MILE * km; printf("%8.3lf %14.3lf\n", km, mi); break; } You successfully printed the whole number values, but need to print the final value when that is complete. All you need to do at the end (above) is convert the value directly from kilometers to miles.
C programming - How to print numbers with a decimal component using only loops?
I'm currently taking a basic intro to C programming class, and for our current assignment I am to write a program to convert the number of kilometers to miles using loops--no if-else, switch statements, or any other construct we haven't learned yet are allowed. So basically we can only use loops and some operators. The program will generate three identical tables (starting from 1 kilometer through the input value) for one number input using the while loop for the first set of calculations, the for loop for the second, and the do loop for the third. I've written the entire program, however I'm having a bit of a problem with getting it to recognize an input with a decimal component. The code reads in and converts integers fine, but because the increment only increases by 1 it won't print a number with a decimal component (e.g. 3.2, 22.6, etc.). Can someone point me in the right direction on this? I'd really appreciate any help! :)
[ "It's not clear what you're trying to get as output. You use the example of starting with 3.2, so based from that, and based on your current program, your output is:\n KILOMETERS MILES (while loop)\n ========== =====\n 1.000 0.620\n 2.000 1.240\n 3.000 1.860\n\nIs the problem that your table ends without putting out a value for 3.2? A simple way to solve that (only using loop statements, per your requirement) would be to add the following code:\nwhile (count < km)\n{\n printf (\"%8.3lf %14.3lf\\n\", km, KM_TO_MILE * km);\n count = km;\n}\n\nIt's really an if statement in disguise, and I don't know if your prof would accept it, but it does provide the final line of output.\nAre you required to put out entries that increase by 1.0 (km) for each line? If not, perhaps a better solution is to determine an offset from one line to the next which lets you iterate between 1.0 and km, over a finite number of rows.\n", "A simple solution is multiplying the input (km) by 10, 100 or 1000. Then dividing the result (mi) by the same constant. But avoid printing the result in the loop, take it out of there.\nYou may lose precision, though (that's your next exercise :)\n#include <stdio.h>\n#define KM_TO_MILE .62 \n\n#define NAMEITHOWYOULIKE 100.0\n\nmain (void)\n{\n double km, mi, count; \n\n printf (\"This program converts kilometers to miles.\\n\");\n\n do \n {\n printf (\"\\nEnter a positive non-zero number\"); \n printf (\" of kilometers of the race: \");\n scanf (\"%lf\", &km); \n getchar(); \n }while (km <= 1); \n\n km = km * NAMEITHOWYOULIKE;\n\n printf (\"\\n KILOMETERS MILES (while loop)\\n\"); \n printf (\" ========== =====\\n\");\n\n count = 1; \n while (count <= km) \n { \n mi = KM_TO_MILE * count;\n ++count; \n }\n printf (\"%8.3lf %14.3lf\\n\", count/NAMEITHOWYOULIKE, mi/NAMEITHOWYOULIKE); \n getchar();\n }\n\n", "If you want this for output:\n KILOMETERS MILES (while loop)\n ========== =====\n 1.000 0.620\n 2.000 1.240\n 3.000 1.860\n 3.200 1.984\n\nJust add the following after your while loop (for an exclusive \"final result\"):\nmi = KM_TO_MILE * km;\nprintf(\"%8.3lf %14.3lf\\n\", km, mi);\n\nor an inclusive \"final result\" to prevent the last two results being the same if a whole number is used:\nwhile (km > count)\n{\n mi = KM_TO_MILE * km;\n printf(\"%8.3lf %14.3lf\\n\", km, mi);\n break;\n}\n\nYou successfully printed the whole number values, but need to print the final value when that is complete. All you need to do at the end (above) is convert the value directly from kilometers to miles.\n" ]
[ 0, 0, 0 ]
[ "output image\n#include<stdio.h>\nint main() {\ndouble kilo, miles, i;\nprintf(\"enter the kilometer to be converted :\");\nscanf(\"%lf\",&kilo);\nprintf(\"kilos\\t miles\\n\");\nprintf(\"-----------------------------------------------------\\n\");\ni=1;\nwhile(i<=kilo){\n miles=i/1.609;\n\nprintf(\"%lf\\t %lf\\n\",i,miles);\n\ni++;\n\n}\n}\n" ]
[ -1 ]
[ "c", "loops" ]
stackoverflow_0010166712_c_loops.txt
Q: Snippet to allow just 1 active Subscription at WooCommerce Subscriptions I've got a snippet which allows to have just one active subscription, so they can't order another until canceled. But this snippet also blocks the up-downgrade-function. Any Ideas how I can get just the switch subscription part aviable? add_filter('woocommerce_add_to_cart_validation', 'check_num_of_subscriptions', 10, 2); function check_num_of_subscriptions( $valid, $product_id ) { $product_to_add = wc_get_product( $product_id ); if ( $product_to_add instanceof WC_Product_Subscription || $product_to_add instanceof WC_Product_Variable_Subscription) { // alternative use: $has_sub = wcs_user_has_subscription( '', '', 'active' ); if ( has_active_subscription() ) { // cart validation must fail, because user is not allowed to have multiple subscriptions wc_clear_notices(); wc_add_notice(__('Du hast bereits ein aktives Abonnement.', 'woocommerce'), 'error'); return false; } else { return true; } } return $valid; } function has_active_subscription() { $user_id = get_current_user_id(); $active_subscriptions = get_posts(array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => $user_id, 'post_type' => 'shop_subscription', 'post_status' => 'wc-active' )); if (!empty($active_subscriptions)) return true; else return false; } A: add_filter('woocommerce_add_to_cart_validation', 'check_num_of_subscriptions', 10, 2); function check_num_of_subscriptions( $valid, $product_id ){ $product_to_add = wc_get_product( $product_id ); if ($product_to_add instanceof WC_Product_Subscription || $product_to_add instanceof WC_Product_Variable_Subscription){ // alternative use: $has_sub = wcs_user_has_subscription( '', '', 'active' ); if ( has_active_subscription() && (! has_woocommerce_subscription('',$product_id,''))) { // cart validation must fail, because user is not allowed to have multiple subscriptions wc_clear_notices(); wc_add_notice(__('You already have an active subscription.', 'woocommerce'), 'error'); return false; } else{ return true; } } return $valid; } function has_active_subscription(){ $user_id = get_current_user_id(); $active_subscriptions = get_posts(array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => $user_id, 'post_type' => 'shop_subscription', 'post_status' => 'wc-active' )); if (!empty($active_subscriptions)) return true; else return false; } function has_woocommerce_subscription($the_user_id, $the_product_id, $the_status) { $current_user = wp_get_current_user(); if (empty($the_user_id)) { $the_user_id = $current_user->ID; } if (WC_Subscriptions_Manager::user_has_subscription( $the_user_id, $the_product_id, $the_status)) { return true; } } this Code will run for upgrade and downgrade, tested and working.
Snippet to allow just 1 active Subscription at WooCommerce Subscriptions
I've got a snippet which allows to have just one active subscription, so they can't order another until canceled. But this snippet also blocks the up-downgrade-function. Any Ideas how I can get just the switch subscription part aviable? add_filter('woocommerce_add_to_cart_validation', 'check_num_of_subscriptions', 10, 2); function check_num_of_subscriptions( $valid, $product_id ) { $product_to_add = wc_get_product( $product_id ); if ( $product_to_add instanceof WC_Product_Subscription || $product_to_add instanceof WC_Product_Variable_Subscription) { // alternative use: $has_sub = wcs_user_has_subscription( '', '', 'active' ); if ( has_active_subscription() ) { // cart validation must fail, because user is not allowed to have multiple subscriptions wc_clear_notices(); wc_add_notice(__('Du hast bereits ein aktives Abonnement.', 'woocommerce'), 'error'); return false; } else { return true; } } return $valid; } function has_active_subscription() { $user_id = get_current_user_id(); $active_subscriptions = get_posts(array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => $user_id, 'post_type' => 'shop_subscription', 'post_status' => 'wc-active' )); if (!empty($active_subscriptions)) return true; else return false; }
[ "add_filter('woocommerce_add_to_cart_validation', 'check_num_of_subscriptions', 10, 2);\n \n function check_num_of_subscriptions( $valid, $product_id ){\n $product_to_add = wc_get_product( $product_id );\n if ($product_to_add instanceof WC_Product_Subscription || $product_to_add instanceof WC_Product_Variable_Subscription){\n // alternative use: $has_sub = wcs_user_has_subscription( '', '', 'active' );\n \n if ( has_active_subscription() && (! has_woocommerce_subscription('',$product_id,''))) {\n // cart validation must fail, because user is not allowed to have multiple subscriptions\n wc_clear_notices();\n wc_add_notice(__('You already have an active subscription.', 'woocommerce'), 'error');\n return false;\n } else{\n return true;\n }\n }\n return $valid;\n }\n function has_active_subscription(){\n $user_id = get_current_user_id();\n $active_subscriptions = get_posts(array(\n 'numberposts' => -1,\n 'meta_key' => '_customer_user',\n 'meta_value' => $user_id,\n 'post_type' => 'shop_subscription',\n 'post_status' => 'wc-active'\n \n ));\n if (!empty($active_subscriptions))\n return true;\n else\n return false;\n }\n \n function has_woocommerce_subscription($the_user_id, $the_product_id, $the_status) {\n $current_user = wp_get_current_user();\n if (empty($the_user_id)) {\n $the_user_id = $current_user->ID;\n }\n if (WC_Subscriptions_Manager::user_has_subscription( $the_user_id, $the_product_id, $the_status)) {\n return true;\n }\n }\n\nthis Code will run for upgrade and downgrade, tested and working.\n" ]
[ 0 ]
[]
[]
[ "php", "subscription", "woocommerce", "wordpress" ]
stackoverflow_0069719478_php_subscription_woocommerce_wordpress.txt
Q: JQuery easy Paginate Gallery Not functional I'm trying to use this jquery easy paginate on my Blogspot separate page. https://st3ph.github.io/jquery.easyPaginate/ The images show up but no pagination appears and no css too! I need to adapt my css in this jQuery pagination too and make it work! Please can someone help me make this work? Updated code* https:// jsfiddle.net/Anon13/4syqnavw/ A: If the jsfiddle you linked to based on your implementation, then the issue is how you reference the JS file. You can't directly link to script files on github, as they don't serve script files with the appropriate content type (see here for more info). Basically the gist is they don't want you to treat github as a cdn. After updating the fiddle, I can see that the plugin works. Here's a snippet with the same code from the fiddle: $('#easyPaginate').easyPaginate({ paginateElement: 'img', elementsPerPage: 3, effect: 'climb' }); body { font-family: Arial, sans-serif; text-align: center; max-width: 1170px; margin: 3rem auto; background-color: #101010; color: #fff; } /* Cosmetic only */ #easyPaginate {display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 20px;max-width: 1000px; height: auto margin: 0 auto;} #easyPaginate img {width: 100%; height: 150px; padding: 5px; border: none; background: transparent; object-fit: cover; position: relative; } @media only screen and (max-width: 600px) { .easyPaginate { grid-template-columns: repeat(3, 1fr); } } .easyPaginate img:hover { z-index: 9; transform: scale(1.3); transition: transform ease 0.5s; } .easyPaginateNav a {padding:5px;} .easyPaginateNav a.current {font-weight:bold;text-decoration:underline;} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://st3ph.github.io/jquery.easyPaginate/js/jquery.easyPaginate.js"></script> <div id="easyPaginate" class="easyPaginateList"> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> <img src="https://picsum.photos/500/500?random&img=" /> </div>
JQuery easy Paginate Gallery Not functional
I'm trying to use this jquery easy paginate on my Blogspot separate page. https://st3ph.github.io/jquery.easyPaginate/ The images show up but no pagination appears and no css too! I need to adapt my css in this jQuery pagination too and make it work! Please can someone help me make this work? Updated code* https:// jsfiddle.net/Anon13/4syqnavw/
[ "If the jsfiddle you linked to based on your implementation, then the issue is how you reference the JS file. You can't directly link to script files on github, as they don't serve script files with the appropriate content type (see here for more info). Basically the gist is they don't want you to treat github as a cdn.\nAfter updating the fiddle, I can see that the plugin works.\nHere's a snippet with the same code from the fiddle:\n\n\n$('#easyPaginate').easyPaginate({\n paginateElement: 'img',\n elementsPerPage: 3,\n effect: 'climb'\n});\n body {\n font-family: Arial, sans-serif;\n text-align: center;\n max-width: 1170px;\n margin: 3rem auto;\n background-color: #101010;\n color: #fff;\n}\n\n/* Cosmetic only */\n#easyPaginate {display: grid;\ngrid-template-columns: repeat(3, 1fr);\ngrid-gap: 20px;max-width: 1000px;\nheight: auto\nmargin: 0 auto;}\n#easyPaginate img {width: 100%;\nheight: 150px;\npadding: 5px;\nborder: none;\nbackground: transparent;\nobject-fit: cover;\nposition: relative;\n}\n@media only screen and (max-width: 600px) {\n.easyPaginate {\n grid-template-columns: repeat(3, 1fr);\n}\n}\n.easyPaginate img:hover {\nz-index: 9;\ntransform: scale(1.3);\ntransition: transform ease 0.5s;\n}\n.easyPaginateNav a {padding:5px;}\n.easyPaginateNav a.current {font-weight:bold;text-decoration:underline;}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<script src=\"https://st3ph.github.io/jquery.easyPaginate/js/jquery.easyPaginate.js\"></script>\n\n<div id=\"easyPaginate\" class=\"easyPaginateList\">\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n <img src=\"https://picsum.photos/500/500?random&img=\" />\n</div>\n\n\n\n" ]
[ 0 ]
[]
[]
[ "css", "html", "javascript", "jquery" ]
stackoverflow_0074671427_css_html_javascript_jquery.txt
Q: I am trying to get an h4 element text which is a child of divs using puppeteer I am trying this code to extract an h4 which a child of 7 parent divs. like parent div, grandparent div from this website. The h4 is Claimed. It doesnt work because h4 isnt received. const puppeteer = require('puppeteer') async function run() { const browser = await puppeteer.launch({ headless: false, ignoreHTTPSErrors: true, }) var x = 1101; while (x !== 0) { const page = await browser.newPage(); await page.setRequestInterception(true); page.on('request', (req) => { if (req.resourceType() == 'image' || req.resourceType() == 'font') { req.abort(); } else { req.continue(); } }); page.setDefaultTimeout(0); await page.goto(`https://play.projectnebula.com/planet/${x}`); await page.waitForSelector('h4'); const elements = await page.$$("h4"); let text = await (await elements[elements.length - 2].getProperty("innerText")).jsonValue() text = text.toLowerCase().trim(); if (text == 'claimed' || text == 'on sale') { console.log(text, x) x += 1; await page.close(); } else { console.log(x, text) x = 0 } } } run(); A: You are probably missing await before page.waitForSelector('h4'). This: page.waitForSelector('h4') should be: await page.waitForSelector('h4')
I am trying to get an h4 element text which is a child of divs using puppeteer
I am trying this code to extract an h4 which a child of 7 parent divs. like parent div, grandparent div from this website. The h4 is Claimed. It doesnt work because h4 isnt received. const puppeteer = require('puppeteer') async function run() { const browser = await puppeteer.launch({ headless: false, ignoreHTTPSErrors: true, }) var x = 1101; while (x !== 0) { const page = await browser.newPage(); await page.setRequestInterception(true); page.on('request', (req) => { if (req.resourceType() == 'image' || req.resourceType() == 'font') { req.abort(); } else { req.continue(); } }); page.setDefaultTimeout(0); await page.goto(`https://play.projectnebula.com/planet/${x}`); await page.waitForSelector('h4'); const elements = await page.$$("h4"); let text = await (await elements[elements.length - 2].getProperty("innerText")).jsonValue() text = text.toLowerCase().trim(); if (text == 'claimed' || text == 'on sale') { console.log(text, x) x += 1; await page.close(); } else { console.log(x, text) x = 0 } } } run();
[ "You are probably missing await before page.waitForSelector('h4').\nThis:\npage.waitForSelector('h4')\n\nshould be:\nawait page.waitForSelector('h4')\n\n" ]
[ 0 ]
[]
[]
[ "automation", "javascript", "node.js", "puppeteer" ]
stackoverflow_0074673672_automation_javascript_node.js_puppeteer.txt
Q: AWS appsync graphql subscription I have two seprate apps each has seprate AWS cognito userpool appsync api but has shared dynamodb. I want to create subscription for chat feature where app 1 (client app) and app 2 (admin app) will communicate. Is it possible please advise. I have followed this article from aws: enter link description here need advise how would that work in my case with two different apps. A: I think you first need to take a step back and separate the problem from the technology. You want to create a chat app, how would you build this? Do you need a data store or a queue? First think in abstractions then look what technology fits those abstractions best. If you start with the technology first you will most likely end up with a sub-par solution. If you really want to go for the technology first approach you could think of storing chats in DynamoDB(DDB) and using DDB streams to update the subscription. It can work but it will most likely be expensive.
AWS appsync graphql subscription
I have two seprate apps each has seprate AWS cognito userpool appsync api but has shared dynamodb. I want to create subscription for chat feature where app 1 (client app) and app 2 (admin app) will communicate. Is it possible please advise. I have followed this article from aws: enter link description here need advise how would that work in my case with two different apps.
[ "I think you first need to take a step back and separate the problem from the technology. You want to create a chat app, how would you build this? Do you need a data store or a queue? First think in abstractions then look what technology fits those abstractions best. If you start with the technology first you will most likely end up with a sub-par solution.\nIf you really want to go for the technology first approach you could think of storing chats in DynamoDB(DDB) and using DDB streams to update the subscription. It can work but it will most likely be expensive.\n" ]
[ 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "aws_appsync", "aws_cdk" ]
stackoverflow_0074656223_amazon_dynamodb_amazon_web_services_aws_appsync_aws_cdk.txt
Q: Execute a batch file on a remote PC using a batch file on local PC I want to execute a batch file D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat Which is on my server inidsoasrv01. How should I write my .bat file? A: Use microsoft's tool for remote commands executions: PsExec If there isn't your bat-file on remote host, copy it first. For example: copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\ And then execute: psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat Note: filepath for psexec is path to file on remote server, not your local. A: You can use WMIC or SCHTASKS (which means no third party software is needed): SCHTASKS: SCHTASKS /s remote_machine /U username /P password /create /tn "On demand demo" /tr "C:\some.bat" /sc ONCE /sd 01/01/1910 /st 00:00 SCHTASKS /s remote_machine /U username /P password /run /TN "On demand demo" WMIC (wmic will return the pid of the started process) WMIC /NODE:"remote_machine" /user:user /password:password process call create "c:\some.bat","c:\exec_dir" A: If you are in same WORKGROUP shutdown.exe /s /m \\<target-computer-name> should be enough shutdown /? for more, otherwise you need software to connect and control the target server. UPDATE: Seems shutdown.bat here is for shutting down apache-tomcat. So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client As native solution could be wmic Example: wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat" In your example should be: wmic /node:inidsoasrv01 process call create ^ "cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat" wmic /? and wmic /node /? for more A: With all the new security updates from Microsoft in the latest operating systems it is becoming more and more difficult to connect and execute scripts remotely. PsExec is one tool that helps you to connect a windows host from another windows host and execute command(s) or a script. Limitation of this tool is that it will execute the command(s) or a script, but it will not print the execution details. It will only return the process id. C:\apps\tools\psexec \\%RemoteHostName% -u %Domain%\%userName% -p %userPassword% -accepteula -d -h -i 1 cmd.exe /c "cd C:\apps\test\ & echo Hello World" & call C:\apps\test\script.bat
Execute a batch file on a remote PC using a batch file on local PC
I want to execute a batch file D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat Which is on my server inidsoasrv01. How should I write my .bat file?
[ "Use microsoft's tool for remote commands executions: PsExec\nIf there isn't your bat-file on remote host, copy it first. For example:\ncopy D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat \\\\RemoteServerNameOrIP\\d$\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\\n\nAnd then execute:\npsexec \\\\RemoteServerNameOrIP d:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat\n\nNote: filepath for psexec is path to file on remote server, not your local.\n", "You can use WMIC or SCHTASKS (which means no third party software is needed):\n\nSCHTASKS:\nSCHTASKS /s remote_machine /U username /P password /create /tn \"On demand demo\" /tr \"C:\\some.bat\" /sc ONCE /sd 01/01/1910 /st 00:00\nSCHTASKS /s remote_machine /U username /P password /run /TN \"On demand demo\"\n\nWMIC (wmic will return the pid of the started process)\nWMIC /NODE:\"remote_machine\" /user:user /password:password process call create \"c:\\some.bat\",\"c:\\exec_dir\"\n\n\n", "If you are in same WORKGROUP shutdown.exe /s /m \\\\<target-computer-name> should be enough shutdown /? for more, otherwise you need software to connect and control the target server.\nUPDATE: \nSeems shutdown.bat here is for shutting down apache-tomcat.\nSo, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client \nAs native solution could be wmic\nExample:\nwmic /node:<target-computer-name> process call create \"cmd.exe c:\\\\somefolder\\\\batch.bat\"\nIn your example should be:\nwmic /node:inidsoasrv01 process call create ^\n \"cmd.exe D:\\\\apache-tomcat-6.0.20\\\\apache-tomcat-7.0.30\\\\bin\\\\shutdown.bat\"\n\nwmic /? and wmic /node /? for more\n", "With all the new security updates from Microsoft in the latest operating systems it is becoming more and more difficult to connect and execute scripts remotely. PsExec is one tool that helps you to connect a windows host from another windows host and execute command(s) or a script. Limitation of this tool is that it will execute the command(s) or a script, but it will not print the execution details. It will only return the process id.\nC:\\apps\\tools\\psexec \\\\%RemoteHostName% -u %Domain%\\%userName% -p %userPassword% -accepteula -d -h -i 1 cmd.exe /c \"cd C:\\apps\\test\\ & echo Hello World\" & call C:\\apps\\test\\script.bat\n\n" ]
[ 25, 12, 1, 0 ]
[ "While I would recommend against this. \nBut you can use shutdown as client if the target machine has remote shutdown enabled and is in the same workgroup. \nExample:\nshutdown.exe /s /m \\\\<target-computer-name> /t 00\n\nreplacing <target-computer-name> with the URI for the target machine, \nOtherwise, if you want to trigger this through Apache, you'll need to configure the batch script as a CGI script by putting AddHandler cgi-script .bat and Options +ExecCGI into either a local .htaccess file or in the main configuration for your Apache install. \nThen you can just call the .bat file containing the shutdown.exe command from your browser.\n" ]
[ -2 ]
[ "batch_file", "cmd" ]
stackoverflow_0032482483_batch_file_cmd.txt
Q: Kotlin Syntax for whenCompleteAsync(BiConsumer,Executor) How do I implement a function in Kotlin for below method signature. I am facing issues getting the syntax correct. public CompletableFuture<T> whenCompleteAsync( BiConsumer<? super T, ? super Throwable> action, Executor executor) A: The analogue to Java's BiConsumer<? super T, ? super Throwable> generic type would be written in Kotlin as BiConsumer<in T, in Throwable>. The in keyword indicates that the generic type T is contravariant. This is how whenCompleteAsync function could be implemented in Kotlin using the provided method signature: fun <T> whenCompleteAsync( action: BiConsumer<in T, in Throwable>, executor: Executor ): CompletableFuture<T> { val future = CompletableFuture<T>() executor.execute { try { val result = future.get() action.accept(result, null) } catch (e: Throwable) { action.accept(null, e) } } return future } This function creates a new CompletableFuture and executes the provided action using the given executor when the future completes. The action is passed the result of the future (or null if the future completed exceptionally) and the exception thrown by the future (or null if the future completed successfully). Usage: val future = whenCompleteAsync( BiConsumer { result, ex -> if (ex != null) { // Handle exception } else { // Handle result } }, Executors.newSingleThreadExecutor() ) In this example, the whenCompleteAsync function is used to create a new CompletableFuture that will execute the provided BiConsumer on a single-threaded executor when the future completes. The BiConsumer will receive the result of the future or the exception thrown by the future, depending on how the future completed. Use this information to handle the result or exception as appropriate. In Kotlin no need to use BiConsumer interface (unless it is reqired for some reason). Instead it is possible to use Kotlin function with two arguments and simplify the example: fun <T> whenCompleteAsync( action: (T?, Throwable?) -> Unit, executor: Executor ): CompletableFuture<T> { val future = CompletableFuture<T>() executor.execute { try { val result = future.get() action(result, null) } catch (e: Throwable) { action(null, e) } } return future } val future = whenCompleteAsync( { result, ex -> if (ex != null) { // Handle exception } else { // Handle result } }, Executors.newSingleThreadExecutor() )
Kotlin Syntax for whenCompleteAsync(BiConsumer,Executor)
How do I implement a function in Kotlin for below method signature. I am facing issues getting the syntax correct. public CompletableFuture<T> whenCompleteAsync( BiConsumer<? super T, ? super Throwable> action, Executor executor)
[ "The analogue to Java's BiConsumer<? super T, ? super Throwable> generic type would be written in Kotlin as BiConsumer<in T, in Throwable>. The in keyword indicates that the generic type T is contravariant.\nThis is how whenCompleteAsync function could be implemented in Kotlin using the provided method signature:\nfun <T> whenCompleteAsync(\n action: BiConsumer<in T, in Throwable>, \n executor: Executor\n): CompletableFuture<T> {\n val future = CompletableFuture<T>()\n\n executor.execute {\n try {\n val result = future.get()\n action.accept(result, null)\n } catch (e: Throwable) {\n action.accept(null, e)\n }\n }\n\n return future\n}\n\nThis function creates a new CompletableFuture and executes the provided action using the given executor when the future completes. The action is passed the result of the future (or null if the future completed exceptionally) and the exception thrown by the future (or null if the future completed successfully).\nUsage:\nval future = whenCompleteAsync(\n BiConsumer { result, ex ->\n if (ex != null) {\n // Handle exception\n } else {\n // Handle result\n }\n },\n Executors.newSingleThreadExecutor()\n)\n\nIn this example, the whenCompleteAsync function is used to create a new CompletableFuture that will execute the provided BiConsumer on a single-threaded executor when the future completes. The BiConsumer will receive the result of the future or the exception thrown by the future, depending on how the future completed. Use this information to handle the result or exception as appropriate.\n\nIn Kotlin no need to use BiConsumer interface (unless it is reqired for some reason). Instead it is possible to use Kotlin function with two arguments and simplify the example:\nfun <T> whenCompleteAsync(\n action: (T?, Throwable?) -> Unit,\n executor: Executor\n): CompletableFuture<T> {\n val future = CompletableFuture<T>()\n\n executor.execute {\n try {\n val result = future.get()\n action(result, null)\n } catch (e: Throwable) {\n action(null, e)\n }\n }\n\n return future\n}\n\nval future = whenCompleteAsync(\n { result, ex ->\n if (ex != null) {\n // Handle exception\n } else {\n // Handle result\n }\n },\n Executors.newSingleThreadExecutor()\n)\n\n" ]
[ 0 ]
[]
[]
[ "completable_future", "java", "kotlin", "syntax" ]
stackoverflow_0074673464_completable_future_java_kotlin_syntax.txt
Q: Prevent user from erasing drawings with PencilKit - Swift I'm building a drawing app using PencilKit and I have a pre-loaded PKDrawing that loads with PKCanvasView. My goal it's to allow the user to play with the canvas using the pre-loaded PKDrawing as a reference. My question is: Is it possible to make the pre-loaded PKDraw unerasable? Please notice that I don't want to completely block the Eraser tool, users must be able to erase its own drawing, but not the reference one. A: This is an alternate way to resolve this issue. It's work for me. Let me try to explain with example. Here I have remove only Highlighter and redraw other path on same canvas. so It'll looks like removing only Highlighter not a other text. I have mention here 4 steps you need to follow STEP 1> Declare temp variable in class var tempPKDrawing: PKDrawing? STEP 2> Now add this PKCanvasViewDelegate methods // MARK: Canvas View Delegate extension PKCanvas: PKCanvasViewDelegate { /// Delegate method: Note that the drawing has changed. public func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) { print("canvasViewDrawingDidChange\(canvasView.drawing)") print ("toolPicker isVisible:\(toolPicker?.isVisible)") //****** STEP 4> ****** //Remove Highlighter text if canvasView.tool is PKEraserTool, let tempDrawing = self.tempPKDrawing { if canvasView.drawing.strokes.count != tempDrawing.strokes.count { var newDrawing : [PKStroke] = tempDrawing.strokes.filter({$0.ink.inkType != .marker}) newDrawing += canvasView.drawing.strokes.filter({$0.ink.inkType == .marker}) self.tempPKDrawing = nil self.canvasView?.drawing = PKDrawing(strokes: newDrawing) } } } public func canvasViewDidBeginUsingTool(_ canvasView: PKCanvasView) { print("canvasViewDidBeginUsingTool:\(canvasView.drawing)") //****** STEP 3> ****** if canvasView.tool is PKEraserTool { self.tempPKDrawing = canvasView.drawing } //canvasView.drawingPolicy = PKEraserToolReference(eraserType: .) } public func canvasViewDidEndUsingTool(_ canvasView: PKCanvasView) { print("canvasViewDidEndUsingTool") } public func canvasViewDidFinishRendering(_ canvasView: PKCanvasView) { print("canvasViewDidFinishRendering") } } Thanks KOOL ;)
Prevent user from erasing drawings with PencilKit - Swift
I'm building a drawing app using PencilKit and I have a pre-loaded PKDrawing that loads with PKCanvasView. My goal it's to allow the user to play with the canvas using the pre-loaded PKDrawing as a reference. My question is: Is it possible to make the pre-loaded PKDraw unerasable? Please notice that I don't want to completely block the Eraser tool, users must be able to erase its own drawing, but not the reference one.
[ "This is an alternate way to resolve this issue. It's work for me.\nLet me try to explain with example. Here I have remove only Highlighter and redraw other path on same canvas. so It'll looks like removing only Highlighter not a other text.\nI have mention here 4 steps you need to follow\nSTEP 1> Declare temp variable in class\nvar tempPKDrawing: PKDrawing?\n\nSTEP 2> Now add this PKCanvasViewDelegate methods\n // MARK: Canvas View Delegate\nextension PKCanvas: PKCanvasViewDelegate {\n\n /// Delegate method: Note that the drawing has changed.\n public func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {\n print(\"canvasViewDrawingDidChange\\(canvasView.drawing)\")\n print (\"toolPicker isVisible:\\(toolPicker?.isVisible)\")\n\n//****** STEP 4> ******\n //Remove Highlighter text\n if canvasView.tool is PKEraserTool, let tempDrawing = self.tempPKDrawing {\n if canvasView.drawing.strokes.count != tempDrawing.strokes.count {\n var newDrawing : [PKStroke] = tempDrawing.strokes.filter({$0.ink.inkType != .marker})\n newDrawing += canvasView.drawing.strokes.filter({$0.ink.inkType == .marker})\n self.tempPKDrawing = nil\n self.canvasView?.drawing = PKDrawing(strokes: newDrawing)\n }\n }\n\n }\n\n public func canvasViewDidBeginUsingTool(_ canvasView: PKCanvasView) {\n print(\"canvasViewDidBeginUsingTool:\\(canvasView.drawing)\")\n\n//****** STEP 3> ******\n if canvasView.tool is PKEraserTool {\n self.tempPKDrawing = canvasView.drawing\n }\n //canvasView.drawingPolicy = PKEraserToolReference(eraserType: .)\n }\n public func canvasViewDidEndUsingTool(_ canvasView: PKCanvasView) {\n print(\"canvasViewDidEndUsingTool\")\n }\n public func canvasViewDidFinishRendering(_ canvasView: PKCanvasView) {\n print(\"canvasViewDidFinishRendering\")\n }\n}\n\n\nThanks KOOL ;)\n" ]
[ 0 ]
[]
[]
[ "ios", "mobile", "pencilkit", "swift", "xcode" ]
stackoverflow_0070385470_ios_mobile_pencilkit_swift_xcode.txt
Q: Create invisible samba server that is still accessible Is it possible to configure the smb.cfg of a samba server to not show up automatically in any lists on the client side but still be accessible when the server address is typed into the explorer? If yes, how so? I'm using the samba and samba-common-bin packages on raspbian. A: Yes, it is possible to configure a Samba server so that it does not show up automatically in client lists, but is still accessible when the server address is manually entered. To do this, you will need to edit the smb.conf file for your Samba server. To edit the smb.conf file, open a terminal window and use the following command: sudo nano /etc/samba/smb.conf This will open the smb.conf file in the nano text editor. From there, you can edit the file to your liking. To make the Samba server invisible to clients, you will need to add the following line to the file: browseable = no Once you have added this line, save the file and exit the editor. Then, you will need to restart the Samba service in order for the changes to take effect. You can do this by using the following command: sudo service smbd restart After restarting the service, the Samba server will no longer show up automatically in client lists, but will still be accessible when the server address is manually entered. Keep in mind that this will only hide the server from clients that use the SMB protocol to browse for network shares. Other protocols, such as NFS, may still show the server in their lists.
Create invisible samba server that is still accessible
Is it possible to configure the smb.cfg of a samba server to not show up automatically in any lists on the client side but still be accessible when the server address is typed into the explorer? If yes, how so? I'm using the samba and samba-common-bin packages on raspbian.
[ "Yes, it is possible to configure a Samba server so that it does not show up automatically in client lists, but is still accessible when the server address is manually entered. To do this, you will need to edit the smb.conf file for your Samba server.\nTo edit the smb.conf file, open a terminal window and use the following command:\nsudo nano /etc/samba/smb.conf\n\nThis will open the smb.conf file in the nano text editor. From there, you can edit the file to your liking. To make the Samba server invisible to clients, you will need to add the following line to the file:\nbrowseable = no\n\nOnce you have added this line, save the file and exit the editor. Then, you will need to restart the Samba service in order for the changes to take effect. You can do this by using the following command:\nsudo service smbd restart\n\nAfter restarting the service, the Samba server will no longer show up automatically in client lists, but will still be accessible when the server address is manually entered. Keep in mind that this will only hide the server from clients that use the SMB protocol to browse for network shares. Other protocols, such as NFS, may still show the server in their lists.\n" ]
[ 1 ]
[]
[]
[ "samba" ]
stackoverflow_0074673701_samba.txt
Q: Trying to append csv into another csv AS A ROW but I am getting this AttributeError: '_io.TextIOWrapper' object has no attribute 'writerows' i am trying to append the content in one of my CSV as a ROW to another csv but i am getting this attribute error...I am unsure how to fix it. I think the issue is with writer.writerows(row) but I don't what i should change it to for .writerows(row) to work This is my below code for appending the first csv to the second csv. with open(csv1', 'r', encoding='utf8') as reader, open(csv2', 'a', encoding='utf8') as writer: for row in reader: writer.writerows(row) A: Use write() instead because writerows() is belong to csv.writer, not normal io. However, if you want to append at the end of the file, you need to make sure that the last row contain new line (i.e., \n) already. with open('test1.csv', 'r', encoding='utf8') as reader: with open('test2.csv', 'a', encoding='utf8') as writer: writer.write("\n") # no need if the last row have new line already for line in reader: writer.write(line) Or, if you want to use csv, you can use writerows() as shown in code below: import csv with open('test1.csv', 'r', encoding='utf8') as reader: with open('test2.csv', 'a', encoding='utf8') as writer: csv_reader = csv.reader(reader) csv_writer = csv.writer(writer) csv_writer.writerow([]) # again, no need if the last row have new line already csv_writer.writerows(csv_reader)
Trying to append csv into another csv AS A ROW but I am getting this AttributeError: '_io.TextIOWrapper' object has no attribute 'writerows'
i am trying to append the content in one of my CSV as a ROW to another csv but i am getting this attribute error...I am unsure how to fix it. I think the issue is with writer.writerows(row) but I don't what i should change it to for .writerows(row) to work This is my below code for appending the first csv to the second csv. with open(csv1', 'r', encoding='utf8') as reader, open(csv2', 'a', encoding='utf8') as writer: for row in reader: writer.writerows(row)
[ "Use write() instead because writerows() is belong to csv.writer, not normal io. However, if you want to append at the end of the file, you need to make sure that the last row contain new line (i.e., \\n) already.\nwith open('test1.csv', 'r', encoding='utf8') as reader:\n with open('test2.csv', 'a', encoding='utf8') as writer:\n writer.write(\"\\n\") # no need if the last row have new line already\n for line in reader:\n writer.write(line)\n\nOr, if you want to use csv, you can use writerows() as shown in code below:\nimport csv\n\nwith open('test1.csv', 'r', encoding='utf8') as reader:\n with open('test2.csv', 'a', encoding='utf8') as writer:\n csv_reader = csv.reader(reader)\n csv_writer = csv.writer(writer)\n csv_writer.writerow([]) # again, no need if the last row have new line already\n csv_writer.writerows(csv_reader)\n\n" ]
[ 1 ]
[]
[]
[ "append", "attributeerror", "csv", "python" ]
stackoverflow_0074673250_append_attributeerror_csv_python.txt
Q: Make React Props Readonly in Typescript I heard that React Props is read only by default, however, I could overwrite props value in a component without errors. Is there settings to make props read only? interface Props { readonly isText: boolean; } const ComponentA: FC<Props> = ({isText}: Props) { isText = false // <- I can change isText even if I add readonly. why? return <>{isText}</> } A: In TypeScript, the readonly keyword is a modifier that you can add to properties in an interface to indicate that they are read-only. This means that the property can only be read and cannot be changed. However, the readonly keyword only has an effect at compile time, not at runtime. So, even if you add the readonly keyword to a property, you can still change its value in your code if you want to. If you want to make a property truly read-only at runtime, you can use the Object.freeze() method. This method freezes an object, which means that it cannot be changed. Here's an example: interface Props { readonly isText: boolean; } const ComponentA: FC<Props> = ({isText}: Props) { // Make isText truly read-only by freezing the object Object.freeze(isText); // This line will throw an error because isText is frozen isText = false; return <>{isText}</>; } A: Typescript won't detect error when you decompose the object. Try to access it as an object const ComponentA: React.FC<Props> = (prop: Props) => { prop.isText = false; // <- error return <div>{prop.isText}</div> } Demo
Make React Props Readonly in Typescript
I heard that React Props is read only by default, however, I could overwrite props value in a component without errors. Is there settings to make props read only? interface Props { readonly isText: boolean; } const ComponentA: FC<Props> = ({isText}: Props) { isText = false // <- I can change isText even if I add readonly. why? return <>{isText}</> }
[ "In TypeScript, the readonly keyword is a modifier that you can add to properties in an interface to indicate that they are read-only. This means that the property can only be read and cannot be changed. However, the readonly keyword only has an effect at compile time, not at runtime. So, even if you add the readonly keyword to a property, you can still change its value in your code if you want to.\nIf you want to make a property truly read-only at runtime, you can use the Object.freeze() method. This method freezes an object, which means that it cannot be changed. Here's an example:\ninterface Props {\n readonly isText: boolean;\n}\n\nconst ComponentA: FC<Props> = ({isText}: Props) {\n // Make isText truly read-only by freezing the object\n Object.freeze(isText);\n\n // This line will throw an error because isText is frozen\n isText = false;\n\n return <>{isText}</>;\n}\n\n\n", "Typescript won't detect error when you decompose the object. Try to access it as an object\nconst ComponentA: React.FC<Props> = (prop: Props) => {\n prop.isText = false; // <- error\n\n return <div>{prop.isText}</div>\n}\n\nDemo\n" ]
[ 1, 1 ]
[]
[]
[ "reactjs", "typescript" ]
stackoverflow_0074673700_reactjs_typescript.txt
Q: VirtualBox NS_ERROR_FAILURE (0x80004005) macOS I'm using macOS and installed VirtualBox. When I start a machine, I'm getting the following error : Failed to open a session for the virtual machine ubuntu. The virtual machine 'ubuntu' has terminated unexpectedly during startup with exit code 1 (0x1). Result Code: NS_ERROR_FAILURE (0x80004005) Component: MachineWrap Interface: IMachine {85cd948e-a71f-4289-281e-0ca7ad48cd89} A: This error seems to appear with VirtualBox installs on versions of macOS 10.13. To fix this issue, you have to uninstall VirtualBox (use the VirtualBox_uninstall.tool of the VirtualBox downloaded dmg). Then, install it again executing VirtualBox.pkg. At the end of the install, go to System Preferences, Security and Privacy, and the click the allow button : The preferences pane has changed in macOS Ventura. You have to find the corresponding section in Privacy & Security which has a button to configure the extensions and then asks fora restart. This should solve your issue. A: Here is what worked for me. I kept getting that error when I was trying to 'add' the ISO after clicking start on the VM to set it up. However, when I clicked on 'Tools' on the left sidebar, then click "Media". From there I was able to add my Kali Linux ISO so when I started the VM again, the ISO showed up in the list. A: Download the virtualbox extension from https://www.virtualbox.org/wiki/Downloads Run it and it works! A: Let's look at this from a troubleshooting perspective. The number one thing to do instead of guessing is diagnose and the best way to do that when you don't know what the problem is. I'll take you through the steps for my particular use case but it should give you a general idea on how to look at the problem in order to find the correct solution. a.-Have a look at the actual logs of the VM: Click on the Menu Item, you should see three choices: Details Snapshots Logs Look for this error code: VMSetError and look for the matching RETURN CODE (rc) rc=VERR_VD_IMAGE_READ_ONLY In the example below the file under /build/virtualbox....is in read only mode. VMSetError: /build/virtualbox-8vePuu/virtualbox-6.1.16-dfsg/src/VBox/Devices/Storage/DrvVD.cpp(5228) int drvvdConstruct(PPDMDRVINS, PCFGMNODE, uint32_t); rc=VERR_VD_IMAGE_READ_ONLY b.-Interpret what that means: But the problem is the /build directory does not exist at all. So what the rc above really means is that it cannot FIND that file, because /build doesn't even exist (nor it seems to be supposed to). cd: /build/virtualbox-8vePuu/virtualbox-6.1.16-dfsg/src/VBox/Devices/Storage/: No such file or directory root@pop-os:~# cd /build/virtualbox-8vePuu/virtualbox-6.1.16-dfsg/ -bash: cd: /build/virtualbox-8vePuu/virtualbox-6.1.16-dfsg/: No such file or directory root@pop-os:~# cd /build -bash: cd: /build: No such file or directory root@pop-os:~# ls / bin dev home lib32 libx32 media opt root sbin sys usr boot etc lib lib64 lost+found mnt proc run srv tmp var Another thing to notice is that for my case other VMs with VDIs in the same location don't have the problem. That completely discards two possibilities: There's a problem with the install of Virtual Box There's an actual file permissions issue The possibility is that the VM got corrupted at some point during shut down and that created the config corruption, not a VDI corruption at the VM level, not VirtualBox level. Unless you power off your VM the "Close" function on your Vm window will ALWAYS save the state of the machine, so "Discarding" the state is only possible when you have two or more states because in that case at a minimum there is always the LAST state. The conclusion is then that the corruption is at the VM state level and we need to get rid of that. c.-Solution: Go to VM-> Menu->Snapshots -> Clone Create a linked Clone. That will simply copy the config files to the right place and link with the same VDI. Start that one. If it starts you know you have a problem with the original VM. You can either re-create the VM and point to the existing VDI or create a full clone (it will take longer) and the delete the original. To prevent this (at least for my case), avoid sending the Power Off Message to your VM when closing, better use the ACPI Shutdown method as Power off can leave (as we saw) your machine on an unwanted state. A: Using a readonly filesystem, blocking VBox files wrtiting access causes this error. Move VBox virtual machines files to a new location with writing permissions must resolves this problem. In my case, i use a Linux server, with VBOx software but my machine was moved to a Windows partition with BitLocker active and the windows Disk was mounted in ReadOnly, causing this problem. A: If somebody have problem with run virtual machine after upgrade VirtualBox on BigSur 11.6.3, first should check System Extension in System preferences -> Security & Privacy and allow Run Oracle. After rebooting computer, virtual machine start normally. A: I had the issue when I upgraded and I used the Extensions feature. Check that your extensions have been updated as well. Download the latest from VirtualBox Website. Select File / Preferences and then the Extensions. Click the add symbol and select the new updated extension file. Try and restart your virtual machine again. A: Had the same issue on Mac OS Big Sur 11.4 when I was trying to add my Ubuntu instance (on Intel tho), nothing suggested here and other topics helped. Turned out you have to give access (Full Disc Access) to Virtual Box in Settings. Go to Settings -> Security & Privacy -> Privacy -> Full Disc Access -> plus sign (unlock it if needed) -> choose Virtual Box Application -> Open. After that I was able to choose my Ubuntu image in Finder. A: I was having the same problem with the latest Monterey Macos. Just run the following commands on your terminal. sudo kextload -b org.virtualbox.kext.VBoxDrv sudo kextload -b org.virtualbox.kext.VBoxNetFlt sudo kextload -b org.virtualbox.kext.VBoxNetAdp sudo kextload -b org.virtualbox.kext.VBoxUSB And here's where I got these commands from: https://forums.virtualbox.org/viewtopic.php?f=39&t=104272&sid=617676a134b8f244304a58cbe41c3e86 [update] Unfortunately, I have to execute this command every time I restart my laptop. I'll put a definitive solution once I get it. A: I had this issue after I upgraded to Monterrey from Big Sur. To fix: completely uninstall Virtualbox. Do this by downloading and opening the DMG and choose 'Virtualbox_uninstall.tool'. You will get a permission denied error, so go to System Preferences->Security and Privacy->General tab, and click on the relevant 'Allow' in 'Allow apps downloaded from:' section. This will run the script install VirtualBox 6.1.30 (the latest will likely work as well). I still got the same "NS_ERROR_FAILURE" error. Again go to System Preferences->Security and Privacy->General tab and allow Oracle from the 'Allow apps downloaded from:' section. You will have to reboot A: That file is obviously corrupted. If you go to that location [1], you'll see a 0-bytes file. In that same folder, chances are you're going to find a file named "VirtualBox.xml-prev". Delete the "VirtualBox.xml" file (the 0-bytes one) and rename the "VirtualBox.xml-prev" to "VirtualBox.xml". If there is no "VirtualBox.xml-prev", or if it's also a 0-bytes file, then don't worry, it's still fixable. Just delete both of these files, they will be re-created when VirtualBox runs again. You simply would have lost any VirtualBox preferences and registered VMs that you might have had. Not the VMs themselves, the list of the VMs. You need to re-register your VMs, by either double-clicking on the .vbox file of every VM that you have, or go to the menu "Machine" » "Add" and navigate to the .vbox file of each of your existing VMs. Your VMs are located (by default) in "/Users//VirtualBox VMs". A: If you are working on Vagrant and VirtualBox with the latest macOS Monterey, I will tell you based on my hour's search that it is the incompatible issue of the latest Monterey. I now have several options to do. one is to downgrade to the last version of macOS(annoying), the other is to continually find a walk around. you may find this to be useful as a walk around: add code below in your vagrant file to start with GUI instead of headless config.vm.provider "virtualbox" do |vb| vb.gui = true end A: macOS BIG Sur v 11.6: this post is open for a long time but no solution worked for me but finally I found the solution start virtualbox with terminal in sudo mode sudo virtualbox install your ova system kali, unbutu... start your vm after to have change the settings during the launch of your vm it is possible that macos must have allow your audio device click "allow" I found this solution forums.virtualbox thanks to them A: I was facing a similar issue with vagrant version v2.3.2 and VirtualBox version 7.0.2 on macOS Ventura. In my case, the issue was solved by doing the following: # 1 sudo su csrutil clear #2 Then uninstall VirtualBox using the official uninstaller after that reboot the system. #3 After the reboot install VirtualBox again using: brew install --cask virtualbox #4 Add this line to your Vagrantfile: virtualbox__intnet: true #5 vagrant up A: I'm running macOs Ventura. After getting this error, I simply downloaded and installed latest version of Virtualbox, it simply fixed this issue and run without any problems. A: I got this when I was trying to restore a suspended session. The fix was to click the "Discard" button (down arrow icon) and just discard the saved machine state. It's at least faster that uninstall/reinstall, I'd try it first. A: On MacOS Mojave, owner for /Applications folder needs to be user root, group admin. Same for the VirtualBox.app folder. This was the only thing that worked for me. A: If you are trying to run an OS with state saved, then right clicking the Virtual machine and pressing discard saved state could resolve the issue. A: For me it happened after upgrading my MacOS to Ventura. I also had to upgrade my VB to 7.x as mentioned here to fix the issue
VirtualBox NS_ERROR_FAILURE (0x80004005) macOS
I'm using macOS and installed VirtualBox. When I start a machine, I'm getting the following error : Failed to open a session for the virtual machine ubuntu. The virtual machine 'ubuntu' has terminated unexpectedly during startup with exit code 1 (0x1). Result Code: NS_ERROR_FAILURE (0x80004005) Component: MachineWrap Interface: IMachine {85cd948e-a71f-4289-281e-0ca7ad48cd89}
[ "This error seems to appear with VirtualBox installs on versions of macOS 10.13.\nTo fix this issue, you have to uninstall VirtualBox (use the VirtualBox_uninstall.tool of the VirtualBox downloaded dmg).\nThen, install it again executing VirtualBox.pkg. At the end of the install, go to System Preferences, Security and Privacy, and the click the allow button :\n\nThe preferences pane has changed in macOS Ventura. You have to find the corresponding section in Privacy & Security which has a button to configure the extensions and then asks fora restart.\n\nThis should solve your issue.\n", "Here is what worked for me. I kept getting that error when I was trying to 'add' the ISO after clicking start on the VM to set it up.\nHowever, when I clicked on 'Tools' on the left sidebar, then click \"Media\". From there I was able to add my Kali Linux ISO so when I started the VM again, the ISO showed up in the list.\n\n", "\nDownload the virtualbox extension from https://www.virtualbox.org/wiki/Downloads\n\n\n\nRun it and it works!\n\n", "Let's look at this from a troubleshooting perspective. The number one thing to do instead of guessing is diagnose and the best way to do that when you don't know what the problem is. I'll take you through the steps for my particular use case but it should give you a general idea on how to look at the problem in order to find the correct solution.\na.-Have a look at the actual logs of the VM:\nClick on the Menu Item, you should see three choices:\n\nDetails\nSnapshots\nLogs\n\nLook for this error code:\nVMSetError and look for the matching RETURN CODE (rc)\nrc=VERR_VD_IMAGE_READ_ONLY\nIn the example below the file under /build/virtualbox....is in read only mode.\n VMSetError: /build/virtualbox-8vePuu/virtualbox-6.1.16-dfsg/src/VBox/Devices/Storage/DrvVD.cpp(5228) int drvvdConstruct(PPDMDRVINS, PCFGMNODE, uint32_t); rc=VERR_VD_IMAGE_READ_ONLY\n\nb.-Interpret what that means:\nBut the problem is the /build directory does not exist at all. So what the rc above really means is that it cannot FIND that file, because /build doesn't even exist (nor it seems to be supposed to).\ncd: /build/virtualbox-8vePuu/virtualbox-6.1.16-dfsg/src/VBox/Devices/Storage/: No such file or directory\nroot@pop-os:~# cd /build/virtualbox-8vePuu/virtualbox-6.1.16-dfsg/\n-bash: cd: /build/virtualbox-8vePuu/virtualbox-6.1.16-dfsg/: No such file or directory\nroot@pop-os:~# cd /build\n-bash: cd: /build: No such file or directory\nroot@pop-os:~# ls /\nbin dev home lib32 libx32 media opt root sbin sys usr\nboot etc lib lib64 lost+found mnt proc run srv tmp var\n\nAnother thing to notice is that for my case other VMs with VDIs in the same location don't have the problem.\nThat completely discards two possibilities:\n\nThere's a problem with the install of Virtual Box\nThere's an actual file permissions issue\n\nThe possibility is that the VM got corrupted at some point during shut down and that created the config corruption, not a VDI corruption at the VM level, not VirtualBox level.\nUnless you power off your VM the \"Close\" function on your Vm window will ALWAYS save the state of the machine, so \"Discarding\" the state is only possible when you have two or more states because in that case at a minimum there is always the LAST state.\nThe conclusion is then that the corruption is at the VM state level and we need to get rid of that.\nc.-Solution:\nGo to VM-> Menu->Snapshots -> Clone\nCreate a linked Clone. That will simply copy the config files to the right place and link with the same VDI.\nStart that one.\nIf it starts you know you have a problem with the original VM. You can either re-create the VM and point to the existing VDI or create a full clone (it will take longer) and the delete the original.\nTo prevent this (at least for my case), avoid sending the Power Off Message to your VM when closing, better use the ACPI Shutdown method as Power off can leave (as we saw) your machine on an unwanted state.\n", "Using a readonly filesystem, blocking VBox files wrtiting access causes this error.\nMove VBox virtual machines files to a new location with writing permissions must resolves this problem. In my case, i use a Linux server, with VBOx software but my machine was moved to a Windows partition with BitLocker active and the windows Disk was mounted in ReadOnly, causing this problem.\n", "If somebody have problem with run virtual machine after upgrade VirtualBox on BigSur 11.6.3, first should check System Extension in System preferences -> Security & Privacy and allow Run Oracle. After rebooting computer, virtual machine start normally.\n", "I had the issue when I upgraded and I used the Extensions feature.\nCheck that your extensions have been updated as well. Download the latest from VirtualBox Website. Select File / Preferences and then the Extensions. Click the add symbol and select the new updated extension file.\nTry and restart your virtual machine again.\n", "Had the same issue on Mac OS Big Sur 11.4 when I was trying to add my Ubuntu instance (on Intel tho), nothing suggested here and other topics helped. Turned out you have to give access (Full Disc Access) to Virtual Box in Settings. Go to Settings -> Security & Privacy -> Privacy -> Full Disc Access -> plus sign (unlock it if needed) -> choose Virtual Box Application -> Open. After that I was able to choose my Ubuntu image in Finder.\n", "I was having the same problem with the latest Monterey Macos. Just run the following commands on your terminal.\nsudo kextload -b org.virtualbox.kext.VBoxDrv\nsudo kextload -b org.virtualbox.kext.VBoxNetFlt\nsudo kextload -b org.virtualbox.kext.VBoxNetAdp\nsudo kextload -b org.virtualbox.kext.VBoxUSB\n\nAnd here's where I got these commands from:\nhttps://forums.virtualbox.org/viewtopic.php?f=39&t=104272&sid=617676a134b8f244304a58cbe41c3e86\n[update] Unfortunately, I have to execute this command every time I restart my laptop. I'll put a definitive solution once I get it.\n", "I had this issue after I upgraded to Monterrey from Big Sur. To fix:\n\ncompletely uninstall Virtualbox. Do this by downloading and opening the DMG and choose 'Virtualbox_uninstall.tool'. You will get a permission denied error, so go to System Preferences->Security and Privacy->General tab, and click on the relevant 'Allow' in 'Allow apps downloaded from:' section. This will run the script\ninstall VirtualBox 6.1.30 (the latest will likely work as well). I still got the same \"NS_ERROR_FAILURE\" error. Again go to System Preferences->Security and Privacy->General tab and allow Oracle from the 'Allow apps downloaded from:' section. You will have to reboot\n\n", "That file is obviously corrupted. If you go to that location [1], you'll see a 0-bytes file. In that same folder, chances are you're going to find a file named \"VirtualBox.xml-prev\". Delete the \"VirtualBox.xml\" file (the 0-bytes one) and rename the \"VirtualBox.xml-prev\" to \"VirtualBox.xml\".\nIf there is no \"VirtualBox.xml-prev\", or if it's also a 0-bytes file, then don't worry, it's still fixable. Just delete both of these files, they will be re-created when VirtualBox runs again. You simply would have lost any VirtualBox preferences and registered VMs that you might have had. Not the VMs themselves, the list of the VMs. You need to re-register your VMs, by either double-clicking on the .vbox file of every VM that you have, or go to the menu \"Machine\" » \"Add\" and navigate to the .vbox file of each of your existing VMs. Your VMs are located (by default) in \"/Users//VirtualBox VMs\".\n", "If you are working on Vagrant and VirtualBox with the latest macOS Monterey, I will tell you based on my hour's search that it is the incompatible issue of the latest Monterey.\nI now have several options to do. one is to downgrade to the last version of macOS(annoying), the other is to continually find a walk around.\nyou may find this to be useful as a walk around:\nadd code below in your vagrant file to start with GUI instead of headless\nconfig.vm.provider \"virtualbox\" do |vb|\n vb.gui = true\nend\n\n", "macOS BIG Sur v 11.6:\nthis post is open for a long time but no solution worked for me but finally I found the solution\n\nstart virtualbox with terminal in sudo mode\n\nsudo virtualbox \n\n\ninstall your ova system kali, unbutu...\n\nstart your vm after to have change the settings\n\nduring the launch of your vm it is possible that macos must have allow your audio device click \"allow\"\n\n\nI found this solution forums.virtualbox\nthanks to them\n", "I was facing a similar issue with vagrant version v2.3.2 and VirtualBox version 7.0.2 on macOS Ventura. In my case, the issue was solved by doing the following:\n# 1\nsudo su\ncsrutil clear\n\n#2\nThen uninstall VirtualBox using the official uninstaller after that reboot the system.\n\n#3\nAfter the reboot install VirtualBox again using:\n\nbrew install --cask virtualbox\n\n#4 \nAdd this line to your Vagrantfile:\nvirtualbox__intnet: true\n\n#5\nvagrant up\n\n", "I'm running macOs Ventura. After getting this error, I simply downloaded and installed latest version of Virtualbox, it simply fixed this issue and run without any problems.\n", "I got this when I was trying to restore a suspended session. The fix was to click the \"Discard\" button (down arrow icon) and just discard the saved machine state. It's at least faster that uninstall/reinstall, I'd try it first.\n", "On MacOS Mojave, owner for /Applications folder needs to be user root, group admin. Same for the VirtualBox.app folder.\nThis was the only thing that worked for me.\n", "If you are trying to run an OS with state saved, then right clicking the Virtual machine and pressing discard saved state could resolve the issue.\n", "For me it happened after upgrading my MacOS to Ventura. I also had to upgrade my VB to 7.x as mentioned here to fix the issue\n" ]
[ 80, 18, 14, 5, 4, 3, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "macos", "virtualbox" ]
stackoverflow_0052689672_macos_virtualbox.txt
Q: AttributeError: 'str' object has no attribute 'append' I am completely newbee in programming. So I started learning python. In this proram i want to print the name of second lowest scorers and for multiple students print them alphabetically. So I have written this program and I am trying to add those student who has second lowest score. So I add in list named "name". But it is showing the error. My doubt is that I am not appending to any string rather to a list. Then why this error? if __name__ == '__main__': student_info = [] name = [] for _ in range(int(input())): name = input() score = float(input()) student_info.extend([[name,score]]) student_info.sort(key=lambda x:x[1]) for i in range(0,len(student_info)): if student_info[1][1] == student_info[i][1]: name.append(student_info[i][1]) name.sort() for i in name: print(i) AttributeError Traceback (most recent call last) C:\Users\PABANG~1\AppData\Local\Temp/ipykernel_1504/3074229933.py in <module> 10 11 if student_info[1][1] == student_info[i][1]: ---> 12 name.append(student_info[i][1]) 13 name.sort() 14 for i in name: AttributeError: 'str' object has no attribute 'append' A: I've spotted a couple of issues in your code and hope this helps. Your name variable has been assigned by the input(), which is a string type. So declare a different variable name. For getting the student name, it should be name.append(student_info[i][0]). if __name__ == '__main__': student_info = [] name = [] for _ in range(int(input())): student_name = input() score = float(input()) student_info.extend([[student_name ,score]]) student_info.sort(key=lambda x:x[1]) for i in range(0,len(student_info)): if student_info[1][1] == student_info[i][1]: name.append(student_info[i][0]) name.sort() for i in name: print(i)
AttributeError: 'str' object has no attribute 'append'
I am completely newbee in programming. So I started learning python. In this proram i want to print the name of second lowest scorers and for multiple students print them alphabetically. So I have written this program and I am trying to add those student who has second lowest score. So I add in list named "name". But it is showing the error. My doubt is that I am not appending to any string rather to a list. Then why this error? if __name__ == '__main__': student_info = [] name = [] for _ in range(int(input())): name = input() score = float(input()) student_info.extend([[name,score]]) student_info.sort(key=lambda x:x[1]) for i in range(0,len(student_info)): if student_info[1][1] == student_info[i][1]: name.append(student_info[i][1]) name.sort() for i in name: print(i) AttributeError Traceback (most recent call last) C:\Users\PABANG~1\AppData\Local\Temp/ipykernel_1504/3074229933.py in <module> 10 11 if student_info[1][1] == student_info[i][1]: ---> 12 name.append(student_info[i][1]) 13 name.sort() 14 for i in name: AttributeError: 'str' object has no attribute 'append'
[ "I've spotted a couple of issues in your code and hope this helps.\n\nYour name variable has been assigned by the input(), which is a\nstring type. So declare a different variable name.\n\nFor getting the student name, it should be\nname.append(student_info[i][0]).\n\n\nif __name__ == '__main__':\n student_info = []\n name = []\n for _ in range(int(input())):\n student_name = input()\n score = float(input())\n student_info.extend([[student_name ,score]])\n student_info.sort(key=lambda x:x[1])\n for i in range(0,len(student_info)):\n if student_info[1][1] == student_info[i][1]:\n name.append(student_info[i][0])\n name.sort()\n for i in name:\n print(i)\n\n\n" ]
[ 0 ]
[]
[]
[ "append", "list", "python" ]
stackoverflow_0074673687_append_list_python.txt
Q: Inserting an integer into a regular binary tree While revising for my final, I came across binary trees (regular ones). After going through the lecture, I started to solve previous labs. My problem here is that only 6 is inserted into the tree. What is wrong with my method? What I'm trying to input: tree.insert(1); tree.insert(15); tree.insert(7); tree.insert(13); tree.insert(58); tree.insert(6); The Node class: public class Node { public int key; public Node left_child; public Node right_child; // The Constructor(s). public Node() { } public Node(int key) { this.key = key; left_child = null; right_child = null; } // The Get Methods. public int getKey() { return key; } public Node getLeft_child() { return left_child; } public Node getRight_child() { return right_child; } // The Set Methods. public void setKey(int key) { this.key = key; } public void setLeft_child(Node left_child) { this.left_child = left_child; } public void setRight_child(Node right_child) { this.right_child = right_child; } } The BinaryTree class: public class BinaryTree { private Node root; // The Constructor Method(s) public BinaryTree() { root = null; } public boolean is_empty() { return (root == null); } public void insert(int k) { insert(root, k); } private Node insert(Node x, int k) { Node p = new Node(k); if (x == null) { root = p; } else { if (x.left_child != null) { insert(x.left_child, k); } else { insert(x.right_child, k); } } return x; } // Printing Method(s). public void print_inorder() { print_inorder(root); } public void print_inorder(Node node) { if (node == null) { return; } print_inorder(node.left_child); System.out.print(node.key + " "); print_inorder(node.right_child); } public void print_preorder() { print_preorder(root); } public void print_preorder(Node node) { if (node == null) { return; } System.out.print(node.key + " "); print_preorder(node.left_child); print_preorder(node.right_child); } public void print_postorder() { print_postorder(root); } public void print_postorder(Node node) { if (node == null) { return; } print_postorder(node.left_child); print_postorder(node.right_child); System.out.print(node.key + " "); } } A: This will have a node to the left if a number is even and a node to the right if a node is odd. I had to change your if condition because the way it was it was never going to use the left node. private void insert(Node x, int k) { Node p = new Node(k); if (root == null) { this.root = p; return; } if (x.getKey() - k % 2 == 0) { if (x.left_child == null) { x.left_child = p; } else { insert(x.left_child, k); } } else { if (x.right_child == null) { x.right_child = p; } else { insert(x.right_child, k); } } }
Inserting an integer into a regular binary tree
While revising for my final, I came across binary trees (regular ones). After going through the lecture, I started to solve previous labs. My problem here is that only 6 is inserted into the tree. What is wrong with my method? What I'm trying to input: tree.insert(1); tree.insert(15); tree.insert(7); tree.insert(13); tree.insert(58); tree.insert(6); The Node class: public class Node { public int key; public Node left_child; public Node right_child; // The Constructor(s). public Node() { } public Node(int key) { this.key = key; left_child = null; right_child = null; } // The Get Methods. public int getKey() { return key; } public Node getLeft_child() { return left_child; } public Node getRight_child() { return right_child; } // The Set Methods. public void setKey(int key) { this.key = key; } public void setLeft_child(Node left_child) { this.left_child = left_child; } public void setRight_child(Node right_child) { this.right_child = right_child; } } The BinaryTree class: public class BinaryTree { private Node root; // The Constructor Method(s) public BinaryTree() { root = null; } public boolean is_empty() { return (root == null); } public void insert(int k) { insert(root, k); } private Node insert(Node x, int k) { Node p = new Node(k); if (x == null) { root = p; } else { if (x.left_child != null) { insert(x.left_child, k); } else { insert(x.right_child, k); } } return x; } // Printing Method(s). public void print_inorder() { print_inorder(root); } public void print_inorder(Node node) { if (node == null) { return; } print_inorder(node.left_child); System.out.print(node.key + " "); print_inorder(node.right_child); } public void print_preorder() { print_preorder(root); } public void print_preorder(Node node) { if (node == null) { return; } System.out.print(node.key + " "); print_preorder(node.left_child); print_preorder(node.right_child); } public void print_postorder() { print_postorder(root); } public void print_postorder(Node node) { if (node == null) { return; } print_postorder(node.left_child); print_postorder(node.right_child); System.out.print(node.key + " "); } }
[ "This will have a node to the left if a number is even and a node to the right if a node is odd.\nI had to change your if condition because the way it was it was never going to use the left node.\nprivate void insert(Node x, int k) {\n Node p = new Node(k);\n if (root == null) {\n this.root = p;\n return;\n }\n if (x.getKey() - k % 2 == 0) {\n if (x.left_child == null) {\n x.left_child = p;\n } else {\n insert(x.left_child, k);\n }\n } else {\n if (x.right_child == null) {\n x.right_child = p;\n } else {\n insert(x.right_child, k);\n }\n }\n }\n\n" ]
[ 0 ]
[]
[]
[ "binary", "binary_tree", "data_structures", "java" ]
stackoverflow_0074673011_binary_binary_tree_data_structures_java.txt
Q: Tetris rotation algorithm in c++ using 2D array I am making a `Tetris game and throughout this, I'm following this video. In this video, they are using an algorithm to rotate blocks but I'm not getting how is it working please can someone explain to me how it is working and what is the name of the algorithm used here? int figures[7][4] = { 1,3,5,7, // I 2,4,5,7, // Z 3,5,4,6, // S 3,5,4,7, // T 2,3,5,7, // L 3,5,7,6, // J 2,3,4,5, // O }; struct Point {int x,y;} a[4], b[4]; //////Rotate////// if (rotate) { Point p = a[1]; // center of rotation for (int i=0;i<4;i++) { int x = a[i].y-p.y; int y = a[i].x-p.x; a[i].x = p.x - x; a[i].y = p.y + y; } if (!check()) for (int i=0;i<4;i++) a[i]=b[i]; } full source code A: you can cross compare Your Tetris with this C++ Tetris of mine however looks like you are using different data structures to hold the tetrominos... The rotattion is based on 2D rodrigues rotation formula: which btw can be derived using trigonometry (we used to do it in math classes in high school back in the days)... now if you realize the rotation angles you use are 90 deg then all the cos and sin will change to +/-1 ... resulting in 2D 90 deg rotations: x' = y y' = -x or: x' = -y y' = x one is CW and the other CCW rotation which is which depends on your coordinate system properties. btw just a side note the first equation is also 2D cross product as: vec2(y,-x) = cross(vec2(x,y)). Now this rotates around (0,0) but we want to rotate around some point (x0,y0) so we simply translate (so (x0,y0) becomes (0,0), rotate and then translate back leading to: x' = (y-y0) + x0 y' = -(x-x0) + y0 or: x' = -(y-y0) + x0 y' = (x-x0) + y0
Tetris rotation algorithm in c++ using 2D array
I am making a `Tetris game and throughout this, I'm following this video. In this video, they are using an algorithm to rotate blocks but I'm not getting how is it working please can someone explain to me how it is working and what is the name of the algorithm used here? int figures[7][4] = { 1,3,5,7, // I 2,4,5,7, // Z 3,5,4,6, // S 3,5,4,7, // T 2,3,5,7, // L 3,5,7,6, // J 2,3,4,5, // O }; struct Point {int x,y;} a[4], b[4]; //////Rotate////// if (rotate) { Point p = a[1]; // center of rotation for (int i=0;i<4;i++) { int x = a[i].y-p.y; int y = a[i].x-p.x; a[i].x = p.x - x; a[i].y = p.y + y; } if (!check()) for (int i=0;i<4;i++) a[i]=b[i]; } full source code
[ "you can cross compare Your Tetris with this C++ Tetris of mine however looks like you are using different data structures to hold the tetrominos...\nThe rotattion is based on 2D rodrigues rotation formula:\n\nwhich btw can be derived using trigonometry (we used to do it in math classes in high school back in the days)...\nnow if you realize the rotation angles you use are 90 deg then all the cos and sin will change to +/-1 ...\nresulting in 2D 90 deg rotations:\nx' = y\ny' = -x \n\nor:\nx' = -y\ny' = x \n\none is CW and the other CCW rotation which is which depends on your coordinate system properties. btw just a side note the first equation is also 2D cross product as: vec2(y,-x) = cross(vec2(x,y)).\nNow this rotates around (0,0) but we want to rotate around some point (x0,y0) so we simply translate (so (x0,y0) becomes (0,0), rotate and then translate back leading to:\nx' = (y-y0) + x0\ny' = -(x-x0) + y0 \n\nor:\nx' = -(y-y0) + x0\ny' = (x-x0) + y0 \n\n" ]
[ 0 ]
[]
[]
[ "algorithm", "c++", "formula", "logic", "sfml" ]
stackoverflow_0074669783_algorithm_c++_formula_logic_sfml.txt
Q: How to check for strings after a character in Java I am trying to make it so anytime a user enters ."insert word here" the program will recognize this an invalid command and send the user a message saying something like "invalid command type .help for a list of commands". I already have my active commands working but Im not sure how to catch invalid commands here is my code so far. while (true) { String userInput = scan.nextLine(); if (userInput.equals(".help")) { //print list of commands } else if (userInput.equals(".ping") { //print pong } //check for any String that starts with . but does not equal the previous commands and return an error message } A: You could use a switch statement to handle unknown commands: while (true) { String userInput = scan.nextLine(); switch(userInput) { case ".help": // print list of commands break; case ".ping": // print pong break; default: // print error message for unknown command } } A: You can use the startsWith method to check if the user's input starts with a period, and then use the equals method to check if it is not equal to any of the valid commands. Here is an example: while (true) { String userInput = scan.nextLine(); if (userInput.equals(".help")) { // print list of commands } else if (userInput.equals(".ping")) { // print pong } else if (userInput.startsWith(".")) { System.out.println("Invalid command. Type .help for a list of commands."); } } A: while (true) { String userInput = scan.nextLine(); if (userInput.equals(".help")) { //print list of commands } else if (userInput.equals(".ping")) { //print pong } else if(userInput.startsWith(".")) { // applies if userInput starts with "." but is not .help or .ping } else { // applies if userInput does not start with a "." } }
How to check for strings after a character in Java
I am trying to make it so anytime a user enters ."insert word here" the program will recognize this an invalid command and send the user a message saying something like "invalid command type .help for a list of commands". I already have my active commands working but Im not sure how to catch invalid commands here is my code so far. while (true) { String userInput = scan.nextLine(); if (userInput.equals(".help")) { //print list of commands } else if (userInput.equals(".ping") { //print pong } //check for any String that starts with . but does not equal the previous commands and return an error message }
[ "You could use a switch statement to handle unknown commands:\nwhile (true) {\n String userInput = scan.nextLine();\n\n switch(userInput) {\n case \".help\":\n // print list of commands\n break;\n\n case \".ping\":\n // print pong\n break;\n\n default:\n // print error message for unknown command\n }\n}\n\n", "You can use the startsWith method to check if the user's input starts with a period, and then use the equals method to check if it is not equal to any of the valid commands. Here is an example:\nwhile (true) {\n String userInput = scan.nextLine();\n\n if (userInput.equals(\".help\")) {\n // print list of commands\n } else if (userInput.equals(\".ping\")) {\n // print pong\n } else if (userInput.startsWith(\".\")) {\n System.out.println(\"Invalid command. Type .help for a list of commands.\");\n }\n}\n\n\n", " while (true) {\n String userInput = scan.nextLine();\n if (userInput.equals(\".help\")) {\n //print list of commands\n } else if (userInput.equals(\".ping\")) {\n //print pong\n } else if(userInput.startsWith(\".\")) {\n // applies if userInput starts with \".\" but is not .help or .ping\n }\n else {\n // applies if userInput does not start with a \".\"\n }\n }\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "java" ]
stackoverflow_0074673476_java.txt
Q: CloudWatch Logs Insights isn't finding data that exists in logstream I am running fluent-bit as a sidecar on my EKS cluster for an application to tail application log files and write events to CloudWatch Logs. Through CloudWatch Logs Insights, I then set up some queries and dashboards to analyze those logs. This all works fine. I have some older logs over the past week from before I was able to get this setup working. In fluent-bit tail input, it has an option to read new files entirely from the top if it discovers a new file. Using this option, I was able to get the older logs loaded into CloudWatch Logs in the same log group as the up-to-the minute log events. If I go into the AWS console and into my log group, I can see all of the log streams listed. I can click into each one and see the events and search through them. All looks right. However, when I try to use Insights to query the older streams, no results appear. I have verified that I set a time period for my query that should include the events. When I run this query, I get no results: filter @logStream = 'myfile.log' | fields @timestamp, @message Do log events with older timestamps not automatically get pulled into Insights? Is there a long delay before that data becomes available? I don't see anything in the documentation about it. A: If the event appears in Log groups, but doesn't appear in Log Insights. Did you use the Amazon CloudWatch Logs API PutLogEvents and inject logs with older timestamp ? If yes. You can't view the log Insights events that are previous to the log group creation. Try inject events with timestamp newer than the log group creation time.
CloudWatch Logs Insights isn't finding data that exists in logstream
I am running fluent-bit as a sidecar on my EKS cluster for an application to tail application log files and write events to CloudWatch Logs. Through CloudWatch Logs Insights, I then set up some queries and dashboards to analyze those logs. This all works fine. I have some older logs over the past week from before I was able to get this setup working. In fluent-bit tail input, it has an option to read new files entirely from the top if it discovers a new file. Using this option, I was able to get the older logs loaded into CloudWatch Logs in the same log group as the up-to-the minute log events. If I go into the AWS console and into my log group, I can see all of the log streams listed. I can click into each one and see the events and search through them. All looks right. However, when I try to use Insights to query the older streams, no results appear. I have verified that I set a time period for my query that should include the events. When I run this query, I get no results: filter @logStream = 'myfile.log' | fields @timestamp, @message Do log events with older timestamps not automatically get pulled into Insights? Is there a long delay before that data becomes available? I don't see anything in the documentation about it.
[ "If the event appears in Log groups, but doesn't appear in Log Insights.\nDid you use the Amazon CloudWatch Logs API PutLogEvents and inject logs with older timestamp ?\nIf yes.\nYou can't view the log Insights events that are previous to the log group creation.\nTry inject events with timestamp newer than the log group creation time.\n" ]
[ 2 ]
[]
[]
[ "amazon_cloudwatchlogs", "amazon_web_services", "aws_cloudwatch_log_insights" ]
stackoverflow_0072823862_amazon_cloudwatchlogs_amazon_web_services_aws_cloudwatch_log_insights.txt
Q: Create files from one column of a csv. And write data from the other column to thos files I have a csv file (xyz.csv) contains hostnames and IPs. e.g.: HOSTNAME;IP;GW device1;ip1;gw1 device2;ip2;gw2 I want to create files named with data from the column1 and those files contain data from column2. So, file "device1" contain ip1 and gw1(the order dose matter) and so on. Expected output: cat device1 ip1 gw1 cat device2 ip2 gw2 A: You could use the great Miller to run # create output folder mkdir -p ./output # extract in it one file for each HOSTNAME mlr --csv --fs ";" --from input.csv put -q 'tee > "./output/".$HOSTNAME.".csv", $*' # keep only the IP column mlr -I --headerless-csv-output --csv --ifs ";" cut -x -f HOSTNAME then reshape -r "." -o i,v then cut -f v ./output/*.csv and get cat ./output/device1.csv ip1 gw1 cat ./output/device2.csv ip2 gw2
Create files from one column of a csv. And write data from the other column to thos files
I have a csv file (xyz.csv) contains hostnames and IPs. e.g.: HOSTNAME;IP;GW device1;ip1;gw1 device2;ip2;gw2 I want to create files named with data from the column1 and those files contain data from column2. So, file "device1" contain ip1 and gw1(the order dose matter) and so on. Expected output: cat device1 ip1 gw1 cat device2 ip2 gw2
[ "You could use the great Miller to run\n# create output folder\nmkdir -p ./output\n# extract in it one file for each HOSTNAME\nmlr --csv --fs \";\" --from input.csv put -q 'tee > \"./output/\".$HOSTNAME.\".csv\", $*'\n# keep only the IP column\nmlr -I --headerless-csv-output --csv --ifs \";\" cut -x -f HOSTNAME then reshape -r \".\" -o i,v then cut -f v ./output/*.csv\n\nand get\ncat ./output/device1.csv\n\nip1\ngw1\n\ncat ./output/device2.csv\n\nip2\ngw2\n\n" ]
[ 1 ]
[]
[]
[ "bash", "csv" ]
stackoverflow_0074671186_bash_csv.txt
Q: Apache Airflow not starting in local Getting below error on running the command airflow standalone Error scheduler | [2022-12-04 13:18:14 +0530] [47519] [ERROR] Can't connect to ('::', 8793) webserver | [2022-12-04 13:18:14 +0530] [47517] [ERROR] Can't connect to ('0.0.0.0', 8080) I have tried installing apache airflow multiple times, killing the processes in activity monitor, but still same error is coming. A: This error typically indicates that there is another process or service running on the same ports that the Apache Airflow webserver and scheduler are trying to use. This can cause a conflict and prevent Apache Airflow from starting properly. To resolve this error, you will need to identify and stop the process or service that is using the ports that Apache Airflow is trying to use. This can be done by using the netstat command to list the processes that are listening on the relevant ports, and then using the kill command to stop the process. For example, to stop the process that is using port 8080, you could run the following command: netstat -plnt | grep :8080 This will list the process that is using port 8080. You can then use the kill command to stop the process, using the process ID that is displayed in the output of the netstat command. Once you have stopped the conflicting process or service, you should be able to start Apache Airflow without encountering the error. You can then verify that it is running properly by accessing the Airflow web interface and checking the status of the webserver and scheduler.
Apache Airflow not starting in local
Getting below error on running the command airflow standalone Error scheduler | [2022-12-04 13:18:14 +0530] [47519] [ERROR] Can't connect to ('::', 8793) webserver | [2022-12-04 13:18:14 +0530] [47517] [ERROR] Can't connect to ('0.0.0.0', 8080) I have tried installing apache airflow multiple times, killing the processes in activity monitor, but still same error is coming.
[ "This error typically indicates that there is another process or service running on the same ports that the Apache Airflow webserver and scheduler are trying to use. This can cause a conflict and prevent Apache Airflow from starting properly.\nTo resolve this error, you will need to identify and stop the process or service that is using the ports that Apache Airflow is trying to use. This can be done by using the netstat command to list the processes that are listening on the relevant ports, and then using the kill command to stop the process.\nFor example, to stop the process that is using port 8080, you could run the following command:\nnetstat -plnt | grep :8080\n\nThis will list the process that is using port 8080. You can then use the kill command to stop the process, using the process ID that is displayed in the output of the netstat command.\nOnce you have stopped the conflicting process or service, you should be able to start Apache Airflow without encountering the error. You can then verify that it is running properly by accessing the Airflow web interface and checking the status of the webserver and scheduler.\n" ]
[ 0 ]
[]
[]
[ "airflow", "python" ]
stackoverflow_0074673719_airflow_python.txt
Q: Scrape all possible results from a search bar with search result limit Trying to scrape all the names from this website with Python: https://profile.tmb.state.tx.us/Search.aspx?9e94dec6-c7e7-4054-b5fb-20a1fcdbab53 The issue is that it limits each search to the top 50 results. Since the last name search allows wildcards, I tried using one search result to narrow down subsequent search results (using prefixes). However, this approach becomes difficult when more than 50 people have the same last name. Any other ideas on how to get every possible name from this website? Thank you!! A: Looking at the request and JS, it seems like this limit is server-side. I don't see any way to retrieve more than 50 results. Brute-force is the only way I think you could scrape this site, and it's not so trivial. You would need to generate queries more and more specific until the response has less than 50 results. For each length one combination, starting with a for example's sake, you could search a*. If there are less than 50 results, scrape them and move on to the next combination. Otherwise you'll need to scrape all length two combinations of characters beginning with a: aa*, ab*, ac*, etc. I'm sure there's some term for this, but I don't know it! A: I think it will be better with char decrement. Exemple AAB -> AAA. You’ll find all name that the trivial solution but it’ll take a lot of time. For the optimisation you can use headless browser.
Scrape all possible results from a search bar with search result limit
Trying to scrape all the names from this website with Python: https://profile.tmb.state.tx.us/Search.aspx?9e94dec6-c7e7-4054-b5fb-20a1fcdbab53 The issue is that it limits each search to the top 50 results. Since the last name search allows wildcards, I tried using one search result to narrow down subsequent search results (using prefixes). However, this approach becomes difficult when more than 50 people have the same last name. Any other ideas on how to get every possible name from this website? Thank you!!
[ "Looking at the request and JS, it seems like this limit is server-side. I don't see any way to retrieve more than 50 results.\nBrute-force is the only way I think you could scrape this site, and it's not so trivial. You would need to generate queries more and more specific until the response has less than 50 results.\nFor each length one combination, starting with a for example's sake, you could search a*. If there are less than 50 results, scrape them and move on to the next combination. Otherwise you'll need to scrape all length two combinations of characters beginning with a: aa*, ab*, ac*, etc.\nI'm sure there's some term for this, but I don't know it!\n", "I think it will be better with char decrement. Exemple AAB -> AAA. You’ll find all name that the trivial solution but it’ll take a lot of time. For the optimisation you can use headless browser.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "scrapy", "search", "selenium", "web_scraping" ]
stackoverflow_0074673245_python_scrapy_search_selenium_web_scraping.txt
Q: Create 3D array using Python I would like to create a 3D array in Python (2.7) to use like this: distance[i][j][k] And the sizes of the array should be the size of a variable I have. (nnn) I tried using: distance = [[[]*n]*n] but that didn't seem to work. I can only use the default libraries, and the method of multiplying (i.e.,[[0]*n]*n) wont work because they are linked to the same pointer and I need all of the values to be individual A: You should use a list comprehension: >>> import pprint >>> n = 3 >>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)] >>> pprint.pprint(distance) [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]] >>> distance[0][1] [0, 0, 0] >>> distance[0][1][2] 0 You could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference: >>> distance=[[[0]*n]*n]*n >>> pprint.pprint(distance) [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]] >>> distance[0][0][0] = 1 >>> pprint.pprint(distance) [[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]]] A: numpy.arrays are designed just for this case: numpy.zeros((i,j,k)) will give you an array of dimensions ijk, filled with zeroes. depending what you need it for, numpy may be the right library for your needs. A: The right way would be [[[0 for _ in range(n)] for _ in range(n)] for _ in range(n)] (What you're trying to do should be written like (for NxNxN) [[[0]*n]*n]*n but that is not correct, see @Adaman comment why). A: d3 = [[[0 for col in range(4)]for row in range(4)] for x in range(6)] d3[1][2][1] = 144 d3[4][3][0] = 3.12 for x in range(len(d3)): print d3[x] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 144, 0, 0], [0, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3.12, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] A: """ Create 3D array for given dimensions - (x, y, z) @author: Naimish Agarwal """ def three_d_array(value, *dim): """ Create 3D-array :param dim: a tuple of dimensions - (x, y, z) :param value: value with which 3D-array is to be filled :return: 3D-array """ return [[[value for _ in xrange(dim[2])] for _ in xrange(dim[1])] for _ in xrange(dim[0])] if __name__ == "__main__": array = three_d_array(False, *(2, 3, 1)) x = len(array) y = len(array[0]) z = len(array[0][0]) print x, y, z array[0][0][0] = True array[1][1][0] = True print array Prefer to use numpy.ndarray for multi-dimensional arrays. A: You can also use a nested for loop like shown below n = 3 arr = [] for x in range(n): arr.append([]) for y in range(n): arr[x].append([]) for z in range(n): arr[x][y].append(0) print(arr) A: There are many ways to address your problem. First one as accepted answer by @robert. Here is the generalised solution for it: def multi_dimensional_list(value, *args): #args dimensions as many you like. EG: [*args = 4,3,2 => x=4, y=3, z=2] #value can only be of immutable type. So, don't pass a list here. Acceptable value = 0, -1, 'X', etc. if len(args) > 1: return [ multi_dimensional_list(value, *args[1:]) for col in range(args[0])] elif len(args) == 1: #base case of recursion return [ value for col in range(args[0])] else: #edge case when no values of dimensions is specified. return None Eg: >>> multi_dimensional_list(-1, 3, 4) #2D list [[-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]] >>> multi_dimensional_list(-1, 4, 3, 2) #3D list [[[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]]] >>> multi_dimensional_list(-1, 2, 3, 2, 2 ) #4D list [[[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]], [[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]]] P.S If you are keen to do validation for correct values for args i.e. only natural numbers, then you can write a wrapper function before calling this function. Secondly, any multidimensional dimensional array can be written as single dimension array. This means you don't need a multidimensional array. Here are the function for indexes conversion: def convert_single_to_multi(value, max_dim): dim_count = len(max_dim) values = [0]*dim_count for i in range(dim_count-1, -1, -1): #reverse iteration values[i] = value%max_dim[i] value /= max_dim[i] return values def convert_multi_to_single(values, max_dim): dim_count = len(max_dim) value = 0 length_of_dimension = 1 for i in range(dim_count-1, -1, -1): #reverse iteration value += values[i]*length_of_dimension length_of_dimension *= max_dim[i] return value Since, these functions are inverse of each other, here is the output: >>> convert_single_to_multi(convert_multi_to_single([1,4,6,7],[23,45,32,14]),[23,45,32,14]) [1, 4, 6, 7] >>> convert_multi_to_single(convert_single_to_multi(21343,[23,45,32,14]),[23,45,32,14]) 21343 If you are concerned about performance issues then you can use some libraries like pandas, numpy, etc. A: n1=np.arange(90).reshape((3,3,-1)) print(n1) print(n1.shape) A: def n_arr(n, default=0, size=1): if n is 0: return default return [n_arr(n-1, default, size) for _ in range(size)] arr = n_arr(3, 42, 3) assert arr[2][2][2], 42 A: I just want notice that distance = [[[0 for k in range(n)] for j in range(n)] for i in range(n)] can be shortened to distance = [[[0] * n for j in range(n)] for i in range(n)]
Create 3D array using Python
I would like to create a 3D array in Python (2.7) to use like this: distance[i][j][k] And the sizes of the array should be the size of a variable I have. (nnn) I tried using: distance = [[[]*n]*n] but that didn't seem to work. I can only use the default libraries, and the method of multiplying (i.e.,[[0]*n]*n) wont work because they are linked to the same pointer and I need all of the values to be individual
[ "You should use a list comprehension:\n>>> import pprint\n>>> n = 3\n>>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]\n>>> pprint.pprint(distance)\n[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]\n>>> distance[0][1]\n[0, 0, 0]\n>>> distance[0][1][2]\n0\n\nYou could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference:\n>>> distance=[[[0]*n]*n]*n\n>>> pprint.pprint(distance)\n[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]\n>>> distance[0][0][0] = 1\n>>> pprint.pprint(distance)\n[[[1, 0, 0], [1, 0, 0], [1, 0, 0]],\n [[1, 0, 0], [1, 0, 0], [1, 0, 0]],\n [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]\n\n", "numpy.arrays are designed just for this case:\n numpy.zeros((i,j,k))\n\nwill give you an array of dimensions ijk, filled with zeroes.\ndepending what you need it for, numpy may be the right library for your needs.\n", "The right way would be\n[[[0 for _ in range(n)] for _ in range(n)] for _ in range(n)]\n\n(What you're trying to do should be written like (for NxNxN)\n[[[0]*n]*n]*n\n\nbut that is not correct, see @Adaman comment why).\n", "d3 = [[[0 for col in range(4)]for row in range(4)] for x in range(6)]\n\nd3[1][2][1] = 144\n\nd3[4][3][0] = 3.12\n\nfor x in range(len(d3)):\n print d3[x]\n\n\n\n[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n[[0, 0, 0, 0], [0, 0, 0, 0], [0, 144, 0, 0], [0, 0, 0, 0]]\n[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3.12, 0, 0, 0]]\n[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n\n", "\"\"\"\nCreate 3D array for given dimensions - (x, y, z)\n\n@author: Naimish Agarwal\n\"\"\"\n\n\ndef three_d_array(value, *dim):\n \"\"\"\n Create 3D-array\n :param dim: a tuple of dimensions - (x, y, z)\n :param value: value with which 3D-array is to be filled\n :return: 3D-array\n \"\"\"\n\n return [[[value for _ in xrange(dim[2])] for _ in xrange(dim[1])] for _ in xrange(dim[0])]\n\nif __name__ == \"__main__\":\n array = three_d_array(False, *(2, 3, 1))\n x = len(array)\n y = len(array[0])\n z = len(array[0][0])\n print x, y, z\n\n array[0][0][0] = True\n array[1][1][0] = True\n\n print array\n\nPrefer to use numpy.ndarray for multi-dimensional arrays.\n", "You can also use a nested for loop like shown below\nn = 3\narr = []\nfor x in range(n):\n arr.append([])\n for y in range(n):\n arr[x].append([])\n for z in range(n):\n arr[x][y].append(0)\nprint(arr)\n\n", "There are many ways to address your problem.\n\nFirst one as accepted answer by @robert. Here is the generalised\nsolution for it:\n\ndef multi_dimensional_list(value, *args):\n #args dimensions as many you like. EG: [*args = 4,3,2 => x=4, y=3, z=2]\n #value can only be of immutable type. So, don't pass a list here. Acceptable value = 0, -1, 'X', etc.\n if len(args) > 1:\n return [ multi_dimensional_list(value, *args[1:]) for col in range(args[0])]\n elif len(args) == 1: #base case of recursion\n return [ value for col in range(args[0])]\n else: #edge case when no values of dimensions is specified.\n return None\n\nEg:\n>>> multi_dimensional_list(-1, 3, 4) #2D list\n[[-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]]\n>>> multi_dimensional_list(-1, 4, 3, 2) #3D list\n[[[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]]]\n>>> multi_dimensional_list(-1, 2, 3, 2, 2 ) #4D list\n[[[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]], [[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]]]\n\nP.S If you are keen to do validation for correct values for args i.e. only natural numbers, then you can write a wrapper function before calling this function.\n\nSecondly, any multidimensional dimensional array can be written as single dimension array. This means you don't need a multidimensional array. Here are the function for indexes conversion:\n\ndef convert_single_to_multi(value, max_dim):\n dim_count = len(max_dim)\n values = [0]*dim_count\n for i in range(dim_count-1, -1, -1): #reverse iteration\n values[i] = value%max_dim[i]\n value /= max_dim[i]\n return values\n\n\ndef convert_multi_to_single(values, max_dim):\n dim_count = len(max_dim)\n value = 0\n length_of_dimension = 1\n for i in range(dim_count-1, -1, -1): #reverse iteration\n value += values[i]*length_of_dimension\n length_of_dimension *= max_dim[i]\n return value\n\nSince, these functions are inverse of each other, here is the output:\n>>> convert_single_to_multi(convert_multi_to_single([1,4,6,7],[23,45,32,14]),[23,45,32,14])\n[1, 4, 6, 7]\n>>> convert_multi_to_single(convert_single_to_multi(21343,[23,45,32,14]),[23,45,32,14])\n21343\n\n\nIf you are concerned about performance issues then you can use some libraries like pandas, numpy, etc.\n\n", "n1=np.arange(90).reshape((3,3,-1))\nprint(n1)\nprint(n1.shape)\n\n", "def n_arr(n, default=0, size=1):\n if n is 0:\n return default\n\n return [n_arr(n-1, default, size) for _ in range(size)]\n\narr = n_arr(3, 42, 3)\nassert arr[2][2][2], 42\n\n", "I just want notice that\ndistance = [[[0 for k in range(n)] for j in range(n)] for i in range(n)]\n\ncan be shortened to\ndistance = [[[0] * n for j in range(n)] for i in range(n)]\n\n" ]
[ 79, 46, 9, 5, 5, 4, 1, 1, 0, 0 ]
[ "If you insist on everything initializing as empty, you need an extra set of brackets on the inside ([[]] instead of [], since this is \"a list containing 1 empty list to be duplicated\" as opposed to \"a list containing nothing to duplicate\"):\ndistance=[[[[]]*n]*n]*n\n\n" ]
[ -3 ]
[ "arrays", "multidimensional_array", "python", "python_2.7" ]
stackoverflow_0010668341_arrays_multidimensional_array_python_python_2.7.txt
Q: Rps game not working as expected from the shown website that I posted ROCK, PAPER, SCISSORS 0 Wins,0 Losses, 0 Ties Enter your move: (r)ock (p)aper (s)cissors or (q)uit P Enter your move: (r)ock (p)aper (s)cissors or (q)uit S Enter your move: (r)ock (p)aper (s)cissors or (q)uit Q Enter your move: (r)ock (p)aper (s)cissors or (q)uit p Enter your move: (r)ock (p)aper (s)cissors or (q)uit r Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit p Enter your move: (r)ock (p)aper (s)cissors or (q)uit r Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit ss Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit Enter your move: (r)ock (p)aper (s)cissors or (q)uit Enter your move: (r)ock (p)aper (s)cissors or (q)uits s Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit Enter your move: (r)ock (p)aper (s)cissors or (q)uit This is the result of the execution of what I put to create rps game, as you see, it does not not move on to next step. import random, sys print('ROCK, PAPER, SCISSORS') #These variables keep track of the number of wins, losses, and ties. wins = 0 losses = 0 ties = 0 while True: # The main game loop. print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties)) while True: # The player input loop. print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit') playerMove = input() if playerMove == 'q': sys.exit() # Quit the program. if playerMove == 'r' or playerMove == 'p' or playerMove == 's': break # Break out of the player input loop. print('Type one of r, p, s, or q.') # Display what the player chose: if playerMove == 'r': print('ROCK versus...') elif playerMove == 'p': print('PAPER versus...') elif playerMove == 's': print('SCISSORS versus...') # Display what the computer chose: randomNumber = random.randiant(1,3) if randomNumber == 1: computerMove = 'r' print('ROCK') elif randomNumber == 2: computerMove = 'p' print('PAPER') elif randomNumber == 3: computerMove = 's' print('SCISSORS') # Display and record the win/loss/tie: if playerMove == computerMove: print('It is a tie!') ties = ties + 1 elif playerMove == 'r' and computerMove == 's': print('You win!') wins = wins + 1 elif playerMove == 'p' and computerMove == 'r': print('You win!') wins = wins + 1 elif playerMove == 's' and computerMove == 'p': print('You win!') wins = wins + 1 elif playerMove == 'r' and computerMove == 'p': print('You lose!') losses = losses + 1 elif playerMove == 'p' and computerMove == 's': print('You lose!') losses = losses + 1 elif playerMove == 's' and computerMove == 'r': print('You lose!') losses = losses + 1 please refer to this website, 'https://automatetheboringstuff.com/2e/chapter2/', it is a book name 'Automate the Boring Stuff with Python'. As shown at the bottom of this content title named, "A SHORT, PROGRAM: ROCK, PAPER, SISSORS shows how to program rps game, and I put exactly same source code into the file editor from above website, but game does not work as expected on the interactive shell. A: Your solution with a few changes to make it work. Reindented some parts : parts of the code were unreachable : the player could never enter his move all the game logic was outside of the loop Note the new position of if playerMove == "r" that is now at the same indentation level as if playerMove == "q". Replaced randiant() that doesn't exist with randint(). Indentation is very important in Python because there are no characters to delimit blocks as brackets in other languages. Control structures (if, elif, else) and loops depend on indentation. import random, sys print("ROCK, PAPER, SCISSORS") # These variables keep track of the number of wins, losses, and ties. wins = 0 losses = 0 ties = 0 while True: # The main game loop. print("%s Wins, %s Losses, %s Ties" % (wins, losses, ties)) while True: # The player input loop. print("Enter your move: (r)ock (p)aper (s)cissors or (q)uit") playerMove = input() if playerMove == "q": sys.exit() # Quit the program. if playerMove == "r" or playerMove == "p" or playerMove == "s": break # Break out of the player input loop. print("Type one of r, p, s, or q.") # Display what the player chose: if playerMove == "r": print("ROCK versus...") elif playerMove == "p": print("PAPER versus...") elif playerMove == "s": print("SCISSORS versus...") # Display what the computer chose: randomNumber = random.randint(1, 3) if randomNumber == 1: computerMove = "r" print("ROCK") elif randomNumber == 2: computerMove = "p" print("PAPER") elif randomNumber == 3: computerMove = "s" print("SCISSORS") # Display and record the win/loss/tie: if playerMove == computerMove: print("It is a tie!") ties = ties + 1 elif playerMove == "r" and computerMove == "s": print("You win!") wins = wins + 1 elif playerMove == "p" and computerMove == "r": print("You win!") wins = wins + 1 elif playerMove == "s" and computerMove == "p": print("You win!") wins = wins + 1 elif playerMove == "r" and computerMove == "p": print("You lose!") losses = losses + 1 elif playerMove == "p" and computerMove == "s": print("You lose!") losses = losses + 1 elif playerMove == "s" and computerMove == "r": print("You lose!") losses = losses + 1
Rps game not working as expected from the shown website that I posted
ROCK, PAPER, SCISSORS 0 Wins,0 Losses, 0 Ties Enter your move: (r)ock (p)aper (s)cissors or (q)uit P Enter your move: (r)ock (p)aper (s)cissors or (q)uit S Enter your move: (r)ock (p)aper (s)cissors or (q)uit Q Enter your move: (r)ock (p)aper (s)cissors or (q)uit p Enter your move: (r)ock (p)aper (s)cissors or (q)uit r Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit p Enter your move: (r)ock (p)aper (s)cissors or (q)uit r Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit ss Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit Enter your move: (r)ock (p)aper (s)cissors or (q)uit Enter your move: (r)ock (p)aper (s)cissors or (q)uits s Enter your move: (r)ock (p)aper (s)cissors or (q)uit s Enter your move: (r)ock (p)aper (s)cissors or (q)uit Enter your move: (r)ock (p)aper (s)cissors or (q)uit This is the result of the execution of what I put to create rps game, as you see, it does not not move on to next step. import random, sys print('ROCK, PAPER, SCISSORS') #These variables keep track of the number of wins, losses, and ties. wins = 0 losses = 0 ties = 0 while True: # The main game loop. print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties)) while True: # The player input loop. print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit') playerMove = input() if playerMove == 'q': sys.exit() # Quit the program. if playerMove == 'r' or playerMove == 'p' or playerMove == 's': break # Break out of the player input loop. print('Type one of r, p, s, or q.') # Display what the player chose: if playerMove == 'r': print('ROCK versus...') elif playerMove == 'p': print('PAPER versus...') elif playerMove == 's': print('SCISSORS versus...') # Display what the computer chose: randomNumber = random.randiant(1,3) if randomNumber == 1: computerMove = 'r' print('ROCK') elif randomNumber == 2: computerMove = 'p' print('PAPER') elif randomNumber == 3: computerMove = 's' print('SCISSORS') # Display and record the win/loss/tie: if playerMove == computerMove: print('It is a tie!') ties = ties + 1 elif playerMove == 'r' and computerMove == 's': print('You win!') wins = wins + 1 elif playerMove == 'p' and computerMove == 'r': print('You win!') wins = wins + 1 elif playerMove == 's' and computerMove == 'p': print('You win!') wins = wins + 1 elif playerMove == 'r' and computerMove == 'p': print('You lose!') losses = losses + 1 elif playerMove == 'p' and computerMove == 's': print('You lose!') losses = losses + 1 elif playerMove == 's' and computerMove == 'r': print('You lose!') losses = losses + 1 please refer to this website, 'https://automatetheboringstuff.com/2e/chapter2/', it is a book name 'Automate the Boring Stuff with Python'. As shown at the bottom of this content title named, "A SHORT, PROGRAM: ROCK, PAPER, SISSORS shows how to program rps game, and I put exactly same source code into the file editor from above website, but game does not work as expected on the interactive shell.
[ "Your solution with a few changes to make it work.\nReindented some parts :\n\nparts of the code were unreachable : the player could never enter his move\nall the game logic was outside of the loop\n\nNote the new position of if playerMove == \"r\" that is now at the same indentation level as if playerMove == \"q\".\nReplaced randiant() that doesn't exist with randint().\nIndentation is very important in Python because there are no characters to delimit blocks as brackets in other languages.\nControl structures (if, elif, else) and loops depend on indentation.\nimport random, sys\n\nprint(\"ROCK, PAPER, SCISSORS\")\n\n# These variables keep track of the number of wins, losses, and ties.\nwins = 0\nlosses = 0\nties = 0\n\nwhile True: # The main game loop.\n print(\"%s Wins, %s Losses, %s Ties\" % (wins, losses, ties))\n while True: # The player input loop.\n print(\"Enter your move: (r)ock (p)aper (s)cissors or (q)uit\")\n playerMove = input()\n if playerMove == \"q\":\n sys.exit() # Quit the program.\n if playerMove == \"r\" or playerMove == \"p\" or playerMove == \"s\":\n break # Break out of the player input loop.\n print(\"Type one of r, p, s, or q.\")\n\n # Display what the player chose:\n if playerMove == \"r\":\n print(\"ROCK versus...\")\n elif playerMove == \"p\":\n print(\"PAPER versus...\")\n elif playerMove == \"s\":\n print(\"SCISSORS versus...\")\n\n # Display what the computer chose:\n randomNumber = random.randint(1, 3)\n if randomNumber == 1:\n computerMove = \"r\"\n print(\"ROCK\")\n elif randomNumber == 2:\n computerMove = \"p\"\n print(\"PAPER\")\n elif randomNumber == 3:\n computerMove = \"s\"\n print(\"SCISSORS\")\n\n # Display and record the win/loss/tie:\n if playerMove == computerMove:\n print(\"It is a tie!\")\n ties = ties + 1\n elif playerMove == \"r\" and computerMove == \"s\":\n print(\"You win!\")\n wins = wins + 1\n elif playerMove == \"p\" and computerMove == \"r\":\n print(\"You win!\")\n wins = wins + 1\n elif playerMove == \"s\" and computerMove == \"p\":\n print(\"You win!\")\n wins = wins + 1\n elif playerMove == \"r\" and computerMove == \"p\":\n print(\"You lose!\")\n losses = losses + 1\n elif playerMove == \"p\" and computerMove == \"s\":\n print(\"You lose!\")\n losses = losses + 1\n elif playerMove == \"s\" and computerMove == \"r\":\n print(\"You lose!\")\n losses = losses + 1\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074656256_python.txt
Q: how to provide a value for an imported embedded struct literal? noob here :) i'm having trouble understanding when i do this in one file: scratch.go package main import "fmt" type foo struct { field1 string field2 string } type bar struct { foo field3 string field4 string } func main() { fooBar := bar{ foo{ "apples", "banana", }, "spam", "eggs", } fmt.Printf("%#v\n", fooBar) } it works but when i have 3 files like this rootproject ├── magazine │   ├── address.go │   └── employee.go └── main.go magazine/address.go package magazine type Address struct { Street string City string State string PostalCode string } magazine/employee.go package magazine type Employee struct { Name string Salary float64 Address } and main.go package main import ( "fmt" "magazine" ) func main() { employee := magazine.Employee{ Name: "pogi", Salary: 69420, magazine.Address{ Street: "23 pukinginamo st.", City: "bactol city", State: "betlog", PostalCode: "23432", }, } fmt.Printf("%#v\n", employee) } it's error :( mixture of field:value and value elements in struct literal i don't get it, what am i doing wrong? i thought if the struct was nested it is said to be embedded in the outer struct and i can access the the fields of the inner struct from the outer one. which is the case for my first example(the singular file), but when i do it within packages. it's different? A: i thought if the struct was nested it is said to be embedded in the outer struct and i can access the the fields of the inner struct from the outer one. Yes, you can access an embedded field's members directly, however that does not apply when constructing the struct with a composite literal. If you look through the rules for struct literals you'll find this one: If any element has a key, every element must have a key. This rule applies regardless of whether a field is embedded or not. To fix the error you can either remove the other keys: func main() { employee := magazine.Employee{ "pogi", 69420, magazine.Address{ Street: "23 pukinginamo st.", City: "bactol city", State: "betlog", PostalCode: "23432", }, } fmt.Printf("%#v\n", employee) } Or you can specify all the keys: func main() { employee := magazine.Employee{ Name: "pogi", Salary: 69420, Address: magazine.Address{ Street: "23 pukinginamo st.", City: "bactol city", State: "betlog", PostalCode: "23432", }, } fmt.Printf("%#v\n", employee) } Note that for an embedded field you can use the type's unqualified name to refer to the embedded field. https://go.dev/ref/spec#Struct_types: A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.
how to provide a value for an imported embedded struct literal?
noob here :) i'm having trouble understanding when i do this in one file: scratch.go package main import "fmt" type foo struct { field1 string field2 string } type bar struct { foo field3 string field4 string } func main() { fooBar := bar{ foo{ "apples", "banana", }, "spam", "eggs", } fmt.Printf("%#v\n", fooBar) } it works but when i have 3 files like this rootproject ├── magazine │   ├── address.go │   └── employee.go └── main.go magazine/address.go package magazine type Address struct { Street string City string State string PostalCode string } magazine/employee.go package magazine type Employee struct { Name string Salary float64 Address } and main.go package main import ( "fmt" "magazine" ) func main() { employee := magazine.Employee{ Name: "pogi", Salary: 69420, magazine.Address{ Street: "23 pukinginamo st.", City: "bactol city", State: "betlog", PostalCode: "23432", }, } fmt.Printf("%#v\n", employee) } it's error :( mixture of field:value and value elements in struct literal i don't get it, what am i doing wrong? i thought if the struct was nested it is said to be embedded in the outer struct and i can access the the fields of the inner struct from the outer one. which is the case for my first example(the singular file), but when i do it within packages. it's different?
[ "\ni thought if the struct was nested it is said to be embedded in the outer struct and i can access the the fields of the inner struct from the outer one.\n\nYes, you can access an embedded field's members directly, however that does not apply when constructing the struct with a composite literal. If you look through the rules for struct literals you'll find this one:\n\nIf any element has a key, every element must have a key.\n\nThis rule applies regardless of whether a field is embedded or not.\n\nTo fix the error you can either remove the other keys:\nfunc main() {\n employee := magazine.Employee{\n \"pogi\",\n 69420,\n magazine.Address{\n Street: \"23 pukinginamo st.\",\n City: \"bactol city\",\n State: \"betlog\",\n PostalCode: \"23432\",\n },\n }\n fmt.Printf(\"%#v\\n\", employee)\n}\n\nOr you can specify all the keys:\nfunc main() {\n employee := magazine.Employee{\n Name: \"pogi\",\n Salary: 69420,\n Address: magazine.Address{\n Street: \"23 pukinginamo st.\",\n City: \"bactol city\",\n State: \"betlog\",\n PostalCode: \"23432\",\n },\n }\n fmt.Printf(\"%#v\\n\", employee)\n}\n\nNote that for an embedded field you can use the type's unqualified name to refer to the embedded field.\nhttps://go.dev/ref/spec#Struct_types:\n\nA field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.\n\n" ]
[ 1 ]
[]
[]
[ "go" ]
stackoverflow_0074673693_go.txt
Q: Can't determine type for tag '?attr/colorSurface' I'm having a problem with running my android app: Can't determine type for tag '<macro name="m3_comp_bottom_app_bar_container_color">?attr/colorSurface</macro>' A: That is caused by 1.7.0: implementation 'com.google.android.material:material:1.7.0' You better stick to 1.6.0 till they fix this implementation 'com.google.android.material:material:1.6.0' A: In your build.gradle file where "dependencies" section is paste this: implementation 'androidx.appcompat:appcompat:1.4.1' implementation 'com.google.android.material:material:1.6.0' in this section. And remove old strings with same text and other number versions. (in my case: implementation 'androidx.appcompat:appcompat:1.5.1' implementation 'com.google.android.material:material:1.7.0' ). Have worked for me. source: https://github.com/facebook/react-native/issues/33926 A: Upgraded android gradle plugin to 7.2.2 and the problem is solved. Try updating Android Studio too A: I resolved it by replacing implementation 'androidx.recyclerview:recyclerview:1.2.1' instead of implementation 'com.google.android.material:material:1.7.0' in build.gradle(:app) A: In build.gradle(:app), Updating, compileSdk and targetSdk to 33 helped me(from 32). A: update your build.gradle file as below: classpath 'com.android.tools.build:gradle:7.2.1' It will fix the issues, remember v7.3.x wont fix the issue, so stick to 7.2.1 as of now. A: For Flutter User with this issue this is how you solve it:: Goto : build.gradle change "classpath 'com.andriod.tools.build:gradle:5.6.0'" to "classpath 'com.andriod.tools.build:gradle:<latest version>'" in my case :: classpath 'com.android.tools.build:gradle:7.2.1' then goto :: android/gradle/wrapper/gradle-wrapper.properties then change distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.3-all.zip to distributionUrl=https\://services.gradle.org/distributions/gradle-<latest>-all.zip in my case distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip
Can't determine type for tag '?attr/colorSurface'
I'm having a problem with running my android app: Can't determine type for tag '<macro name="m3_comp_bottom_app_bar_container_color">?attr/colorSurface</macro>'
[ "That is caused by 1.7.0:\nimplementation 'com.google.android.material:material:1.7.0'\n\nYou better stick to 1.6.0 till they fix this\nimplementation 'com.google.android.material:material:1.6.0'\n\n", "In your build.gradle file where \"dependencies\" section is paste this:\nimplementation 'androidx.appcompat:appcompat:1.4.1'\nimplementation 'com.google.android.material:material:1.6.0'\n\nin this section. And remove old strings with same text and other number versions. (in my case:\nimplementation 'androidx.appcompat:appcompat:1.5.1' \nimplementation 'com.google.android.material:material:1.7.0'\n\n). Have worked for me.\nsource: https://github.com/facebook/react-native/issues/33926\n", "Upgraded android gradle plugin to 7.2.2 and the problem is solved. Try updating Android Studio too\n", "I resolved it by replacing implementation 'androidx.recyclerview:recyclerview:1.2.1' instead of implementation 'com.google.android.material:material:1.7.0' in build.gradle(:app)\n", "In build.gradle(:app),\nUpdating, compileSdk and targetSdk to 33 helped me(from 32).\n", "update your build.gradle file as below:\nclasspath 'com.android.tools.build:gradle:7.2.1'\nIt will fix the issues, remember v7.3.x wont fix the issue, so stick to 7.2.1 as of now.\n", "For Flutter User with this issue this is how you solve it::\nGoto : build.gradle\nchange \"classpath 'com.andriod.tools.build:gradle:5.6.0'\"\nto\n\"classpath 'com.andriod.tools.build:gradle:<latest version>'\"\nin my case :: classpath 'com.android.tools.build:gradle:7.2.1' \nthen goto :: android/gradle/wrapper/gradle-wrapper.properties\nthen change\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-5.4.3-all.zip\nto\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-<latest>-all.zip\nin my case distributionUrl=https\\://services.gradle.org/distributions/gradle-7.3.3-all.zip \n" ]
[ 18, 11, 4, 0, 0, 0, 0 ]
[]
[]
[ "android", "android_studio" ]
stackoverflow_0074191324_android_android_studio.txt
Q: Loop inside React JSX I'm trying to do something like the following in React JSX (where ObjectRow is a separate component): <tbody> for (var i=0; i < numrows; i++) { <ObjectRow/> } </tbody> I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times). A: Think of it like you're just calling JavaScript functions. You can't use a for loop where the arguments to a function call would go: return tbody( for (let i = 0; i < numrows; i++) { ObjectRow() } ) See how the function tbody is being passed a for loop as an argument – leading to a syntax error. But you can make an array, and then pass that in as an argument: const rows = []; for (let i = 0; i < numrows; i++) { rows.push(ObjectRow()); } return tbody(rows); You can basically use the same structure when working with JSX: const rows = []; for (let i = 0; i < numrows; i++) { // note: we are adding a key prop here to allow react to uniquely identify each // element in this array. see: https://reactjs.org/docs/lists-and-keys.html rows.push(<ObjectRow key={i} />); } return <tbody>{rows}</tbody>; Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works. A: I am not sure if this will work for your situation, but often map is a good answer. If this was your code with the for loop: <tbody> for (var i=0; i < objects.length; i++) { <ObjectRow obj={objects[i]} key={i}> } </tbody> You could write it like this with map: <tbody> {objects.map(function(object, i){ return <ObjectRow obj={object} key={i} />; })} </tbody> ES6 syntax: <tbody> {objects.map((object, i) => <ObjectRow obj={object} key={i} />)} </tbody> A: If you don't already have an array to map() like @FakeRainBrigand's answer, and want to inline this so the source layout corresponds to the output closer than @SophieAlpert's answer: With ES2015 (ES6) syntax (spread and arrow functions) http://plnkr.co/edit/mfqFWODVy8dKQQOkIEGV?p=preview <tbody> {[...Array(10)].map((x, i) => <ObjectRow key={i} /> )} </tbody> Re: transpiling with Babel, its caveats page says that Array.from is required for spread, but at present (v5.8.23) that does not seem to be the case when spreading an actual Array. I have a documentation issue open to clarify that. But use at your own risk or polyfill. Vanilla ES5 Array.apply <tbody> {Array.apply(0, Array(10)).map(function (x, i) { return <ObjectRow key={i} />; })} </tbody> Inline IIFE http://plnkr.co/edit/4kQjdTzd4w69g8Suu2hT?p=preview <tbody> {(function (rows, i, len) { while (++i <= len) { rows.push(<ObjectRow key={i} />) } return rows; })([], 0, 10)} </tbody> Combination of techniques from other answers Keep the source layout corresponding to the output, but make the inlined part more compact: render: function () { var rows = [], i = 0, len = 10; while (++i <= len) rows.push(i); return ( <tbody> {rows.map(function (i) { return <ObjectRow key={i} index={i} />; })} </tbody> ); } With ES2015 syntax & Array methods With Array.prototype.fill you could do this as an alternative to using spread as illustrated above: <tbody> {Array(10).fill(1).map((el, i) => <ObjectRow key={i} /> )} </tbody> (I think you could actually omit any argument to fill(), but I'm not 100% on that.) Thanks to @FakeRainBrigand for correcting my mistake in an earlier version of the fill() solution (see revisions). key In all cases the key attr alleviates a warning with the development build, but isn't accessible in the child. You can pass an extra attr if you want the index available in the child. See Lists and Keys for discussion. A: Simply using map Array method with ES6 syntax: <tbody> {items.map(item => <ObjectRow key={item.id} name={item.name} />)} </tbody> Don't forget the key property. A: Using the Array map function is a very common way to loop through an Array of elements and create components according to them in React. This is a great way to do a loop which is a pretty efficient and is a tidy way to do your loops in JSX. It's not the only way to do it, but the preferred way. Also, don't forget having a unique Key for each iteration as required. The map function creates a unique index from 0, but it's not recommended using the produced index, but if your value is unique or if there is a unique key, you can use them: <tbody> {numrows.map(x=> <ObjectRow key={x.id} />)} </tbody> Also, a few lines from MDN if you not familiar with the map function on Array: map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value). callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. If a thisArg parameter is provided to the map, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value. This value ultimately observable by the callback is determined according to the usual rules for determining the this seen by a function. map does not mutate the array on which it is called (although callback, if invoked, may do so). A: If you're already using lodash, the _.times function is handy. import React, { Component } from "react"; import Select from "./Select"; import _ from "lodash"; export default class App extends Component { render() { return ( <div className="container"> <ol> {_.times(3, (i) => ( <li key={i}>repeated 3 times</li> ))} </ol> </div> ); } } A: There are multiple ways to go about doing this. JSX eventually gets compiled to JavaScript, so as long as you're writing valid JavaScript, you'll be good. My answer aims to consolidate all the wonderful ways already presented here: If you do not have an array of object, simply the number of rows: Within the return block, creating an Array and using Array.prototype.map: render() { return ( <tbody> {Array(numrows).fill(null).map((value, index) => ( <ObjectRow key={index}> ))} </tbody> ); } Outside the return block, simply use a normal JavaScript for loop: render() { let rows = []; for (let i = 0; i < numrows; i++) { rows.push(<ObjectRow key={i}/>); } return ( <tbody>{rows}</tbody> ); } Immediately invoked function expression: render() { return ( <tbody> {(() => { let rows = []; for (let i = 0; i < numrows; i++) { rows.push(<ObjectRow key={i}/>); } return rows; })()} </tbody> ); } If you have an array of objects Within the return block, .map() each object to a <ObjectRow> component: render() { return ( <tbody> {objectRows.map((row, index) => ( <ObjectRow key={index} data={row} /> ))} </tbody> ); } Outside the return block, simply use a normal JavaScript for loop: render() { let rows = []; for (let i = 0; i < objectRows.length; i++) { rows.push(<ObjectRow key={i} data={objectRows[i]} />); } return ( <tbody>{rows}</tbody> ); } Immediately invoked function expression: render() { return ( <tbody> {(() => { const rows = []; for (let i = 0; i < objectRows.length; i++) { rows.push(<ObjectRow key={i} data={objectRows[i]} />); } return rows; })()} </tbody> ); } A: You can also extract outside the return block: render: function() { var rows = []; for (var i = 0; i < numrows; i++) { rows.push(<ObjectRow key={i}/>); } return (<tbody>{rows}</tbody>); } A: You might want to checkout React Templates, which does let you use JSX-style templates in React, with a few directives (such as rt-repeat). Your example, if you used react-templates, would be: <tbody> <ObjectRow rt-repeat="obj in objects"/> </tbody> A: If you opt to convert this inside return() of the render method, the easiest option would be using the map( ) method. Map your array into JSX syntax using the map() function, as shown below (ES6 syntax is used). Inside the parent component: <tbody> { objectArray.map(object => <ObjectRow key={object.id} object={object.value} />) } </tbody> Please note the key attribute is added to your child component. If you didn't provide a key attribute, you can see the following warning on your console. Warning: Each child in an array or iterator should have a unique "key" prop. Note: One common mistake people do is using index as the key when iterating. Using index of the element as a key is an antipattern, and you can read more about it here. In short, if it's not a static list, never use index as the key. Now at the ObjectRow component, you can access the object from its properties. Inside the ObjectRow component const { object } = this.props Or const object = this.props.object This should fetch you the object you passed from the parent component to the variable object in the ObjectRow component. Now you can spit out the values in that object according to your purpose. References: map() method in JavaScript ECMAScript 6 or ES6 A: If numrows is an array, it's very simple: <tbody> {numrows.map(item => <ObjectRow />)} </tbody> The array data type in React is much better. An array can back a new array, and support filter, reduce, etc. A: There are several answers pointing to using the map statement. Here is a complete example using an iterator within the FeatureList component to list Feature components based on a JSON data structure called features. const FeatureList = ({ features, onClickFeature, onClickLikes }) => ( <div className="feature-list"> {features.map(feature => <Feature key={feature.id} {...feature} onClickFeature={() => onClickFeature(feature.id)} onClickLikes={() => onClickLikes(feature.id)} /> )} </div> ); You can view the complete FeatureList code on GitHub. The features fixture is listed here. A: Let us say we have an array of items in your state: [{name: "item1", id: 1}, {name: "item2", id: 2}, {name: "item3", id: 3}] <tbody> {this.state.items.map((item) => { <ObjectRow key={item.id} name={item.name} /> })} </tbody> A: To loop for a number of times and return, you can achieve it with the help of from and map: <tbody> { Array.from(Array(i)).map(() => <ObjectRow />) } </tbody> where i = number of times If you want to assign unique key IDs into the rendered components, you can use React.Children.toArray as proposed in the React documentation React.Children.toArray Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down. Note: React.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it. <tbody> { React.Children.toArray( Array.from(Array(i)).map(() => <ObjectRow />) ) } </tbody> A: An ECMAScript 2015 / Babel possibility is using a generator function to create an array of JSX: function* jsxLoop(times, callback) { for(var i = 0; i < times; ++i) yield callback(i); } ... <tbody> {[...jsxLoop(numrows, i => <ObjectRow key={i}/> )]} </tbody> A: This can be done in multple ways. As suggested above, before return store all elements in the array Loop inside return Method 1 let container = []; let arr = [1, 2, 3] //can be anything array, object arr.forEach((val, index) => { container.push( <div key={index}> val </div>) /** * 1. All loop generated elements require a key * 2. only one parent element can be placed in Array * e.g. container.push( * <div key={index}> val </div> <div> this will throw error </div> ) **/ }); return ( <div> <div>any things goes here</div> <div>{container}</div> </div> ) Method 2 return ( <div> <div>any things goes here</div> <div> { (() => { let container = []; let arr = [1, 2, 3] //can be anything array, object arr.forEach((val, index) => { container.push( <div key={index}> val </div>) }); return container; })() } </div> </div> ) A: ES2015 Array.from with the map function + key If you have nothing to .map() you can use Array.from() with the map function to repeat elements: <tbody> {Array.from({ length: 5 }, (value, key) => <ObjectRow key={key} />)} </tbody> A: ...Or you can also prepare an array of objects and map it to a function to have the desired output. I prefer this, because it helps me to maintain the good practice of coding with no logic inside the return of render. render() { const mapItem = []; for(let i =0;i<item.length;i++) mapItem.push(i); const singleItem => (item, index) { // item the single item in the array // the index of the item in the array // can implement any logic here return ( <ObjectRow/> ) } return( <tbody>{mapItem.map(singleItem)}</tbody> ) } A: I use this: gridItems = this.state.applications.map(app => <ApplicationItem key={app.Id} app={app } /> ); PS: never forget the key or you will have a lot of warnings! A: You can of course solve with a .map as suggested by the other answer. If you already use Babel, you could think about using jsx-control-statements. They require a little of setting, but I think it's worth in terms of readability (especially for non-React developer). If you use a linter, there's also eslint-plugin-jsx-control-statements. A: Here's a simple solution to it. var Object_rows = []; for (var i = 0; i < numrows; i++) { Object_rows.push(<ObjectRow />); } <tbody>{Object_rows}</tbody>; No mapping and complex code is required. You just need to push the rows to the array and return the values to render it. A: Simply use .map() to loop through your collection and return <ObjectRow> items with props from each iteration. Assuming objects is an array somewhere... <tbody> { objects.map((obj, index) => <ObjectRow obj={ obj } key={ index }/> ) } </tbody> A: Your JSX code will compile into pure JavaScript code, any tags will be replaced by ReactElement objects. In JavaScript, you cannot call a function multiple times to collect their returned variables. It is illegal, the only way is to use an array to store the function returned variables. Or you can use Array.prototype.map which is available since JavaScript ES5 to handle this situation. Maybe we can write other compiler to recreate a new JSX syntax to implement a repeat function just like Angular's ng-repeat. A: I tend to favor an approach where programming logic happens outside the return value of render. This helps keep what is actually rendered easy to grok. So I'd probably do something like: import _ from 'lodash'; ... const TableBody = ({ objects }) => { const objectRows = objects.map(obj => <ObjectRow object={obj} />); return <tbody>{objectRows}</tbody>; } Admittedly this is such a small amount of code that inlining it might work fine. A: You may use .map() in a React for loop. <tbody> { newArray.map(() => <ObjectRow />) } </tbody> A: Here is a sample from the React documentation, JavaScript Expressions as Children: function Item(props) { return <li>{props.message}</li>; } function TodoList() { const todos = ['finish doc', 'submit pr', 'nag dan to review']; return ( <ul> {todos.map((message) => <Item key={message} message={message} />)} </ul> ); } As for your case, I suggest writing like this: function render() { return ( <tbody> {numrows.map((roe, index) => <ObjectRow key={index} />)} </tbody> ); } Please notice the key is very important, because React use the key to differ data in array. A: Since you are writing JavaScript syntax inside JSX code, you need to wrap your JavaScript code in curly braces. row = () => { var rows = []; for (let i = 0; i<numrows; i++) { rows.push(<ObjectRow/>); } return rows; } <tbody> {this.row()} </tbody> A: I use it like <tbody> { numrows ? ( numrows.map(obj => { return <ObjectRow /> }) ) : null } </tbody> A: If you really want a for loop equivalent (you have a single number, not an array), just use range from Lodash. Don't reinvent the wheel and don't obfuscate your code. Just use the standard utility library. import range from 'lodash/range' range(4); // => [0, 1, 2, 3] range(1, 5); // => [1, 2, 3, 4] A: You can also use a self-invoking function: return <tbody> {(() => { let row = [] for (var i = 0; i < numrows; i++) { row.push(<ObjectRow key={i} />) } return row })()} </tbody> A: When I want to add a certain number of components, I use a helper function. Define a function that returns JSX: const myExample = () => { let myArray = [] for(let i = 0; i<5;i++) { myArray.push(<MyComponent/>) } return myArray } //... in JSX <tbody> {myExample()} </tbody> A: Even this piece of code does the same job. <tbody> {array.map(i => <ObjectRow key={i.id} name={i.name} /> )} </tbody> A: With time, the language is becoming more mature, and we often stumble upon common problems like this. The problem is to loop a Component 'n' times. {[...new Array(n)].map((item, index) => <MyComponent key={index} />)} where, n -is the number of times you want to loop. item will be undefined and index will be as usual. Also, ESLint discourages using an array index as key. But you have the advantage of not requiring to initialize the array before and most importantly avoiding the for loop... To avoid the inconvenience of item as undefined you can use an _, so that it will be ignored when linting and won't throw any linting error, such as {[...new Array(n)].map((_, index) => <MyComponent key={index} />)} A: Array.from is the best way. If you want to create an array of JSX with some length. function App() { return ( <tbody> {Array.from({ length: 10 }, (_, key) => ( <ObjectRow {...{ key }} /> ))} </tbody> ); } The above example is for when you do not have an array, so if you have an array you should map it in JSX like this: function App() { return ( <tbody> {list.map((item, key) => ( <ObjectRow {...{ key }} /> ))} </tbody> ); } A: You can do something like: let foo = [1,undefined,3] { foo.map(e => !!e ? <Object /> : null )} A: A loop inside JSX is very simple. Try this: return this.state.data.map((item, index) => ( <ComponentName key={index} data={item} /> )); A: If you need JavaScript code inside your JSX, you add { } and then write your JavaScript code inside these brackets. It is just that simple. And the same way you can loop inside JSX/react. Say: <tbody> {`your piece of code in JavaScript` } </tbody> Example: <tbody> { items.map((item, index) => { console.log(item)}) ; // Print item return <span>{index}</span>; } // Looping using map() </tbody> A: Below are possible solutions that you can do in React in terms of iterating array of objects or plain array const rows = []; const numrows = [{"id" : 01, "name" : "abc"}]; numrows.map((data, i) => { rows.push(<ObjectRow key={data.id} name={data.name}/>); }); <tbody> { rows } </tbody> Or const rows = []; const numrows = [1,2,3,4,5]; for(let i=1, i <= numrows.length; i++){ rows.push(<ObjectRow key={numrows[i]} />); }; <tbody> { rows } </tbody> An even more better approach I became familiar with recent days for iterating an array of objects is .map directly in the render with return or without return: .map with return const numrows = [{"id" : 01, "name" : "abc"}]; <tbody> {numrows.map(data=> { return <ObjectRow key={data.id} name={data.name}/> })} </tbody> .map without return const numrows = [{"id" : 01, "name" : "abc"}]; <tbody> {numrows.map(data=> ( <ObjectRow key={data.id} name={data.name}/> ))} </tbody> A: React elements are simple JavaScript, so you can follow the rule of JavaScript. You can use a for loop in JavaScript like this:- <tbody> for (var i=0; i < numrows; i++) { <ObjectRow/> } </tbody> But the valid and best way is to use the .map function. Shown below:- <tbody> {listObject.map(function(listObject, i){ return <ObjectRow key={i} />; })} </tbody> Here, one thing is necessary: to define the key. Otherwise it will throw a warning like this:- Warning.js:36 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of ComponentName. See "link" for more information. A: For printing an array value if you don't have the key value par, then use the below code - <div> {my_arr.map(item => <div>{item} </div> )} </div> A: You can try the new for of loop: const apple = { color: 'red', size: 'medium', weight: 12, sugar: 10 } for (const prop of apple.entries()){ console.log(prop); } Here's a few examples: A: Unless you declare a function and enclose it with parameters, it is not possible. In a JSXExpression you can only write expressions and cannot write statements like a for(), declare variables or classes, or a if() statement. That's why function CallExpressions are so in the mood today. My advice: get used to them. This is what I would do: const names = ['foo', 'bar', 'seba'] const people = <ul>{names.map(name => <li>{name}</li>)}</ul> Filtering: const names = ['foo', undefined, 'seba'] const people = <ul>{names.filter(person => !!person).map(name => <li>{name}</li>)}</ul> if(): var names = getNames() const people = {names && names.length && <ul>{names.map(name => <li>{name}</li>)}</ul> } if - else: var names = getNames() const people = {names && names.length ? <ul>{names.map(name => <li>{name}</li>)}</ul> : <p>no results</p> } A: Use the map function. <tbody> {objects.map((object, i) => <ObjectRow obj={object} key={i} />)} </tbody> A: Just do something like this: <tbody> {new Array(numRows).fill("", 0, numRows).map((p, i) => <YourRaw key={i} />)} </tbody> A: Well, here you go. { [1, 2, 3, 4, 5, 6].map((value, index) => { return <div key={index}>{value}</div> }) } All you have to do is just map your array and return whatever you want to render. And please don't forget to use key in the returned element. A: You can do the same directly in the JSX, using map instead of a for-of loop: render: function() { const items = ['one', 'two', 'three']; return ( <ul> {items.map((value, index) => { return <li key={index}>{value}</li> })} </ul> ) } A: try this <tbody> {new Array(numrows).map((row,index)=><ObjectRow key={***someThingUniqe***}/>)} //don't use index as key </tbody> if you wanna know why you shouldn't use indices as keys in react check this A: You can use an IIFE if you really want to literally use a for loop inside JSX. <tbody> { (function () { const view = []; for (let i = 0; i < numrows; i++) { view.push(<ObjectRow key={i}/>); } return view; }()) } </tbody> A: @jacefarm If I understand right you can use this code: <tbody> { new Array(numrows).fill(<ObjectRow/>) } </tbody> Either you can use this code: <tbody> { new Array(numrows).fill('').map((item, ind) => <ObjectRow key={ind}/>) } </tbody> And this: <tbody> new Array(numrows).fill(ObjectRow).map((Item, ind) => <Item key={ind}/>) </tbody> A: Using map in React are best practices for iterating over an array. To prevent some errors with ES6, the syntax map is used like this in React: <tbody> {items.map((item, index) => <ObjectRow key={index} name={item.name} />)} </tbody> Here you call a Component, <ObjectRow/>, so you don't need to put parenthesis after the arrow. But you can be make this too: {items.map((item, index) => ( <ObjectRow key={index} name={item.name} /> ))} Or: {items.map((item, index) => { // Here you can log 'item' return ( <ObjectRow key={index} name={item.name} /> ) })} I say that because if you put a bracket "{}" after the arrow React will not throw an error and will display a whitelist. A: The problem is you don't return any JSX element. There are another solutions for such cases, but I will provide the simplest one: "use the map function"! <tbody> { numrows.map(item => <ObjectRow key={item.uniqueField} />) } </tbody> It's so simple and beautiful, isn't it? A: You can create a new component like below: Pass key and data to your ObjectRow component like this: export const ObjectRow = ({key,data}) => { return ( <div> ... </div> ); } Create a new component ObjectRowList to act like a container for your data: export const ObjectRowList = (objectRows) => { return ( <tbody> {objectRows.map((row, index) => ( <ObjectRow key={index} data={row} /> ))} </tbody> ); } A: I am not sure if this will work for your situation, but often [map][1] is a good answer. If this was your code with the for loop: <tbody> for (var i=0; i < objects.length; i++) { <ObjectRow obj={objects[i]} key={i}> } </tbody> You could write it like this with the map function: <tbody> {objects.map(function(object, i){ return <ObjectRow obj={object} key={i} />; })} </tbody> objects.map is the best way to do a loop, and objects.filter is the best way to filter the required data. The filtered data will form a new array, and objects.some is the best way to check whether the array satisfies the given condition (it returns Boolean). A: You could do the following to repeat a component numrows times <tbody>{Array(numrows).fill(<ObjectRow />)}</tbody> A: This is what I used in most of my projects up to now: const length = 5; ... <tbody> {Array.from({ length }).map((_,i) => ( <ObjectRow key={i}/> ))} </tbody> A: try this one please <tbody> {Array.apply(0, Array(numrows)).map(function (x, i) { return <ObjectRow/>; })} </tbody> or {[...Array(numrows)].map((x, i) => <ObjectRow/> )} A: return ( <table> <tbody> { numrows.map((item, index) => { <ObjectRow data={item} key={index}> }) } </tbody> </table> ); A: If numrows is an array, as the other answers, the best way is the map method. If it's not and you only access it from JSX, you can also use this ES6 method: <tbody> { [...Array(numrows).fill(0)].map((value,index)=><ObjectRow key={index} />) } </tbody> A: You'll want to add elements to an array and render the array of elements. This can help reduce the time required to re-render the component. Here's some rough code that might help: MyClass extends Component { constructor() { super(props) this.state = { elements: [] } } render() { return (<tbody>{this.state.elements}<tbody>) } add() { /* * The line below is a cheap way of adding to an array in the state. * 1) Add <tr> to this.state.elements * 2) Trigger a lifecycle update. */ this.setState({ elements: this.state.elements.concat([<tr key={elements.length}><td>Element</td></tr>]) }) } } A: I've found one more solution to follow the map render: <tbody>{this.getcontent()}</tbody> And a separate function: getcontent() { const bodyarea = this.state.movies.map(movies => ( <tr key={movies._id}> <td>{movies.title}</td> <td>{movies.genre.name}</td> <td>{movies.numberInStock}</td> <td>{movies.publishDate}</td> <td> <button onClick={this.deletMovie.bind(this, movies._id)} className="btn btn-danger" > Delete </button> </td> </tr> )); return bodyarea; } This example solves many problems easily. A: Use {} around JavaScript code within a JSX block to get it to properly perform whatever JavaScript action you are trying to do. <tr> <td> {data.map((item, index) => { {item} })} </td> </tr> This is kind of vague, but you can swap out data for any array. This will give you a table row and table item for each item. If you have more than just one thing in each node of the array, you will want to target that specifically by doing something like this: <td>{item.someProperty}</td> In which case, you will want to surround it with a different td and arrange the previous example differently. A: There are many solutions posted out there in terms of iterating an array and generating JSX elements. All of them are good, but all of them used an index directly in a loop. We are recommended to use unique id from data as a key, but when we do not have a unique id from each object in the array we will use index as a key, but you are not recommended to use an index as a key directly. One more thing why we go for .map, but why not .foEach because .map returns a new array. There are different ways of doing .map these days. Below different versions of using .map illustrates in detail about how to use a unique key and how to use .map for looping JSX elements. .map without return when returning single a JSX element and unique id from data as a key version: const {objects} = this.state; <tbody> {objects.map(object => <ObjectRow obj={object} key={object.id} />)} </tbody> .map without return when returning multiple JSX elements and unique id from data as a key version const {objects} = this.state; <tbody> {objects.map(object => ( <div key={object.id}> <ObjectRow obj={object} /> </div> ))} </tbody> .map without return when returning a single JSX element and index as a key version: const {objects} = this.state; <tbody> {objects.map((object, index) => <ObjectRow obj={object} key={`Key${index}`} />)} </tbody> .map without return when returning multiple JSX elements and index as a key version: const {objects} = this.state; <tbody> {objects.map((object, index) => ( <div key={`Key${index}`}> <ObjectRow obj={object} /> </div> ))} </tbody> .map with return when returning multiple JSX elements and index as a key version: const {objects} = this.state; <tbody> {objects.map((object, index) => { return ( <div key={`Key${index}`}> <ObjectRow obj={object} /> </div> ) })} </tbody> .map with return when returning multiple JSX elements and unique id from data as a key version: const {objects} = this.state; <tbody> {objects.map(object => { return ( <div key={object.id}> <ObjectRow obj={object} /> </div> ) })} </tbody> The other way is render() { const {objects} = this.state; const objectItems = objects.map(object => { return ( <div key={object.id}> <ObjectRow obj={object} /> </div> ) }) return( <div> <tbody> {objectItems} </tbody> </div> ) } A: To provide a more straightforward solution in case you want to use a specific row count which is stored as Integer-value. With the help of typedArrays we could achieve the desired solution in the following manner. // Let's create a typedArray with length of `numrows`-value const typedArray = new Int8Array(numrows); // typedArray.length is now 2 const rows = []; // Prepare rows-array for (let arrKey in typedArray) { // Iterate keys of typedArray rows.push(<ObjectRow key={arrKey} />); // Push to an rows-array } // Return rows return <tbody>{rows}</tbody>; A: render() { const elements = ['one', 'two', 'three']; const items = [] for (const [index, value] of elements.entries()) { items.push(<li key={index}>{value}</li>) } return ( <div> {items} </div> ) } A: You have to write in JSX: <tbody> { objects.map((object, i) => ( <ObjectRow obj={object} key={i} /> )); } </tbody> A: <tbody> numrows.map((row,index) => ( return <ObjectRow key={index}/> ) </tbody> A: Maybe the standard of today maximum developer, use a structure like this: let data = [ { id: 1, name: "name1" }, { id: 2, name: "name2" }, { id: 3, name: "name3" }, { id: 100, name: "another name" } ]; export const Row = data => { return ( <tr key={data.id}> <td>{data.id}</td> <td>{data.name}</td> </tr> ); }; function App() { return ( <table> <thead> <tr> <th>Id</th> <th>Name</th> </tr> </thead> <tbody>{data.map(item => Row(item))}</tbody> </table> ); } In the JSX, write your JavaScript action inside HTML or any code here, {data.map(item => Row(item))}, use single curly braces and inside a map function. Get to know more about map. And also see the following output here. A: There are multiple ways to loop inside JSX Using a for loop function TableBodyForLoop(props) { const rows = []; // Create an array to store list of tr for (let i = 0; i < props.people.length; i++) { const person = props.people[i]; // Push the tr to array, the key is important rows.push( <tr key={person.id}> <td>{person.id}</td> <td>{person.name}</td> </tr> ); } // Return the rows inside the tbody return <tbody>{rows}</tbody>; } Using the ES6 array map method function TableBody(props) { return ( <tbody> {props.people.map(person => ( <tr key={person.id}> <td>{person.id}</td> <td>{person.name}</td> </tr> ))} </tbody> ); } Full example: https://codesandbox.io/s/cocky-meitner-yztif The following React Docs will be helpful Lists and Keys Conditional Rendering A: It's funny how people give "creative" answers using a newer syntax or uncommon ways to create an array. In my experience working with JSX, I have seen these tricks only used by inexperienced React programmers. The simpler the solution - the better it is for future maintainers. And since React is a web framework, usually this type of (table) data comes from the API. Therefore, the simplest and most practical way would be: const tableRows = [ {id: 1, title: 'row1'}, {id: 2, title: 'row2'}, {id: 3, title: 'row3'} ]; // Data from the API (domain-driven names would be better of course) ... return ( tableRows.map(row => <ObjectRow key={row.id} {...row} />) ); A: You can only write a JavaScript expression in a JSX element, so a for loop cannot work. You can convert the element into an array first and use the map function to render it: <tbody> {[...new Array(numrows)].map((e) => ( <ObjectRow/> ))} </tbody> A: Having the JSX content in the map can be clunky syntax. Instead you can do this: const ObjectRow = ({ ... }) => <tr key={}>...</tr> const TableBody = ({ objects }) => { return <tbody>{objects.map(ObjectRow)}</tbody>; } This is shorthand for { objects.map(object => ObjectRow(object)) If ObjectRow is set up to take the same keys that are in the object, this will work great. Note - You may need to set the key prop when the ObjectRow is rendered. It can't be passed in through the function call. More notes - I've run into a few places where this technique is a bad idea. For example, it doesn't go through the normal create component path and won't default prop values for example, so do beware. Still, it's handy to know about and is useful sometimes. A: use map to looping Array.map(arrayItem => { return <ObjectRow arrayItem={arrayItem}/> // pass array item in component }) A: If you want to add some amount of the same React Component of DOM elements this answer is for you create a Nth length Array (choose length you want) and call method map SomeComponent.jsx/.tsx No matter which extension you use in this situation import React from "react" let length = 10 (for example) const SomeComponent = () => ( <div> {new Array(length).fill(null).map(item => { return <ObjectRow/> })} </div> ) A: I have seen one person/previous answer use .concat() in an array, but not like this... I have used concat to add to a string and then just render the JSX content on the element via the jQuery selector: let list = "<div><ul>"; for (let i=0; i<myArray.length; i++) { list = list.concat(`<li>${myArray[i].valueYouWant}</li>`); } list = list.concat("</ul></div>); $("#myItem").html(list); A: const numrows = [1, 2, 3, 4, 5]; cosnt renderRows = () => { return numros.map((itm,index) => <td key={index}>{itm}</td>) } return <table> ............ <tr> {renderRows()} </tr> </table> A: Inside your render or any function and before return, you can use a variable to store JSX elements. Just like this - const tbodyContent = []; for (let i=0; i < numrows; i++) { tbodyContent.push(<ObjectRow/>); } Use it inside your tbody like this: <tbody> { tbodyContent } </tbody> But I'll prefer map() over this. A: function PriceList({ self }) { let p = 10000; let rows = []; for(let i=0; i<p; i=i+50) { let r = i + 50; rows.push(<Dropdown.Item key={i} onClick={() => self.setState({ searchPrice: `${i}-${r}` })}>{i}-{r} &#8378;</Dropdown.Item>); } return rows; } <PriceList self={this} /> A: If you are used to Angular and want a more React-like approach: Try using this simple component with auto hashing and optional trackBy similar to Angular's. Usage: <For items={items}> {item => <div>item</div>} </For> Custom key/trackBy: <For items={items} trackBy={'name'}> {item => <div>item</div>} </For> Definition: export default class For<T> extends Component<{ items: T[], trackBy?: keyof T, children: (item: T) => React.ReactElement }, {}> { render() { return ( <Fragment> {this.props.items.map((item: any, index) => <Fragment key={this.props.trackBy ?? item.id ?? index}>{this.props.children(item)}</Fragment>)} </Fragment> ); } } React Dev Tools: A: you can use .map() for loop in reactjs <tbody> {items.map((value, index) => { return <li key={index}>{value}</li> })} </tbody> ) A: A one liner (assuming numrows is a number): <tbody> { Array(numrows).fill().map(function (v, i) { return <ObjectRow/> }) } </tbody> A: Simple way You can put numrows in state and use map() instead of a for loop: {this.state.numrows.map((numrows , index) => { return ( <ObjectRow key={index} /> A: Below code will help you to create Loop inside JSX with passing unique key props import React, { Children, Fragment } from 'react'; export const ObjectRow = ({ data }) => ( <div> <Fragment>{data}</Fragment> </div> ); /** Wrapping your list inside React.Children.toArray allows you to not pass unique key props. It will be dynamically generated from Virtual Dom to Real Dom */ export const ObjectRowListComponent = (objectRows) => ( <tbody> {Children.toArray(objectRows.map((row) => <ObjectRow data={row} />))} </tbody> ); A: You can make array from numRows and map it sth like this : <tbody> {Array.from({ length: numrows }).map((_,i)=><ObjectRow key={i}/>) </tbody>
Loop inside React JSX
I'm trying to do something like the following in React JSX (where ObjectRow is a separate component): <tbody> for (var i=0; i < numrows; i++) { <ObjectRow/> } </tbody> I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times).
[ "Think of it like you're just calling JavaScript functions. You can't use a for loop where the arguments to a function call would go:\nreturn tbody(\n for (let i = 0; i < numrows; i++) {\n ObjectRow()\n } \n)\n\nSee how the function tbody is being passed a for loop as an argument – leading to a syntax error.\nBut you can make an array, and then pass that in as an argument:\nconst rows = [];\nfor (let i = 0; i < numrows; i++) {\n rows.push(ObjectRow());\n}\nreturn tbody(rows);\n\n\nYou can basically use the same structure when working with JSX:\nconst rows = [];\nfor (let i = 0; i < numrows; i++) {\n // note: we are adding a key prop here to allow react to uniquely identify each\n // element in this array. see: https://reactjs.org/docs/lists-and-keys.html\n rows.push(<ObjectRow key={i} />);\n}\nreturn <tbody>{rows}</tbody>;\n\nIncidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works.\n", "I am not sure if this will work for your situation, but often map is a good answer.\nIf this was your code with the for loop:\n<tbody>\n for (var i=0; i < objects.length; i++) {\n <ObjectRow obj={objects[i]} key={i}>\n }\n</tbody>\n\nYou could write it like this with map:\n<tbody>\n {objects.map(function(object, i){\n return <ObjectRow obj={object} key={i} />;\n })}\n</tbody>\n\nES6 syntax:\n<tbody>\n {objects.map((object, i) => <ObjectRow obj={object} key={i} />)}\n</tbody>\n\n", "If you don't already have an array to map() like @FakeRainBrigand's answer, and want to inline this so the source layout corresponds to the output closer than @SophieAlpert's answer:\nWith ES2015 (ES6) syntax (spread and arrow functions)\nhttp://plnkr.co/edit/mfqFWODVy8dKQQOkIEGV?p=preview\n<tbody>\n {[...Array(10)].map((x, i) =>\n <ObjectRow key={i} />\n )}\n</tbody>\n\nRe: transpiling with Babel, its caveats page says that Array.from is required for spread, but at present (v5.8.23) that does not seem to be the case when spreading an actual Array. I have a documentation issue open to clarify that. But use at your own risk or polyfill.\nVanilla ES5\nArray.apply\n<tbody>\n {Array.apply(0, Array(10)).map(function (x, i) {\n return <ObjectRow key={i} />;\n })}\n</tbody>\n\nInline IIFE\nhttp://plnkr.co/edit/4kQjdTzd4w69g8Suu2hT?p=preview\n<tbody>\n {(function (rows, i, len) {\n while (++i <= len) {\n rows.push(<ObjectRow key={i} />)\n }\n return rows;\n })([], 0, 10)}\n</tbody>\n\nCombination of techniques from other answers\nKeep the source layout corresponding to the output, but make the inlined part more compact:\nrender: function () {\n var rows = [], i = 0, len = 10;\n while (++i <= len) rows.push(i);\n\n return (\n <tbody>\n {rows.map(function (i) {\n return <ObjectRow key={i} index={i} />;\n })}\n </tbody>\n );\n}\n\nWith ES2015 syntax & Array methods\nWith Array.prototype.fill you could do this as an alternative to using spread as illustrated above:\n<tbody>\n {Array(10).fill(1).map((el, i) =>\n <ObjectRow key={i} />\n )}\n</tbody>\n\n(I think you could actually omit any argument to fill(), but I'm not 100% on that.) Thanks to @FakeRainBrigand for correcting my mistake in an earlier version of the fill() solution (see revisions).\nkey\nIn all cases the key attr alleviates a warning with the development build, but isn't accessible in the child. You can pass an extra attr if you want the index available in the child. See Lists and Keys for discussion.\n", "Simply using map Array method with ES6 syntax:\n<tbody>\n {items.map(item => <ObjectRow key={item.id} name={item.name} />)} \n</tbody>\n\nDon't forget the key property.\n", "Using the Array map function is a very common way to loop through an Array of elements and create components according to them in React. This is a great way to do a loop which is a pretty efficient and is a tidy way to do your loops in JSX. It's not the only way to do it, but the preferred way.\nAlso, don't forget having a unique Key for each iteration as required. The map function creates a unique index from 0, but it's not recommended using the produced index, but if your value is unique or if there is a unique key, you can use them:\n<tbody>\n {numrows.map(x=> <ObjectRow key={x.id} />)}\n</tbody>\n\nAlso, a few lines from MDN if you not familiar with the map function on Array:\n\nmap calls a provided callback function once for each element in an\narray, in order, and constructs a new array from the results. callback\nis invoked only for indexes of the array which have assigned values,\nincluding undefined. It is not called for missing elements of the\narray (that is, indexes that have never been set, which have been\ndeleted or which have never been assigned a value).\ncallback is invoked with three arguments: the value of the element,\nthe index of the element, and the Array object being traversed.\nIf a thisArg parameter is provided to the map, it will be used as\ncallback's this value. Otherwise, the value undefined will be used as\nits this value. This value ultimately observable by the callback is\ndetermined according to the usual rules for determining the this seen\nby a function.\nmap does not mutate the array on which it is called (although\ncallback, if invoked, may do so).\n\n", "If you're already using lodash, the _.times function is handy.\nimport React, { Component } from \"react\";\nimport Select from \"./Select\";\nimport _ from \"lodash\";\n\nexport default class App extends Component {\n render() {\n return (\n <div className=\"container\">\n <ol>\n {_.times(3, (i) => (\n <li key={i}>repeated 3 times</li>\n ))}\n </ol>\n </div>\n );\n }\n}\n\n", "There are multiple ways to go about doing this. JSX eventually gets compiled to JavaScript, so as long as you're writing valid JavaScript, you'll be good.\nMy answer aims to consolidate all the wonderful ways already presented here:\nIf you do not have an array of object, simply the number of rows:\nWithin the return block, creating an Array and using Array.prototype.map:\nrender() {\n return (\n <tbody>\n {Array(numrows).fill(null).map((value, index) => (\n <ObjectRow key={index}>\n ))}\n </tbody>\n );\n}\n\nOutside the return block, simply use a normal JavaScript for loop:\nrender() {\n let rows = [];\n for (let i = 0; i < numrows; i++) {\n rows.push(<ObjectRow key={i}/>);\n }\n return (\n <tbody>{rows}</tbody>\n );\n}\n\nImmediately invoked function expression:\nrender() {\n return (\n <tbody>\n {(() => {\n let rows = [];\n for (let i = 0; i < numrows; i++) {\n rows.push(<ObjectRow key={i}/>);\n }\n return rows;\n })()}\n </tbody>\n );\n}\n\nIf you have an array of objects\nWithin the return block, .map() each object to a <ObjectRow> component:\nrender() {\n return (\n <tbody>\n {objectRows.map((row, index) => (\n <ObjectRow key={index} data={row} />\n ))}\n </tbody>\n );\n}\n\nOutside the return block, simply use a normal JavaScript for loop:\nrender() {\n let rows = [];\n for (let i = 0; i < objectRows.length; i++) {\n rows.push(<ObjectRow key={i} data={objectRows[i]} />);\n }\n return (\n <tbody>{rows}</tbody>\n );\n}\n\nImmediately invoked function expression:\nrender() {\n return (\n <tbody>\n {(() => {\n const rows = [];\n for (let i = 0; i < objectRows.length; i++) {\n rows.push(<ObjectRow key={i} data={objectRows[i]} />);\n }\n return rows;\n })()}\n </tbody>\n );\n}\n\n", "You can also extract outside the return block:\nrender: function() {\n var rows = [];\n for (var i = 0; i < numrows; i++) {\n rows.push(<ObjectRow key={i}/>);\n } \n\n return (<tbody>{rows}</tbody>);\n}\n\n", "You might want to checkout React Templates, which does let you use JSX-style templates in React, with a few directives (such as rt-repeat).\nYour example, if you used react-templates, would be:\n<tbody>\n <ObjectRow rt-repeat=\"obj in objects\"/>\n</tbody>\n\n", "If you opt to convert this inside return() of the render method, the easiest option would be using the map( ) method. Map your array into JSX syntax using the map() function, as shown below (ES6 syntax is used).\n\nInside the parent component:\n<tbody>\n { objectArray.map(object => <ObjectRow key={object.id} object={object.value} />) }\n</tbody>\n\nPlease note the key attribute is added to your child component. If you didn't provide a key attribute, you can see the following warning on your console.\n\nWarning: Each child in an array or iterator should have\na unique \"key\" prop.\n\nNote: One common mistake people do is using index as the key when iterating. Using index of the element as a key is an antipattern, and you can read more about it here. In short, if it's not a static list, never use index as the key.\n\nNow at the ObjectRow component, you can access the object from its properties.\nInside the ObjectRow component\nconst { object } = this.props\n\nOr\nconst object = this.props.object\n\nThis should fetch you the object you passed from the parent component to the variable object in the ObjectRow component. Now you can spit out the values in that object according to your purpose.\n\nReferences:\nmap() method in JavaScript\nECMAScript 6 or ES6\n", "If numrows is an array, it's very simple:\n<tbody>\n {numrows.map(item => <ObjectRow />)}\n</tbody>\n\nThe array data type in React is much better. An array can back a new array, and support filter, reduce, etc.\n", "There are several answers pointing to using the map statement. Here is a complete example using an iterator within the FeatureList component to list Feature components based on a JSON data structure called features.\nconst FeatureList = ({ features, onClickFeature, onClickLikes }) => (\n <div className=\"feature-list\">\n {features.map(feature =>\n <Feature\n key={feature.id}\n {...feature}\n onClickFeature={() => onClickFeature(feature.id)}\n onClickLikes={() => onClickLikes(feature.id)}\n />\n )}\n </div>\n); \n\nYou can view the complete FeatureList code on GitHub. The features fixture is listed here.\n", "Let us say we have an array of items in your state:\n[{name: \"item1\", id: 1}, {name: \"item2\", id: 2}, {name: \"item3\", id: 3}]\n\n<tbody>\n {this.state.items.map((item) => {\n <ObjectRow key={item.id} name={item.name} />\n })}\n</tbody>\n\n", "To loop for a number of times and return, you can achieve it with the help of from and map:\n<tbody>\n {\n Array.from(Array(i)).map(() => <ObjectRow />)\n }\n</tbody>\n\nwhere i = number of times\n\nIf you want to assign unique key IDs into the rendered components, you can use React.Children.toArray as proposed in the React documentation\nReact.Children.toArray\nReturns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.\n\nNote:\nReact.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.\n\n<tbody>\n {\n React.Children.toArray(\n Array.from(Array(i)).map(() => <ObjectRow />)\n )\n }\n</tbody>\n\n", "An ECMAScript 2015 / Babel possibility is using a generator function to create an array of JSX:\nfunction* jsxLoop(times, callback)\n{\n for(var i = 0; i < times; ++i)\n yield callback(i);\n}\n\n...\n\n<tbody>\n {[...jsxLoop(numrows, i =>\n <ObjectRow key={i}/>\n )]}\n</tbody>\n\n", "This can be done in multple ways.\n\nAs suggested above, before return store all elements in the array\n\nLoop inside return\nMethod 1\nlet container = [];\nlet arr = [1, 2, 3] //can be anything array, object\narr.forEach((val, index) => {\n container.push(\n <div key={index}>\n val\n </div>)\n /**\n * 1. All loop generated elements require a key\n * 2. only one parent element can be placed in Array\n * e.g. container.push(\n * <div key={index}>\n val\n </div>\n <div>\n this will throw error\n </div>\n )\n **/\n});\nreturn (\n <div>\n <div>any things goes here</div>\n <div>{container}</div>\n </div>\n)\n\nMethod 2\nreturn (\n <div>\n <div>any things goes here</div>\n <div>\n {\n (() => {\n let container = [];\n let arr = [1, 2, 3] //can be anything array, object\n arr.forEach((val, index) => {\n container.push(\n <div key={index}>\n val\n </div>)\n });\n return container;\n })()\n }\n </div>\n </div>\n)\n\n\n\n", "ES2015 Array.from with the map function + key\nIf you have nothing to .map() you can use Array.from() with the map function to repeat elements:\n<tbody>\n {Array.from({ length: 5 }, (value, key) => <ObjectRow key={key} />)}\n</tbody>\n\n", "...Or you can also prepare an array of objects and map it to a function to have the desired output. I prefer this, because it helps me to maintain the good practice of coding with no logic inside the return of render. \nrender() {\nconst mapItem = [];\nfor(let i =0;i<item.length;i++) \n mapItem.push(i);\nconst singleItem => (item, index) {\n // item the single item in the array \n // the index of the item in the array\n // can implement any logic here\n return (\n <ObjectRow/>\n)\n\n}\n return(\n <tbody>{mapItem.map(singleItem)}</tbody>\n )\n}\n\n", "I use this:\ngridItems = this.state.applications.map(app =>\n <ApplicationItem key={app.Id} app={app } />\n);\n\nPS: never forget the key or you will have a lot of warnings!\n", "You can of course solve with a .map as suggested by the other answer. If you already use Babel, you could think about using jsx-control-statements.\nThey require a little of setting, but I think it's worth in terms of readability (especially for non-React developer).\nIf you use a linter, there's also eslint-plugin-jsx-control-statements.\n", "Here's a simple solution to it.\nvar Object_rows = [];\nfor (var i = 0; i < numrows; i++) {\n Object_rows.push(<ObjectRow />);\n}\n<tbody>{Object_rows}</tbody>;\n\n\nNo mapping and complex code is required. You just need to push the rows to the array and return the values to render it.\n", "Simply use .map() to loop through your collection and return <ObjectRow> items with props from each iteration.\nAssuming objects is an array somewhere...\n<tbody>\n { objects.map((obj, index) => <ObjectRow obj={ obj } key={ index }/> ) }\n</tbody>\n\n", "Your JSX code will compile into pure JavaScript code, any tags will be replaced by ReactElement objects. In JavaScript, you cannot call a function multiple times to collect their returned variables.\nIt is illegal, the only way is to use an array to store the function returned variables.\nOr you can use Array.prototype.map which is available since JavaScript ES5 to handle this situation.\nMaybe we can write other compiler to recreate a new JSX syntax to implement a repeat function just like Angular's ng-repeat.\n", "I tend to favor an approach where programming logic happens outside the return value of render. This helps keep what is actually rendered easy to grok.\nSo I'd probably do something like:\nimport _ from 'lodash';\n\n...\n\nconst TableBody = ({ objects }) => {\n const objectRows = objects.map(obj => <ObjectRow object={obj} />); \n\n return <tbody>{objectRows}</tbody>;\n} \n\nAdmittedly this is such a small amount of code that inlining it might work fine.\n", "You may use .map() in a React for loop.\n<tbody>\n { newArray.map(() => <ObjectRow />) }\n</tbody>\n\n", "Here is a sample from the React documentation, JavaScript Expressions as Children:\nfunction Item(props) {\n return <li>{props.message}</li>;\n}\n\nfunction TodoList() {\n const todos = ['finish doc', 'submit pr', 'nag dan to review'];\n return (\n <ul>\n {todos.map((message) => <Item key={message} message={message} />)}\n </ul>\n );\n}\n\nAs for your case, I suggest writing like this:\nfunction render() {\n return (\n <tbody>\n {numrows.map((roe, index) => <ObjectRow key={index} />)}\n </tbody>\n );\n}\n\nPlease notice the key is very important, because React use the key to differ data in array.\n", "Since you are writing JavaScript syntax inside JSX code, you need to wrap your JavaScript code in curly braces.\nrow = () => {\n var rows = [];\n for (let i = 0; i<numrows; i++) {\n rows.push(<ObjectRow/>);\n }\n return rows;\n}\n<tbody>\n{this.row()}\n</tbody>\n\n", "I use it like\n<tbody>\n { numrows ? (\n numrows.map(obj => { return <ObjectRow /> }) \n ) : null\n }\n</tbody>\n\n", "If you really want a for loop equivalent (you have a single number, not an array), just use range from Lodash.\nDon't reinvent the wheel and don't obfuscate your code. Just use the standard utility library.\nimport range from 'lodash/range'\n\nrange(4);\n// => [0, 1, 2, 3]\n\nrange(1, 5);\n// => [1, 2, 3, 4]\n\n", "You can also use a self-invoking function: \nreturn <tbody>\n {(() => {\n let row = []\n for (var i = 0; i < numrows; i++) {\n row.push(<ObjectRow key={i} />)\n }\n return row\n\n })()}\n </tbody>\n\n", "When I want to add a certain number of components, I use a helper function.\nDefine a function that returns JSX:\nconst myExample = () => {\n let myArray = []\n for(let i = 0; i<5;i++) {\n myArray.push(<MyComponent/>)\n }\n return myArray\n}\n\n//... in JSX\n\n<tbody>\n {myExample()}\n</tbody>\n\n", "Even this piece of code does the same job.\n<tbody>\n {array.map(i => \n <ObjectRow key={i.id} name={i.name} />\n )}\n</tbody>\n\n", "With time, the language is becoming more mature, and we often stumble upon common problems like this. The problem is to loop a Component 'n' times.\n{[...new Array(n)].map((item, index) => <MyComponent key={index} />)}\n\nwhere, n -is the number of times you want to loop. item will be undefined and index will be as usual. Also, ESLint discourages using an array index as key.\nBut you have the advantage of not requiring to initialize the array before and most importantly avoiding the for loop...\nTo avoid the inconvenience of item as undefined you can use an _, so that it will be ignored when linting and won't throw any linting error, such as\n{[...new Array(n)].map((_, index) => <MyComponent key={index} />)}\n\n", "Array.from is the best way. If you want to create an array of JSX with some length.\nfunction App() {\n return (\n <tbody>\n {Array.from({ length: 10 }, (_, key) => (\n <ObjectRow {...{ key }} />\n ))}\n </tbody>\n );\n}\n\nThe above example is for when you do not have an array, so if you have an array you should map it in JSX like this:\nfunction App() {\n return (\n <tbody>\n {list.map((item, key) => (\n <ObjectRow {...{ key }} />\n ))}\n </tbody>\n );\n}\n\n", "You can do something like:\nlet foo = [1,undefined,3]\n{ foo.map(e => !!e ? <Object /> : null )}\n\n", "A loop inside JSX is very simple. Try this:\nreturn this.state.data.map((item, index) => (\n <ComponentName key={index} data={item} />\n));\n\n", "If you need JavaScript code inside your JSX, you add { } and then write your JavaScript code inside these brackets.\nIt is just that simple.\nAnd the same way you can loop inside JSX/react.\nSay:\n<tbody>\n {`your piece of code in JavaScript` }\n</tbody>\n\nExample:\n<tbody>\n { items.map((item, index) => {\n console.log(item)}) ; // Print item\n return <span>{index}</span>;\n } // Looping using map()\n</tbody>\n\n", "Below are possible solutions that you can do in React in terms of iterating array of objects or plain array\nconst rows = [];\nconst numrows = [{\"id\" : 01, \"name\" : \"abc\"}];\nnumrows.map((data, i) => {\n rows.push(<ObjectRow key={data.id} name={data.name}/>);\n});\n\n<tbody>\n { rows }\n</tbody>\n\nOr\nconst rows = [];\nconst numrows = [1,2,3,4,5];\nfor(let i=1, i <= numrows.length; i++){\n rows.push(<ObjectRow key={numrows[i]} />);\n};\n\n<tbody>\n { rows }\n</tbody>\n\nAn even more better approach I became familiar with recent days for iterating an array of objects is .map directly in the render with return or without return:\n.map with return\n const numrows = [{\"id\" : 01, \"name\" : \"abc\"}];\n <tbody>\n {numrows.map(data=> {\n return <ObjectRow key={data.id} name={data.name}/>\n })}\n</tbody>\n\n.map without return\n const numrows = [{\"id\" : 01, \"name\" : \"abc\"}];\n <tbody>\n {numrows.map(data=> (\n <ObjectRow key={data.id} name={data.name}/>\n ))}\n</tbody>\n\n", "React elements are simple JavaScript, so you can follow the rule of JavaScript. You can use a for loop in JavaScript like this:-\n<tbody>\n for (var i=0; i < numrows; i++) {\n <ObjectRow/>\n } \n</tbody>\n\nBut the valid and best way is to use the .map function. Shown below:-\n<tbody>\n {listObject.map(function(listObject, i){\n return <ObjectRow key={i} />;\n })}\n</tbody>\n\nHere, one thing is necessary: to define the key. Otherwise it will throw a warning like this:-\n\nWarning.js:36 Warning: Each child in an array or iterator should have\na unique \"key\" prop. Check the render method of ComponentName. See\n\"link\" for more information.\n\n", "For printing an array value if you don't have the key value par, then use the below code -\n<div>\n {my_arr.map(item => <div>{item} </div> )} \n</div>\n\n", "You can try the new for of loop:\nconst apple = {\n color: 'red',\n size: 'medium',\n weight: 12,\n sugar: 10\n}\nfor (const prop of apple.entries()){\n console.log(prop);\n}\n\nHere's a few examples:\n", "Unless you declare a function and enclose it with parameters, it is not possible. In a JSXExpression you can only write expressions and cannot write statements like a for(), declare variables or classes, or a if() statement.\nThat's why function CallExpressions are so in the mood today. My advice: get used to them. This is what I would do:\nconst names = ['foo', 'bar', 'seba']\nconst people = <ul>{names.map(name => <li>{name}</li>)}</ul>\n\nFiltering:\nconst names = ['foo', undefined, 'seba']\nconst people = <ul>{names.filter(person => !!person).map(name => <li>{name}</li>)}</ul>\n\nif():\nvar names = getNames()\nconst people = {names && names.length &&\n <ul>{names.map(name => <li>{name}</li>)}</ul> }\n\nif - else:\nvar names = getNames()\nconst people = {names && names.length ?\n <ul>{names.map(name => <li>{name}</li>)}</ul> : <p>no results</p> }\n\n", "Use the map function.\n<tbody> \n {objects.map((object, i) => <ObjectRow obj={object} key={i} />)} \n</tbody>\n\n", "Just do something like this:\n\n\n<tbody>\n {new Array(numRows).fill(\"\", 0, numRows).map((p, i) => <YourRaw key={i} />)}\n</tbody>\n\n\n\n", "Well, here you go.\n{\n [1, 2, 3, 4, 5, 6].map((value, index) => {\n return <div key={index}>{value}</div>\n })\n}\n\nAll you have to do is just map your array and return whatever you want to render. And please don't forget to use key in the returned element.\n", "You can do the same directly in the JSX, using map instead of a for-of loop:\nrender: function() {\nconst items = ['one', 'two', 'three'];\n return (\n <ul>\n {items.map((value, index) => {\n return <li key={index}>{value}</li>\n })}\n </ul>\n )\n}\n\n", "try this\n<tbody>\n {new Array(numrows).map((row,index)=><ObjectRow key={***someThingUniqe***}/>)} //don't use index as key \n</tbody>\n\nif you wanna know why you shouldn't use indices as keys in react check this\n", "You can use an IIFE if you really want to literally use a for loop inside JSX.\n<tbody>\n {\n (function () {\n const view = [];\n for (let i = 0; i < numrows; i++) {\n view.push(<ObjectRow key={i}/>);\n }\n return view;\n }())\n }\n</tbody>\n\n", "@jacefarm If I understand right you can use this code:\n<tbody>\n { new Array(numrows).fill(<ObjectRow/>) } \n</tbody>\n\nEither you can use this code:\n<tbody>\n { new Array(numrows).fill('').map((item, ind) => <ObjectRow key={ind}/>) } \n</tbody>\n\nAnd this:\n<tbody>\n new Array(numrows).fill(ObjectRow).map((Item, ind) => <Item key={ind}/>)\n</tbody>\n\n", "Using map in React are best practices for iterating over an array.\nTo prevent some errors with ES6, the syntax map is used like this in React:\n<tbody>\n {items.map((item, index) => <ObjectRow key={index} name={item.name} />)}\n</tbody>\n\nHere you call a Component, <ObjectRow/>, so you don't need to put parenthesis after the arrow.\nBut you can be make this too:\n{items.map((item, index) => (\n <ObjectRow key={index} name={item.name} />\n))}\n\nOr:\n{items.map((item, index) => {\n // Here you can log 'item'\n return (\n <ObjectRow key={index} name={item.name} />\n )\n})}\n\nI say that because if you put a bracket \"{}\" after the arrow React will not throw an error and will display a whitelist.\n", "The problem is you don't return any JSX element. There are another solutions for such cases, but I will provide the simplest one: \"use the map function\"!\n<tbody>\n { numrows.map(item => <ObjectRow key={item.uniqueField} />) }\n</tbody>\n\nIt's so simple and beautiful, isn't it?\n", "You can create a new component like below:\nPass key and data to your ObjectRow component like this:\nexport const ObjectRow = ({key,data}) => {\n return (\n <div>\n ...\n </div>\n );\n}\n\nCreate a new component ObjectRowList to act like a container for your data:\nexport const ObjectRowList = (objectRows) => {\n return (\n <tbody>\n {objectRows.map((row, index) => (\n <ObjectRow key={index} data={row} />\n ))}\n </tbody>\n );\n}\n\n", "I am not sure if this will work for your situation, but often [map][1] is a good answer.\nIf this was your code with the for loop:\n<tbody>\n for (var i=0; i < objects.length; i++) {\n <ObjectRow obj={objects[i]} key={i}>\n }\n</tbody>\n\nYou could write it like this with the map function:\n<tbody>\n {objects.map(function(object, i){\n return <ObjectRow obj={object} key={i} />;\n })}\n</tbody>\n\nobjects.map is the best way to do a loop, and objects.filter is the best way to filter the required data. The filtered data will form a new array, and objects.some is the best way to check whether the array satisfies the given condition (it returns Boolean).\n", "You could do the following to repeat a component numrows times\n<tbody>{Array(numrows).fill(<ObjectRow />)}</tbody>\n\n", "This is what I used in most of my projects up to now:\nconst length = 5;\n...\n<tbody>\n {Array.from({ length }).map((_,i) => (\n <ObjectRow key={i}/>\n ))}\n</tbody>\n\n", "try this one please\n<tbody>\n {Array.apply(0, Array(numrows)).map(function (x, i) {\n return <ObjectRow/>;\n })}\n</tbody>\n\nor\n{[...Array(numrows)].map((x, i) =>\n <ObjectRow/>\n)}\n\n", "return (\n <table>\n <tbody>\n {\n numrows.map((item, index) => {\n <ObjectRow data={item} key={index}>\n })\n }\n </tbody>\n </table>\n);\n\n", "If numrows is an array, as the other answers, the best way is the map method. If it's not and you only access it from JSX, you can also use this ES6 method:\n<tbody>\n {\n [...Array(numrows).fill(0)].map((value,index)=><ObjectRow key={index} />)\n }\n</tbody>\n\n", "You'll want to add elements to an array and render the array of elements.\nThis can help reduce the time required to re-render the component.\nHere's some rough code that might help:\nMyClass extends Component {\n constructor() {\n super(props)\n this.state = { elements: [] }\n }\n render() {\n return (<tbody>{this.state.elements}<tbody>)\n }\n add() {\n /*\n * The line below is a cheap way of adding to an array in the state.\n * 1) Add <tr> to this.state.elements\n * 2) Trigger a lifecycle update.\n */\n this.setState({\n elements: this.state.elements.concat([<tr key={elements.length}><td>Element</td></tr>])\n })\n }\n}\n\n", "I've found one more solution to follow the map\nrender:\n <tbody>{this.getcontent()}</tbody>\n\nAnd a separate function:\ngetcontent() {\n const bodyarea = this.state.movies.map(movies => (\n <tr key={movies._id}>\n <td>{movies.title}</td>\n <td>{movies.genre.name}</td>\n <td>{movies.numberInStock}</td>\n <td>{movies.publishDate}</td>\n <td>\n <button\n onClick={this.deletMovie.bind(this, movies._id)}\n className=\"btn btn-danger\"\n >\n Delete\n </button>\n </td>\n </tr>\n ));\n return bodyarea;\n}\n\nThis example solves many problems easily.\n", "Use {} around JavaScript code within a JSX block to get it to properly perform whatever JavaScript action you are trying to do.\n<tr>\n <td>\n {data.map((item, index) => {\n {item}\n })}\n </td>\n</tr>\n\nThis is kind of vague, but you can swap out data for any array. This will give you a table row and table item for each item. If you have more than just one thing in each node of the array, you will want to target that specifically by doing something like this:\n<td>{item.someProperty}</td>\n\nIn which case, you will want to surround it with a different td and arrange the previous example differently.\n", "There are many solutions posted out there in terms of iterating an array and generating JSX elements. All of them are good, but all of them used an index directly in a loop. We are recommended to use unique id from data as a key, but when we do not have a unique id from each object in the array we will use index as a key, but you are not recommended to use an index as a key directly.\nOne more thing why we go for .map, but why not .foEach because .map returns a new array. There are different ways of doing .map these days.\nBelow different versions of using .map illustrates in detail about how to use a unique key and how to use .map for looping JSX elements.\n.map without return when returning single a JSX element and unique id from data as a key version:\nconst {objects} = this.state;\n\n<tbody>\n {objects.map(object => <ObjectRow obj={object} key={object.id} />)}\n</tbody>\n\n.map without return when returning multiple JSX elements and unique id from data as a key version\nconst {objects} = this.state;\n\n<tbody>\n {objects.map(object => (\n <div key={object.id}>\n <ObjectRow obj={object} />\n </div>\n ))}\n</tbody>\n\n.map without return when returning a single JSX element and index as a key version:\nconst {objects} = this.state;\n\n<tbody>\n {objects.map((object, index) => <ObjectRow obj={object} key={`Key${index}`} />)}\n</tbody>\n\n.map without return when returning multiple JSX elements and index as a key version:\nconst {objects} = this.state;\n\n<tbody>\n {objects.map((object, index) => (\n <div key={`Key${index}`}>\n <ObjectRow obj={object} />\n </div>\n ))}\n</tbody>\n\n.map with return when returning multiple JSX elements and index as a key version:\nconst {objects} = this.state;\n\n<tbody>\n {objects.map((object, index) => {\n return (\n <div key={`Key${index}`}>\n <ObjectRow obj={object} />\n </div>\n )\n })}\n</tbody>\n\n.map with return when returning multiple JSX elements and unique id from data as a key version:\nconst {objects} = this.state;\n\n<tbody>\n {objects.map(object => {\n return (\n <div key={object.id}>\n <ObjectRow obj={object} />\n </div>\n )\n })}\n</tbody>\n\nThe other way is\nrender() {\n const {objects} = this.state;\n const objectItems = objects.map(object => {\n return (\n <div key={object.id}>\n <ObjectRow obj={object} />\n </div>\n )\n })\n return(\n <div>\n <tbody>\n {objectItems}\n </tbody>\n </div>\n )\n}\n\n", "To provide a more straightforward solution in case you want to use a specific row count which is stored as Integer-value.\nWith the help of typedArrays we could achieve the desired solution in the following manner.\n// Let's create a typedArray with length of `numrows`-value\nconst typedArray = new Int8Array(numrows); // typedArray.length is now 2\nconst rows = []; // Prepare rows-array\nfor (let arrKey in typedArray) { // Iterate keys of typedArray\n rows.push(<ObjectRow key={arrKey} />); // Push to an rows-array\n}\n// Return rows\nreturn <tbody>{rows}</tbody>;\n\n", "render() {\n const elements = ['one', 'two', 'three'];\n\n const items = []\n\n for (const [index, value] of elements.entries()) {\n items.push(<li key={index}>{value}</li>)\n }\n\n return (\n <div>\n {items}\n </div>\n )\n}\n\n", "You have to write in JSX:\n<tbody>\n {\n objects.map((object, i) => (\n <ObjectRow obj={object} key={i} />\n ));\n }\n</tbody>\n\n", "<tbody>\n numrows.map((row,index) => (\n return <ObjectRow key={index}/>\n )\n</tbody>\n\n", "Maybe the standard of today maximum developer, use a structure like this:\n let data = [\n {\n id: 1,\n name: \"name1\"\n },\n {\n id: 2,\n name: \"name2\"\n },\n {\n id: 3,\n name: \"name3\"\n },\n {\n id: 100,\n name: \"another name\"\n }\n];\n\nexport const Row = data => {\n return (\n <tr key={data.id}>\n <td>{data.id}</td>\n <td>{data.name}</td>\n </tr>\n );\n};\n\nfunction App() {\n return (\n <table>\n <thead>\n <tr>\n <th>Id</th>\n <th>Name</th>\n </tr>\n </thead>\n <tbody>{data.map(item => Row(item))}</tbody>\n </table>\n );\n}\n\nIn the JSX, write your JavaScript action inside HTML or any code here, {data.map(item => Row(item))}, use single curly braces and inside a map function. Get to know more about map.\nAnd also see the following output here.\n", "There are multiple ways to loop inside JSX\n\nUsing a for loop\nfunction TableBodyForLoop(props) {\n const rows = []; // Create an array to store list of tr\n\n for (let i = 0; i < props.people.length; i++) {\n const person = props.people[i];\n // Push the tr to array, the key is important\n rows.push(\n <tr key={person.id}>\n <td>{person.id}</td>\n <td>{person.name}</td>\n </tr>\n );\n }\n\n // Return the rows inside the tbody\n return <tbody>{rows}</tbody>;\n}\n\n\nUsing the ES6 array map method\nfunction TableBody(props) {\n return (\n <tbody>\n {props.people.map(person => (\n <tr key={person.id}>\n <td>{person.id}</td>\n <td>{person.name}</td>\n </tr>\n ))}\n </tbody>\n );\n}\n\n\n\n\nFull example: https://codesandbox.io/s/cocky-meitner-yztif\nThe following React Docs will be helpful\n\nLists and Keys\nConditional Rendering\n\n", "It's funny how people give \"creative\" answers using a newer syntax or uncommon ways to create an array. In my experience working with JSX, I have seen these tricks only used by inexperienced React programmers.\nThe simpler the solution - the better it is for future maintainers. And since React is a web framework, usually this type of (table) data comes from the API. Therefore, the simplest and most practical way would be:\nconst tableRows = [\n {id: 1, title: 'row1'}, \n {id: 2, title: 'row2'}, \n {id: 3, title: 'row3'}\n]; // Data from the API (domain-driven names would be better of course)\n...\n\nreturn (\n tableRows.map(row => <ObjectRow key={row.id} {...row} />)\n);\n\n\n\n\n", "You can only write a JavaScript expression in a JSX element, so a for loop cannot work. You can convert the element into an array first and use the map function to render it:\n<tbody>\n {[...new Array(numrows)].map((e) => (\n <ObjectRow/>\n ))}\n</tbody>\n\n", "Having the JSX content in the map can be clunky syntax. Instead you can do this:\nconst ObjectRow = ({ ... }) => <tr key={}>...</tr>\n\nconst TableBody = ({ objects }) => {\n return <tbody>{objects.map(ObjectRow)}</tbody>;\n}\n\nThis is shorthand for\n{ objects.map(object => ObjectRow(object))\n\nIf ObjectRow is set up to take the same keys that are in the object, this will work great.\nNote - You may need to set the key prop when the ObjectRow is rendered. It can't be passed in through the function call.\n\nMore notes - I've run into a few places where this technique is a bad idea. For example, it doesn't go through the normal create component path and won't default prop values for example, so do beware. Still, it's handy to know about and is useful sometimes.\n", "use map to looping\n Array.map(arrayItem => {\nreturn <ObjectRow arrayItem={arrayItem}/> // pass array item in component\n})\n\n", "If you want to add some amount of the same React Component of DOM elements this answer is for you\ncreate a Nth length Array (choose length you want) and call method map\nSomeComponent.jsx/.tsx \nNo matter which extension you use in this situation\nimport React from \"react\"\n\nlet length = 10 (for example)\n\nconst SomeComponent = () => ( \n <div>\n {new Array(length).fill(null).map(item => {\n return <ObjectRow/>\n })}\n </div>\n\n)\n\n\n\n", "I have seen one person/previous answer use .concat() in an array, but not like this...\nI have used concat to add to a string and then just render the JSX content on the element via the jQuery selector:\nlet list = \"<div><ul>\";\n\nfor (let i=0; i<myArray.length; i++) {\n list = list.concat(`<li>${myArray[i].valueYouWant}</li>`);\n}\n\nlist = list.concat(\"</ul></div>);\n\n$(\"#myItem\").html(list);\n\n", "const numrows = [1, 2, 3, 4, 5];\n\ncosnt renderRows = () => {\n return numros.map((itm,index) => <td key={index}>{itm}</td>)\n}\n\nreturn <table>\n ............\n <tr>\n {renderRows()}\n </tr>\n</table>\n\n", "Inside your render or any function and before return, you can use a variable to store JSX elements. Just like this -\nconst tbodyContent = [];\nfor (let i=0; i < numrows; i++) {\n tbodyContent.push(<ObjectRow/>);\n}\n\nUse it inside your tbody like this:\n<tbody>\n {\n tbodyContent\n }\n</tbody>\n\nBut I'll prefer map() over this.\n", "function PriceList({ self }) {\n let p = 10000;\n let rows = [];\n for(let i=0; i<p; i=i+50) {\n let r = i + 50;\n rows.push(<Dropdown.Item key={i} onClick={() => self.setState({ searchPrice: `${i}-${r}` })}>{i}-{r} &#8378;</Dropdown.Item>);\n }\n return rows;\n}\n\n<PriceList self={this} />\n\n", "If you are used to Angular and want a more React-like approach:\nTry using this simple component with auto hashing and optional trackBy similar to Angular's.\nUsage:\n<For items={items}>\n {item => <div>item</div>}\n</For>\n\nCustom key/trackBy:\n<For items={items} trackBy={'name'}>\n {item => <div>item</div>}\n</For>\n\nDefinition:\nexport default class For<T> extends Component<{ items: T[], trackBy?: keyof T, children: (item: T) => React.ReactElement }, {}> {\n render() {\n return (\n <Fragment>\n {this.props.items.map((item: any, index) => <Fragment key={this.props.trackBy ?? item.id ?? index}>{this.props.children(item)}</Fragment>)}\n </Fragment>\n );\n }\n}\n\nReact Dev Tools:\n\n", "you can use .map() for loop in reactjs\n <tbody>\n {items.map((value, index) => {\n return <li key={index}>{value}</li>\n })}\n </tbody>\n)\n\n", "A one liner (assuming numrows is a number):\n<tbody>\n {\n Array(numrows).fill().map(function (v, i) {\n return <ObjectRow/>\n })\n }\n</tbody>\n\n", "Simple way\nYou can put numrows in state and use map() instead of a for loop:\n{this.state.numrows.map((numrows , index) => {\n return (\n <ObjectRow\n key={index}\n />\n\n", "Below code will help you to create Loop inside JSX with passing unique key props\nimport React, { Children, Fragment } from 'react';\n\nexport const ObjectRow = ({ data }) => (\n <div>\n <Fragment>{data}</Fragment>\n </div>\n);\n\n\n/** Wrapping your list inside React.Children.toArray allows you to not \npass unique key props.\nIt will be dynamically generated from Virtual Dom to Real Dom */\n\nexport const ObjectRowListComponent = (objectRows) => (\n<tbody>\n {Children.toArray(objectRows.map((row) => <ObjectRow data={row} />))}\n</tbody>\n);\n\n", "You can make array from numRows and map it\nsth like this :\n <tbody>\n {Array.from({ length: numrows }).map((_,i)=><ObjectRow key={i}/>)\n </tbody>\n\n" ]
[ 1663, 1093, 660, 128, 109, 84, 73, 56, 46, 41, 36, 31, 30, 29, 27, 23, 21, 20, 20, 17, 17, 17, 16, 16, 15, 14, 13, 11, 11, 10, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0 ]
[]
[]
[ "javascript", "jsx", "reactjs" ]
stackoverflow_0022876978_javascript_jsx_reactjs.txt
Q: AttributeError: 'Series' object has no attribute 'Mean_μg_L' Why am I getting this error if the column name exists. I have tried everything. I am out of ideas A: Since the AttributeError is raised at the first column with a name containing a mathematical symbol (µ), I would suggest you these two solutions : Use replace right before the loop to get rid of this special character df.columns = df.columns.str.replace("_\wg_", "_ug_", regex=True) #change df to Table_1_1a_Tarawa_Terrace_System_1975_to_1985 Then inside the loop, use row.Mean_ug_L, .. instead of row.Mean_µg_L, .. Use row["col_name"] (highly recommended) to refer to the column rather than row.col_name for index, row in Table_1_1a_Tarawa_Terrace_System_1975_to_1985.iterrows(): SQL_VALUES_Tarawa = (row["Chemicals"], rows["Contamminant"], row["Mean_µg_L"], row["Median_µg_L"], row["Range_µg_L"], row["Num_Months_Greater_MCL"], row["Num_Months_Greater_100_µg_L"]) cursor.execute(SQL_insert_Tarawa, SQL_VALUES_Tarawa) counting = cursor.rowcount print(counting, "Record added") conn.commit()
AttributeError: 'Series' object has no attribute 'Mean_μg_L'
Why am I getting this error if the column name exists. I have tried everything. I am out of ideas
[ "Since the AttributeError is raised at the first column with a name containing a mathematical symbol (µ), I would suggest you these two solutions :\n\nUse replace right before the loop to get rid of this special character\ndf.columns = df.columns.str.replace(\"_\\wg_\", \"_ug_\", regex=True)\n#change df to Table_1_1a_Tarawa_Terrace_System_1975_to_1985\n\n\n\nThen inside the loop, use row.Mean_ug_L, .. instead of row.Mean_µg_L, ..\n\nUse row[\"col_name\"] (highly recommended) to refer to the column rather than row.col_name\n for index, row in Table_1_1a_Tarawa_Terrace_System_1975_to_1985.iterrows():\n SQL_VALUES_Tarawa = (row[\"Chemicals\"], rows[\"Contamminant\"], row[\"Mean_µg_L\"], row[\"Median_µg_L\"], row[\"Range_µg_L\"], row[\"Num_Months_Greater_MCL\"], row[\"Num_Months_Greater_100_µg_L\"])\n cursor.execute(SQL_insert_Tarawa, SQL_VALUES_Tarawa)\n counting = cursor.rowcount\n print(counting, \"Record added\")\n conn.commit()\n\n\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "sqlite" ]
stackoverflow_0074673550_dataframe_pandas_python_sqlite.txt
Q: delete records from mongodb collection after skip by beanie ODM I want to delete some records after sort and skip items but this query always delete all records after find.as if sort and skip don't do anything': await Book.find(Book.owner.id == user.id).sort("-created_at").skip(2).delete() A: To achieve the target you can first fetch the docs by applying a skip function & then use deleteMany function. Note: You can also use sort({_id:-1}) to sort the docs. See the Example code below- const data = await Book.find(pass-your-query-here).sort({_id:-1}).skip(2); if(data.length>0){ const ress = await Book.deleteMany({ _id: {$lte: data[0]._id } }); } A: We can delete the items by beanie functionality like this: from app.models.book_model import Book from beanie.operators import In books= await Book.find(Book.owner.id == user.id).sort("-created_at").skip(2).to_list() books_del= Book.find(In(Book.id, [_.id for _ in books])) await books_del.delete()
delete records from mongodb collection after skip by beanie ODM
I want to delete some records after sort and skip items but this query always delete all records after find.as if sort and skip don't do anything': await Book.find(Book.owner.id == user.id).sort("-created_at").skip(2).delete()
[ "To achieve the target you can first fetch the docs by applying a skip function & then use deleteMany function.\nNote: You can also use sort({_id:-1}) to sort the docs.\nSee the Example code below-\n\n\nconst data = await Book.find(pass-your-query-here).sort({_id:-1}).skip(2);\n if(data.length>0){\n const ress = await Book.deleteMany({ _id: {$lte: data[0]._id } });\n }\n\n\n\n", "We can delete the items by beanie functionality like this:\nfrom app.models.book_model import Book\nfrom beanie.operators import In\n\nbooks= await Book.find(Book.owner.id == user.id).sort(\"-created_at\").skip(2).to_list()\n\nbooks_del= Book.find(In(Book.id, [_.id for _ in books]))\nawait books_del.delete()\n\n" ]
[ 0, 0 ]
[]
[]
[ "fastapi", "mongodb", "pydantic" ]
stackoverflow_0074667361_fastapi_mongodb_pydantic.txt
Q: PyCharm doesn't recognize installed module I'm having trouble with using 'requests' module on my Mac. I use python34 and I installed 'requests' module via pip. I can verify this via running installation again and it'll show me that module is already installed. 15:49:29|mymac [~]:pip install requests Requirement already satisfied (use --upgrade to upgrade): requests in /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages Although I can import 'requests' module via interactive Python interpreter, trying to execute 'import requests' in PyCharm yields error 'No module named requests'. I checked my PyCharm Python interpreter settings and (I believe) it's set to same python34 as used in my environment. However, I can't see 'requests' module listed in PyCharm either. It's obvious that I'm missing something here. Can you guys advise where should I look or what should I fix in order to get this module working? I was living under impression that when I install module via pip in my environment, PyCharm will detect these changes. However, it seems something is broken on my side ... A: If you are using PyCharms CE (Community Edition), then click on: File->Default Settings->Project Interpretor See the + sign at the bottom, click on it. It will open another dialog with a host of modules available. Select your package (e.g. requests) and PyCharm will do the rest. MD A: In my case, using a pre-existing virtualenv did not work in the editor - all modules were marked as unresolved reference (running naturally works, as this is outside of the editor's config, just running an external process (not so easy for debugging)). Turns out PyCharm did not add the site-packages directory... the fix is to manually add it. Open File -> Settings -> Project Interpreter, pick "Show All..." (to edit the config) (1), pick your interpreter (2), and click "Show paths of selected interpreter" (3). In that screen, manually add the "site-packages" directory of the virtual environment (4) (I've added the "Lib" also, for a good measure); once done and saved, they will turn up in the interpreter paths. The other thing that won't hurt to do is select "Associate this virtual environment with the current project", in the interpreter's edit box. A: This issue arises when the package you're using was installed outside of the environment (Anaconda or virtualenv, for example). In order to have PyCharm recognize packages installed outside of your particular environment, execute the following steps: Go to Preferences -> Project -> Project Interpreter -> 3 dots -> Show All -> Select relevant interpreter -> click on tree icon Show paths for the selected interpreter Now check what paths are available and add the path that points to the package installation directory outside of your environment to the interpreter paths. To find a package location use: $ pip show gym Name: gym Version: 0.13.0 Summary: The OpenAI Gym: A toolkit for developing and comparing your reinforcement learning agents. Home-page: https://github.com/openai/gym Author: OpenAI Author-email: [email protected] License: UNKNOWN Location: /usr/local/lib/python3.7/site-packages ... Add the path specified under Location to the interpreter paths, here /usr/local/lib/python3.7/site-packages Then, let indexing finish and perhaps additionally reopen your project. A: Open python console of your pyCharm. Click on Rerun. It will say something like following on the very first line /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py 52631 52632 in this scenario pyCharm is using following interpretor /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 Now fire up console and run following command sudo /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 -m pip install <name of the package> This should install your package :) A: Pycharm is unable to recognize installed local modules, since python interpreter selected is wrong. It should be the one, where your pip packages are installed i.e. virtual environment. I had installed packages via pip in Windows. In Pycharm, they were neither detected nor any other Python interpreter was being shown (only python 3.6 is installed on my system). I restarted the IDE. Now I was able to see python interpreter created in my virtual environment. Select that python interpreter and all your packages will be shown and detected. Enjoy! A: Using dual python 2.7 and 3.4 with 2.7 as default, I've always used pip3 to install modules for the 3.4 interpreter, and pip to install modules for the 2.7 interpreter. Try this: pip3 install requests A: This is because you have not selected two options while creating your project:- ** inherit global site packages ** make available to all projects Now you need to create a new project and don't forget to tick these two options while selecting project interpreter. A: The solution is easy (PyCharm 2021.2.3 Community Edition). I'm on Windows but the user interface should be the same. In the project tree, open External libraries > Python interpreter > venv > pyvenv.cfg. Then change: include-system-site-packages = false to: include-system-site-packages = true A: If you go to pycharm project interpreter -> clicked on one of the installed packages then hover -> you will see where pycharm is installing the packages. This is where you are supposed to have your package installed. Now if you did sudo -H pip3 install <package> pip3 installs it to different directory which is /usr/local/lib/site-packages since it is different directory from what pycharm knows hence your package is not showing in pycharm. Solution: just install the package using pycharm by going to File->Settings->Project->Project Interpreter -> click on (+) and search the package you want to install and just click ok. -> you will be prompted package successfully installed and you will see it pycharm. A: Before going further, I want to point out how to configure a Python interpreter in PyCharm: [SO]: How to install Python using the "embeddable zip file" (@CristiFati's answer). Although the question is for Win, and has some particularities, configuring PyCharm is generic enough and should apply to any situation (with minor changes). There are multiple possible reasons for this behavior. 1. Python instance mismatch Happens when there are multiple Python instances (installed, VEnvs, Conda, custom built, ...) on a machine. Users think they're using one particular instance (with a set of properties (installed packages)), but in fact they are using another (with different properties), hence the confusion. It's harder to figure out things when the 2 instances have the same version (and somehow similar locations) Happens mostly due to environmental configuration (whichever path comes 1st in ${PATH}, aliases (on Nix), ...) It's not PyCharm specific (meaning that it's more generic, also happens outside it), but a typical PyCharm related example is different console interpreter and project interpreter, leading to confusion The fix is to specify full paths (and pay attention to them) when using tools like Python, PIP, .... Check [SO]: How to install a package for a specific Python version on Windows 10? (@CristiFati's answer) for more details This is precisely the reason why this question exists. There are 2 Python versions involved: Project interpreter: /Library/Frameworks/Python.framework/Versions/3.4 Interpreter having the Requests module: /opt/local/Library/Frameworks/Python.framework/Versions/3.4 well, assuming the 2 paths are not somehow related (SymLinked), but in latest OSX versions that I had the chance to check (Catalina, Big Sur, Monterey) this doesn't happen (by default) 2. Python's module search mechanism misunderstanding According to [Python.Docs]: Modules - The Module Search Path: When a module named spam is imported, the interpreter first searches for a built-in module with that name. These module names are listed in sys.builtin_module_names. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations: The directory containing the input script (or the current directory when no file is specified). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). The installation-dependent default (by convention including a site-packages directory, handled by the site module). A module might be located in the current dir, or its path might be added to ${PYTHONPATH}. That could trick users into making them believe that the module is actually installed in the current Python instance ('s site-packages). But, when running the current Python instance from a different dir (or with different ${PYTHONPATH}) the module would be missing, yielding lots of headaches For a fix, check [SO]: How PyCharm imports differently than system command prompt (Windows) (@CristiFati's answer) 3. A PyCharm bug Not very likely, but it could happen. An example (not related to this question): [SO]: PyCharm 2019.2 not showing Traceback on Exception (@CristiFati's answer) To fix, follow one of the options from the above URL 4. A glitch Not likely, but mentioning anyway. Due to some cause (e.g.: HW / SW failure), the system ended up in an inconsistent state, yielding all kinds of strange behaviors Possible fixes: Restart PyCharm Restart the machine Recreate the project (remove the .idea dir from the project) Reset PyCharm settings: from menu select File -> Manage IDE Settings -> Restore Default Settings.... Check [JetBrains]: Configuring PyCharm settings or [JetBrains.IntelliJ-Support]: Changing IDE default directories used for config, plugins, and caches storage for more details Reinstall PyCharm Needless to say that the last 2 options should only be attempted as a last resort, and only by experts, as they might mess up other projects and not even fix the problem Not quite related to the question, but posting a PyCharm related investigation from a while ago: [SO]: Run / Debug a Django application's UnitTests from the mouse right click context menu in PyCharm Community Edition?. A: This did my head in as well, and turns out, the only thing I needed to do is RESTART Pycharm. Sometimes after you've installed the pip, you can't load it into your project, even if the pip shows as installed in your Settings. Bummer. A: I got this issue when I created the project using Virtualenv. Solution suggested by Neeraj Aggarwal worked for me. However, if you do not want to create a new project then the following can resolve the issue. Close the project Find the file <Your Project Folder>/venv/pyvenv.cfg Open this file with any text editor Set the include-system-site-packages = true Save it Open the project A: For Anaconda: Start Anaconda Navigator -> Enviroments -> "Your_Enviroment" -> Update Index -> Restart IDE. Solved it for me. A: If any one faces the same problem that he/she installs the python packages but the PyCharm IDE doesn't shows these packages then following the following steps: Go to the project in the left side of the PyCharm IDE then Click on the venv library then Open the pyvenv.cfg file in any editor then Change this piece of code (include-system-site-packages = flase) from false to true Then save it and close it and also close then pycharm then Open PyCharm again and your problem is solved. Thanks A: After pip installing everything I needed. I went to the interpreter and re-pointed it back to where it was at already. My case: python3.6 in /anaconda3/bin/python using virtualenv... Additionally, before I hit the plus "+" sign to install a new package. I had to deselect the conda icon to the right of it. Seems like it would be the opposite, but only then did it recognize the packages I had/needed via query. A: In my case the packages were installed via setup.py + easy_install, and the they ends up in *.egg directories in site_package dir, which can be recognized by python but not pycharm. I removed them all then reinstalled with pip install and it works after that, luckily the project I was working on came up with a requirements.txt file, so the command for it was: pip install -r ./requirement.txt A: On windows I had to cd into the venv folder and then cd into the scripts folder, then pip install module started to work cd venv cd scripts pip install module A: I just ran into this issue in a brand new install/project, but I'm using the Python plugin for IntelliJ IDEA. It's essentially the same as PyCharm but the project settings are a little different. For me, the project was pointing to the right Python virtual environment but not even built-in modules were being recognized. It turns out the SDK classpath was empty. I added paths for venv/lib/python3.8 and venv/lib/python3.8/site-packages and the issue was resolved. File->Project Structure and under Platform Settings, click SDKs, select your Python SDK, and make sure the class paths are there. A: pip install --user discord above command solves my problem, just use the "--user" flag A: I fixed my particular issue by installing directly to the interpreter. Go to settings and hit the "+" below the in-use interpreter then search for the package and install. I believe I'm having the issue in the first place because I didn't set up with my interpreter correctly with my venv (not exactly sure, but this fixed it). I was having issues with djangorestframework-simplejwt because it was the first package I hadn't installed to this interpreter from previous projects before starting the current one, but should work for any other package that isn't showing as imported. To reiterate though I think this is a workaround that doesn't solve the setup issue causing this. A: instead of running pip install in the terminal -> local use terminal -> command prompt see below image pycharm_command_prompt_image A: If you are having issues with the underlying (i.e. pycharm's languge server) mark everything as root and create a new project. See details: https://stackoverflow.com/a/73418320/1601580 this seems to happy to me only when I install packages as in editable mode with pip (i.e. pip install -e . or conda develop). Details: https://stackoverflow.com/a/73418320/1601580 A: --WINDOWS-- if using Pycharm GUI package installer works fine for installing packages for your virtual environment but you cannot do the same in the terminal, this is because you did not setup virtual env in your terminal, instead, your terminal uses Power Shell which doesn't use your virtual env there should be (venv) before you're command line as shown instead of (PS) if you have (PS), this means your terminal is using Power Shell instead of cmd to fix this, click on the down arrow and select the command prompt select command prompt now you will get (venv) and just type pip install #package name# and the package will be added to your virtual environment A: i just use the terminal option for output then it works. terminal allows to run python interpreter directly from pycharm platform
PyCharm doesn't recognize installed module
I'm having trouble with using 'requests' module on my Mac. I use python34 and I installed 'requests' module via pip. I can verify this via running installation again and it'll show me that module is already installed. 15:49:29|mymac [~]:pip install requests Requirement already satisfied (use --upgrade to upgrade): requests in /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages Although I can import 'requests' module via interactive Python interpreter, trying to execute 'import requests' in PyCharm yields error 'No module named requests'. I checked my PyCharm Python interpreter settings and (I believe) it's set to same python34 as used in my environment. However, I can't see 'requests' module listed in PyCharm either. It's obvious that I'm missing something here. Can you guys advise where should I look or what should I fix in order to get this module working? I was living under impression that when I install module via pip in my environment, PyCharm will detect these changes. However, it seems something is broken on my side ...
[ "If you are using PyCharms CE (Community Edition), then click on:\nFile->Default Settings->Project Interpretor\n\nSee the + sign at the bottom, click on it. It will open another dialog with a host of modules available. Select your package (e.g. requests) and PyCharm will do the rest.\nMD\n", "In my case, using a pre-existing virtualenv did not work in the editor - all modules were marked as unresolved reference (running naturally works, as this is outside of the editor's config, just running an external process (not so easy for debugging)).\nTurns out PyCharm did not add the site-packages directory... the fix is to manually add it.\nOpen File -> Settings -> Project Interpreter, pick \"Show All...\" (to edit the config) (1), pick your interpreter (2), and click \"Show paths of selected interpreter\" (3).\nIn that screen, manually add the \"site-packages\" directory of the virtual environment (4) (I've added the \"Lib\" also, for a good measure); once done and saved, they will turn up in the interpreter paths.\n\nThe other thing that won't hurt to do is select \"Associate this virtual environment with the current project\", in the interpreter's edit box.\n", "This issue arises when the package you're using was installed outside of the environment (Anaconda or virtualenv, for example). In order to have PyCharm recognize packages installed outside of your particular environment, execute the following steps:\nGo to\nPreferences -> Project -> Project Interpreter -> 3 dots -> Show All ->\nSelect relevant interpreter -> click on tree icon Show paths for the selected interpreter\nNow check what paths are available and add the path that points to the package installation directory outside of your environment to the interpreter paths.\nTo find a package location use:\n$ pip show gym\nName: gym\nVersion: 0.13.0\nSummary: The OpenAI Gym: A toolkit for developing and comparing your reinforcement learning agents.\nHome-page: https://github.com/openai/gym\nAuthor: OpenAI\nAuthor-email: [email protected]\nLicense: UNKNOWN\nLocation: /usr/local/lib/python3.7/site-packages\n...\n\nAdd the path specified under Location to the interpreter paths, here\n\n/usr/local/lib/python3.7/site-packages\n\nThen, let indexing finish and perhaps additionally reopen your project.\n", "Open python console of your pyCharm. Click on Rerun.\n It will say something like following on the very first line\n/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py 52631 52632\n\nin this scenario pyCharm is using following interpretor\n/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 \n\nNow fire up console and run following command\nsudo /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 -m pip install <name of the package>\n\nThis should install your package :)\n", "Pycharm is unable to recognize installed local modules, since python interpreter selected is wrong. It should be the one, where your pip packages are installed i.e. virtual environment.\nI had installed packages via pip in Windows. In Pycharm, they were neither detected nor any other Python interpreter was being shown (only python 3.6 is installed on my system).\n\nI restarted the IDE. Now I was able to see python interpreter created in my virtual environment. Select that python interpreter and all your packages will be shown and detected. Enjoy!\n\n", "Using dual python 2.7 and 3.4 with 2.7 as default, I've always used pip3 to install modules for the 3.4 interpreter, and pip to install modules for the 2.7 interpreter.\nTry this:\npip3 install requests\n", "This is because you have not selected two options while creating your project:-\n** inherit global site packages\n** make available to all projects\nNow you need to create a new project and don't forget to tick these two options while selecting project interpreter.\n", "The solution is easy (PyCharm 2021.2.3 Community Edition).\nI'm on Windows but the user interface should be the same.\nIn the project tree, open External libraries > Python interpreter > venv > pyvenv.cfg.\nThen change:\ninclude-system-site-packages = false\n\nto:\ninclude-system-site-packages = true\n\n\n", "\nIf you go to pycharm project interpreter -> clicked on one of the installed packages then hover -> you will see where pycharm is installing the packages. This is where you are supposed to have your package installed.\nNow if you did sudo -H pip3 install <package>\npip3 installs it to different directory which is /usr/local/lib/site-packages\n\nsince it is different directory from what pycharm knows hence your package is not showing in pycharm.\nSolution: just install the package using pycharm by going to File->Settings->Project->Project Interpreter -> click on (+) and search the package you want to install and just click ok.\n-> you will be prompted package successfully installed and you will see it pycharm.\n", "Before going further, I want to point out how to configure a Python interpreter in PyCharm: [SO]: How to install Python using the \"embeddable zip file\" (@CristiFati's answer). Although the question is for Win, and has some particularities, configuring PyCharm is generic enough and should apply to any situation (with minor changes).\nThere are multiple possible reasons for this behavior.\n1. Python instance mismatch\n\nHappens when there are multiple Python instances (installed, VEnvs, Conda, custom built, ...) on a machine. Users think they're using one particular instance (with a set of properties (installed packages)), but in fact they are using another (with different properties), hence the confusion. It's harder to figure out things when the 2 instances have the same version (and somehow similar locations)\n\nHappens mostly due to environmental configuration (whichever path comes 1st in ${PATH}, aliases (on Nix), ...)\n\nIt's not PyCharm specific (meaning that it's more generic, also happens outside it), but a typical PyCharm related example is different console interpreter and project interpreter, leading to confusion\n\nThe fix is to specify full paths (and pay attention to them) when using tools like Python, PIP, .... Check [SO]: How to install a package for a specific Python version on Windows 10? (@CristiFati's answer) for more details\n\nThis is precisely the reason why this question exists. There are 2 Python versions involved:\n\nProject interpreter: /Library/Frameworks/Python.framework/Versions/3.4\n\nInterpreter having the Requests module: /opt/local/Library/Frameworks/Python.framework/Versions/3.4\n\n\nwell, assuming the 2 paths are not somehow related (SymLinked), but in latest OSX versions that I had the chance to check (Catalina, Big Sur, Monterey) this doesn't happen (by default)\n\n\n2. Python's module search mechanism misunderstanding\n\nAccording to [Python.Docs]: Modules - The Module Search Path:\n\nWhen a module named spam is imported, the interpreter first searches for a built-in module with that name. These module names are listed in sys.builtin_module_names. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:\n\nThe directory containing the input script (or the current directory when no file is specified).\n\nPYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).\n\nThe installation-dependent default (by convention including a site-packages directory, handled by the site module).\n\n\n\nA module might be located in the current dir, or its path might be added to ${PYTHONPATH}. That could trick users into making them believe that the module is actually installed in the current Python instance ('s site-packages). But, when running the current Python instance from a different dir (or with different ${PYTHONPATH}) the module would be missing, yielding lots of headaches\n\nFor a fix, check [SO]: How PyCharm imports differently than system command prompt (Windows) (@CristiFati's answer)\n\n\n3. A PyCharm bug\n\nNot very likely, but it could happen. An example (not related to this question): [SO]: PyCharm 2019.2 not showing Traceback on Exception (@CristiFati's answer)\n\nTo fix, follow one of the options from the above URL\n\n\n4. A glitch\n\nNot likely, but mentioning anyway. Due to some cause (e.g.: HW / SW failure), the system ended up in an inconsistent state, yielding all kinds of strange behaviors\n\nPossible fixes:\n\nRestart PyCharm\n\nRestart the machine\n\nRecreate the project (remove the .idea dir from the project)\n\nReset PyCharm settings: from menu select File -> Manage IDE Settings -> Restore Default Settings.... Check [JetBrains]: Configuring PyCharm settings or [JetBrains.IntelliJ-Support]: Changing IDE default directories used for config, plugins, and caches storage for more details\n\nReinstall PyCharm\n\n\nNeedless to say that the last 2 options should only be attempted as a last resort, and only by experts, as they might mess up other projects and not even fix the problem\n\n\nNot quite related to the question, but posting a PyCharm related investigation from a while ago: [SO]: Run / Debug a Django application's UnitTests from the mouse right click context menu in PyCharm Community Edition?.\n", "This did my head in as well, and turns out, the only thing I needed to do is RESTART Pycharm. Sometimes after you've installed the pip, you can't load it into your project, even if the pip shows as installed in your Settings. Bummer.\n", "I got this issue when I created the project using Virtualenv.\nSolution suggested by Neeraj Aggarwal worked for me. However, if you do not want to create a new project then the following can resolve the issue.\n\nClose the project\nFind the file <Your Project Folder>/venv/pyvenv.cfg\nOpen this file with any text editor\nSet the include-system-site-packages = true\nSave it\nOpen the project\n\n", "For Anaconda:\nStart Anaconda Navigator -> Enviroments -> \"Your_Enviroment\" -> Update Index -> Restart IDE.\nSolved it for me.\n", "If any one faces the same problem that he/she installs the python packages but the PyCharm IDE doesn't shows these packages then following the following steps:\n\nGo to the project in the left side of the PyCharm IDE then\nClick on the venv library then\nOpen the pyvenv.cfg file in any editor then\nChange this piece of code (include-system-site-packages = flase) from false to true\nThen save it and close it and also close then pycharm then\nOpen PyCharm again and your problem is solved.\nThanks\n\n", "After pip installing everything I needed. I went to the interpreter and re-pointed it back to where it was at already. \n My case: python3.6 in /anaconda3/bin/python using virtualenv...\nAdditionally, before I hit the plus \"+\" sign to install a new package. I had to deselect the conda icon to the right of it. Seems like it would be the opposite, but only then did it recognize the packages I had/needed via query.\n", "In my case the packages were installed via setup.py + easy_install, and the they ends up in *.egg directories in site_package dir, which can be recognized by python but not pycharm.\nI removed them all then reinstalled with pip install and it works after that, luckily the project I was working on came up with a requirements.txt file, so the command for it was: \npip install -r ./requirement.txt\n", "On windows I had to cd into the venv folder and then cd into the scripts folder, then pip install module started to work\ncd venv\ncd scripts\npip install module\n\n", "I just ran into this issue in a brand new install/project, but I'm using the Python plugin for IntelliJ IDEA. It's essentially the same as PyCharm but the project settings are a little different. For me, the project was pointing to the right Python virtual environment but not even built-in modules were being recognized.\nIt turns out the SDK classpath was empty. I added paths for venv/lib/python3.8 and venv/lib/python3.8/site-packages and the issue was resolved. File->Project Structure and under Platform Settings, click SDKs, select your Python SDK, and make sure the class paths are there. \n\n", "pip install --user discord\n\nabove command solves my problem, just use the \"--user\" flag\n", "I fixed my particular issue by installing directly to the interpreter. Go to settings and hit the \"+\" below the in-use interpreter then search for the package and install. I believe I'm having the issue in the first place because I didn't set up with my interpreter correctly with my venv (not exactly sure, but this fixed it).\nI was having issues with djangorestframework-simplejwt because it was the first package I hadn't installed to this interpreter from previous projects before starting the current one, but should work for any other package that isn't showing as imported. To reiterate though I think this is a workaround that doesn't solve the setup issue causing this.\n\n", "instead of running pip install in the terminal -> local use terminal -> command prompt\nsee below image\npycharm_command_prompt_image\n\n", "If you are having issues with the underlying (i.e. pycharm's languge server) mark everything as root and create a new project. See details: https://stackoverflow.com/a/73418320/1601580 this seems to happy to me only when I install packages as in editable mode with pip (i.e. pip install -e . or conda develop). Details: https://stackoverflow.com/a/73418320/1601580\n", "--WINDOWS--\nif using Pycharm GUI package installer works fine for installing packages for your virtual environment but you cannot do the same in the terminal,\nthis is because you did not setup virtual env in your terminal, instead, your terminal uses Power Shell which doesn't use your virtual env\nthere should be (venv) before you're command line as shown instead of (PS) \nif you have (PS), this means your terminal is using Power Shell instead of cmd\nto fix this, click on the down arrow and select the command prompt\nselect command prompt\nnow you will get (venv) and just type pip install #package name# and the package will be added to your virtual environment\n", "i just use the terminal option for output then it works. terminal allows to run python interpreter directly from pycharm platform\n" ]
[ 43, 42, 12, 11, 8, 7, 6, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "In your pycharm terminal run pip/pip3 install package_name\n" ]
[ -2 ]
[ "anaconda", "pip", "pycharm", "python", "virtualenv" ]
stackoverflow_0031235376_anaconda_pip_pycharm_python_virtualenv.txt
Q: how to get file name of the upload file using form type is ModelForm directly from models.Models I've been trying to find a solution for a while now, but I still haven't found anything that could help me, so if one of you has any idea how to solve my problem, I would be really thankful. I am new to Django (total beginner), I provided my code below. models.py class Video(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to="video/%y/%m") upload = models.DateTimeField(auto_now_add=True) def str(self): return self.title +'@' +str(self.upload) form.py class VideoForm(ModelForm): class Meta: model = Video fields = ['video'] views.py def upload(request): vidform = VideoForm() if request.method == 'POST': vidform = VideoForm(request.POST, request.FILES) if vidform.is_valid(): name = request.FILES['file'].name print(name) Video().save else: vidform = VideoForm() return render (request, 'base/home.html') context = {'vidform':vidform,} return render (request, 'base/upload.html',context) When I try to upload a file Django returns... Exception Type: MultiValueDictKeyError Exception Value:'file' how can I get the uploaded file name and assign to the title the video title is needed to store on the database A: Here I tried to solve your problem. models.py from django.db import models class Video(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to="video/%y/%m") upload = models.DateTimeField(auto_now_add=True) def str(self): return self.title +'@' +str(self.upload) form.py from django import forms from myapp.models import Video class VideoForm(forms.ModelForm): class Meta: model = Video fields = ['video'] HTML Code {% block body %} <div class="container"> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit">Add</button> </form> </div> {% endblock body %} views.py def InsertData(request): form = VideoForm() if request.method == 'POST': form = VideoForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data['video'] print(name) form.save() context= {'form':form} return render(request,'home.html',context) Output in terminal (I saved a file whose name has Animation.gif) In Admin Panel
how to get file name of the upload file using form type is ModelForm directly from models.Models
I've been trying to find a solution for a while now, but I still haven't found anything that could help me, so if one of you has any idea how to solve my problem, I would be really thankful. I am new to Django (total beginner), I provided my code below. models.py class Video(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to="video/%y/%m") upload = models.DateTimeField(auto_now_add=True) def str(self): return self.title +'@' +str(self.upload) form.py class VideoForm(ModelForm): class Meta: model = Video fields = ['video'] views.py def upload(request): vidform = VideoForm() if request.method == 'POST': vidform = VideoForm(request.POST, request.FILES) if vidform.is_valid(): name = request.FILES['file'].name print(name) Video().save else: vidform = VideoForm() return render (request, 'base/home.html') context = {'vidform':vidform,} return render (request, 'base/upload.html',context) When I try to upload a file Django returns... Exception Type: MultiValueDictKeyError Exception Value:'file' how can I get the uploaded file name and assign to the title the video title is needed to store on the database
[ "Here I tried to solve your problem.\nmodels.py\nfrom django.db import models\n\nclass Video(models.Model):\n title = models.CharField(max_length=100)\n video = models.FileField(upload_to=\"video/%y/%m\")\n upload = models.DateTimeField(auto_now_add=True)\n\n def str(self):\n return self.title +'@' +str(self.upload)\n\nform.py\nfrom django import forms\nfrom myapp.models import Video\n\nclass VideoForm(forms.ModelForm):\n class Meta: \n model = Video \n fields = ['video']\n\nHTML Code\n{% block body %}\n <div class=\"container\">\n <form action=\"\" method=\"POST\" enctype=\"multipart/form-data\">\n {% csrf_token %}\n {{form.as_p}}\n <button type=\"submit\">Add</button>\n </form>\n </div>\n{% endblock body %}\n\nviews.py\ndef InsertData(request):\n form = VideoForm() \n if request.method == 'POST': \n form = VideoForm(request.POST, request.FILES) \n if form.is_valid(): \n name = form.cleaned_data['video'] \n print(name)\n form.save()\n context= {'form':form}\n return render(request,'home.html',context)\n\nOutput in terminal (I saved a file whose name has Animation.gif)\n\nIn Admin Panel\n\n" ]
[ 0 ]
[]
[]
[ "django_forms", "django_models", "django_views" ]
stackoverflow_0074669905_django_forms_django_models_django_views.txt
Q: metric-server : TLS handshake error from 20.99.219.64:57467: EOF I have deployed metric server using : kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.3.6/components.yaml Metric server pod is running but in logs I am getting error : I0601 20:00:01.321004 1 log.go:172] http: TLS handshake error from 20.99.219.64:34903: EOF I0601 20:00:01.321160 1 log.go:172] http: TLS handshake error from 20.99.219.64:22575: EOF I0601 20:00:01.332318 1 log.go:172] http: TLS handshake error from 20.99.219.64:14603: EOF I0601 20:00:01.333174 1 log.go:172] http: TLS handshake error from 20.99.219.64:22517: EOF I0601 20:00:01.351649 1 log.go:172] http: TLS handshake error from 20.99.219.64:3598: EOF IP : 20.99.219.64 This is not present in Cluster. I have checked using : kubectl get all --all-namespaces -o wide | grep "20.99.219.64" Nothing is coming as O/P. I have using Calico and initialize the cluster with --pod-network-cidr=20.96.0.0/12 Also kubectl top nodes is not working, Getting error : node@kubemaster:~/Desktop/dashboard$ kubectl top nodes Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io) A: During deployment of metrics-server remember to add following line in args section: - args: - --kubelet-insecure-tls - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname Also add the following line at the spec:spec level outside of the previous containers level: hostNetwork: true restartPolicy: Always Remember to apply changes. Metrics-server attempts to authorize itself using token authentication. Please ensure that you're running your kubelets with webhook token authentication turned on. Speaking about TLS directly. TLS message is big packet and MTU in calico is wrong so change it according calico-project-mtu. Execute command: $ kubectl edit configmap calico-config -n kube-system and change the MTU value from 1500 to 1430. Take a look: metrics-server-mtu. A: I also met the this problem that I can't make metrics-server to work in my k8s cluster (kubectl version is 1.25.4). I follow the instructions above and solve the issue! I downloaded the components.yaml file and only add the - --kubelet-insecure-tls in the args of deployment. Then I got the metrics-server work!
metric-server : TLS handshake error from 20.99.219.64:57467: EOF
I have deployed metric server using : kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.3.6/components.yaml Metric server pod is running but in logs I am getting error : I0601 20:00:01.321004 1 log.go:172] http: TLS handshake error from 20.99.219.64:34903: EOF I0601 20:00:01.321160 1 log.go:172] http: TLS handshake error from 20.99.219.64:22575: EOF I0601 20:00:01.332318 1 log.go:172] http: TLS handshake error from 20.99.219.64:14603: EOF I0601 20:00:01.333174 1 log.go:172] http: TLS handshake error from 20.99.219.64:22517: EOF I0601 20:00:01.351649 1 log.go:172] http: TLS handshake error from 20.99.219.64:3598: EOF IP : 20.99.219.64 This is not present in Cluster. I have checked using : kubectl get all --all-namespaces -o wide | grep "20.99.219.64" Nothing is coming as O/P. I have using Calico and initialize the cluster with --pod-network-cidr=20.96.0.0/12 Also kubectl top nodes is not working, Getting error : node@kubemaster:~/Desktop/dashboard$ kubectl top nodes Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io)
[ "During deployment of metrics-server remember to add following line in args section:\n - args:\n - --kubelet-insecure-tls\n - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname\n\nAlso add the following line at the spec:spec level outside of the previous containers level:\n hostNetwork: true\n restartPolicy: Always\n\nRemember to apply changes. \nMetrics-server attempts to authorize itself using token authentication. Please ensure that you're running your kubelets with webhook token authentication turned on.\nSpeaking about TLS directly. TLS message is big packet and MTU in calico is wrong so change it according calico-project-mtu. \nExecute command:\n$ kubectl edit configmap calico-config -n kube-system and change the MTU value from 1500 to 1430.\nTake a look: metrics-server-mtu.\n", "I also met the this problem that I can't make metrics-server to work in my k8s cluster (kubectl version is 1.25.4). I follow the instructions above and solve the issue!\nI downloaded the components.yaml file and only add the - --kubelet-insecure-tls in the args of deployment. Then I got the metrics-server work!\n" ]
[ 0, 0 ]
[]
[]
[ "kubernetes" ]
stackoverflow_0062140119_kubernetes.txt
Q: Metaplex-master on github only has Readme file I am trying to set up a Solana candy machine. I am using the Hasplips Metaplex-master but it only has one readme file. Its supposed to have a js folder, some .JSON files and more. Can any send me a link to the correct Metaplex-master for the candy machine? I can only find the Metaplex contain a readme file. When I extracted the files all I found was a read me file. I created a js folder myself and tried to run some yarn commands in the Visual Studio code terminal but I need the other .json files that were supposed to be there to execute the commands. A: You are using a very old guide. The js sdk has been deprecated and removed from that repo for months now. It is way easier to create a candy machine with sugar, e.g. following this guide https://docs.metaplex.com/programs/candy-machine/how-to-guides/my-first-candy-machine-part1
Metaplex-master on github only has Readme file
I am trying to set up a Solana candy machine. I am using the Hasplips Metaplex-master but it only has one readme file. Its supposed to have a js folder, some .JSON files and more. Can any send me a link to the correct Metaplex-master for the candy machine? I can only find the Metaplex contain a readme file. When I extracted the files all I found was a read me file. I created a js folder myself and tried to run some yarn commands in the Visual Studio code terminal but I need the other .json files that were supposed to be there to execute the commands.
[ "You are using a very old guide. The js sdk has been deprecated and removed from that repo for months now.\nIt is way easier to create a candy machine with sugar, e.g. following this guide https://docs.metaplex.com/programs/candy-machine/how-to-guides/my-first-candy-machine-part1\n" ]
[ 1 ]
[]
[]
[ "candy_machine", "hadoop_yarn", "metaplex", "solana" ]
stackoverflow_0074672384_candy_machine_hadoop_yarn_metaplex_solana.txt
Q: SIMCOM A7600E, can't make voice call but sms works If I connect this sim module to laptop via USB, I can send and receive SMS-messages. But voice call doesn't work, it gives NO CARRIER, VOICE CALL: END I've tried connecting the module's VCC and GND to Arduino Uno's 5v and GND in addition of USB-plug for messaging but I think these are the same power and don't provide more power because AT+CBC gives 0V. So I assume I need to connect power from the other pins, is it the 3.7V BAT? Or is my module broken? A: I was able to fix this myself. I had "preferred mode selection" set to LTE Only. It might work in some countries. By setting this to automatic with AT+CNMP=2, I was able to make calls and receive calls. I hope this helps if someone is having similar trouble.
SIMCOM A7600E, can't make voice call but sms works
If I connect this sim module to laptop via USB, I can send and receive SMS-messages. But voice call doesn't work, it gives NO CARRIER, VOICE CALL: END I've tried connecting the module's VCC and GND to Arduino Uno's 5v and GND in addition of USB-plug for messaging but I think these are the same power and don't provide more power because AT+CBC gives 0V. So I assume I need to connect power from the other pins, is it the 3.7V BAT? Or is my module broken?
[ "I was able to fix this myself. I had \"preferred mode selection\" set to LTE Only. It might work in some countries. By setting this to automatic with AT+CNMP=2, I was able to make calls and receive calls. I hope this helps if someone is having similar trouble.\n" ]
[ 0 ]
[]
[]
[ "4g", "arduino", "at_command", "iot", "lte" ]
stackoverflow_0074320846_4g_arduino_at_command_iot_lte.txt
Q: Nuxt js useFetch limit items from hackernews API I need limit items from hackernews API.How can I do that? Code is: <template> <p>Products</p> <div> <div class="grid grid-cols-4 gap-5"> <div v-for="s in results" :key="story"> <ProductCard :story="s"/> </div> </div> </div> </template> <script setup> definePageMeta({ layout: "products" }) const { data: stories } = await useFetch('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty') </script> I tried: const { data: stories } = await useFetch('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty').limit(1000) but no result. A: according to this there is a default limit of 500 items but there is no option to limit the items you will get, you can store the whole 500 items in an array and display the number of items you want by changing the array using map,for loop filter etc ...
Nuxt js useFetch limit items from hackernews API
I need limit items from hackernews API.How can I do that? Code is: <template> <p>Products</p> <div> <div class="grid grid-cols-4 gap-5"> <div v-for="s in results" :key="story"> <ProductCard :story="s"/> </div> </div> </div> </template> <script setup> definePageMeta({ layout: "products" }) const { data: stories } = await useFetch('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty') </script> I tried: const { data: stories } = await useFetch('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty').limit(1000) but no result.
[ "according to this\nthere is a default limit of 500 items but there is no option to limit the items you will get, you can store the whole 500 items in an array and display the number of items you want by changing the array using map,for loop filter etc ...\n" ]
[ 0 ]
[]
[]
[ "hacker_news_api", "nuxt.js", "vue.js" ]
stackoverflow_0074673046_hacker_news_api_nuxt.js_vue.js.txt
Q: focus:outline-none not working Tailwind CSS with Laravel I am using Tailwind CSS for my Laravel application, and want to remove the focus border on the input boxes. According to the documentation, focus:outline-none should achieve this, although it is not working for me and the border still appears on focus. It looks like I am targeting the wrong thing, as if I do focus:outline-black, I can see a black outline as well as the standard blue one on focus. focus:border-none also does not fix the problem. Any ideas? <input class="text-input" placeholder="Your Name" /> .text-input { @apply focus:outline:none; } tailwind.config.js const defaultTheme = require('tailwindcss/defaultTheme'); const colors = require('tailwindcss/colors'); module.exports = { mode: 'jit', purge: [ './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php', './vendor/laravel/jetstream/**/*.blade.php', './storage/framework/views/*.php', './resources/views/**/*.blade.php', ], theme: { extend: { fontFamily: { sans: ['Nunito', ...defaultTheme.fontFamily.sans], }, }, colors: { black: colors.black, white: colors.white, gray: colors.trueGray, indigo: colors.indigo, red: colors.rose, yellow: colors.amber, blue: colors.blue, }, }, plugins: [require('@tailwindcss/forms'), require('@tailwindcss/typography')], }; webpack.mix.js const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel applications. By default, we are compiling the CSS | file for the application as well as bundling up all the JS files. | */ mix.js('resources/js/app.js', 'public/js') .postCss('resources/css/app.css', 'public/css', [ require('postcss-import'), require('tailwindcss'), ]); if (mix.inProduction()) { mix.version(); } A: Having same issue right now, Laravel 8, Inertia, Breeze & Tailwind: when I set outline-none on a element, it is ignored. Everything else seems to work properly. The only thing which solved it was to add css: border-transparent focus:border-transparent focus:ring-0 on the element itself. A: The proper way: border-none focus:ring-0 You don't need to bother making a border transparent if it doesn't exist. A: !outline-none This fixed it for me. A: Maybe you can try add focus:outline-none direct in your class. Demo : https://jsfiddle.net/p73xfy1h/ A: the correct way to handle this is in Tailwind 3 focus:ring-transparent A: working with this: focus:border-current focus:ring-0 A: this is my configuration when working with TailwindCSS <input /> border // border-width: 1px; border-slate-700 // DEFAULT border-color hover:border-slate-500 // HOVER border-color focus:border-blue-500 // WHEN WRITE border-color focus:outline-none // NONE OUTLINE WHEN WRITE A: I am using MudBlazor together with TailwindCSS and found that my input text/select boxes all had an odd square border when focused. I located the Tailwind CSS responsible and declared the CSS again at the end of the page <head> and also included !important on the overwritten attributes to ensure I have disabled it. [type='text']:focus, [type='email']:focus, [type='url']:focus, [type='password']:focus, [type='number']:focus, [type='date']:focus, [type='datetime-local']:focus, [type='month']:focus, [type='search']:focus, [type='tel']:focus, [type='time']:focus, [type='week']:focus, [multiple]:focus, textarea:focus, select:focus { outline: 0px !important; outline-offset: 0px !important; box-shadow: none !important; } A: just use focus:ring-0 focus:ring-offset-0 both. focus:ring-0 focus:ring-offset-0 A: There is simple way for solve this problem, only use outline outline:none
focus:outline-none not working Tailwind CSS with Laravel
I am using Tailwind CSS for my Laravel application, and want to remove the focus border on the input boxes. According to the documentation, focus:outline-none should achieve this, although it is not working for me and the border still appears on focus. It looks like I am targeting the wrong thing, as if I do focus:outline-black, I can see a black outline as well as the standard blue one on focus. focus:border-none also does not fix the problem. Any ideas? <input class="text-input" placeholder="Your Name" /> .text-input { @apply focus:outline:none; } tailwind.config.js const defaultTheme = require('tailwindcss/defaultTheme'); const colors = require('tailwindcss/colors'); module.exports = { mode: 'jit', purge: [ './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php', './vendor/laravel/jetstream/**/*.blade.php', './storage/framework/views/*.php', './resources/views/**/*.blade.php', ], theme: { extend: { fontFamily: { sans: ['Nunito', ...defaultTheme.fontFamily.sans], }, }, colors: { black: colors.black, white: colors.white, gray: colors.trueGray, indigo: colors.indigo, red: colors.rose, yellow: colors.amber, blue: colors.blue, }, }, plugins: [require('@tailwindcss/forms'), require('@tailwindcss/typography')], }; webpack.mix.js const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel applications. By default, we are compiling the CSS | file for the application as well as bundling up all the JS files. | */ mix.js('resources/js/app.js', 'public/js') .postCss('resources/css/app.css', 'public/css', [ require('postcss-import'), require('tailwindcss'), ]); if (mix.inProduction()) { mix.version(); }
[ "Having same issue right now, Laravel 8, Inertia, Breeze & Tailwind: when I set outline-none on a element, it is ignored. Everything else seems to work properly.\nThe only thing which solved it was to add css: border-transparent focus:border-transparent focus:ring-0 on the element itself.\n", "The proper way: border-none focus:ring-0 You don't need to bother making a border transparent if it doesn't exist. \n", "!outline-none\n\nThis fixed it for me.\n", "Maybe you can try add focus:outline-none direct in your class.\nDemo : https://jsfiddle.net/p73xfy1h/\n", "the correct way to handle this is in Tailwind 3 focus:ring-transparent\n", "working with this:\nfocus:border-current focus:ring-0\n\n", "this is my configuration when working with TailwindCSS <input />\nborder // border-width: 1px;\nborder-slate-700 // DEFAULT border-color\nhover:border-slate-500 // HOVER border-color\nfocus:border-blue-500 // WHEN WRITE border-color\nfocus:outline-none // NONE OUTLINE WHEN WRITE\n\n", "I am using MudBlazor together with TailwindCSS and found that my input text/select boxes all had an odd square border when focused.\n\nI located the Tailwind CSS responsible and declared the CSS again at the end of the page <head> and also included !important on the overwritten attributes to ensure I have disabled it.\n[type='text']:focus, [type='email']:focus, [type='url']:focus, [type='password']:focus, [type='number']:focus, [type='date']:focus, [type='datetime-local']:focus, [type='month']:focus, [type='search']:focus, [type='tel']:focus, [type='time']:focus, [type='week']:focus, [multiple]:focus, textarea:focus, select:focus {\n outline: 0px !important;\n outline-offset: 0px !important;\n box-shadow: none !important;\n}\n\n\n", "just use focus:ring-0 focus:ring-offset-0 both.\nfocus:ring-0 focus:ring-offset-0\n\n", "There is simple way for solve this problem, only use outline\noutline:none\n\n" ]
[ 43, 14, 11, 9, 5, 2, 0, 0, 0, 0 ]
[]
[]
[ "css", "laravel", "tailwind_css" ]
stackoverflow_0069981112_css_laravel_tailwind_css.txt
Q: Tkinter: Calling function when button is pressed but i am getting attribute error 'Application' object has no attribute 'hi' from tkinter import * import sqlite3 conn = sqlite3.connect('database.db') c = conn.cursor() class Application: def __init__(self, master): self.master = master self.left = Frame(master, width=800, height=720, bg='lightgreen') self.left.pack(side=LEFT) self.right = Frame(master, width=400, height=720, bg='lightblue') self.right.pack(side=RIGHT) self.heading=Label(self.left,text="HM hospital Appointments",font=('arial 40 bold'),fg='white',bg='lightgreen') self.heading.place(x=0,y=0) self.name=Label(self.left,text="Patient Name",font=('arial 20 italic'),fg='black',bg='lightgreen') self.name.place(x=0,y=100) self.age=Label(self.left,text="Age",font=('arial 20 italic'),fg='black',bg='lightgreen') self.age.place(x=0,y=150) self.gender=Label(self.left,text="Gender",font=('arial 20 italic'),fg='black',bg='lightgreen') self.gender.place(x=0,y=200) self.location=Label(self.left,text="Location",font=('arial 20 italic'),fg='black',bg='lightgreen') self.location.place(x=0,y=250) self.time=Label(self.left,text="Appointment Time",font=('arial 20 italic'),fg='black',bg='lightgreen') self.time.place(x=0,y=300) self.name_ent=Entry(self.left,width=30) self.name_ent.place(x=250,y=110) self.age_ent=Entry(self.left,width=30) self.age_ent.place(x=250,y=160) self.gender_ent=Entry(self.left,width=30) self.gender_ent.place(x=250,y=210) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250,y=260) self.time_ent=Entry(self.left,width=30) self.time_ent.place(x=250,y=310) self.submit=Button(self.left,text="Add appointment",width=20,height=2,bg='steelblue',command=self.hi) self.submit.place(x=300,y=350) def hi(self): self.val1=self.name_ent.get() root = Tk() b = Application(root) root.geometry("1200x720+0+0") root.resizable(False, False) root.mainloop() I looked many videos to solve it but can't find the right one so please help me. A: To fix the error you are seeing, you need to move the definition of the hi function inside the Application class and not inside __init__, like this: class Application: def __init__(self, master): # code for the rest of the __init__ method self.submit=Button(self.left,text="Add appointment",width=20,height=2,bg='steelblue',command=self.hi) ... ... def hi(self): self.val1=self.name_ent.get()
Tkinter: Calling function when button is pressed but i am getting attribute error 'Application' object has no attribute 'hi'
from tkinter import * import sqlite3 conn = sqlite3.connect('database.db') c = conn.cursor() class Application: def __init__(self, master): self.master = master self.left = Frame(master, width=800, height=720, bg='lightgreen') self.left.pack(side=LEFT) self.right = Frame(master, width=400, height=720, bg='lightblue') self.right.pack(side=RIGHT) self.heading=Label(self.left,text="HM hospital Appointments",font=('arial 40 bold'),fg='white',bg='lightgreen') self.heading.place(x=0,y=0) self.name=Label(self.left,text="Patient Name",font=('arial 20 italic'),fg='black',bg='lightgreen') self.name.place(x=0,y=100) self.age=Label(self.left,text="Age",font=('arial 20 italic'),fg='black',bg='lightgreen') self.age.place(x=0,y=150) self.gender=Label(self.left,text="Gender",font=('arial 20 italic'),fg='black',bg='lightgreen') self.gender.place(x=0,y=200) self.location=Label(self.left,text="Location",font=('arial 20 italic'),fg='black',bg='lightgreen') self.location.place(x=0,y=250) self.time=Label(self.left,text="Appointment Time",font=('arial 20 italic'),fg='black',bg='lightgreen') self.time.place(x=0,y=300) self.name_ent=Entry(self.left,width=30) self.name_ent.place(x=250,y=110) self.age_ent=Entry(self.left,width=30) self.age_ent.place(x=250,y=160) self.gender_ent=Entry(self.left,width=30) self.gender_ent.place(x=250,y=210) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250,y=260) self.time_ent=Entry(self.left,width=30) self.time_ent.place(x=250,y=310) self.submit=Button(self.left,text="Add appointment",width=20,height=2,bg='steelblue',command=self.hi) self.submit.place(x=300,y=350) def hi(self): self.val1=self.name_ent.get() root = Tk() b = Application(root) root.geometry("1200x720+0+0") root.resizable(False, False) root.mainloop() I looked many videos to solve it but can't find the right one so please help me.
[ "To fix the error you are seeing, you need to move the definition of the hi function inside the Application class and not inside __init__, like this:\nclass Application:\n def __init__(self, master):\n # code for the rest of the __init__ method\n\n self.submit=Button(self.left,text=\"Add appointment\",width=20,height=2,bg='steelblue',command=self.hi)\n\n ...\n ...\n def hi(self):\n self.val1=self.name_ent.get()\n\n" ]
[ 4 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074673731_python_tkinter.txt
Q: How to return back to main menus I was doing a multi menus, but I need a way to go back to the Main Menu when User type "0" I have tried to insert while( choice ==0) but it won't jump back to Main menu when I input 0 I was able to go back to main menus in the first case (The choosing language menus), but other case I can't go back to main menu when input 0 Sry for the code is so many, because this is the first time, I create a Program with multi menus, would like to hear suggestion from you guys on how to improve my Code I do this program by using Do-while method and using a switch-case method inside the do-while. #include <string> #include <iostream> using namespace std; int main() { int choice; cout << endl << "-------------------------------------" << endl; cout << endl << " Welcome to Our Book Store " << endl; cout << endl << "-------------------------------------" << endl; do { //choosing language menus cout<<"\n1. Malay\n2. English\n3. Chinese\n"; cout<<"Type your choice: "; cin>>choice; switch(choice) { case 1: cout<<"\n1=horror\n"; cout<<"2=love\n"; cout<<"3=comedy\n"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"\nChoose Horror Book\n"; cout<<"\n1. Hantu dalam rumah kamu Rm20"; cout<<"\n2. Bapa saya hantu Rm30"; cout<<"\n3. China HantuR Rm50"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Pada suatu hari............."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Pada suatu hari, bapa saya menjadi hantu............."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Pada suatu hari, hantu dari china............."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } return 0; case 2: cout<<"\nChoose love Book\n"; cout<<"\n1. Romeo dan Julia"; cout<<"\n2. Mr. London Ms.Langkawi"; cout<<"\n3. KL. Noir: Red"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Romeo take me, somewhere we can be alone..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Romeo take me, somewhere we can be alone..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Romeo take me, somewhere we can be alone..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } case 3: cout<<"\n Choose Comedy Book\n"; cout<<"\n1. Nasi Lemak Story"; cout<<"\n2. Apa yang laku"; cout<<"\n3. Sayang Bapakau"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Wish I can be Nasi Lemak..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Wish I can be Nasi Lemak..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } } // case for choosing language case 2: cout<<"1=horror\n"; cout<<"2=love\n"; cout<<"3=comedy\n"; cout<<"\nType your choice: "; cin>>choice; switch (choice) { case 1: cout<<"\n1. Ghost Hunter"; cout<<"\n2. Demon Slayer"; cout<<"\n3. Doctor Ghost"; cout<<"\nType your choice: "; cin>>choice; switch (choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Gun, cross, pray are all what Ghost Hunter need..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Demon Slayer are born to kill demon, whatever it take..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Weirld doctor living in a castle..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } case 2: cout<<"\n1.A kind of sad"; cout<<"\n2. Loving Beijing 101"; cout<<"\n3. Love you 3000"; cout<<"\nType of choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Cancer is their enemy..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Beijing, a place full of pressure and love..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Last word Ironman said...."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } case 3: cout<<"\n1. laughing 1"; cout<<"\n2. laughing 2"; cout<<"\n3. laughing 3"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"so funny hahahaha"; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"so funny huhuhuuuuuuuu"; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"so funny aaaaaaaahahahahah"; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } } // case for choosing language case 3: cout<<"1=horror\n"; cout<<"2=love\n"; cout<<"3=comedy\n"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"\n1. China Ghost story"; cout<<"\n2. Story of Apollo Hotel"; cout<<"\n3. Little town story"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"China, A big country with weird place"; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Apollo Hotel, Hotel full of Apollo..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Two Lovers first meet at the town..."; cout<<"\nType your choice: "; break; } break; } } return 0; } while(choice ==0); } A: One problem is that you are missing a break here } // case for choosing language case 3: It should be } break; // case for choosing language case 3: But really, stop what you are doing right now, and instead put some of the submenus into separate functions. The code is getting very, very unwieldy.
How to return back to main menus
I was doing a multi menus, but I need a way to go back to the Main Menu when User type "0" I have tried to insert while( choice ==0) but it won't jump back to Main menu when I input 0 I was able to go back to main menus in the first case (The choosing language menus), but other case I can't go back to main menu when input 0 Sry for the code is so many, because this is the first time, I create a Program with multi menus, would like to hear suggestion from you guys on how to improve my Code I do this program by using Do-while method and using a switch-case method inside the do-while. #include <string> #include <iostream> using namespace std; int main() { int choice; cout << endl << "-------------------------------------" << endl; cout << endl << " Welcome to Our Book Store " << endl; cout << endl << "-------------------------------------" << endl; do { //choosing language menus cout<<"\n1. Malay\n2. English\n3. Chinese\n"; cout<<"Type your choice: "; cin>>choice; switch(choice) { case 1: cout<<"\n1=horror\n"; cout<<"2=love\n"; cout<<"3=comedy\n"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"\nChoose Horror Book\n"; cout<<"\n1. Hantu dalam rumah kamu Rm20"; cout<<"\n2. Bapa saya hantu Rm30"; cout<<"\n3. China HantuR Rm50"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Pada suatu hari............."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Pada suatu hari, bapa saya menjadi hantu............."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Pada suatu hari, hantu dari china............."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } return 0; case 2: cout<<"\nChoose love Book\n"; cout<<"\n1. Romeo dan Julia"; cout<<"\n2. Mr. London Ms.Langkawi"; cout<<"\n3. KL. Noir: Red"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Romeo take me, somewhere we can be alone..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Romeo take me, somewhere we can be alone..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Romeo take me, somewhere we can be alone..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } case 3: cout<<"\n Choose Comedy Book\n"; cout<<"\n1. Nasi Lemak Story"; cout<<"\n2. Apa yang laku"; cout<<"\n3. Sayang Bapakau"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Wish I can be Nasi Lemak..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Wish I can be Nasi Lemak..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } } // case for choosing language case 2: cout<<"1=horror\n"; cout<<"2=love\n"; cout<<"3=comedy\n"; cout<<"\nType your choice: "; cin>>choice; switch (choice) { case 1: cout<<"\n1. Ghost Hunter"; cout<<"\n2. Demon Slayer"; cout<<"\n3. Doctor Ghost"; cout<<"\nType your choice: "; cin>>choice; switch (choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Gun, cross, pray are all what Ghost Hunter need..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Demon Slayer are born to kill demon, whatever it take..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Weirld doctor living in a castle..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } case 2: cout<<"\n1.A kind of sad"; cout<<"\n2. Loving Beijing 101"; cout<<"\n3. Love you 3000"; cout<<"\nType of choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Cancer is their enemy..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Beijing, a place full of pressure and love..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Last word Ironman said...."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } case 3: cout<<"\n1. laughing 1"; cout<<"\n2. laughing 2"; cout<<"\n3. laughing 3"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"so funny hahahaha"; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"so funny huhuhuuuuuuuu"; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"so funny aaaaaaaahahahahah"; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } } } // case for choosing language case 3: cout<<"1=horror\n"; cout<<"2=love\n"; cout<<"3=comedy\n"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"\n1. China Ghost story"; cout<<"\n2. Story of Apollo Hotel"; cout<<"\n3. Little town story"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"China, A big country with weird place"; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 2: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Apollo Hotel, Hotel full of Apollo..."; cout<<"\n1. Proceed to checkout"; cout<<"\n0. Return to Main menu"; cout<<"\nType your choice: "; cin>>choice; switch(choice) { case 1: cout<<"--------------------------------\n"; cout<<"Thank you!\n"; cout<<"Pls come again~"; return 0; } case 3: cout<<"--------------------------------\n"; cout<<"\nDescription: \n"; cout<<"Two Lovers first meet at the town..."; cout<<"\nType your choice: "; break; } break; } } return 0; } while(choice ==0); }
[ "One problem is that you are missing a break here\n }\n \n \n \n // case for choosing language \n case 3:\n\nIt should be\n }\n break; \n \n \n // case for choosing language \n case 3:\n\nBut really, stop what you are doing right now, and instead put some of the submenus into separate functions. The code is getting very, very unwieldy.\n" ]
[ 0 ]
[]
[]
[ "c++", "menu", "switch_statement", "while_loop" ]
stackoverflow_0074673736_c++_menu_switch_statement_while_loop.txt
Q: Date on posts is updated after another post is added ja JavaScript Currently I am doing a small school project, its a forum where you can add posts, see the date when it was added, sort by date, etc. My problem here is when the post is added, it always update the latest date on every post (see on screenshot, time between adding them is few minutes) enter image description here const date = new Date(); let hour = date.getHours(); let minute = date.getMinutes(); let second = date.getSeconds(); let day = date.getDate(); let month = date.getMonth() + 1; let year = date.getFullYear(); postsView.innerHTML += `<div class="card mb-3"> <div class="card-body"> <p> ${title} [${day}-${month}-${year}, ${hour}:${minute}:${second} AM]: ${description} <a href="#" onclick="deletePost('${title}')" class="btn btn-danger ml-5">Delete</a> </p> </div> </div>`; I tried with: const date = new Date(); console.log(date.toLocaleString()); but the result is the same. Thanks! :) A: It looks like you are using the date variable in a way that causes all of your posts to have the same timestamp. This is because you are creating a new Date object and using it to set the timestamp for all of your posts, so they all have the same timestamp, which is the time at which the date variable was created. To fix this, you can move the creation of the date variable inside the function where you are adding the posts, so that a new Date object is created for each post and it will have a unique timestamp. Here is an example of how you can do this: function addPost(title, description) { // Create a new Date object for the current time const date = new Date(); let hour = date.getHours(); let minute = date.getMinutes(); let second = date.getSeconds(); let day = date.getDate(); let month = date.getMonth() + 1; let year = date.getFullYear(); postsView.innerHTML += `<div class="card mb-3"> <div class="card-body"> <p> ${title} [${day}-${month}-${year}, ${hour}:${minute}:${second} AM]: ${description} <a href="#" onclick="deletePost('${title}')" class="btn btn-danger ml-5">Delete</a> </p> </div> </div>`; } A: You should define an onClick function for your button to add posts and then update the content in that function. const handleAddPost = (title, description) => { const date = new Date(); const hour = date.getHours(); const minute = date.getMinutes(); const second = date.getSeconds(); const day = date.getDate(); const month = date.getMonth() + 1; const year = date.getFullYear(); const postsView = document.getElementById("post-view"); postsView.innerHTML += `<div class="card mb-3"> <div class="card-body"> <p> ${title} [${day}-${month}-${year}, ${hour}:${minute}:${second} AM]: ${description} <a href="#" onclick="deletePost('${title}')" class="btn btn-danger ml-5">Delete</a> </p> </div> </div>`; } <div> <div id="post-view"></div> <button onclick="handleAddPost('${title}', '${description}')">Add Post</button> </div>
Date on posts is updated after another post is added ja JavaScript
Currently I am doing a small school project, its a forum where you can add posts, see the date when it was added, sort by date, etc. My problem here is when the post is added, it always update the latest date on every post (see on screenshot, time between adding them is few minutes) enter image description here const date = new Date(); let hour = date.getHours(); let minute = date.getMinutes(); let second = date.getSeconds(); let day = date.getDate(); let month = date.getMonth() + 1; let year = date.getFullYear(); postsView.innerHTML += `<div class="card mb-3"> <div class="card-body"> <p> ${title} [${day}-${month}-${year}, ${hour}:${minute}:${second} AM]: ${description} <a href="#" onclick="deletePost('${title}')" class="btn btn-danger ml-5">Delete</a> </p> </div> </div>`; I tried with: const date = new Date(); console.log(date.toLocaleString()); but the result is the same. Thanks! :)
[ "It looks like you are using the date variable in a way that causes all of your posts to have the same timestamp. This is because you are creating a new Date object and using it to set the timestamp for all of your posts, so they all have the same timestamp, which is the time at which the date variable was created.\nTo fix this, you can move the creation of the date variable inside the function where you are adding the posts, so that a new Date object is created for each post and it will have a unique timestamp.\nHere is an example of how you can do this:\nfunction addPost(title, description) {\n // Create a new Date object for the current time\n const date = new Date();\n\n let hour = date.getHours();\n let minute = date.getMinutes();\n let second = date.getSeconds();\n let day = date.getDate();\n let month = date.getMonth() + 1;\n let year = date.getFullYear();\n\n postsView.innerHTML += `<div class=\"card mb-3\">\n <div class=\"card-body\">\n <p> ${title} [${day}-${month}-${year}, ${hour}:${minute}:${second} AM]: ${description}\n <a href=\"#\" onclick=\"deletePost('${title}')\" class=\"btn btn-danger ml-5\">Delete</a>\n </p>\n </div>\n </div>`;\n}\n\n", "You should define an onClick function for your button to add posts and then update the content in that function.\nconst handleAddPost = (title, description) => {\n const date = new Date();\n const hour = date.getHours();\n const minute = date.getMinutes();\n const second = date.getSeconds();\n const day = date.getDate();\n const month = date.getMonth() + 1;\n const year = date.getFullYear();\n\n const postsView = document.getElementById(\"post-view\");\n\n postsView.innerHTML += `<div class=\"card mb-3\">\n <div class=\"card-body\">\n <p> ${title} [${day}-${month}-${year}, ${hour}:${minute}:${second} AM]: ${description}\n <a href=\"#\" onclick=\"deletePost('${title}')\" class=\"btn btn-danger ml-5\">Delete</a>\n </p>\n </div>\n </div>`;\n}\n\n<div>\n <div id=\"post-view\"></div>\n <button onclick=\"handleAddPost('${title}', '${description}')\">Add Post</button>\n</div>\n\n" ]
[ 0, 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074673715_javascript.txt
Q: Django Models: Filter a subset of a query set I have these two models: class InspectionPoint(models.Model): ... review_check = models.BooleanField(default = 0) flight = models.ForeignKey( Flight, related_name='inspection_points', on_delete=models.CASCADE, null=True, blank=True ) ... class ImageSnapshot(models.Model): ... inspection = models.ForeignKey( InspectionPoint, on_delete=models.CASCADE, related_name = 'snapshots' ) flight = models.ForeignKey( Flight, related_name='snapshots', on_delete=models.CASCADE, null=True, blank=True ) ... I already have snapshots queryset with: snapshots = ImageSnapshots.objects.filter(flight=flight) but that gives me all snapshots. I want to filter snapshots that have only (review_check = True) Any idea? A: Try this: ImageSnapshot.objects.filter(flight=flight, inspection__review_check=True)
Django Models: Filter a subset of a query set
I have these two models: class InspectionPoint(models.Model): ... review_check = models.BooleanField(default = 0) flight = models.ForeignKey( Flight, related_name='inspection_points', on_delete=models.CASCADE, null=True, blank=True ) ... class ImageSnapshot(models.Model): ... inspection = models.ForeignKey( InspectionPoint, on_delete=models.CASCADE, related_name = 'snapshots' ) flight = models.ForeignKey( Flight, related_name='snapshots', on_delete=models.CASCADE, null=True, blank=True ) ... I already have snapshots queryset with: snapshots = ImageSnapshots.objects.filter(flight=flight) but that gives me all snapshots. I want to filter snapshots that have only (review_check = True) Any idea?
[ "Try this:\nImageSnapshot.objects.filter(flight=flight, inspection__review_check=True)\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_views", "python_3.x" ]
stackoverflow_0074673301_django_django_models_django_views_python_3.x.txt
Q: webpack-dev-server not reloading I am using webpack 5 and I currently have the following setup: webpack.prod.js - where I have some specific configs for production (e.g. image compression, devtool, CSS minification, specific meta tags values) webpack.dev.js - where I have some specific configs for development (e.g. no image compression, no CSS minification, specific meta tags values) The issue I am currently facing is that I am unable to get webpack dev server live reloading to work (this apply to all file types). I've been through the docs but no luck so far. As far as I understand, when in development mode, webpack runs stuff in memory rather than in disk (which is supposed to be faster and that is great!). For some reason it appears that the watcher is not reacting to changes in the files specified in the devServer.watchFiles config. I was expecting webpack to detect changes on a typescript file, compile it and reload, but that's not happening. You can find the contents of both files below. webpack.prod.js: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); const TerserPlugin = require('terser-webpack-plugin'); const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin'); const CopyPlugin = require('copy-webpack-plugin'); const buildPath = path.resolve(__dirname, 'dist'); module.exports = { //devtool: 'source-map', entry: { index: "./src/index/index.ts", error: "./src/error/error.ts", }, output: { filename: "js/[name].[contenthash].js", path: buildPath, clean: true, }, module: { rules: [{ test: /\.ts$/i, exclude: /node_modules/, use: "ts-loader", }, { test: /\.html$/i, exclude: /node_modules/, use: "html-loader", }, { test: /\.css$/i, exclude: /node_modules/, use: [ MiniCssExtractPlugin.loader, "css-loader", ] }, { test: /\.png$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "img/[name].[contenthash][ext]", }, }, { test: /\.(woff|woff2|ttf)$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "fonts/[name].[contenthash][ext]", }, }, { test: /\.mp3$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "[name].[contenthash][ext]", }, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index/index.ejs", inject: "body", chunks: ["index"], filename: "index.html", meta: { "robots": { name: "robots", content: "index,follow" }, }, }), new HtmlWebpackPlugin({ template: "./src/error/error.html", inject: "body", chunks: ["error"], filename: "error.html", }), new MiniCssExtractPlugin({ filename: "css/[name].[contenthash].css", chunkFilename: "css/[id].[contenthash].css", }), new CopyPlugin({ patterns: [{ from: "src/robots.txt", to: "robots.txt", }, ], }), ], optimization: { minimize: true, minimizer: [ new TerserPlugin({ parallel: true, }), new CssMinimizerPlugin(), new ImageMinimizerPlugin({ minimizer: { implementation: ImageMinimizerPlugin.imageminMinify, options: { plugins: [ ["imagemin-pngquant", { quality: [0.5, 0.9] }], ], }, }, }), ], }, }; webpack.dev.js: const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { mode: "development", devtool: "eval-cheap-module-source-map", entry: { index: "./src/index/index.ts", error: "./src/error/error.ts", }, devServer: { watchFiles: [path.resolve(__dirname, "src/**/*")], open: true, }, module: { rules: [ { test: /\.ts$/i, exclude: /node_modules/, use: "ts-loader", }, { test: /\.html$/i, exclude: /node_modules/, use: "html-loader", }, { test: /\.css$/i, exclude: /node_modules/, use: ["style-loader", "css-loader"] }, { test: /\.png$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "img/[name].[contenthash][ext]", }, }, { test: /\.(woff|woff2|ttf)$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "fonts/[name].[contenthash][ext]", }, }, { test: /\.mp3$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "[name].[contenthash][ext]", }, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index/index.ejs", inject: "body", chunks: ["index"], filename: "index.html", meta: { "robots": { name: "robots", content: "noindex, nofollow" }, }, }), new HtmlWebpackPlugin({ template: "./src/error/error.html", inject: "body", chunks: ["error"], filename: "error.html" }), ], optimization: { runtimeChunk: "single", }, }; A: There are a few spots where I am a little bit blind because you didn't add some description about your tsconfig.json file and your package.json, but I will try to do my best to explain you the key points here and afterwards explain the solution. The ts-module It is the module that uses the typescript module for compiling the files, it requires the typescript node_module installed in the app and a proper tsconfig.json. For practical purposes I pasted bellow the configuration that I used in previous projects -- super basic you can improve it depending on your project --; There is nothing special about the config, it will not affect the HMR but it is required for the compiling. { "compilerOptions": { "noImplicitAny": true, "removeComments": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, "outDir": "./dist/", "sourceMap": true, "module": "commonjs", "target": "es6", "allowJs": true, }, "includes": ["/**/*"] } webpack-dev-server The package for starting the dev server in your local environment, this is quite straight forward, this should be installed along webpack and webpack-cli. Your package.json could have a start script pointing to your webpack.dev.js configuration: "scripts" { "start": "webpack-dev-server --config ./webpack.dev.js", } In my understanding there are a few different ways to start the dev server, you can check the documentation The Webpack configuration There are a few missing things to consider before implementing a "Hot reload" The resolver configuration I pasted bellow a pre-define list that I did for one of my projects, you can modify it to accept less/more extensions, but the idea is to "tell webpack" which files will be able to compile. This will allow you to imports files with those extensions. resolve: { extensions: [ ".js", ".jsx", ".ts", ".tsx", ".less", ".css", ".json", ".mjs", ], } After applying that, Webpack should already be able to compile the files; typescript and the ts-loader should be able to watch your files properly. But, this doesn't mean "Hot Module Reload", this is just reloading your browser when something changes, the dev server will do "its magic" by its own. I hope that the gif shows the proof that the configuration works The full webpack config looks like: const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { mode: "development", devtool: "eval-cheap-module-source-map", entry: { index: "./src/index/index.ts", error: "./src/error/error.ts", }, resolve: { extensions: [ ".js", ".jsx", ".ts", ".tsx", ".less", ".css", ".json", ".mjs", ], }, module: { rules: [ { test: /\.ts$/i, exclude: /node_modules/, use: [ { loader: "ts-loader", }, ], }, { test: /\.html$/i, exclude: /node_modules/, use: "html-loader", }, { test: /\.css$/i, exclude: /node_modules/, use: ["style-loader", "css-loader"], }, { test: /\.png$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "img/[name].[contenthash][ext]", }, }, { test: /\.(woff|woff2|ttf)$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "fonts/[name].[contenthash][ext]", }, }, { test: /\.mp3$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "[name].[contenthash][ext]", }, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index/index.ejs", inject: "body", chunks: ["index"], filename: "index.html", meta: { "robots": { name: "robots", content: "noindex, nofollow" }, }, }), new HtmlWebpackPlugin({ template: "./src/error/error.html", inject: "body", chunks: ["error"], filename: "error.html" }) ], optimization: { runtimeChunk: "single", }, }; For proper Hot Module Reload -- stands for just update pieces of your changed code without reloading the whole browser -- A few more adjustments are required, there are a lot of resources in the internet about this that I will try to list at the end, but since you are not using babel -- that works differently -- you need to provide a few more configurations in your webpack and also remove other properties. Update ts-loader configuration First check the ts-loader docs about HMR https://github.com/TypeStrong/ts-loader#hot-module-replacement and the implications. They advice to add a configuration called transpileOnly, but if you check the specifications about that option you will see that you loose some type checking in the next compilation, for that reason they advice to install another package It's advisable to use transpileOnly alongside the fork-ts-checker-webpack-plugin to get full type checking again. To see what this looks like in practice then either take a look at our example. Your ts-loader rule should look like: rules: [ { test: /\.ts$/i, exclude: /node_modules/, use: [ { loader: "ts-loader", options: { transpileOnly: true, }, }, ], }, And your plugins: plugins: [ ..., // Your HTML plugins new ForkTsCheckerWebpackPlugin(), ], Enabling Hot Module Reload This is easier than it looks, you need to consider two key points: Let webpack know that you want HMR Let your code know that will be Hot reloaded -- sound like funny but yes -- The first point, is super easy, just add to your webpack configuration the following configuration: devServer: { hot: true, }, But for the second point, it is a little bit tricky, with a simple tweaks you can do it; The easiest way is via creating a new file per entry point, the file can be named as you wish, but in this example I will call it hot.ts, and will look like the code pasted bellow: // Inside of your index folder require("./index"); if (module.hot) { module.hot.accept("./index.ts", function () { console.log("Hot reloading index"); require("./index"); }); } // Inside of your error folder require("./error"); if (module.hot) { module.hot.accept("./error.ts", function () { console.log("Hot reloading error"); require("./error"); }); } Side Note: You will find yourself with type errors with the module global variable, to solve that you need to install the following types npm i --save -D @types/node @types/webpack-env And in your dev configuration mode -- usually the HRM is intended for development not for production -- you need to adjust the entry points: entry: { index: "./src/index/hot.ts", error: "./src/error/hot.ts", }, Don't override the HMR watcher I didn't find a clear answer from the documentation, but seems like your watchFiles inside of your devServer overrides the HMR watcher, if you remove that -- even from the build dev, it doesn't makes a difference in this configuration -- the HMR should work smoothly. After following the previous steps your webpack file should look like the following code: const HtmlWebpackPlugin = require("html-webpack-plugin"); const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); module.exports = { mode: "development", devtool: "eval-cheap-module-source-map", entry: { index: "./src/index/hot.ts", error: "./src/error/hot.ts", }, devServer: { hot: true, }, resolve: { extensions: [ ".js", ".jsx", ".ts", ".tsx", ".less", ".css", ".json", ".mjs", ], }, module: { rules: [ { test: /\.ts$/i, exclude: /node_modules/, use: [ { loader: "ts-loader", options: { transpileOnly: true, }, }, ], }, { test: /\.html$/i, exclude: /node_modules/, use: "html-loader", }, { test: /\.css$/i, exclude: /node_modules/, use: ["style-loader", "css-loader"], }, { test: /\.png$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "img/[name].[contenthash][ext]", }, }, { test: /\.(woff|woff2|ttf)$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "fonts/[name].[contenthash][ext]", }, }, { test: /\.mp3$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "[name].[contenthash][ext]", }, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index/index.ejs", inject: "body", chunks: ["index"], filename: "index.html", meta: { "robots": { name: "robots", content: "noindex, nofollow" }, }, }), new HtmlWebpackPlugin({ template: "./src/error/error.html", inject: "body", chunks: ["error"], filename: "error.html" }), new ForkTsCheckerWebpackPlugin(), ], optimization: { runtimeChunk: "single", }, }; Repository with the working example: https://github.com/nicolasjuarezn/webpack-ts-example Example of configuration working: Useful links: Issue in ts-config: https://github.com/TypeStrong/ts-loader/issues/352 Issue with module var: Webpack TypeScript module.hot does not exist I hope that this helps you! A: The issue was related with WSL. More specifically running webpack in WSL on Windows file system (e.g. at /mnt/c/Users/MyUser/Documents/MyProject). After moving the project to WSL file system (e.g. at /home/MyUser/MyProject) I was able to get live reload to work. Even though this question mentions Parcel and Webpack, it is similar. I found the answer provides good context around the issue: https://stackoverflow.com/a/72786450/3685587 A: For webpack 5 use devServer: { watchFiles: ['src/**/*.php', 'public/**/*'], }, See details here https://webpack.js.org/configuration/dev-server/#devserverwatchfiles
webpack-dev-server not reloading
I am using webpack 5 and I currently have the following setup: webpack.prod.js - where I have some specific configs for production (e.g. image compression, devtool, CSS minification, specific meta tags values) webpack.dev.js - where I have some specific configs for development (e.g. no image compression, no CSS minification, specific meta tags values) The issue I am currently facing is that I am unable to get webpack dev server live reloading to work (this apply to all file types). I've been through the docs but no luck so far. As far as I understand, when in development mode, webpack runs stuff in memory rather than in disk (which is supposed to be faster and that is great!). For some reason it appears that the watcher is not reacting to changes in the files specified in the devServer.watchFiles config. I was expecting webpack to detect changes on a typescript file, compile it and reload, but that's not happening. You can find the contents of both files below. webpack.prod.js: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); const TerserPlugin = require('terser-webpack-plugin'); const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin'); const CopyPlugin = require('copy-webpack-plugin'); const buildPath = path.resolve(__dirname, 'dist'); module.exports = { //devtool: 'source-map', entry: { index: "./src/index/index.ts", error: "./src/error/error.ts", }, output: { filename: "js/[name].[contenthash].js", path: buildPath, clean: true, }, module: { rules: [{ test: /\.ts$/i, exclude: /node_modules/, use: "ts-loader", }, { test: /\.html$/i, exclude: /node_modules/, use: "html-loader", }, { test: /\.css$/i, exclude: /node_modules/, use: [ MiniCssExtractPlugin.loader, "css-loader", ] }, { test: /\.png$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "img/[name].[contenthash][ext]", }, }, { test: /\.(woff|woff2|ttf)$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "fonts/[name].[contenthash][ext]", }, }, { test: /\.mp3$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "[name].[contenthash][ext]", }, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index/index.ejs", inject: "body", chunks: ["index"], filename: "index.html", meta: { "robots": { name: "robots", content: "index,follow" }, }, }), new HtmlWebpackPlugin({ template: "./src/error/error.html", inject: "body", chunks: ["error"], filename: "error.html", }), new MiniCssExtractPlugin({ filename: "css/[name].[contenthash].css", chunkFilename: "css/[id].[contenthash].css", }), new CopyPlugin({ patterns: [{ from: "src/robots.txt", to: "robots.txt", }, ], }), ], optimization: { minimize: true, minimizer: [ new TerserPlugin({ parallel: true, }), new CssMinimizerPlugin(), new ImageMinimizerPlugin({ minimizer: { implementation: ImageMinimizerPlugin.imageminMinify, options: { plugins: [ ["imagemin-pngquant", { quality: [0.5, 0.9] }], ], }, }, }), ], }, }; webpack.dev.js: const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { mode: "development", devtool: "eval-cheap-module-source-map", entry: { index: "./src/index/index.ts", error: "./src/error/error.ts", }, devServer: { watchFiles: [path.resolve(__dirname, "src/**/*")], open: true, }, module: { rules: [ { test: /\.ts$/i, exclude: /node_modules/, use: "ts-loader", }, { test: /\.html$/i, exclude: /node_modules/, use: "html-loader", }, { test: /\.css$/i, exclude: /node_modules/, use: ["style-loader", "css-loader"] }, { test: /\.png$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "img/[name].[contenthash][ext]", }, }, { test: /\.(woff|woff2|ttf)$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "fonts/[name].[contenthash][ext]", }, }, { test: /\.mp3$/i, exclude: /node_modules/, type: "asset/resource", generator: { filename: "[name].[contenthash][ext]", }, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index/index.ejs", inject: "body", chunks: ["index"], filename: "index.html", meta: { "robots": { name: "robots", content: "noindex, nofollow" }, }, }), new HtmlWebpackPlugin({ template: "./src/error/error.html", inject: "body", chunks: ["error"], filename: "error.html" }), ], optimization: { runtimeChunk: "single", }, };
[ "There are a few spots where I am a little bit blind because you didn't add some description about your tsconfig.json file and your package.json, but I will try to do my best to explain you the key points here and afterwards explain the solution.\nThe ts-module\nIt is the module that uses the typescript module for compiling the files, it requires the typescript node_module installed in the app and a proper tsconfig.json.\nFor practical purposes I pasted bellow the configuration that I used in previous projects -- super basic you can improve it depending on your project --; There is nothing special about the config, it will not affect the HMR but it is required for the compiling.\n{\n \"compilerOptions\": {\n \"noImplicitAny\": true,\n \"removeComments\": true,\n \"allowSyntheticDefaultImports\": true,\n \"esModuleInterop\": true,\n \"outDir\": \"./dist/\",\n \"sourceMap\": true,\n \"module\": \"commonjs\",\n \"target\": \"es6\",\n \"allowJs\": true,\n },\n \"includes\": [\"/**/*\"]\n}\n\nwebpack-dev-server\nThe package for starting the dev server in your local environment, this is quite straight forward, this should be installed along webpack and webpack-cli.\nYour package.json could have a start script pointing to your webpack.dev.js configuration:\n\"scripts\" {\n \"start\": \"webpack-dev-server --config ./webpack.dev.js\",\n}\n\nIn my understanding there are a few different ways to start the dev server, you can check the documentation\nThe Webpack configuration\nThere are a few missing things to consider before implementing a \"Hot reload\"\nThe resolver configuration\nI pasted bellow a pre-define list that I did for one of my projects, you can modify it to accept less/more extensions, but the idea is to \"tell webpack\" which files will be able to compile.\nThis will allow you to imports files with those extensions.\nresolve: {\n extensions: [\n \".js\",\n \".jsx\",\n \".ts\",\n \".tsx\",\n \".less\",\n \".css\",\n \".json\",\n \".mjs\",\n ],\n }\n\nAfter applying that, Webpack should already be able to compile the files; typescript and the ts-loader should be able to watch your files properly. But, this doesn't mean \"Hot Module Reload\", this is just reloading your browser when something changes, the dev server will do \"its magic\" by its own.\nI hope that the gif shows the proof that the configuration works\n\nThe full webpack config looks like:\nconst HtmlWebpackPlugin = require(\"html-webpack-plugin\");\n\n\nmodule.exports = {\n mode: \"development\",\n devtool: \"eval-cheap-module-source-map\",\n entry: {\n index: \"./src/index/index.ts\",\n error: \"./src/error/error.ts\",\n },\n resolve: {\n extensions: [\n \".js\",\n \".jsx\",\n \".ts\",\n \".tsx\",\n \".less\",\n \".css\",\n \".json\",\n \".mjs\",\n ],\n },\n module: {\n rules: [\n {\n test: /\\.ts$/i,\n exclude: /node_modules/,\n use: [\n {\n loader: \"ts-loader\",\n },\n ],\n },\n {\n test: /\\.html$/i,\n exclude: /node_modules/,\n use: \"html-loader\",\n },\n {\n test: /\\.css$/i,\n exclude: /node_modules/,\n use: [\"style-loader\", \"css-loader\"],\n },\n {\n test: /\\.png$/i,\n exclude: /node_modules/,\n type: \"asset/resource\",\n generator: {\n filename: \"img/[name].[contenthash][ext]\",\n },\n },\n {\n test: /\\.(woff|woff2|ttf)$/i,\n exclude: /node_modules/,\n type: \"asset/resource\",\n generator: {\n filename: \"fonts/[name].[contenthash][ext]\",\n },\n },\n {\n test: /\\.mp3$/i,\n exclude: /node_modules/,\n type: \"asset/resource\",\n generator: {\n filename: \"[name].[contenthash][ext]\",\n },\n },\n ],\n },\n plugins: [\n new HtmlWebpackPlugin({\n template: \"./src/index/index.ejs\",\n inject: \"body\",\n chunks: [\"index\"],\n filename: \"index.html\",\n meta: {\n \"robots\": { name: \"robots\", content: \"noindex, nofollow\" },\n },\n }),\n new HtmlWebpackPlugin({\n template: \"./src/error/error.html\",\n inject: \"body\",\n chunks: [\"error\"],\n filename: \"error.html\"\n })\n ],\n optimization: {\n runtimeChunk: \"single\",\n },\n};\n\n\nFor proper Hot Module Reload -- stands for just update pieces of your changed code without reloading the whole browser --\nA few more adjustments are required, there are a lot of resources in the internet about this that I will try to list at the end, but since you are not using babel -- that works differently -- you need to provide a few more configurations in your webpack and also remove other properties.\nUpdate ts-loader configuration\nFirst check the ts-loader docs about HMR https://github.com/TypeStrong/ts-loader#hot-module-replacement and the implications.\nThey advice to add a configuration called transpileOnly, but if you check the specifications about that option you will see that you loose some type checking in the next compilation, for that reason they advice to install another package\n\nIt's advisable to use transpileOnly alongside the fork-ts-checker-webpack-plugin to get full type checking again. To see what this looks like in practice then either take a look at our example.\n\nYour ts-loader rule should look like:\nrules: [\n {\n test: /\\.ts$/i,\n exclude: /node_modules/,\n use: [\n {\n loader: \"ts-loader\",\n options: {\n transpileOnly: true,\n },\n },\n ],\n },\n\nAnd your plugins:\nplugins: [\n ..., // Your HTML plugins\n new ForkTsCheckerWebpackPlugin(),\n ],\n\nEnabling Hot Module Reload\nThis is easier than it looks, you need to consider two key points:\n\nLet webpack know that you want HMR\nLet your code know that will be Hot reloaded -- sound like funny but yes --\n\nThe first point, is super easy, just add to your webpack configuration the following configuration:\ndevServer: {\n hot: true,\n},\n\nBut for the second point, it is a little bit tricky, with a simple tweaks you can do it; The easiest way is via creating a new file per entry point, the file can be named as you wish, but in this example I will call it hot.ts, and will look like the code pasted bellow:\n// Inside of your index folder\nrequire(\"./index\");\n\nif (module.hot) {\n module.hot.accept(\"./index.ts\", function () {\n console.log(\"Hot reloading index\");\n require(\"./index\");\n });\n}\n\n// Inside of your error folder\nrequire(\"./error\");\n\nif (module.hot) {\n module.hot.accept(\"./error.ts\", function () {\n console.log(\"Hot reloading error\");\n require(\"./error\");\n });\n}\n\nSide Note: You will find yourself with type errors with the module global variable, to solve that you need to install the following types npm i --save -D @types/node @types/webpack-env\nAnd in your dev configuration mode -- usually the HRM is intended for development not for production -- you need to adjust the entry points:\nentry: {\n index: \"./src/index/hot.ts\",\n error: \"./src/error/hot.ts\",\n},\n\nDon't override the HMR watcher\nI didn't find a clear answer from the documentation, but seems like your watchFiles inside of your devServer overrides the HMR watcher, if you remove that -- even from the build dev, it doesn't makes a difference in this configuration -- the HMR should work smoothly.\nAfter following the previous steps your webpack file should look like the following code:\nconst HtmlWebpackPlugin = require(\"html-webpack-plugin\");\nconst ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');\n\n\nmodule.exports = {\n mode: \"development\",\n devtool: \"eval-cheap-module-source-map\",\n entry: {\n index: \"./src/index/hot.ts\",\n error: \"./src/error/hot.ts\",\n },\n devServer: {\n hot: true,\n },\n resolve: {\n extensions: [\n \".js\",\n \".jsx\",\n \".ts\",\n \".tsx\",\n \".less\",\n \".css\",\n \".json\",\n \".mjs\",\n ],\n },\n module: {\n rules: [\n {\n test: /\\.ts$/i,\n exclude: /node_modules/,\n use: [\n {\n loader: \"ts-loader\",\n options: {\n transpileOnly: true,\n },\n },\n ],\n },\n {\n test: /\\.html$/i,\n exclude: /node_modules/,\n use: \"html-loader\",\n },\n {\n test: /\\.css$/i,\n exclude: /node_modules/,\n use: [\"style-loader\", \"css-loader\"],\n },\n {\n test: /\\.png$/i,\n exclude: /node_modules/,\n type: \"asset/resource\",\n generator: {\n filename: \"img/[name].[contenthash][ext]\",\n },\n },\n {\n test: /\\.(woff|woff2|ttf)$/i,\n exclude: /node_modules/,\n type: \"asset/resource\",\n generator: {\n filename: \"fonts/[name].[contenthash][ext]\",\n },\n },\n {\n test: /\\.mp3$/i,\n exclude: /node_modules/,\n type: \"asset/resource\",\n generator: {\n filename: \"[name].[contenthash][ext]\",\n },\n },\n ],\n },\n plugins: [\n new HtmlWebpackPlugin({\n template: \"./src/index/index.ejs\",\n inject: \"body\",\n chunks: [\"index\"],\n filename: \"index.html\",\n meta: {\n \"robots\": { name: \"robots\", content: \"noindex, nofollow\" },\n },\n }),\n new HtmlWebpackPlugin({\n template: \"./src/error/error.html\",\n inject: \"body\",\n chunks: [\"error\"],\n filename: \"error.html\"\n }),\n new ForkTsCheckerWebpackPlugin(),\n ],\n optimization: {\n runtimeChunk: \"single\",\n },\n};\n\nRepository with the working example: https://github.com/nicolasjuarezn/webpack-ts-example\nExample of configuration working:\n\nUseful links:\n\nIssue in ts-config: https://github.com/TypeStrong/ts-loader/issues/352\nIssue with module var: Webpack TypeScript module.hot does not exist\n\nI hope that this helps you!\n", "The issue was related with WSL. More specifically running webpack in WSL on Windows file system (e.g. at /mnt/c/Users/MyUser/Documents/MyProject).\nAfter moving the project to WSL file system (e.g. at /home/MyUser/MyProject) I was able to get live reload to work.\nEven though this question mentions Parcel and Webpack, it is similar. I found the answer provides good context around the issue: https://stackoverflow.com/a/72786450/3685587\n", "For webpack 5 use\n devServer: {\n watchFiles: ['src/**/*.php', 'public/**/*'],\n },\n\nSee details here https://webpack.js.org/configuration/dev-server/#devserverwatchfiles\n" ]
[ 1, 1, 0 ]
[]
[]
[ "webpack", "webpack_5", "webpack_dev_server", "webpack_hmr" ]
stackoverflow_0073499449_webpack_webpack_5_webpack_dev_server_webpack_hmr.txt