qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,569,488
<p>I am trying to make the total of the price of checkbox values given to the function. My value attribute stores the id of my database so I can not assign a price to the value tag.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function UpdateCost(elem) { let total = Number(elem.value); if (isNaN(total)) { total = 0; } if (elem.checked === true) { total += Number(elem.value); } else { total -= Number(elem.value); } alert(total); document.getElementById('total').value = total.toFixed(0); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form&gt; &lt;input type="checkbox" value="1" onclick="UpdateCost(20);" /&gt; Price = 20 &lt;input type="checkbox" value="2" onclick="UpdateCost(25);" /&gt; Price = 25 &lt;input type="checkbox" value="3" onclick="UpdateCost(30);" /&gt; Price = 30 &lt;input type="checkbox" value="4" onclick="UpdateCost(20);" /&gt; Price = 40 &lt;input type=text id=total value=0&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74569553, "author": "Anant - Alive to die", "author_id": 4248328, "author_profile": "https://Stackoverflow.com/users/4248328", "pm_score": 1, "selected": true, "text": "data- let total = 0;\n\nfunction UpdateCost(element) {\n if (element.checked === true) {\n total += Number(element.getAttribute('data-price'));\n } else {\n total -= Number(element.getAttribute('data-price'));\n }\n \n document.getElementById('total').innerHTML = total.toFixed(0);\n} <!DOCTYPE html>\n<html>\n\n<body>\n <form>\n <input type=\"checkbox\" value=\"1\" onclick=\"UpdateCost(this);\" data-price=\"20\" /> Price = 20\n <input type=\"checkbox\" value=\"2\" onclick=\"UpdateCost(this);\" data-price=\"25\" /> Price = 25\n <input type=\"checkbox\" value=\"3\" onclick=\"UpdateCost(this);\" data-price=\"30\" /> Price = 30\n <input type=\"checkbox\" value=\"4\" onclick=\"UpdateCost(this);\" data-price=\"40\" /> Price = 40\n <div id=\"total\"> </div>\n </form>\n\n</body>\n\n</html> parseFloat() let total = 0;\n\nfunction UpdateCost(element) {\n if (element.checked === true) {\n total = total + parseFloat(element.getAttribute('data-price'));\n } else {\n total -= parseFloat(element.getAttribute('data-price'));\n }\n \n document.getElementById('total').innerHTML = total.toFixed(1);\n} <!DOCTYPE html>\n<html>\n\n<body>\n <form>\n <input type=\"checkbox\" value=\"1\" onclick=\"UpdateCost(this);\" data-price=\"20.2\" /> Price = 20.2\n <input type=\"checkbox\" value=\"2\" onclick=\"UpdateCost(this);\" data-price=\"25.4\" /> Price = 25.4\n <input type=\"checkbox\" value=\"3\" onclick=\"UpdateCost(this);\" data-price=\"30.6\" /> Price = 30.6\n <input type=\"checkbox\" value=\"4\" onclick=\"UpdateCost(this);\" data-price=\"40.8\" /> Price = 40.8\n <div id=\"total\"> </div>\n </form>\n\n</body>\n\n</html>" }, { "answer_id": 74569658, "author": "Lokendra Singh Panwar", "author_id": 5602878, "author_profile": "https://Stackoverflow.com/users/5602878", "pm_score": 0, "selected": false, "text": "<form>\n <input type=\"checkbox\" value=\"1\" onclick=\"UpdateCost(this);\" /> \n <input type=\"checkbox\" value=\"2\" onclick=\"UpdateCost(this);\" /> \n <input type=\"checkbox\" value=\"3\" onclick=\"UpdateCost(this);\" /> \n <input type=\"checkbox\" value=\"4\" onclick=\"UpdateCost(this);\" /> \n <div id=\"total\"> </div>\n</form>\n\n\nvar total = 0;\nfunction UpdateCost(elem) {\nalert(elem.value);\n\nif (elem.checked === true) {\ntotal = total+Number(elem.value);\n} else {\ntotal = total -Number(elem.value);\n}\nconsole.log(total)\n\n document.getElementById('total').value = total.toFixed(0);\n}\n" }, { "answer_id": 74569737, "author": "Malik", "author_id": 10804565, "author_profile": "https://Stackoverflow.com/users/10804565", "pm_score": 2, "selected": false, "text": "function UpdateCost() {\n var checkboxes = document.getElementsByName('checkbox[]');\n var len = checkboxes.length;\n\n var result = 0;\n for (var i = 0; i < len; i++) {\n if (checkboxes[i].checked) {\n result = result + Number(checkboxes[i].value);\n }\n }\n document.getElementById('total').innerHTML = result;\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20596998/" ]
74,569,536
<p>I have a gridView.builder in my code but when I scroll it scrolls only gridView, not all page. I want to scroll the whole page, how can i fix it?</p> <p>my code:</p> <pre><code>FutureBuilder&lt;List&lt;Product&gt;&gt;( future: productFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else if (snapshot.hasData) { final product = snapshot.data; return buildProduct(product!); } else { return Text(&quot;No widget to build&quot;); } }), Widget buildProduct(List&lt;Product&gt; product) =&gt; GridView.builder( gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 300, childAspectRatio: 3.15 / 5, crossAxisSpacing: 5, mainAxisSpacing: 10), itemCount: product.length, itemBuilder: (context, index) { final productItem = product[index]; final media = product[index].media?.map((e) =&gt; e.toJson()).toList(); final photo = media?[0]['links']['local']['thumbnails']['350']; return Container(); }, ); </code></pre> <p><a href="https://i.stack.imgur.com/pw8wS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pw8wS.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74569851, "author": "Moïse Rajesearison", "author_id": 20517248, "author_profile": "https://Stackoverflow.com/users/20517248", "pm_score": 1, "selected": false, "text": "SingleChildScrollView(\n child: Column(\n children: [\n // Your code\n ]\n))\n\n\n" }, { "answer_id": 74569891, "author": "Septian Dika", "author_id": 13096991, "author_profile": "https://Stackoverflow.com/users/13096991", "pm_score": 3, "selected": true, "text": "SingleChildScrollView() Column() GridView.builder() Column() physics: const NeverScrollableScrollPhysics() shrinkWrap: true GridView.builder() SingleChildScrollView(\n child: Column(\n children:[\n imageCarouselWidget(),\n imageSliderWidget(),\n anotherWidget(),\n\n /// your GridView.builder(),\n GridView.builder(\n // Set this shrinkWrap and physics\n shrinkWrap: true,\n physics: const NeverScrollableScrollPhysics(),\n //\n gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(\n maxCrossAxisExtent: 300,\n childAspectRatio: 3.15 / 5,\n crossAxisSpacing: 5,\n mainAxisSpacing: 10,\n ),\n itemCount: product.length,\n itemBuilder: (context, index) {\n return yourGridWidget();\n },\n ),\n ],\n ),\n),\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20320364/" ]
74,569,540
<p>For days I've been trying to find a way to make the headlines and texts of the individual Masonry cards occupy certain positions without affecting the other cards. I almost had a solution in the meantime, but it destroyed the view in other devices. Quite frustrating although the solution is certainly very simple.</p> <p>I want the Text of the Green Cards in the same position like the Text of the other Cards. <a href="https://i.stack.imgur.com/P2X9m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P2X9m.jpg" alt="Screenshot of the Masonry" /></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; padding: 0; box-sizing: border-box; } body { display: flex; justify-content: center; align-self: center; min-height: 100vh; } .container { position: relative; max-width: 100%; display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); grid-template-rows: minmax(100px, auto); margin: 40px; grid-auto-flow: dense; grid-gap: 35px; } .container .box { background: #333; padding: 90px; display: grid; place-items: center; text-align: left; color: #000; transition: 0.5s; border-radius: 10px; background: radial-gradient(#f9d423, #f83600); font-family: "bergen mono"; font-size: 2.1vh; display: flex; flex-direction: column; } h6 { color: #000; font-weight: 200; font-size: 30px; letter-spacing: 1px; font-family: "bergen mono"; } .container .box:hover { transition: all 0.3s ease; transform: scale(1.05, 1.05); } .container .box img { position: relative; max-width: 100px; margin-bottom: 10px; } .container .box:nth-child(1) { grid-column: span 2; grid-row: span 1; background: radial-gradient(#2bffc3, #72afd3); padding-top: 3vh } .container .box:nth-child(2) { grid-column: span 1; grid-row: span 2; background: radial-gradient(#c4ff29, #89d294); } .container .box:nth-child(4) { grid-column: span 1; grid-row: span 2; background: radial-gradient(#c4ff29, #89d294); } .container .box:nth-child(5) { grid-column: span 3; grid-row: span 1; background: radial-gradient(#2bffc3, #72afd3); } @media (max-width: 960px) { .container { grid-template-columns: repeat(auto-fill, minmax(50%, 1fr)); grid-template-rows: minmax(auto, auto); } .container .box { grid-column: unset !important; grid-row: unset !important; } } @media (max-width: 600px) { .container { grid-template-columns: repeat(auto-fill, minmax(50%, 1fr)); grid-template-rows: minmax(auto, auto); } .container .box { grid-column: unset !important; grid-row: unset !important; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="box"&gt; &lt;div class="content"&gt; &lt;img src="https://image.flaticon.com/icons/svg/2377/2377010.svg" alt=""&gt; &lt;h6 &gt;Überschrift&lt;/h6&gt; &lt;p&gt;Wash hands with soap and water after touching animals and animal products.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="content"&gt; &lt;h6 &gt;Überschrift&lt;/h6&gt; &lt;p&gt;When coughing and sneezing cover mouth and nose with flexed elbow or tissue.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="content"&gt; &lt;h6 &gt;Überschrift&lt;/h6&gt; &lt;p&gt;Avoid travelling if you have a fever or cough.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="content"&gt; &lt;h6 &gt;Überschrift&lt;/h6&gt; &lt;p&gt;If you have a fever, cough and difficulty breathing, seek medical care early.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="content"&gt; &lt;h6 &gt;Überschrift&lt;/h6&gt; &lt;p&gt;If you are coughing or sneezing, wear musk and must know how to use it and dispose it properly.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="content"&gt; &lt;h6 &gt;Überschrift&lt;/h6&gt; &lt;p&gt;Eat only well cooked food.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="content"&gt; &lt;h6 &gt;Überschrift&lt;/h6&gt; &lt;p&gt;Avoid close contact with animals that are sick.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74569851, "author": "Moïse Rajesearison", "author_id": 20517248, "author_profile": "https://Stackoverflow.com/users/20517248", "pm_score": 1, "selected": false, "text": "SingleChildScrollView(\n child: Column(\n children: [\n // Your code\n ]\n))\n\n\n" }, { "answer_id": 74569891, "author": "Septian Dika", "author_id": 13096991, "author_profile": "https://Stackoverflow.com/users/13096991", "pm_score": 3, "selected": true, "text": "SingleChildScrollView() Column() GridView.builder() Column() physics: const NeverScrollableScrollPhysics() shrinkWrap: true GridView.builder() SingleChildScrollView(\n child: Column(\n children:[\n imageCarouselWidget(),\n imageSliderWidget(),\n anotherWidget(),\n\n /// your GridView.builder(),\n GridView.builder(\n // Set this shrinkWrap and physics\n shrinkWrap: true,\n physics: const NeverScrollableScrollPhysics(),\n //\n gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(\n maxCrossAxisExtent: 300,\n childAspectRatio: 3.15 / 5,\n crossAxisSpacing: 5,\n mainAxisSpacing: 10,\n ),\n itemCount: product.length,\n itemBuilder: (context, index) {\n return yourGridWidget();\n },\n ),\n ],\n ),\n),\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19244147/" ]
74,569,589
<p>I want to create JSON object with the new JSON data type in BigQuery, where the key is not the name of the column but instead the value within the column. So for example, for the following query</p> <pre class="lang-sql prettyprint-override"><code>select key, value from unnest(array&lt;struct&lt;key string, value int64&gt;&gt;[(&quot;a&quot;, 1), (&quot;b&quot;, 2)]) </code></pre> <p>I would like to have a JSON that looks like</p> <pre class="lang-sql prettyprint-override"><code>-- {&quot;a&quot;: 1} -- {&quot;b&quot;: 2} </code></pre> <p>The query below doesn't work (<code>Invalid JSON literal: syntax error while parsing object key - invalid literal; last read: '{k'; expected string literal at [1:8] </code>)</p> <pre class="lang-sql prettyprint-override"><code>select json '{key, value}' from unnest(array&lt;struct&lt;key string, value int64&gt;&gt;[(&quot;a&quot;, 1), (&quot;b&quot;, 2)]) </code></pre>
[ { "answer_id": 74569851, "author": "Moïse Rajesearison", "author_id": 20517248, "author_profile": "https://Stackoverflow.com/users/20517248", "pm_score": 1, "selected": false, "text": "SingleChildScrollView(\n child: Column(\n children: [\n // Your code\n ]\n))\n\n\n" }, { "answer_id": 74569891, "author": "Septian Dika", "author_id": 13096991, "author_profile": "https://Stackoverflow.com/users/13096991", "pm_score": 3, "selected": true, "text": "SingleChildScrollView() Column() GridView.builder() Column() physics: const NeverScrollableScrollPhysics() shrinkWrap: true GridView.builder() SingleChildScrollView(\n child: Column(\n children:[\n imageCarouselWidget(),\n imageSliderWidget(),\n anotherWidget(),\n\n /// your GridView.builder(),\n GridView.builder(\n // Set this shrinkWrap and physics\n shrinkWrap: true,\n physics: const NeverScrollableScrollPhysics(),\n //\n gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(\n maxCrossAxisExtent: 300,\n childAspectRatio: 3.15 / 5,\n crossAxisSpacing: 5,\n mainAxisSpacing: 10,\n ),\n itemCount: product.length,\n itemBuilder: (context, index) {\n return yourGridWidget();\n },\n ),\n ],\n ),\n),\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7482962/" ]
74,569,592
<p>I need you help. I'm new in react router v6 so i need to add custom params in route object. But can't find any examples of it</p> <pre><code> const AdminRoutes: FunctionComponent = () =&gt; { const router = createBrowserRouter([ { path: '/', element: &lt;Dashboard /&gt;, permission: ['edit'], //custom param }, ]); return &lt;RouterProvider router={router} /&gt;; }; export default AdminRoutes; </code></pre> <p>Given Error -</p> <pre><code>Type '{ path: string; element: JSX.Element; permission: string[]; }' is not assignable to type 'RouteObject'. Object literal may only specify known properties, and 'permission' does not exist in type 'RouteObject' </code></pre> <p>Thanks for your help.</p>
[ { "answer_id": 74569851, "author": "Moïse Rajesearison", "author_id": 20517248, "author_profile": "https://Stackoverflow.com/users/20517248", "pm_score": 1, "selected": false, "text": "SingleChildScrollView(\n child: Column(\n children: [\n // Your code\n ]\n))\n\n\n" }, { "answer_id": 74569891, "author": "Septian Dika", "author_id": 13096991, "author_profile": "https://Stackoverflow.com/users/13096991", "pm_score": 3, "selected": true, "text": "SingleChildScrollView() Column() GridView.builder() Column() physics: const NeverScrollableScrollPhysics() shrinkWrap: true GridView.builder() SingleChildScrollView(\n child: Column(\n children:[\n imageCarouselWidget(),\n imageSliderWidget(),\n anotherWidget(),\n\n /// your GridView.builder(),\n GridView.builder(\n // Set this shrinkWrap and physics\n shrinkWrap: true,\n physics: const NeverScrollableScrollPhysics(),\n //\n gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(\n maxCrossAxisExtent: 300,\n childAspectRatio: 3.15 / 5,\n crossAxisSpacing: 5,\n mainAxisSpacing: 10,\n ),\n itemCount: product.length,\n itemBuilder: (context, index) {\n return yourGridWidget();\n },\n ),\n ],\n ),\n),\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035619/" ]
74,569,616
<p>Pandas to_records() throws an error while numpy.array is behaving like expected.</p> <pre><code>data = [('myID', 5), ('myID', 10)] myDtype = numpy.dtype([('myID', numpy.str_,4), ('length', numpy.uint16)]) </code></pre> <p>Working:</p> <pre><code>arr = numpy.array(data, dtype=myDtype) output: [('myID', 5) ('myID', 10)] </code></pre> <p>This is not working</p> <pre><code>df = pd.DataFrame(data) df = df.to_records(index=False, column_dtypes=myDtype) </code></pre> <p>ValueError: invalid literal for int() with base 10: 'myID'</p> <p>What I am doing wroing with pandas to_records()?</p>
[ { "answer_id": 74569851, "author": "Moïse Rajesearison", "author_id": 20517248, "author_profile": "https://Stackoverflow.com/users/20517248", "pm_score": 1, "selected": false, "text": "SingleChildScrollView(\n child: Column(\n children: [\n // Your code\n ]\n))\n\n\n" }, { "answer_id": 74569891, "author": "Septian Dika", "author_id": 13096991, "author_profile": "https://Stackoverflow.com/users/13096991", "pm_score": 3, "selected": true, "text": "SingleChildScrollView() Column() GridView.builder() Column() physics: const NeverScrollableScrollPhysics() shrinkWrap: true GridView.builder() SingleChildScrollView(\n child: Column(\n children:[\n imageCarouselWidget(),\n imageSliderWidget(),\n anotherWidget(),\n\n /// your GridView.builder(),\n GridView.builder(\n // Set this shrinkWrap and physics\n shrinkWrap: true,\n physics: const NeverScrollableScrollPhysics(),\n //\n gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(\n maxCrossAxisExtent: 300,\n childAspectRatio: 3.15 / 5,\n crossAxisSpacing: 5,\n mainAxisSpacing: 10,\n ),\n itemCount: product.length,\n itemBuilder: (context, index) {\n return yourGridWidget();\n },\n ),\n ],\n ),\n),\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633189/" ]
74,569,626
<p>Hello guys im new to flutter, and i wanted to ask how do i properly add bottom navigator to flutter? i've been tried few tutorials in youtube but there's always something that won't work.</p> <p>so i want to ask you guys how to do it.</p> <p>so this is gonna be the content i want my BottomNavigator to be in</p> <pre><code>import 'package:flutter/material.dart'; import 'package:get/get_core/src/get_main.dart'; import 'package:get/get_navigation/get_navigation.dart'; import 'Reminder/ui/home_reminder.dart'; import 'Reminder/ui/widgets/button.dart'; void main() { // debugPaintSizeEnabled = true; runApp(const HomePage()); } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text('Medicine Reminder App'), ), body: Column( children: [ Stack( children: [ Image.asset( 'images/MenuImg.jpg', width: 600, height: 200, fit: BoxFit.cover, ), ], ), const SizedBox(height: 10.0), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ ElevatedButton( child: const Text('Button 1'), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) =&gt; const ReminderHomePage()), ); }, ), ElevatedButton( child: const Text('Button 2'), onPressed: () {}, ), ElevatedButton( child: const Text('Button 3'), onPressed: () {}, ), ], ), ], ), ), ); } } </code></pre> <p>and the Button 1 would navigate to &quot;ReminderHomePage&quot;</p> <pre><code>import 'package:date_picker_timeline/date_picker_timeline.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:medreminder/Reminder/services/notification_services.dart'; import 'package:medreminder/Reminder/services/theme_services.dart'; import 'package:intl/intl.dart'; import 'package:medreminder/Reminder/ui/theme.dart'; import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart'; import 'package:medreminder/Reminder/ui/widgets/button.dart'; import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart'; import 'package:medreminder/home_page.dart'; class ReminderHomePage extends StatefulWidget { const ReminderHomePage({super.key}); @override State&lt;ReminderHomePage&gt; createState() =&gt; _ReminderHomePageState(); } class _ReminderHomePageState extends State&lt;ReminderHomePage&gt; { DateTime _selectedDate = DateTime.now(); var notifyHelper; @override void initState() { // TODO: implement initState super.initState(); notifyHelper=NotifyHelper(); notifyHelper.initializeNotification(); } @override Widget build(BuildContext context) { return Scaffold( appBar: _appBar(), backgroundColor: context.theme.backgroundColor, body: Column( children: [ _addTaskBar(), _addDateBar(), ], ), ); } _addDateBar(){ return Container( margin: const EdgeInsets.only(top: 20, left: 20), child: DatePicker( DateTime.now(), height: 100, width: 80, initialSelectedDate: DateTime.now(), selectionColor: Color(0xFFAAB6FB), selectedTextColor: Colors.white, dateTextStyle: GoogleFonts.lato( textStyle: TextStyle( fontSize: 20, fontWeight: FontWeight.w600, color:Colors.grey ), ), dayTextStyle: GoogleFonts.lato( textStyle: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, color:Colors.grey ), ), monthTextStyle: GoogleFonts.lato( textStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, color:Colors.grey ), ), onDateChange: (date){ _selectedDate=date; }, ), ); } _addTaskBar(){ return Container( margin: const EdgeInsets.only(left: 20, right: 20, top: 5), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( margin: const EdgeInsets.symmetric(horizontal: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(DateFormat.yMMMMd().format(DateTime.now()), style: subHeadingStyle, ), Text(&quot;Today&quot;, style: headingStyle, ) ], ), ), MyButton(label: &quot;Add Reminder&quot;, onTap: ()=&gt;Get.to(AddReminderPage())) ], ), ); } _appBar(){ return AppBar( elevation: 0, backgroundColor: context.theme.backgroundColor, leading: GestureDetector( onTap: (){ ThemeService().switchTheme(); notifyHelper.displayNotification( title:&quot;Theme Changed!&quot;, body: Get.isDarkMode?&quot;Activated Light Theme!&quot;:&quot;Activated Dark Theme!&quot; ); notifyHelper.scheduledNotification(); }, child: Icon(Get.isDarkMode ?Icons.wb_sunny_outlined:Icons.nightlight_round, size: 20, color:Get.isDarkMode ? Colors.white:Colors.black ), ), actions: [ CircleAvatar( backgroundImage: AssetImage( &quot;images/profile.png&quot; ), ), // Icon(Icons.person, // size: 20,), SizedBox(width: 20,), ], ); } } </code></pre> <p>when i try tutorials from youtube, the background from &quot;ReminderHomePage&quot; always turns to blue, i dont know how that happen because when i run only &quot;ReminderHomePage&quot; the background is white.</p> <p>any help would mean so much to me. thank you guys</p>
[ { "answer_id": 74569709, "author": "Septian Dika", "author_id": 13096991, "author_profile": "https://Stackoverflow.com/users/13096991", "pm_score": 0, "selected": false, "text": "ReminderHomePage() backgroundColor Scaffold backgroundColor: context.theme.backgroundColor backgroundColor: Colors.white @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: _appBar(),\n backgroundColor: context.theme.backgroundColor, /// change this one, example: Colors.white\n body: Column(\n children: [\n _addTaskBar(),\n _addDateBar(),\n ],\n ),\n );\n }\n" }, { "answer_id": 74569760, "author": "Sabahat Hussain Qureshi", "author_id": 17901132, "author_profile": "https://Stackoverflow.com/users/17901132", "pm_score": 2, "selected": true, "text": "import 'package:flutter/material.dart';\n\nvoid main() => runApp(MyApp());\n\n/// This Widget is the main application widget.\nclass MyApp extends StatelessWidget {\n static const String _title = 'Flutter Code Sample';\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n title: _title,\n home: BottomNavigatiobBarExample(),\n );\n }\n}\n\nclass BottomNavigatiobBarExample extends StatefulWidget {\n BottomNavigatiobBarExample();\n\n @override\n _BottomNavigatiobBarExampleState createState() => _BottomNavigatiobBarExampleState();\n}\n\nclass _BottomNavigatiobBarExampleState extends State<BottomNavigatiobBarExample> {\n int _selectedIndex = 0;\n static const List<Widget> navigationItems = <Widget>[\n Text('Home Tab',style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),),\n Text('Favorites Tab', style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),),\n Text('Profile Tab',style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),),\n ];\n\n void _onItemTapped(int index) {\n setState(() {\n _selectedIndex = index;\n });\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text('Bottom Navigation Bar Example'),\n ),\n body: Center(\n child: navigationItems.elementAt(_selectedIndex),\n ),\n bottomNavigationBar: BottomNavigationBar(\n items: const <BottomNavigationBarItem>[\n BottomNavigationBarItem(\n icon: Icon(Icons.home),\n label: 'Home',\n ),\n BottomNavigationBarItem(\n icon: Icon(Icons.favorite),\n label: 'Favorites',\n ),\n BottomNavigationBarItem(\n icon: Icon(Icons.people),\n label: 'Profile',\n ),\n ],\n currentIndex: _selectedIndex,\n selectedItemColor: Colors.blue,\n onTap: _onItemTapped,\n ),\n );\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229067/" ]
74,569,688
<p>I'm trying to create new Nodejs based lambda but looks like I haven't got appropriate permissions. Unfortunately both me and a root user are not so familiar with AWS.</p> <p>For first I've got this error message:</p> <blockquote> <p>User: arn:aws:sts ... is not authorized to perform: cloudformation:DescribeStacks because no identity-based policy allows the cloudformation:DescribeStacks action but i'm able to start creating</p> </blockquote> <p>After all I've got this one:</p> <blockquote> <p>Error creating application: User: ... is not authorized to perform: serverlessrepo:GetApplication on resource: arn:aws:serverlessrepo:us-east-1:xxx:applications/CICD-toolchain-for-serverless-applications</p> </blockquote> <p>Was trying to create CI/CD app. The main purpose is to migrate from Heroku to AWS.</p>
[ { "answer_id": 74569709, "author": "Septian Dika", "author_id": 13096991, "author_profile": "https://Stackoverflow.com/users/13096991", "pm_score": 0, "selected": false, "text": "ReminderHomePage() backgroundColor Scaffold backgroundColor: context.theme.backgroundColor backgroundColor: Colors.white @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: _appBar(),\n backgroundColor: context.theme.backgroundColor, /// change this one, example: Colors.white\n body: Column(\n children: [\n _addTaskBar(),\n _addDateBar(),\n ],\n ),\n );\n }\n" }, { "answer_id": 74569760, "author": "Sabahat Hussain Qureshi", "author_id": 17901132, "author_profile": "https://Stackoverflow.com/users/17901132", "pm_score": 2, "selected": true, "text": "import 'package:flutter/material.dart';\n\nvoid main() => runApp(MyApp());\n\n/// This Widget is the main application widget.\nclass MyApp extends StatelessWidget {\n static const String _title = 'Flutter Code Sample';\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n title: _title,\n home: BottomNavigatiobBarExample(),\n );\n }\n}\n\nclass BottomNavigatiobBarExample extends StatefulWidget {\n BottomNavigatiobBarExample();\n\n @override\n _BottomNavigatiobBarExampleState createState() => _BottomNavigatiobBarExampleState();\n}\n\nclass _BottomNavigatiobBarExampleState extends State<BottomNavigatiobBarExample> {\n int _selectedIndex = 0;\n static const List<Widget> navigationItems = <Widget>[\n Text('Home Tab',style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),),\n Text('Favorites Tab', style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),),\n Text('Profile Tab',style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),),\n ];\n\n void _onItemTapped(int index) {\n setState(() {\n _selectedIndex = index;\n });\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text('Bottom Navigation Bar Example'),\n ),\n body: Center(\n child: navigationItems.elementAt(_selectedIndex),\n ),\n bottomNavigationBar: BottomNavigationBar(\n items: const <BottomNavigationBarItem>[\n BottomNavigationBarItem(\n icon: Icon(Icons.home),\n label: 'Home',\n ),\n BottomNavigationBarItem(\n icon: Icon(Icons.favorite),\n label: 'Favorites',\n ),\n BottomNavigationBarItem(\n icon: Icon(Icons.people),\n label: 'Profile',\n ),\n ],\n currentIndex: _selectedIndex,\n selectedItemColor: Colors.blue,\n onTap: _onItemTapped,\n ),\n );\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20597148/" ]
74,569,701
<p>The JSON Array get into typescript as response Object from my Java application. I need to pick each object and display into html page corresponding to that typescript page in angular. <br> <strong>list-user.component.ts</strong></p> <pre><code>import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { Router } from '@angular/router'; @Component({ selector: 'app-list-user', templateUrl: './list-user.component.html', styleUrls: ['./list-user.component.css'] }) export class ListUserComponent implements OnInit { loginForm!: FormGroup; submitted = false; jdbc: any; username:any constructor(private http: HttpClient, private router: Router) { } ngOnInit() { this.username = JSON.parse(localStorage.getItem(&quot;session&quot;) || &quot;&quot;); let listuser: any = { username: this.username, } this.http.post('http://localhost:8080/demoprojectjava/list-user/', listuser, { observe: 'response' }).subscribe(res =&gt; { console.log(res); }); } } </code></pre> <p><strong>list-user.component.html</strong> <br></p> <pre><code>&lt;div&gt; &lt;h1 class=&quot;listuser&quot;&gt; Display Data from Json File &lt;/h1&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;User Id&lt;/th&gt; &lt;th&gt;Lastname&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;{{--Here I need value from Json array}}&lt;/td&gt; &lt;td&gt;{{--Here I need value from Json array}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>When I run my code, in console I got the output as a result for <strong>console.log(res);</strong> as :</p> <pre><code>{&quot;user_data&quot;:[{&quot;user_id&quot;:&quot;111&quot;,&quot;username&quot;:&quot;Hridya&quot;},{&quot;user_id&quot;:&quot;222&quot;,&quot;username&quot;:&quot;Rizz&quot;}]} </code></pre>
[ { "answer_id": 74569753, "author": "Philipp Meissner", "author_id": 3686898, "author_profile": "https://Stackoverflow.com/users/3686898", "pm_score": 1, "selected": false, "text": "userData$ async subscribe ngFor import { HttpClient } from '@angular/common/http';\nimport { Component, OnInit } from '@angular/core';\nimport { FormGroup } from '@angular/forms';\nimport { Router } from '@angular/router';\nimport { Observable } from 'rxjs';\n\ntype ResponseTypeFromYourBackend = any;\n\n@Component({\n selector: 'app-list-user',\n templateUrl: './list-user.component.html',\n styleUrls: ['./list-user.component.css']\n})\nexport class ListUserComponent implements OnInit {\n loginForm!: FormGroup;\n submitted = false;\n jdbc: any;\n username:any\n userData$: Observable<ResponseTypeFromYourBackend>;\n\n constructor(private http: HttpClient, private router: Router) { }\n\n ngOnInit() {\n this.username = JSON.parse(localStorage.getItem(\"session\") || \"\");\n let listuser: any = {\n username: this.username,\n }\n this.userData$ = this.http.post('http://localhost:8080/demoprojectjava/list-user/',\n listuser,\n { observe: 'response' }\n );\n }\n}\n\n\n<div>\n <h1 class=\"listuser\"> Display Data from Json File </h1>\n <table *ngIf=\"userData$ | async as data\">\n <thead>\n <tr>\n <th>User Id</th>\n <th>Lastname</th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let user of data.user_data\">\n <td>{{ user.user_id}}</td>\n <td>{{ user.username}}</td>\n </tr>\n </tbody>\n </table>\n</div>\n" }, { "answer_id": 74569767, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 1, "selected": false, "text": "userData$: Observable<YourType>;\n...\nngOnInit() {\n ...\n this.userData$ = this.http.post('http://localhost:8080/demoprojectjava/list-user/',\n listuser).pipe(map(item => item.user_data));\n }\n async <tr *ngFor=\"let item of userData$ | async\">\n <td>{{item.user_id}}</td>\n <td>{{item.username}}</td>\n</tr>\n" }, { "answer_id": 74569807, "author": "Vishnu Prabhu", "author_id": 20587586, "author_profile": "https://Stackoverflow.com/users/20587586", "pm_score": 1, "selected": false, "text": "import { HttpClient } from '@angular/common/http';\nimport { Component, OnInit } from '@angular/core';\nimport { FormGroup } from '@angular/forms';\nimport { Router } from '@angular/router';\n\n@Component({\n selector: 'app-upload-active-census',\n templateUrl: './upload-active-census.component.html',\n styleUrls: ['./upload-active-census.component.css'],\n})\nexport class UploadActiveCensusComponent implements OnInit {\n loginForm!: FormGroup;\n submitted = false;\n jdbc: any;\n username: any;\n data: any;\n\n constructor(private http: HttpClient, private router: Router) {}\n\n ngOnInit() {\n this.username = JSON.parse(localStorage.getItem('session') || '');\n let listuser: any = {\n username: this.username,\n };\n this.http\n .post('http://localhost:8080/demoprojectjava/list-user/', listuser, {\n observe: 'response',\n })\n .subscribe((res) => {\n console.log(res);\n return this.data = res;\n });\n }\n} <div>\n <h1 class=\"listuser\"> Display Data from Json File </h1>\n <table>\n <thead>\n <tr>\n <th>User Id</th>\n <th>Lastname</th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let item of data?.user_data\">\n <td>{{item.user_id}}</td>\n <td>{{item.username}}</td>\n </tr>\n </tbody>\n </table>\n</div>" }, { "answer_id": 74611033, "author": "Hridyadas V D", "author_id": 19697246, "author_profile": "https://Stackoverflow.com/users/19697246", "pm_score": 1, "selected": true, "text": "import { HttpClient } from '@angular/common/http';\nimport { Component, OnInit } from '@angular/core';\nimport { FormGroup } from '@angular/forms';\nimport { Router } from '@angular/router';\n\n@Component({\n selector: 'app-list-user',\n templateUrl: './list-user.component.html',\n styleUrls: ['./list-user.component.css']\n})\nexport class ListUserComponent implements OnInit {\n loginForm!: FormGroup;\n submitted = false;\n jdbc: any;\n username: any;\n data: any;\n\n constructor(private http: HttpClient, private router: Router) { }\n\n ngOnInit(): void {\n this.username = JSON.parse(localStorage.getItem(\"session\") || \"\");\n let listuser: any = {\n username: this.username\n }\n\n this.http.post('http://localhost:8080/demoprojectjava/list-user/',\n listuser, { observe: 'response' }).subscribe(res => {\n console.log(res.body);\n return this.data = res;\n },\n );\n }\n}\n <div>\n <h1 class=\"listuser\"> Display Data from Json File</h1>\n <table>\n <thead>\n <tr>\n <th>User Id</th>\n <th>Lastname</th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let user of data.body.user_data\">\n <td>{{user.user_id}}</td>\n <td>{{user.username}}</td>\n </tr>\n </tbody>\n </table>\n</div>\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19697246/" ]
74,569,729
<p>I have a string <code>a = &quot;\vipin&quot;</code> but when I am printing it, it comes up as: <code>vipin</code>.</p> <p>I tried</p> <pre><code>if(a.contains&quot;\&quot;) { a.replace(&quot;\&quot;,&quot;\\&quot;) </code></pre> <p>but this is not working. Need suggestion to get this fixed</p>
[ { "answer_id": 74569753, "author": "Philipp Meissner", "author_id": 3686898, "author_profile": "https://Stackoverflow.com/users/3686898", "pm_score": 1, "selected": false, "text": "userData$ async subscribe ngFor import { HttpClient } from '@angular/common/http';\nimport { Component, OnInit } from '@angular/core';\nimport { FormGroup } from '@angular/forms';\nimport { Router } from '@angular/router';\nimport { Observable } from 'rxjs';\n\ntype ResponseTypeFromYourBackend = any;\n\n@Component({\n selector: 'app-list-user',\n templateUrl: './list-user.component.html',\n styleUrls: ['./list-user.component.css']\n})\nexport class ListUserComponent implements OnInit {\n loginForm!: FormGroup;\n submitted = false;\n jdbc: any;\n username:any\n userData$: Observable<ResponseTypeFromYourBackend>;\n\n constructor(private http: HttpClient, private router: Router) { }\n\n ngOnInit() {\n this.username = JSON.parse(localStorage.getItem(\"session\") || \"\");\n let listuser: any = {\n username: this.username,\n }\n this.userData$ = this.http.post('http://localhost:8080/demoprojectjava/list-user/',\n listuser,\n { observe: 'response' }\n );\n }\n}\n\n\n<div>\n <h1 class=\"listuser\"> Display Data from Json File </h1>\n <table *ngIf=\"userData$ | async as data\">\n <thead>\n <tr>\n <th>User Id</th>\n <th>Lastname</th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let user of data.user_data\">\n <td>{{ user.user_id}}</td>\n <td>{{ user.username}}</td>\n </tr>\n </tbody>\n </table>\n</div>\n" }, { "answer_id": 74569767, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 1, "selected": false, "text": "userData$: Observable<YourType>;\n...\nngOnInit() {\n ...\n this.userData$ = this.http.post('http://localhost:8080/demoprojectjava/list-user/',\n listuser).pipe(map(item => item.user_data));\n }\n async <tr *ngFor=\"let item of userData$ | async\">\n <td>{{item.user_id}}</td>\n <td>{{item.username}}</td>\n</tr>\n" }, { "answer_id": 74569807, "author": "Vishnu Prabhu", "author_id": 20587586, "author_profile": "https://Stackoverflow.com/users/20587586", "pm_score": 1, "selected": false, "text": "import { HttpClient } from '@angular/common/http';\nimport { Component, OnInit } from '@angular/core';\nimport { FormGroup } from '@angular/forms';\nimport { Router } from '@angular/router';\n\n@Component({\n selector: 'app-upload-active-census',\n templateUrl: './upload-active-census.component.html',\n styleUrls: ['./upload-active-census.component.css'],\n})\nexport class UploadActiveCensusComponent implements OnInit {\n loginForm!: FormGroup;\n submitted = false;\n jdbc: any;\n username: any;\n data: any;\n\n constructor(private http: HttpClient, private router: Router) {}\n\n ngOnInit() {\n this.username = JSON.parse(localStorage.getItem('session') || '');\n let listuser: any = {\n username: this.username,\n };\n this.http\n .post('http://localhost:8080/demoprojectjava/list-user/', listuser, {\n observe: 'response',\n })\n .subscribe((res) => {\n console.log(res);\n return this.data = res;\n });\n }\n} <div>\n <h1 class=\"listuser\"> Display Data from Json File </h1>\n <table>\n <thead>\n <tr>\n <th>User Id</th>\n <th>Lastname</th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let item of data?.user_data\">\n <td>{{item.user_id}}</td>\n <td>{{item.username}}</td>\n </tr>\n </tbody>\n </table>\n</div>" }, { "answer_id": 74611033, "author": "Hridyadas V D", "author_id": 19697246, "author_profile": "https://Stackoverflow.com/users/19697246", "pm_score": 1, "selected": true, "text": "import { HttpClient } from '@angular/common/http';\nimport { Component, OnInit } from '@angular/core';\nimport { FormGroup } from '@angular/forms';\nimport { Router } from '@angular/router';\n\n@Component({\n selector: 'app-list-user',\n templateUrl: './list-user.component.html',\n styleUrls: ['./list-user.component.css']\n})\nexport class ListUserComponent implements OnInit {\n loginForm!: FormGroup;\n submitted = false;\n jdbc: any;\n username: any;\n data: any;\n\n constructor(private http: HttpClient, private router: Router) { }\n\n ngOnInit(): void {\n this.username = JSON.parse(localStorage.getItem(\"session\") || \"\");\n let listuser: any = {\n username: this.username\n }\n\n this.http.post('http://localhost:8080/demoprojectjava/list-user/',\n listuser, { observe: 'response' }).subscribe(res => {\n console.log(res.body);\n return this.data = res;\n },\n );\n }\n}\n <div>\n <h1 class=\"listuser\"> Display Data from Json File</h1>\n <table>\n <thead>\n <tr>\n <th>User Id</th>\n <th>Lastname</th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let user of data.body.user_data\">\n <td>{{user.user_id}}</td>\n <td>{{user.username}}</td>\n </tr>\n </tbody>\n </table>\n</div>\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11992552/" ]
74,569,770
<p>I have a function like so:</p> <pre><code>function progress&lt;T&gt;(data: JsonApiQueryData&lt;T&gt;): number { const { links, meta } = data.getMeta(); if (!links.next) { return 1; } const url = new URL(links.next); return parseInt(url.searchParams.get('page[offset]')) / meta.total; } </code></pre> <p>where <code>JsonApiQueryData</code> is defined as:</p> <pre><code>export declare class JsonApiQueryData&lt;T&gt; { protected jsonApiModels: Array&lt;T&gt;; protected metaData: any; constructor(jsonApiModels: Array&lt;T&gt;, metaData?: any); getModels(): T[]; getMeta(): any; } </code></pre> <p>As you can see from the body of <code>progress</code>, I am not doing anything to or with the underlying <code>T</code> type, so I would <em>love</em> to be able to remove the type argument from it.</p> <p>Naively attempting this, like so:</p> <pre><code>function progress(data: JsonApiQueryData): number { ... } </code></pre> <p>gives me an unfortunate but not surprising error:</p> <pre><code>Generic type 'JsonApiQueryData&lt;T&gt;' requires 1 type argument(s). </code></pre> <h3>Update</h3> <p>I should have clarified when initially asking, but the <code>JsonApiQueryData</code> is a library type that I am unable to change (easily). From the (prompt and pretty great) responses I've seen so far, the best way to achieve <em>exactly</em> what I want involves changing that type (to something like <code>class JsonApiQueryData&lt;T = any&gt;</code> or <code>class JsonApiQueryData&lt;T = unknown&gt;</code>). Sorry for my inadvertent goalpost moving.</p>
[ { "answer_id": 74569822, "author": "Guillaume Brunerie", "author_id": 521624, "author_profile": "https://Stackoverflow.com/users/521624", "pm_score": 3, "selected": true, "text": "export declare class JsonApiQueryData<T = unknown>\n progress function progress(data: JsonApiQueryData<unknown>): number {\n function progress<T>(data: JsonApiQueryData<T>): number {\n" }, { "answer_id": 74569829, "author": "Hervé", "author_id": 16778998, "author_profile": "https://Stackoverflow.com/users/16778998", "pm_score": 1, "selected": false, "text": "// interface declaration\nexport interface HasMetaData\n{\n getMeta(): any;\n}\n\n// implment interface\nexport declare class JsonApiQueryData<T> implements HasMetaData {\n protected jsonApiModels: Array<T>;\n protected metaData: any;\n constructor(jsonApiModels: Array<T>, metaData?: any);\n getModels(): T[];\n getMeta(): any;\n}\n // no need of any generic type\nfunction progress(data: HasMetaData): number {\n // accessing getMeta through HasMetaData\n const { links, meta } = data.getMeta();\n if (!links.next) {\n return 1;\n }\n\n const url = new URL(links.next);\n return parseInt(uri.searchParams.get('page[offset]')) / meta.total;\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7003720/" ]
74,569,772
<p>I'm trying to understand from the below code, how can I print only &quot;species&quot; and &quot;width&quot; key values.</p> <pre class="lang-golang prettyprint-override"><code>package main import ( &quot;encoding/json&quot; &quot;fmt&quot; ) type Dimensions struct { Height int Width int } type Bird struct { Species string Description string Dimensions Dimensions } func main() { birdJson := `{&quot;species&quot;:&quot;pigeon&quot;,&quot;description&quot;:&quot;likes to perch on rocks&quot;, &quot;dimensions&quot;:{&quot;height&quot;:24,&quot;width&quot;:10}}` var bird Bird json.Unmarshal([]byte(birdJson), &amp;bird) fmt.Println(bird) // {pigeon likes to perch on rocks {24 10}} } </code></pre> <p>The output I'm expecting is: pigeon and 10</p>
[ { "answer_id": 74569898, "author": "Woody1193", "author_id": 3121975, "author_profile": "https://Stackoverflow.com/users/3121975", "pm_score": 2, "selected": false, "text": "fmt.Println(bird.Species, bird.Dimensions.Width)\n fmt.Printf fmt.Printf(\"Species: %s, Width: %d\\n\", bird.Species, bird.Dimensions.Width)\n" }, { "answer_id": 74570746, "author": "Gopher_h", "author_id": 19930459, "author_profile": "https://Stackoverflow.com/users/19930459", "pm_score": -1, "selected": false, "text": "json: \"-\"" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538383/" ]
74,569,795
<p>I need to output the Primary Connection or Secondary Connection Strings to use this connection string as an input value in Azure Data Factory MongoApi Linked Services to connect the database to upload the Json files from Azure storage account to Azure cosmos db. But I'm getting the error message while output the connection strings using terraform</p> <p>Can Someone please check and help me in this with detailed explanation is much appreciated.</p> <pre><code>output &quot;cosmosdb_connection_strings&quot; { value = data.azurerm_cosmosdb_account.example.connection_strings sensitive = true } </code></pre> <p>Error: Unsupported attribute │ │ on outputs.tf line 21, in output &quot;cosmosdb_connection_strings&quot;: │ 21: value = data.azurerm_cosmosdb_account.example.connection_strings │ │ This object has no argument, nested block, or exported attribute named &quot;connection_strings&quot;</p> <pre><code></code></pre>
[ { "answer_id": 74601719, "author": "kavya Saraboju", "author_id": 15997509, "author_profile": "https://Stackoverflow.com/users/15997509", "pm_score": 1, "selected": false, "text": "resource \"azurerm_cosmosdb_account\" \"db\" {\n name = \"tfex-cosmos-db-31960\"\n location = \"westus2\"\n resource_group_name = data.azurerm_resource_group.example.name\n offer_type = \"Standard\"\n kind = \"MongoDB\"\n\n enable_automatic_failover = true\n \n\n capabilities {\n name = \"EnableAggregationPipeline\"\n }\n\n capabilities {\n name = \"mongoEnableDocLevelTTL\"\n }\n\n capabilities {\n name = \"MongoDBv3.4\"\n }\n\n capabilities {\n name = \"EnableMongo\"\n }\n\n consistency_policy {\n consistency_level = \"BoundedStaleness\"\n max_interval_in_seconds = 300\n max_staleness_prefix = 100000\n }\n\n geo_location {\n location = \"eastus\"\n failover_priority = 0\n }\n\n \n}\n output \"cosmosdb_connectionstrings\" {\n value = \"AccountEndpoint=${azurerm_cosmosdb_account.db.endpoint};AccountKey=${azurerm_cosmosdb_account.db.primary_key};\"\n sensitive = true\n}\n terraform {\nrequired_providers {\n\n\n azapi = {\n source = \"azure/azapi\"\n version = \"=0.1.0\"\n }\n\n azurerm = {\n source = \"hashicorp/azurerm\"\n version = \"=3.0.2\" \n }\n Try upgrade you terraform version. output \"cosmosdb_connectionstrings\" {\n value = tostring(\"${azurerm_cosmosdb_account.db.connection_strings[0]}\")\nsensitive = true\n}\n data \"azurerm_client_config\" \"current\" {}\n\nresource \"azurerm_key_vault\" \"example\" {\n name = \"kaexamplekeyvault\"\n location = data.azurerm_resource_group.example.location\n resource_group_name = data.azurerm_resource_group.example.name\n enabled_for_disk_encryption = true\n tenant_id = data.azurerm_client_config.current.tenant_id\n soft_delete_retention_days = 7\n purge_protection_enabled = false\n\n sku_name = \"standard\"\n\n access_policy {\n tenant_id = data.azurerm_client_config.current.tenant_id\n object_id = data.azurerm_client_config.current.object_id\n\n key_permissions = [\n \"Get\",\"List\", \"Backup\", \"Create\"\n ]\n\n secret_permissions = [\n \"Get\",\"List\", \"Backup\", \"Delete\", \"Purge\", \"Recover\", \"Restore\", \"Set\"\n ]\n\n storage_permissions = [\n \"Get\", \"List\", \"Backup\", \"Delete\", \"DeleteSAS\", \"GetSAS\", \"ListSAS\", \"Purge\", \"Recover\", \"RegenerateKey\", \"Restore\", \"Set\", \"SetSAS\", \"Update\",\n ]\n }\n}\n\nresource \"azurerm_key_vault_secret\" \"example\" {\n count = length(azurerm_cosmosdb_account.db.connection_strings)\n name = \"ASCosmosDBConnectionString-${count.index}\"\n value = tostring(\"${azurerm_cosmosdb_account.db.connection_strings[count.index]}\")\n key_vault_id = azurerm_key_vault.example.id\n}\n" }, { "answer_id": 74624344, "author": "Mohan Kumar G", "author_id": 20362753, "author_profile": "https://Stackoverflow.com/users/20362753", "pm_score": 0, "selected": false, "text": "resource \"azurerm_key_vault_secret\" \"ewo11\" {\n \n name = \"Cosmos-DB-Primary-String\"\n value = azurerm_cosmosdb_account.acc.connection_strings[0]\n key_vault_id = azurerm_key_vault.ewo11.id\n depends_on = [\n azurerm_key_vault.ewo11,\n azurerm_key_vault_access_policy.aduser,\n azurerm_key_vault_access_policy.demo-terraform-automation\n\n ]\n}\n output \"cosmosdb_account_primary_key\" {\n value = azurerm_cosmosdb_account.acc.primary_key\n sensitive = true\n}\n\nlocals {\n \n kind = \"mongodb\"\n db_name = azurerm_cosmosdb_account.acc.name\n common_value = \".mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=\"\n \n}\n\noutput \"cosmosdb_connection_strings\" {\n value = join(\"\", [local.kind, \":\", \"//\", azurerm_cosmosdb_account.acc.name, \":\", azurerm_cosmosdb_account.acc.primary_key, \"@\", local.db_name, local.common_value, \"@\", local.db_name, \"@\"])\n sensitive = true\n}\n\nresource \"azurerm_key_vault_secret\" \"example\" {\n name = \"cosmos-connection-string\"\n value = join(\"\", [local.kind, \":\", \"//\", azurerm_cosmosdb_account.acc.name, \":\", azurerm_cosmosdb_account.acc.primary_key, \"@\", local.db_name, local.common_value, \"@\", local.db_name, \"@\"])\n key_vault_id = data.azurerm_key_vault.example.id\n}\n\nIn both ways I can be able to fix the problems.\n\nIf we want to see the sensitive values, we check those values in terraform.tfstate file. It will be available when we call them in outputs.\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20362753/" ]
74,569,801
<pre><code>btnA.addEventListener('click', function() { console.log(&quot;Answer choice: A&quot;) answerSelected = choiceA.textContent; checkAnswer(answerSelected); }) btnB.addEventListener('click', function() { console.log(&quot;Answer choice: B&quot;) answerSelected = choiceB.textContent; checkAnswer(answerSelected); }) btnC.addEventListener('click', function() { console.log(&quot;Answer choice: C&quot;) answerSelected = choiceC.textContent; checkAnswer(answerSelected); }) btnD.addEventListener('click', function() { console.log(&quot;Answer choice: D&quot;) answerSelected = choiceD.textContent; checkAnswer(answerSelected); }) </code></pre> <p>how would i condense this so that its only one &quot;function&quot;? still new to javascript <a href="https://github.com/rahimh5/Zuhair-Problem" rel="nofollow noreferrer">https://github.com/rahimh5/Zuhair-Problem</a></p>
[ { "answer_id": 74601719, "author": "kavya Saraboju", "author_id": 15997509, "author_profile": "https://Stackoverflow.com/users/15997509", "pm_score": 1, "selected": false, "text": "resource \"azurerm_cosmosdb_account\" \"db\" {\n name = \"tfex-cosmos-db-31960\"\n location = \"westus2\"\n resource_group_name = data.azurerm_resource_group.example.name\n offer_type = \"Standard\"\n kind = \"MongoDB\"\n\n enable_automatic_failover = true\n \n\n capabilities {\n name = \"EnableAggregationPipeline\"\n }\n\n capabilities {\n name = \"mongoEnableDocLevelTTL\"\n }\n\n capabilities {\n name = \"MongoDBv3.4\"\n }\n\n capabilities {\n name = \"EnableMongo\"\n }\n\n consistency_policy {\n consistency_level = \"BoundedStaleness\"\n max_interval_in_seconds = 300\n max_staleness_prefix = 100000\n }\n\n geo_location {\n location = \"eastus\"\n failover_priority = 0\n }\n\n \n}\n output \"cosmosdb_connectionstrings\" {\n value = \"AccountEndpoint=${azurerm_cosmosdb_account.db.endpoint};AccountKey=${azurerm_cosmosdb_account.db.primary_key};\"\n sensitive = true\n}\n terraform {\nrequired_providers {\n\n\n azapi = {\n source = \"azure/azapi\"\n version = \"=0.1.0\"\n }\n\n azurerm = {\n source = \"hashicorp/azurerm\"\n version = \"=3.0.2\" \n }\n Try upgrade you terraform version. output \"cosmosdb_connectionstrings\" {\n value = tostring(\"${azurerm_cosmosdb_account.db.connection_strings[0]}\")\nsensitive = true\n}\n data \"azurerm_client_config\" \"current\" {}\n\nresource \"azurerm_key_vault\" \"example\" {\n name = \"kaexamplekeyvault\"\n location = data.azurerm_resource_group.example.location\n resource_group_name = data.azurerm_resource_group.example.name\n enabled_for_disk_encryption = true\n tenant_id = data.azurerm_client_config.current.tenant_id\n soft_delete_retention_days = 7\n purge_protection_enabled = false\n\n sku_name = \"standard\"\n\n access_policy {\n tenant_id = data.azurerm_client_config.current.tenant_id\n object_id = data.azurerm_client_config.current.object_id\n\n key_permissions = [\n \"Get\",\"List\", \"Backup\", \"Create\"\n ]\n\n secret_permissions = [\n \"Get\",\"List\", \"Backup\", \"Delete\", \"Purge\", \"Recover\", \"Restore\", \"Set\"\n ]\n\n storage_permissions = [\n \"Get\", \"List\", \"Backup\", \"Delete\", \"DeleteSAS\", \"GetSAS\", \"ListSAS\", \"Purge\", \"Recover\", \"RegenerateKey\", \"Restore\", \"Set\", \"SetSAS\", \"Update\",\n ]\n }\n}\n\nresource \"azurerm_key_vault_secret\" \"example\" {\n count = length(azurerm_cosmosdb_account.db.connection_strings)\n name = \"ASCosmosDBConnectionString-${count.index}\"\n value = tostring(\"${azurerm_cosmosdb_account.db.connection_strings[count.index]}\")\n key_vault_id = azurerm_key_vault.example.id\n}\n" }, { "answer_id": 74624344, "author": "Mohan Kumar G", "author_id": 20362753, "author_profile": "https://Stackoverflow.com/users/20362753", "pm_score": 0, "selected": false, "text": "resource \"azurerm_key_vault_secret\" \"ewo11\" {\n \n name = \"Cosmos-DB-Primary-String\"\n value = azurerm_cosmosdb_account.acc.connection_strings[0]\n key_vault_id = azurerm_key_vault.ewo11.id\n depends_on = [\n azurerm_key_vault.ewo11,\n azurerm_key_vault_access_policy.aduser,\n azurerm_key_vault_access_policy.demo-terraform-automation\n\n ]\n}\n output \"cosmosdb_account_primary_key\" {\n value = azurerm_cosmosdb_account.acc.primary_key\n sensitive = true\n}\n\nlocals {\n \n kind = \"mongodb\"\n db_name = azurerm_cosmosdb_account.acc.name\n common_value = \".mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=\"\n \n}\n\noutput \"cosmosdb_connection_strings\" {\n value = join(\"\", [local.kind, \":\", \"//\", azurerm_cosmosdb_account.acc.name, \":\", azurerm_cosmosdb_account.acc.primary_key, \"@\", local.db_name, local.common_value, \"@\", local.db_name, \"@\"])\n sensitive = true\n}\n\nresource \"azurerm_key_vault_secret\" \"example\" {\n name = \"cosmos-connection-string\"\n value = join(\"\", [local.kind, \":\", \"//\", azurerm_cosmosdb_account.acc.name, \":\", azurerm_cosmosdb_account.acc.primary_key, \"@\", local.db_name, local.common_value, \"@\", local.db_name, \"@\"])\n key_vault_id = data.azurerm_key_vault.example.id\n}\n\nIn both ways I can be able to fix the problems.\n\nIf we want to see the sensitive values, we check those values in terraform.tfstate file. It will be available when we call them in outputs.\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18907749/" ]
74,569,810
<p>I'm trying to run some docker images on Kubernetes.</p> <p>docker images</p> <pre class="lang-bash prettyprint-override"><code>master* $ docker images [15:16:49] REPOSITORY TAG IMAGE ID CREATED SIZE usm latest 4dd5245393bf About an hour ago 158MB kuard latest 497961f486c7 4 days ago 22.9MB </code></pre> <p>docker container</p> <pre class="lang-bash prettyprint-override"><code>master* $ docker ps [15:21:40] CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a46850d28303 usm &quot;/docker-entrypoint.…&quot; About an hour ago Up About an hour 0.0.0.0:6061-&gt;80/tcp, :::6061-&gt;80/tcp usm 88471e086486 gcr.io/k8s-minikube/kicbase:v0.0.32 &quot;/usr/local/bin/entr…&quot; 2 days ago Up 2 hours 127.0.0.1:49157-&gt;22/tcp, 127.0.0.1:49156-&gt;2376/tcp, 127.0.0.1:49155-&gt;5000/tcp, 127.0.0.1:49154-&gt;8443/tcp, 127.0.0.1:49153-&gt;32443/tcp minikube </code></pre> <p>Dockerfile</p> <pre><code>FROM nginx COPY ./dist /usr/share/nginx/html EXPOSE 80 </code></pre> <p>kube version</p> <pre class="lang-bash prettyprint-override"><code>master* $ minikube version [15:37:13] minikube version: v1.26.0 commit: f4b412861bb746be73053c9f6d2895f12cf78565 </code></pre> <p>When I run <code>kubectl run mypod --image=usm</code>, I get <strong>ErrImagePull</strong></p> <p>How to run the pod with the local docker image?</p> <pre class="lang-bash prettyprint-override"><code>master* $ kubectl run mypod --image=usm pod/mypod created </code></pre> <pre class="lang-bash prettyprint-override"><code>master* $ kubectl get pods [15:07:49] NAME READY STATUS RESTARTS AGE mypod 0/1 ErrImagePull 0 6s </code></pre> <p>I'm trying to set the imagePullPolicy to never</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: Pod metadata: name: mypod spec: containers: - image: usm imagePullPolicy: Never name: mypod ports: - containerPort: 80 name: http protocol: TCP </code></pre> <pre class="lang-bash prettyprint-override"><code>master* $ kubectl apply -f kube-pod-usm.yaml [15:55:39] pod/mypod created </code></pre> <pre class="lang-bash prettyprint-override"><code>master* $ kubectl get pods [15:55:54] NAME READY STATUS RESTARTS AGE mypod 0/1 ErrImageNeverPull 0 42s </code></pre>
[ { "answer_id": 74570128, "author": "Rick", "author_id": 5260090, "author_profile": "https://Stackoverflow.com/users/5260090", "pm_score": 3, "selected": true, "text": "minikube image load image:tag minikube docker-env" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16755669/" ]
74,569,839
<p>Say we've got a cursor based paginated API where multiple endpoints can be paginated. The response of such an endpoint is always as follows:</p> <pre class="lang-js prettyprint-override"><code>{ &quot;nextCursor&quot;: &quot;someString&quot;, &quot;PAYLOAD_KEY&quot;: &lt;generic response&gt; } </code></pre> <p>So the payload always returns a cursor and the payload key depends on the actual endpoint we use. For example if we have <code>GET /users</code> it might be <code>users</code> and the value of the key be an array of objects or we could cal a <code>GET /some-large-object</code> and the key being <code>item</code> and the payload be an object.<br /> Bottom line the response is always an object with a cursor and one other key and it's associated value.</p> <p>Trying to make this generic in Swift I was thinking of this:</p> <pre class="lang-swift prettyprint-override"><code>public struct Paginable&lt;Body&gt;: Codable where Body: Codable { public let body: Body public let cursor: String? private enum CodingKeys: String, CodingKey { case body, cursor } } </code></pre> <p>Now the only issue with this code is that it expects the <code>Body</code> to be accessible under the <code>&quot;body&quot;</code> key which isn't the case.</p> <p>We could have a <code>struct User: Codable</code> and the paginable specialized as <code>Paginable&lt;[Users]&gt;</code> where the API response object would have the key <code>users</code> for the array.</p> <p>My question is how can I make this generic <code>Paginable</code> struct work so that I can specify the JSON payload key from the <code>Body</code> type?</p>
[ { "answer_id": 74570231, "author": "Boris", "author_id": 15446571, "author_profile": "https://Stackoverflow.com/users/15446571", "pm_score": -1, "selected": false, "text": "struct GenericInfo: Encodable {\n\n init<T: Encodable>(name: String, params: T) {\n valueEncoder = {\n var container = $0.container(keyedBy: CodingKeys.self)\n try container.encode(name, forKey: . name)\n try container.encode(params, forKey: .params)\n }\n }\n\n // MARK: Public\n\n func encode(to encoder: Encoder) throws {\n try valueEncoder(encoder)\n }\n\n // MARK: Internal\n\n enum CodingKeys: String, CodingKey {\n case name\n case params\n }\n\n let valueEncoder: (Encoder) throws -> Void\n}\n" }, { "answer_id": 74574178, "author": "Sulthan", "author_id": 669586, "author_profile": "https://Stackoverflow.com/users/669586", "pm_score": 2, "selected": true, "text": "Body protocol PaginableBody: Codable {\n static var decodingKey: String { get }\n}\n\nstruct RawCodingKey: CodingKey, Equatable {\n let stringValue: String\n let intValue: Int?\n\n init(stringValue: String) {\n self.stringValue = stringValue\n intValue = nil\n }\n\n init(intValue: Int) {\n stringValue = \"\\(intValue)\"\n self.intValue = intValue\n }\n}\n\nstruct Paginable<Body: PaginableBody>: Codable {\n public let body: Body\n public let cursor: String?\n\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: RawCodingKey.self)\n body = try container.decode(Body.self, forKey: RawCodingKey(stringValue: Body.decodingKey))\n cursor = try container.decodeIfPresent(String.self, forKey: RawCodingKey(stringValue: \"nextCursor\"))\n }\n}\n let jsonString = \"\"\"\n{\n \"nextCursor\": \"someString\",\n \"PAYLOAD_KEY\": {}\n}\n\"\"\"\nlet jsonData = Data(jsonString.utf8)\n\nstruct SomeBody: PaginableBody {\n static let decodingKey = \"PAYLOAD_KEY\"\n}\n\nlet decoder = JSONDecoder()\nlet decoded = try? decoder.decode(Paginable<SomeBody>.self, from: jsonData)\nprint(decoded)\n struct Paginable<Body: Codable>: Codable {\n public let body: Body\n public let cursor: String?\n\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: RawCodingKey.self)\n\n let cursorKey = RawCodingKey(stringValue: \"nextCursor\")\n\n cursor = try container.decodeIfPresent(String.self, forKey: cursorKey)\n\n // ! should be replaced with proper decoding error thrown\n let bodyKey = container.allKeys.first { $0 != cursorKey }!\n body = try container.decode(Body.self, forKey: bodyKey)\n }\n}\n JSONDecoder userInfo init(from:)" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1361768/" ]
74,569,886
<p>Render flex issue is getting when minimizing my screen. My required screen design is attached below.</p> <p><a href="https://i.stack.imgur.com/vOCSN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vOCSN.png" alt="enter image description here" /></a></p> <p>I got this perfectly in normal screen.But when I minimise the screen size I got the below screen, <a href="https://i.stack.imgur.com/e1BVa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e1BVa.png" alt="enter image description here" /></a></p> <p>Is it possible to avoid render flex issue here.I tried by wrap row with flexible and expanded widget but nothing works.</p> <pre><code> Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: 52, height: 52, decoration: BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(5), topRight: Radius.circular(5), ), color:Color(0xffF4F7F9), border: controller.isSelected.value &amp;&amp; controller.eventTitle.value==evntnam? Border.all(color: AppColors.secondaryColor):controller.isSelected.value==false &amp;&amp; isSelected? Border.all(color: AppColors.secondaryColor): Border.all( color: Color(0xffEBEBEB) ) ), child: Padding( padding: const EdgeInsets.only(top: 4.0), child: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Center( child: Text( '$date', textAlign: TextAlign.center, ), Center( child: Text( '$month', textAlign: TextAlign.center, ), ) ], ), ), ), ), SizedBox( width: 10, ), Flexible( child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ AutoSizeText( '$evntnam', textAlign: TextAlign.left, ), SizedBox( height: 13, ), Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, textBaseline: TextBaseline.alphabetic, children: [ Container( height: 12, width: 12, decoration: BoxDecoration( // color: Colors.red, image: DecorationImage( image: AssetImage( 'assets/png/marker2.png'))), ), Padding( padding: const EdgeInsets.only(left:5.0), child: Text( '$loc', textAlign: TextAlign.left, ), SizedBox(height: 5,), loc==&quot;&quot;?endDate.toString()==&quot;&quot;?Text( ' · ${startDate}', textAlign: TextAlign.left, style:eventDateStyleDetails, ):Text( ' · ${startDate} -${endDate}', textAlign: TextAlign.left, style:eventDateStyleDetails, ): endDate.toString()==&quot;&quot;?Text( ' · ${startDate}', textAlign: TextAlign.left, style:eventDateStyleDetails, ):Text( ' · ${startDate} -${endDate}', textAlign: TextAlign.left, style: eventDateStyleDetails, ), ], ), ], ), ), ], ) </code></pre>
[ { "answer_id": 74569984, "author": "pmatatias", "author_id": 12838877, "author_profile": "https://Stackoverflow.com/users/12838877", "pm_score": 0, "selected": false, "text": "SingleChildScrollView //parent widget here\n...\n SingleChildCrollView(\n child: Row(\n children: [\n WidgetOndemand()\n Widget timestamps()\n \n ])\n)\n.... //rest of code\n SingleChildScrollView" }, { "answer_id": 74570426, "author": "Septian Dika", "author_id": 13096991, "author_profile": "https://Stackoverflow.com/users/13096991", "pm_score": 2, "selected": true, "text": "Expanded Flexible Text Expanded Flexible loc == '' ? Row(\n mainAxisAlignment: MainAxisAlignment.start,\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n Container(\n height: 12,\n width: 12,\n decoration: BoxDecoration(\n // color: Colors.red,\n image: DecorationImage(\n image: AssetImage('assets/png/marker2.png'))),\n ),\n \n SizedBox(width: 5,),\n \n Flexible(\n child: Text(\n '$loc',\n textAlign: TextAlign.left, \n ),\n \n SizedBox(height: 5,),\n \n loc == \"\" ?\n endDate.toString() == \"\" ?\n Expanded(\n child: Text(\n ' · ${startDate}',\n textAlign: TextAlign.left,\n style:eventDateStyleDetails,\n )) : \n Expanded(\n child: Text(\n ' · ${startDate} -${endDate}',\n textAlign: TextAlign.left,\n style: eventDateStyleDetails,\n )) : \n endDate.toString() == \"\" ? \n Expanded(\n child: Text(\n ' · ${startDate}',\n textAlign: TextAlign.left,\n style:eventDateStyleDetails,\n )) : \n Expanded(\n child: Text(\n ' · ${startDate} -${endDate}',\n textAlign: TextAlign.left,\n style: eventDateStyleDetails,\n )),\n ],\n),\n" }, { "answer_id": 74570659, "author": "Ravindra S. Patil", "author_id": 13997210, "author_profile": "https://Stackoverflow.com/users/13997210", "pm_score": 1, "selected": false, "text": " Row(\n mainAxisAlignment: MainAxisAlignment.start,\n crossAxisAlignment: CrossAxisAlignment.start,\n textBaseline: TextBaseline.alphabetic,\n children: [\n Container(\n height: 50,\n width: 50,\n decoration: BoxDecoration(\n // color: Colors.red,\n image: DecorationImage(\n image: NetworkImage(\n 'https://upload.wikimedia.org/wikipedia/commons/1/17/Google-flutter-logo.png',\n ),\n ),\n ),\n ),\n Padding(\n padding: const EdgeInsets.only(left: 5.0),\n child: Text(\n ' loc here',\n textAlign: TextAlign.left,\n ),\n ),\n SizedBox(\n height: 5,\n ),\n Expanded(\n child: Text(\n '{startDate} -{endDate}',\n textAlign: TextAlign.left,\n // overflow: TextOverflow.ellipsis,//uncomment this line if you dont want elipses text\n ),\n ),\n ],\n ),\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11118094/" ]
74,569,924
<p>How do I search if a column of strings has these two words &quot;medication&quot; and &quot;infant&quot; anywhere in the sentence ?</p> <p>For example if the column contains strings such as</p> <pre><code> ID Col1 1 Quick Brown fox medication 2 Brown fox infant 3 Quick medication fox infant </code></pre> <p>The expected results should be just row with ID 3</p> <pre><code> ID Col1 3 Quick medication fox infant </code></pre> <p>I have tried <code>str_detect</code> and that did not work, so any suggestions is much appreciated.</p>
[ { "answer_id": 74569950, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "grepl regex <- \"(?=.*\\\\bmedication\\\\b)(?=.*\\\\binfant\\\\b).*\"\ndf[grepl(regex, df$Col1, perl=TRUE), ]\n\n ID Col1\n3 3 Quick medication fox infant\n df <- data.frame(\n ID=c(1,2,3),\n Col1=c(\"Quick Brown fox medication\", \"Brown fox infant\",\n \"Quick medication fox infant\")\n)\n" }, { "answer_id": 74570098, "author": "Armel Soubeiga", "author_id": 11368978, "author_profile": "https://Stackoverflow.com/users/11368978", "pm_score": 1, "selected": false, "text": "grepl filter df <- data.frame(id=c(1,2,3), Col1=c('Quick Brown fox medication',\n 'Brown fox infant',\n 'Quick medication fox infant'))\n dplyr::filter(df,grepl(\"medication\",Col1) &\n grepl(\"infant\",Col1))\n id Col1\n1 3 Quick medication fox infant\n" }, { "answer_id": 74570206, "author": "Neeraj", "author_id": 5047311, "author_profile": "https://Stackoverflow.com/users/5047311", "pm_score": 3, "selected": true, "text": "df[with(df, grepl(\"infant\", Col1) & grepl(\"medication\", Col1)),]\n df <- data.frame(id=c(1,2,3), Col1=c('Quick Brown fox medication',\n 'Brown fox infant',\n 'Quick medication fox infant'))\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18795729/" ]
74,569,982
<p>I have a projects list with dynamic KPIs per project, each KPI has (a value and target)</p> <p>I am receiving the dataset in the below format, I am trying to drow one chart for kpi for one project :</p> <pre><code>dataset &lt;- data.frame( value = c(3,5,200.....), Target = c(10,20,250.....), KPI = c(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,....) ) </code></pre> <p>Is there any way to achieve multi-donut KPIs using ggplot!! (or even a pie chart) to look similar to the below image!</p> <p><a href="https://i.stack.imgur.com/3lInw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3lInw.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74570345, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": true, "text": "library(tidyverse)\n\ndataset %>%\n mutate(perc = value/Target) %>%\n ggplot(aes(x = 3, y = perc)) +\n geom_linerange(aes(ymin = 0, ymax = 1), size = 4, color = \"#caeee3\") +\n geom_linerange(aes(ymin = 0, ymax = perc), size = 4, color = \"#01b8aa\") +\n geom_text(aes(x = 1.5, y = 0, label = scales::percent(perc)), size = 6) +\n geom_text(aes(x = 0, y = 0, label = KPI), size = 8, color = 'gray80') +\n coord_polar(theta = 'y') +\n theme_void() +\n scale_x_continuous(limits = c(0, 4), expand = c(0, 0)) + \n facet_wrap(.~KPI) +\n theme(strip.text = element_blank())\n" }, { "answer_id": 74570375, "author": "Yacine Hajji", "author_id": 17049772, "author_profile": "https://Stackoverflow.com/users/17049772", "pm_score": 2, "selected": false, "text": "##### Libraries\nlibrary(ggplot2)\nlibrary(ggpubr)\n\n##### Data management\n# KPI a\ndataset_a <- data.frame(count=c(3, 7),\n KPI=c(\"a\", \"a\"),\n category=c(\"value\", \"nonReached\"))\ndataset_a$fraction <- prop.table(dataset_a$count)\ndataset_a$ymax <- cumsum(dataset_a$fraction)\ndataset_a$ymin <- c(0, head(dataset_a$ymax, n=-1))\ndataset_a$labelPosition <- (dataset_a$ymax + dataset_a$ymin) / 2\ndataset_a$label <- paste0(dataset_a$category, \"\\n value: \", dataset_a$count)\n# KPI b\ndataset_b <- data.frame(count=c(5, 15),\n KPI=c(\"b\", \"b\"),\n category=c(\"value\", \"nonReached\"))\ndataset_b$fraction <- prop.table(dataset_b$count)\ndataset_b$ymax <- cumsum(dataset_b$fraction)\ndataset_b$ymin <- c(0, head(dataset_b$ymax, n=-1))\ndataset_b$labelPosition <- (dataset_b$ymax + dataset_b$ymin) / 2\ndataset_b$label <- paste0(dataset_b$category, \"\\n value: \", dataset_b$count)\n# KPI c\ndataset_c <- data.frame(count=c(200, 50),\n KPI=c(\"c\", \"c\"),\n category=c(\"value\", \"nonReached\"))\ndataset_c$fraction <- prop.table(dataset_c$count)\ndataset_c$ymax <- cumsum(dataset_c$fraction)\ndataset_c$ymin <- c(0, head(dataset_c$ymax, n=-1))\ndataset_c$labelPosition <- (dataset_c$ymax + dataset_c$ymin) / 2\ndataset_c$label <- paste0(dataset_c$category, \"\\n value: \", dataset_c$count)\n\n##### The plots\npie_a <- ggplot(dataset_a, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) + \n geom_rect() + \n scale_fill_manual(values=c(\"#2bbd97\", \"#64f0cb\")) + \n coord_polar(theta=\"y\") + \n xlim(c(-1, 4)) + \n theme_void() + \n theme(legend.position = \"none\") + \n geom_text(x=0.5, y=2, label=paste(round(subset(dataset_a, category==\"value\")$fraction, 2)*100, \"%\", sep=\"\"), size=9) + \n geom_text(x=-1.5, y=2, label=paste(\"KPI a\"), size=6, color=\"#a4a4a4\")\npie_b <- ggplot(dataset_b, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) + \n geom_rect() + \n scale_fill_manual(values=c(\"#2bbd97\", \"#64f0cb\")) + \n coord_polar(theta=\"y\") + \n xlim(c(-1, 4)) + \n theme_void() + \n theme(legend.position = \"none\") + \n geom_text(x=0.5, y=2, label=paste(round(subset(dataset_b, category==\"value\")$fraction, 2)*100, \"%\", sep=\"\"), size=9) + \n geom_text(x=-1.5, y=2, label=paste(\"KPI b\"), size=6, color=\"#a4a4a4\")\npie_c <- ggplot(dataset_c, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) + \n geom_rect() + \n scale_fill_manual(values=c(\"#2bbd97\", \"#64f0cb\")) + \n coord_polar(theta=\"y\") + \n xlim(c(-1, 4)) + \n theme_void() + \n theme(legend.position = \"none\") + \n geom_text(x=0.5, y=2, label=paste(round(subset(dataset_c, category==\"value\")$fraction, 2)*100, \"%\", sep=\"\"), size=9) + \n geom_text(x=-1.5, y=2, label=paste(\"KPI c\"), size=6, color=\"#a4a4a4\")\n\n##### Display plots\nggarrange(pie_a, \n pie_b, \n pie_c, \n nrow=1, ncol=3)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17632515/" ]
74,569,990
<p>I needed to a library specific output and, so I tired it like this way. But I got &quot;ValueError: I/O operation on closed file.&quot; Error.</p> <p>Here the code example that I tried...</p> <pre><code>import sys def print_test(): print(&quot;Printing testing print...!&quot;) print(&quot;line 01&quot;) print(&quot;line 02&quot;) print(&quot;line 03&quot;) print(&quot;Before capture&quot;) def main(): sys.stdout= open(&quot;test.txt&quot;, 'w') print_test() sys.stdout.close() main() print(&quot;After capture&quot;) with open('test.txt', 'r') as f: lines= f.readlines() for i in lines: print(i) if &quot;line 01&quot; in lines: print(&quot;Found line 01&quot;) </code></pre>
[ { "answer_id": 74570075, "author": "charon25", "author_id": 16114044, "author_profile": "https://Stackoverflow.com/users/16114044", "pm_score": 1, "selected": false, "text": "sys.stdout.close() file def print_test(f):\n print(\"Printing testing print...!\", file=f)\n print(\"line 01\", file=f)\n print(\"line 02\", file=f)\n print(\"line 03\", file=f)\n\n\nprint(\"Before capture\")\n\ndef main():\n f = open(\"test.txt\", 'w')\n print_test(f)\n f.close()\nmain()\n" }, { "answer_id": 74570199, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 1, "selected": true, "text": "sys.stdout.close()\n stdout print file print file main print sys.stdout ValueError sys.stdout print_test def main():\n stdout = sys.stdout # create local copy of stdout\n sys.stdout = open(\"test.txt\", 'w') # change stdout\n print_test()\n sys.stdout.close()\n sys.stdout = stdout # reassign standard output stream to sys.stdout\n print file myoutput = open(\"test.txt\", \"w\")\nprint(\"Print to file\", file=myoutput)\n\n# pass file object to function\ndef my_print(file):\n print(\"function call to print\", file=file)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20597380/" ]
74,569,993
<p>So i try to use some css animated background. It look like this: <a href="https://i.stack.imgur.com/mG4Xz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mG4Xz.png" alt="enter image description here" /></a></p> <p>The particle hovers above the menu list (for now it just &quot;test&quot;). My particle code is in css:</p> <pre><code>.circles { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; } .circles li { position: absolute; display: block; list-style: none; width: 20px; height: 20px; background: rgb(17, 218, 94, 0.4); animation: animate 25s linear infinite; bottom: -150px; } .circles li:nth-child(1) { left: 25%; width: 80px; height: 80px; animation-delay: 0s; } .circles li:nth-child(2) { left: 10%; width: 20px; height: 20px; animation-delay: 2s; animation-duration: 12s; } .circles li:nth-child(3) { left: 70%; width: 20px; height: 20px; animation-delay: 4s; } .circles li:nth-child(4) { left: 40%; width: 60px; height: 60px; animation-delay: 0s; animation-duration: 18s; } .circles li:nth-child(5) { left: 65%; width: 20px; height: 20px; animation-delay: 0s; } .circles li:nth-child(6) { left: 75%; width: 110px; height: 110px; animation-delay: 3s; } .circles li:nth-child(7) { left: 35%; width: 150px; height: 150px; animation-delay: 7s; } .circles li:nth-child(8) { left: 50%; width: 25px; height: 25px; animation-delay: 15s; animation-duration: 45s; } </code></pre> <p>I got this particle effect from some website. As you can see it's just manually assign animation to <code>&lt;li&gt;</code>. I use React, my react code look like this:</p> <pre><code>return ( &lt;div className=&quot;area w-screen&quot;&gt; &lt;div className=&quot; bg-white px-3 py-5&quot;&gt; &lt;nav className=&quot;flex justify-between px-10 &quot;&gt; &lt;ul className=&quot; flex items-center &quot;&gt; &lt;li&gt; &lt;div className=&quot; text-stone-800 font-bold text-xl px-5&quot;&gt; LogoGoesEre &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;a className=&quot; text-zinc-900&quot; href=&quot;&quot;&gt; Dashboard &lt;/a&gt; &lt;/li&gt; &lt;li className=&quot;px-3&quot;&gt; &lt;a className=&quot; text-zinc-900&quot; href=&quot;&quot;&gt; Quiz &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;a href=&quot;#&quot;&gt; &lt;button className=&quot; bg-sky-500 hover:bg-sky-700 rounded-xl px-3 py-2 text-white&quot;&gt; Logout &lt;/button&gt; &lt;/a&gt; &lt;/nav&gt; &lt;/div&gt; &lt;div className=&quot; bg-slate-50 w-1/3 h-1/2 p-5 m-10&quot;&gt; &lt;h1&gt;text&lt;/h1&gt; &lt;/div&gt; &lt;div&gt; &lt;ul className=&quot;circles&quot;&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; ); </code></pre> <p>How to set the particle so it appear bellow my other item?</p>
[ { "answer_id": 74570075, "author": "charon25", "author_id": 16114044, "author_profile": "https://Stackoverflow.com/users/16114044", "pm_score": 1, "selected": false, "text": "sys.stdout.close() file def print_test(f):\n print(\"Printing testing print...!\", file=f)\n print(\"line 01\", file=f)\n print(\"line 02\", file=f)\n print(\"line 03\", file=f)\n\n\nprint(\"Before capture\")\n\ndef main():\n f = open(\"test.txt\", 'w')\n print_test(f)\n f.close()\nmain()\n" }, { "answer_id": 74570199, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 1, "selected": true, "text": "sys.stdout.close()\n stdout print file print file main print sys.stdout ValueError sys.stdout print_test def main():\n stdout = sys.stdout # create local copy of stdout\n sys.stdout = open(\"test.txt\", 'w') # change stdout\n print_test()\n sys.stdout.close()\n sys.stdout = stdout # reassign standard output stream to sys.stdout\n print file myoutput = open(\"test.txt\", \"w\")\nprint(\"Print to file\", file=myoutput)\n\n# pass file object to function\ndef my_print(file):\n print(\"function call to print\", file=file)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15991847/" ]
74,569,996
<p>Suppose I have <code>Post</code> model that has <code>is_verified</code> column with <code>smallint</code> datatype, how can I get all records that is verified? One thing to do this is using this:</p> <pre class="lang-php prettyprint-override"><code>Post::where('is_verified', true)-&gt;get(); </code></pre> <p>The code above will produce the following query:</p> <pre class="lang-sql prettyprint-override"><code>select * from `posts` where `posts`.`is_verified` = true </code></pre> <p>... which will get me all verified <code>Post</code> records; in note that <code>is_verified</code> on all existing records is either <code>0</code> or <code>1</code>.</p> <p>However, after I get myself curious and try to manually change some <code>is_verified</code>'s record value from <code>1</code> to another truthy number e.g. <code>2</code>, the above eloquent query didn't work as expected anymore: records with <code>is_verified</code> value of <code>2</code> didn't get retrieved.</p> <p>I tried to execute the sql query directly from HeidiSQL as well, but it was just the same. Then I tried to change the <code>=</code> in the sql query to <code>is</code>, and now it's working as expected i.e. all records with truthy <code>is_verified</code> get retrieved:</p> <pre class="lang-sql prettyprint-override"><code>select * from `posts` where `posts`.`is_verified` is true </code></pre> <p>So my questions are:</p> <ul> <li>Does the above behaviour is correct and expected?</li> <li>How can I execute the last sql query in eloquent? One thing I can think of is <code>where('is_verified', '!=', 0)</code> but that feels weird in terms of readability especially when the query is pretty long and a bit complicated</li> <li>As I stated before, the <code>is_verified</code> column is a <code>smallint</code>. Does this affects the behaviour? Because this conversation <a href="https://stackoverflow.com/questions/44028862">here</a> states that <code>boolean</code> column datatype is typically <code>tinyint</code>, not <code>smallint</code>.</li> </ul> <p>And that's it. Thank you in advance!</p>
[ { "answer_id": 74570053, "author": "dz0nika", "author_id": 15138278, "author_profile": "https://Stackoverflow.com/users/15138278", "pm_score": 1, "selected": false, "text": "smallint Post::where('is_verified', true)->get(); smallint tinyint" }, { "answer_id": 74580887, "author": "rifqy abdl", "author_id": 12725825, "author_profile": "https://Stackoverflow.com/users/12725825", "pm_score": 1, "selected": true, "text": "boolean tinyint(1) bool boolean tinyint(1) smallint tinyint select * from `posts` where `posts`.`is_verified` = true;\n select * from `posts` where `posts`.`is_verified` = 1;\n Post is_verified 1 Post is_verified 1 2 3 is = select * from `posts` where `posts`.`is_verified` is true;\n Post is_verified where('is_verified', '!=', 0) whereRaw() Post::whereRaw('posts.is_verified is true')->get();\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12725825/" ]
74,570,016
<p>I´m at my second week learning C++ and now i stumbled upon a problem I cant seem to fix. I know how to make structs and use them but I get error codes E0029 and C2059 when I try to debug and run my code.</p> <p><a href="https://i.stack.imgur.com/ikH8h.png" rel="nofollow noreferrer">Print Screen of Code</a></p> <pre><code>#include &lt;iostream&gt; struct Car { std::string make; std::string model; int year; double cost; }; int main() { Car myCar; myCar; { .make = &quot;Tesla&quot;, .model : &quot;Model Y&quot;, .year = 2020, .cost : 60000; }; return 0; } </code></pre> <p>I know how to do this in other ways, it's only when I do it like this I get these error codes.</p>
[ { "answer_id": 74570080, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": -1, "selected": false, "text": " Car myCar;\n myCar = { .make = \"Tesla\", .model : \"Model Y\", .year = 2020, .cost : 60000; };\n" }, { "answer_id": 74570111, "author": "whatswrong", "author_id": 20591990, "author_profile": "https://Stackoverflow.com/users/20591990", "pm_score": 1, "selected": false, "text": "myCar = { \"Tesla\", \"Model Y\", 2020, 60000 };\n myCar = { .make = \"Tesla\", .model = \"Model Y\", .year = 2020, .cost = 60000 };\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20597417/" ]
74,570,042
<p>table1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>New York</td> </tr> <tr> <td>B</td> <td>Istanbul</td> </tr> <tr> <td>B</td> <td>London</td> </tr> </tbody> </table> </div> <p>table2</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>New York</td> </tr> <tr> <td>B</td> <td>Istanbul</td> </tr> <tr> <td>C</td> <td>London</td> </tr> </tbody> </table> </div> <pre><code>SELECT Column A From Table1 minus SELECT Column A From Table2 </code></pre> <p>RESULT -&gt; C</p> <p>I want to see result row so not only columnA</p> <p>RESULT -&gt; C LONDON</p> <p>How can i handle it?</p>
[ { "answer_id": 74570066, "author": "Koen Lostrie", "author_id": 4189814, "author_profile": "https://Stackoverflow.com/users/4189814", "pm_score": 0, "selected": false, "text": "SELECT Column B FROM table \n WHERE Column A IN (\nSELECT Column A From Table\nminus\nSELECT Column A From Table\n)\n" }, { "answer_id": 74570453, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 1, "selected": false, "text": "SQL> with\n 2 table1 (cola, colb) as\n 3 (select 'A', 'New York' from dual union all\n 4 select 'B', 'Istanbul' from dual union all\n 5 select 'B', 'London' from dual\n 6 ),\n 7 table2 (cola, colb) as\n 8 (select 'A', 'New York' from dual union all\n 9 select 'B', 'Istanbul' from dual union all\n 10 select 'C', 'London' from dual\n 11 )\n 12 select b.*\n 13 from table2 b\n 14 where not exists (select null\n 15 from table1 a\n 16 where a.cola = b.cola\n 17 );\n\nC COLB\n- --------\nC London\n\nSQL>\n" }, { "answer_id": 74572514, "author": "nikhil sugandh", "author_id": 6285600, "author_profile": "https://Stackoverflow.com/users/6285600", "pm_score": 0, "selected": false, "text": "btree bitmap select b.* from \ntable2 b left join table1 a \non b.ColumnA=a.ColumnA\nwhere a.ColumnA is null;\n in subquery" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15050958/" ]
74,570,068
<pre class="lang-js prettyprint-override"><code>const Discord = require(&quot;discord.js&quot;) require(&quot;dotenv&quot;).config() const client = new Discord.Client({ intents: [] }) client.on(&quot;ready&quot;, () =&gt; { console.log(`Logged in as ${client.user.tag}!`) }) client.on(&quot;message&quot;, msg =&gt; { if (msg.content === &quot;ping&quot;) { msg.reply(&quot;pong&quot;); } }) client.login(process.env.TOKEN) </code></pre> <pre class="lang-none prettyprint-override"><code>if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid); ^ Error [TokenInvalid]: An invalid token was provided. at Client.login (C:\Users\johnw\node_modules\discord.js\src\client\Client.js:214:52) at Object.&lt;anonymous&gt; (C:\Users\johnw\WebstormProjects\DiscordBot\index.js:15:8) at Module._compile (node:internal/modules/cjs/loader:1159:14) at Module._extensions..js (node:internal/modules/cjs/loader:1213:10) at Module.load (node:internal/modules/cjs/loader:1037:32) at Module._load (node:internal/modules/cjs/loader:878:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12) at node:internal/main/run_main_module:23:47 { code: 'TokenInvalid' } Node.js v19.0.0 </code></pre> <p><strong>ENV FILE</strong> - This is an old Token</p> <pre class="lang-none prettyprint-override"><code>TOKEN=MTA0NTI0ODI0NjIyMzc0NTAzNA.G36OM9.q2GxfF8ZOXqIjkKcAAnOsH_XbuC_vbgLDuOLT8 </code></pre> <p>I am trying to run my bot but it always tells me that my token is invalid.</p> <p>I tried refreshing my token and using the new one but even this won't help.</p> <p><a href="https://i.stack.imgur.com/6VGzu.png" rel="nofollow noreferrer">Folder Structure</a></p>
[ { "answer_id": 74570112, "author": "pvpb0t", "author_id": 20597388, "author_profile": "https://Stackoverflow.com/users/20597388", "pm_score": -1, "selected": false, "text": "const { token } = require('./config.json');\n" }, { "answer_id": 74570116, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": -1, "selected": false, "text": "client.login(process.env.TOKEN)\n console.log(process.env.TOKEN);\nclient.login(process.env.TOKEN);\n undefined .env" }, { "answer_id": 74576432, "author": "Thunder", "author_id": 16499723, "author_profile": "https://Stackoverflow.com/users/16499723", "pm_score": 1, "selected": false, "text": "process.env .env" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19602149/" ]
74,570,070
<p>There are several switches in the app's layout, and when these switches are pressed, the value of sharedPreference is changed to determine whether a specific function is performed. For example, if the funcOnOff switch is off, the voice notification function is off, and when fromOnOff is off, caller information cannot be checked when a notification is received.</p> <p>I am using several source codes that work almost similarly as below. Is it possible to pass multiple android.widgets as parameters to a function so that these actions can be acted upon as a single function?</p> <pre><code>var funcOnOff: Switch = findViewById(R.id.func_on_off) var fromOnOff: Switch = findViewById(R.id.from_on_off) var timeOnOff: Switch = findViewById(R.id.time_on_off) var contentOnOff: Switch = findViewById(R.id.content_on_off) funcOnOff.setOnCheckedChangeListener { buttonView, isChecked -&gt; if (isChecked) { editor.putString(&quot;func&quot;, &quot;ON&quot;) } else { editor.putString(&quot;func&quot;, &quot;OFF&quot;) } editor.commit() } fromOnOff.setOnCheckedChangeListener { buttonView, isChecked -&gt; if (isChecked) { editor.putString(&quot;from&quot;, &quot;ON&quot;) } else { editor.putString(&quot;from&quot;, &quot;OFF&quot;) } editor.commit() } timeOnOff.setOnCheckedChangeListener { buttonView, isChecked -&gt; if (isChecked) { editor.putString(&quot;time&quot;, &quot;ON&quot;) } else { editor.putString(&quot;time&quot;, &quot;OFF&quot;) } editor.commit() } </code></pre>
[ { "answer_id": 74570464, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 2, "selected": true, "text": "OnCheckedChangeListener fun onCheckedChangedListenerForPreferenceKey(key: String): CompoundButton.OnCheckedChangeListener = { _, isChecked ->\n if (isChecked) {\n editor.putString(key, \"ON\") // wouldn't using putBoolean be better?\n } else {\n editor.putString(key, \"OFF\")\n }\n editor.commit()\n}\n funcOnOff.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey(\"func\"))\nfromOnOff.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey(\"from\"))\ntimeOnOff.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey(\"time\"))\n listOf(\n funcOnOff to \"func\"\n fromOnOff to \"from\"\n timeOnOff to \"time\"\n).forEach { (switch, key) -> \n switch.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey(key))\n}\n" }, { "answer_id": 74572783, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 0, "selected": false, "text": "// If the signature here matches the listener function, you can pass a reference\n// to this function directly\nfun handleSwitch(switch: CompoundButton, isChecked: Boolean) {\n when(switch) {\n funcOnOff -> \"func\"\n fromOnOff -> \"from\"\n timeOnOff -> \"time\"\n else -> null\n }?.let { key ->\n editor.putString(key, if (isChecked) \"ON\" else \"OFF\").commit()\n }\n}\n val switches = listOf(funcOnOff, fromOnOff, timeOnOff)\nswitches.forEach { it.setonOnCheckedChangedListener(::handleSwitch) }\n\n// or if you don't want to use a function reference\nswitches.forEach {\n it.setOnCheckedChangedListener { switch, enabled -> handleSwitch(switch, enabled) }\n}\n\n// or since you're iterating over the switches anyway, you could make the current one\n// part of the callback lambda and ignore the parameters\nswitches.forEach { switch ->\n it.setOnCheckedChangedListener { _, _ -> handleSwitch(switch, switch.isChecked) }\n}\n when keys when" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18560558/" ]
74,570,078
<p>I am trying to combine two select statements because my original query was taking way to long with LEFT JOIN</p> <p>Original Query:</p> <pre><code>SELECT DISTINCT a.RequestId, a.*, str_to_date(RequestedTestDate, '%d-%b-%Y') AS cRequestedTestDate, str_to_date(ActualTestDate, '%d-%b-%Y') AS cActualTestDate, name as Engineer, Cancelled FROM ( cert_request_cute a LEFT JOIN tech_schedule b on a.RequestId = b.cute_id ) LEFT JOIN techs ts on b.tech_id = ts.id LEFT JOIN sts c on ( c.id = a.stsCustomer OR c.code = a.stsCustomer ) LEFT JOIN status_cute stat on ( stat.RequestId = a.RequestId )&quot; . $swhere . $orderByQuery . $limitQuery; </code></pre> <p>With the above query I was able to get all the rows but it took forever with over 10k rows</p> <p>Modified Query:</p> <pre><code>SELECT DISTINCT a.RequestId, a.*, str_to_date(RequestedTestDate, '%d-%b-%Y') AS cRequestedTestDate, str_to_date(ActualTestDate, '%d-%b-%Y') AS cActualTestDate, name as Engineer, Cancelled FROM ( cert_request_cute a JOIN tech_schedule b on a.RequestId = b.cute_id ) JOIN techs ts on b.tech_id = ts.id JOIN sts c on ( c.id = a.stsCustomer OR c.code = a.stsCustomer ) JOIN status_cute stat on ( stat.RequestId = a.RequestId )&quot; . $swhere . $orderByQuery . $limitQuery; </code></pre> <p>With this query im able to get results faster but its missing rows that are ether empty or null I guess, How can I include the missing rows with a second query. I've read most of the other questions on here on the topic but I ended up being more confused.</p> <p>Wanted something like the following Query:</p> <pre><code>SELECT DISTINCT a.RequestId, a.*, str_to_date(RequestedTestDate, '%d-%b-%Y') AS cRequestedTestDate, str_to_date(ActualTestDate, '%d-%b-%Y') AS cActualTestDate, name as Engineer, Cancelled FROM ( cert_request_cute a JOIN tech_schedule b on a.RequestId = b.cute_id ) WHERE b.cute_id, ts.id, a.stsCustomer, a.RequestId NOT IN ( DISTINCT a.RequestId, a.*, str_to_date(RequestedTestDate, '%d-%b-%Y') AS cRequestedTestDate, str_to_date(ActualTestDate, '%d-%b-%Y') AS cActualTestDate, name as Engineer, Cancelled FROM ( cert_request_cute a JOIN tech_schedule.b.cute_id b on a.RequestId.b.cute_id = b.cute_id ) JOIN techs.ts.id ts on b.tech_id.ts.id = ts.id JOIN sts c on ( c.id = a.stsCustomer.astsCustomer OR c.code.c.code = a.stsCustomer ) JOIN status_cute stat on ( stat.RequestId.a.RequestId = a.RequestId ) )&quot; . $swhere . $orderByQuery . $limitQuery; </code></pre> <p>I know the above query is absolutely wrong but I just dont know or understand how to put it together. I just want to create a second NOT IN and join the two tables to get the missing rows. Also is there a way to optimize the query period of better speed and results?</p> <p>cert_request_cute Table:</p> <pre><code>CREATE TABLE `cert_request_cute` ( `RequestId` int(10) NOT NULL, `stsCustomer` char(8) DEFAULT NULL, `stsCustomerOtherCode` char(3) DEFAULT NULL, `stsCustomerOtherDescription` mediumtext DEFAULT NULL, `FirstName` mediumtext NOT NULL DEFAULT '', `LastName` mediumtext NOT NULL DEFAULT '', `Email` mediumtext NOT NULL DEFAULT '', `Phone` mediumtext NOT NULL DEFAULT '', `stsHandle` mediumtext NOT NULL, `CertificationRequest` mediumtext DEFAULT NULL, `CertificationRequestDetails` mediumtext NOT NULL, `RequestDescription` mediumtext DEFAULT NULL, `RequestedTestDate` mediumtext DEFAULT NULL, `RequestedBetaDate` mediumtext DEFAULT NULL, `RequestedGlobalReleaseDate` mediumtext DEFAULT NULL, `BetaSiteXP` mediumtext NOT NULL, `BetaSite7` mediumtext NOT NULL, `BetaSiteXP-2` mediumtext NOT NULL, `BetaSite7-2` mediumtext NOT NULL, `FirstBetaSiteChoice` char(7) DEFAULT NULL, `SecondBetaSiteChoice` char(7) DEFAULT NULL, `ThirdBetaSiteChoice` char(7) DEFAULT NULL, `ApplicationName` mediumtext DEFAULT NULL, `ApplicationVersion` mediumtext DEFAULT NULL, `SCutePlatform` mediumtext DEFAULT NULL, `ApplicationLocalServer` char(25) DEFAULT NULL, `ApplicationLocalServerOther` mediumtext DEFAULT NULL, `OSAPI` mediumtext DEFAULT NULL, `OSAPIOther` mediumtext DEFAULT NULL, `NewOSAPI` mediumtext DEFAULT NULL, `WANProtocol` mediumtext DEFAULT NULL, `WANProtocolOther` mediumtext DEFAULT NULL, `NewWANProtocol` mediumtext DEFAULT NULL, `Gateway` mediumtext DEFAULT NULL, `GatewayOther` mediumtext DEFAULT NULL, `SCuteLAN` mediumtext DEFAULT NULL, `LANProtocol` mediumtext DEFAULT NULL, `CommunicationCard` mediumtext DEFAULT NULL, `GatewayOS` mediumtext DEFAULT NULL, `RoutingProtocol` mediumtext DEFAULT NULL, `RegisteredAddressing` char(5) DEFAULT NULL, `AdditionalInformation` mediumtext DEFAULT NULL, `MainFirstName` mediumtext DEFAULT NULL, `MainLastName` mediumtext DEFAULT NULL, `NetworkConfiguratorFirstName` mediumtext NOT NULL, `NetworkConfiguratorLastName` mediumtext NOT NULL, `NetworkConfiguratorEmail` mediumtext NOT NULL, `NetworkConfiguratorPhone` mediumtext NOT NULL, `OperationsManagerFirstName` mediumtext NOT NULL, `OperationsManagerLastName` mediumtext NOT NULL, `OperationsManagerEmail` mediumtext NOT NULL, `OperationsManagerPhone` mediumtext NOT NULL, `TechSupportFirstName` mediumtext NOT NULL, `TechSupportlastName` mediumtext NOT NULL, `TechSupportEmail` mediumtext NOT NULL, `TechSupportPhone` mediumtext NOT NULL, `stsManagerFirstName` mediumtext NOT NULL, `stsManagerLastName` mediumtext NOT NULL, `stsManagerEmail` mediumtext NOT NULL, `stsManagerPhone` mediumtext NOT NULL, `SAccountManagerFirstName` mediumtext NOT NULL DEFAULT '', `SAccountManagerLastName` mediumtext NOT NULL DEFAULT '', `SAccountManagerEmail` mediumtext NOT NULL DEFAULT '', `SAccountManagerPhone` mediumtext NOT NULL DEFAULT '', `PrimaryContactFirstName` mediumtext NOT NULL, `PrimaryContactLastName` mediumtext NOT NULL, `PrimaryContactEmail` mediumtext NOT NULL, `PrimaryContactPhone` mediumtext NOT NULL, `CompanyAddress` mediumtext NOT NULL, `CompanyWebsite` mediumtext NOT NULL, `RequestedDate` mediumtext NOT NULL, `ActualTestDate` mediumtext DEFAULT NULL, `TestDays` char(2) DEFAULT NULL, `PPMNumber` mediumtext DEFAULT NULL, `Comments` mediumtext DEFAULT NULL, `stsUsers` mediumtext NOT NULL COMMENT 'user id of sts', `Cancelled` set('yes','no') NOT NULL DEFAULT 'no', `TestingType` mediumtext NOT NULL, `has_url` set('Yes','No') NOT NULL, `RequestType` mediumtext NOT NULL, `OperatingSystem` mediumtext NOT NULL, `complete` int(1) NOT NULL, `Price` mediumtext NOT NULL, `UpdatePrice` mediumtext NOT NULL DEFAULT '-', `BillingCompanyName` mediumtext NOT NULL, `BillingName` mediumtext NOT NULL, `BillingEmail` mediumtext NOT NULL, `BillingPhone` mediumtext NOT NULL, `ProductOwner` mediumtext NOT NULL COMMENT 'XS only', `CostCenter` mediumtext NOT NULL COMMENT 'XS only', `BudgetCode` mediumtext NOT NULL COMMENT 'XS only', `Reminded` set('yes','no') NOT NULL, `has_ssl` set('Yes','No') DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 PACK_KEYS=0; </code></pre> <p>Tech Schedule Table:</p> <pre><code>CREATE TABLE `tech_schedule` ( `tech_id` int(10) NOT NULL, `b_date` mediumtext NOT NULL, `cute_id` int(10) NOT NULL, `cuss_id` int(10) NOT NULL, `cuss_sbd_id` int(11) NOT NULL, `book` set('yes','no') NOT NULL, `cupps_id` int(6) NOT NULL, `hardware_id` int(6) NOT NULL, `pos_id` int(3) NOT NULL, `realtime_id` int(10) NOT NULL, `sec_tech_id` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; </code></pre> <p>Techs Table:</p> <pre><code>CREATE TABLE `techs` ( `id` int(11) NOT NULL, `Type` text DEFAULT NULL, `name` text NOT NULL, `email` text NOT NULL, `Phone` text DEFAULT NULL, `Title` text DEFAULT NULL, `active` enum('yes','no') NOT NULL DEFAULT 'yes' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; </code></pre> <p>Refactored Query: Page Load 200ms</p> <pre><code>SELECT a.*, STR_TO_DATE(RequestedTestDate, '%d-%b-%Y') AS cRequestedTestDate, STR_TO_DATE(ActualTestDate, '%d-%b-%Y') AS cActualTestDate, ts.NAME AS Engineer FROM ( SELECT * FROM cert_request_cute )a LEFT JOIN tech_schedule b ON a.RequestId = b.cute_id LEFT JOIN techs ts ON b.tech_id = ts.id LEFT JOIN airlines c on c.code = a.AirlineCustomer LEFT JOIN cert_status_cute stat on stat.RequestId = a.RequestId $swhere GROUP BY a.RequestId $orderByQuery $limitQuery&quot;; </code></pre>
[ { "answer_id": 74570464, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 2, "selected": true, "text": "OnCheckedChangeListener fun onCheckedChangedListenerForPreferenceKey(key: String): CompoundButton.OnCheckedChangeListener = { _, isChecked ->\n if (isChecked) {\n editor.putString(key, \"ON\") // wouldn't using putBoolean be better?\n } else {\n editor.putString(key, \"OFF\")\n }\n editor.commit()\n}\n funcOnOff.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey(\"func\"))\nfromOnOff.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey(\"from\"))\ntimeOnOff.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey(\"time\"))\n listOf(\n funcOnOff to \"func\"\n fromOnOff to \"from\"\n timeOnOff to \"time\"\n).forEach { (switch, key) -> \n switch.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey(key))\n}\n" }, { "answer_id": 74572783, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 0, "selected": false, "text": "// If the signature here matches the listener function, you can pass a reference\n// to this function directly\nfun handleSwitch(switch: CompoundButton, isChecked: Boolean) {\n when(switch) {\n funcOnOff -> \"func\"\n fromOnOff -> \"from\"\n timeOnOff -> \"time\"\n else -> null\n }?.let { key ->\n editor.putString(key, if (isChecked) \"ON\" else \"OFF\").commit()\n }\n}\n val switches = listOf(funcOnOff, fromOnOff, timeOnOff)\nswitches.forEach { it.setonOnCheckedChangedListener(::handleSwitch) }\n\n// or if you don't want to use a function reference\nswitches.forEach {\n it.setOnCheckedChangedListener { switch, enabled -> handleSwitch(switch, enabled) }\n}\n\n// or since you're iterating over the switches anyway, you could make the current one\n// part of the callback lambda and ignore the parameters\nswitches.forEach { switch ->\n it.setOnCheckedChangedListener { _, _ -> handleSwitch(switch, switch.isChecked) }\n}\n when keys when" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152183/" ]
74,570,113
<p>I am getting this error when i use many to many field help me plsssssss</p> <h3>views.py</h3> <pre><code>def add_ship(request): if request.method=='POST': m_namedriver = request.POST.get('m_namedriver') driver_id = Driver.objects.get(driver_id=m_namedriver) m_licensepl = request.POST.get('m_licensepl') car_id = Car.objects.get(car_id=m_licensepl) m_weightcoolbox = request.POST.get('m_weightcoolbox') coolbox_id = Coolbox.objects.get(coolbox_id=m_weightcoolbox) ship_date = request.POST.get('ship_date') ship_time = request.POST.get('ship_time') original = request.POST.get('original') destination = request.POST.get('destination') if shipping.objects.count() != 0: ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max'] next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1) else: next_ship_id = &quot;SP1000&quot; new_shipping = shipping.objects.create( shipping_id = next_ship_id, driver_id = driver_id, car_id = car_id, coolbox_id = coolbox_id, ship_date = ship_date, ship_time = ship_time, original = original, destination = destination, ) new_shipping.save() new_shipping.coolbox_id.add(coolbox_id) return render(request,'add_ship.html',{'message1':&quot;Add shipping successful.&quot;}) driver_ship = Driver.objects.all() car_ship = Car.objects.all() coolbox_ship = Coolbox.objects.all() return render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship}) </code></pre> <p>I've been stuck here for 3 days now. At first I used it as a CharField so I could add it, but when I added another ID it couldn't add it. It says there is a problem in this part ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max']</p> <h3>models.py</h3> <pre><code>class Coolbox(models.Model): coolbox_id = models.CharField(max_length=40,primary_key=True) medicine_name = models.ForeignKey(Medicine, on_delete=models.CASCADE, related_name=&quot;medicinename&quot;) weight = models.FloatField(blank=True, null=True) coolboxtemp_max = models.FloatField(blank=True, null=True) coolboxtemp_min = models.FloatField(blank=True, null=True) dimension = models.CharField(max_length=40) d_measurement = models.CharField(max_length=40) t_measurement = models.CharField(max_length=40) total = models.FloatField(blank=True, null=True) status = models.CharField(max_length=20, choices=STATUS, blank=True) def __str__(self): return f&quot;{self.medicine_name}&quot; class shipping(models.Model): shipping_id = models.CharField(max_length=15,primary_key=True) driver_id = models.ForeignKey(Driver, on_delete=models.CASCADE, related_name=&quot;driverfk&quot;) car_id = models.ForeignKey(Car, on_delete=models.CASCADE, related_name=&quot;carfk&quot;) coolbox_id = models.ManyToManyField(Coolbox, related_name=&quot;coolboxfk&quot;) ship_date = models.DateField(blank=True,null=True) ship_time = models.TimeField(blank=True,null=True) original = models.CharField(max_length=200) destination = models.CharField(max_length=200) def __str__(self): return f&quot;{self.shipping_id}: {self.driver_id}&quot; </code></pre> <p><a href="https://i.stack.imgur.com/6ETy3.png" rel="nofollow noreferrer">enter image description here</a> <a href="https://i.stack.imgur.com/SEFzZ.png" rel="nofollow noreferrer">enter image description here</a></p> <h3>HTML</h3> <pre><code>&lt;div class=&quot;col-md-6 mb-4&quot;&gt; &lt;div class=&quot;form-outline multip_select_box&quot;&gt; &lt;label class=&quot;form-label&quot; for=&quot;Coolboxs&quot;&gt;Coolboxs ID&lt;/label&gt; &lt;br&gt; &lt;select name=&quot;m_weightcoolbox&quot; id=&quot;m_weightcoolbox&quot; class=&quot;multi_select form-control&quot; multiple data-selected-text-format=&quot;count &gt; 3&quot; &gt; {% for m_weightcoolbox in coolbox_ship %} &lt;option value=&quot;{{ m_weightcoolbox.coolbox_id }}&quot;&gt;{{ m_weightcoolbox.coolbox_id }}&lt;/option&gt; {% endfor %} &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; enter code here </code></pre> <p>Help me plsssssssssss</p>
[ { "answer_id": 74570640, "author": "Mahammadhusain kadiwala", "author_id": 19205926, "author_profile": "https://Stackoverflow.com/users/19205926", "pm_score": 2, "selected": true, "text": "def add_ship(request):\n if request.method=='POST':\n \n m_namedriver = request.POST.get('m_namedriver')\n driver_id = Driver.objects.get(driver_id=m_namedriver)\n\n m_licensepl = request.POST.get('m_licensepl')\n car_id = Car.objects.get(car_id=m_licensepl)\n\n m_weightcoolbox = request.POST.getlist('m_weightcoolbox')\n print(m_weightcoolbox)\n coolb_id = [i for i in Coolbox.objects.filter(coolbox_id__in=m_weightcoolbox)]\n ship_date = request.POST.get('ship_date')\n ship_time = request.POST.get('ship_time')\n original = request.POST.get('original')\n destination = request.POST.get('destination')\n\n if shipping.objects.count() != 0:\n ship_id_max = shipping.objects.aggregate(Max('shipping_id'))[\"shipping_id__max\"]\n next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1)\n else:\n next_ship_id = \"SP1000\"\n\n new_shipping = shipping.objects.create(\n shipping_id = next_ship_id,\n driver_id = driver_id,\n car_id = car_id,\n ship_date = ship_date,\n ship_time = ship_time,\n original = original,\n destination = destination,\n )\n new_shipping.coolbox_id.set(coolb_id)\n return redirect(\"add_ship\")\n\n return render(request,'add_ship.html',{'message1':\"Add shipping successful.\"})\n driver_ship = Driver.objects.all()\n car_ship = Car.objects.all()\n coolbox_ship = Coolbox.objects.all()\n return render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship})\n" }, { "answer_id": 74572106, "author": "Poramet Rodtanee", "author_id": 14123265, "author_profile": "https://Stackoverflow.com/users/14123265", "pm_score": -1, "selected": false, "text": "<div class=\"col-md-6 mb-4\">\n <div class=\"form-outline multip_select_box\">\n <label class=\"form-label\" for=\"Coolboxs\">Coolboxs ID</label>\n <br>\n <select name=\"m_weightcoolbox\" id=\"m_weightcoolbox\" class=\"multi_select form-control\" multiple data-selected-text-format=\"count > 3\" >\n {% for m_weightcoolbox in coolbox_ship %}\n \n <option value=\"{{ m_weightcoolbox.coolbox_id }}\">{{ m_weightcoolbox.coolbox_id }}</option>\n {% endfor %}\n \n </select>\n \n \n\n \n \n </div>\n \n </div>\n </div> \n" }, { "answer_id": 74572151, "author": "Poramet Rodtanee", "author_id": 14123265, "author_profile": "https://Stackoverflow.com/users/14123265", "pm_score": 0, "selected": false, "text": "def add_ship(request):\n\nif request.method=='POST':\n \n m_namedriver = request.POST.get('m_namedriver')\n driver_id = Driver.objects.get(driver_id=m_namedriver)\n\n m_licensepl = request.POST.get('m_licensepl')\n car_id = Car.objects.get(car_id=m_licensepl)\n\n m_weightcoolbox = request.POST.get('m_weightcoolbox')\n coolbox_id = Coolbox.objects.get(coolbox_id=m_weightcoolbox)\n\n ship_date = request.POST.get('ship_date')\n ship_time = request.POST.get('ship_time')\n original = request.POST.get('original')\n destination = request.POST.get('destination')\n\n if shipping.objects.count() != 0:\n ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max']\n next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1)\n else:\n next_ship_id = \"SP1000\"\n\n new_shipping = shipping.objects.create(\n shipping_id = next_ship_id,\n driver_id = driver_id,\n car_id = car_id,\n coolbox_id = coolbox_id,\n ship_date = ship_date,\n ship_time = ship_time,\n original = original,\n destination = destination,\n )\n\n new_shipping.save()\n new_shipping.shipping.add(coolbox_id)\n\n return render(request,'add_ship.html',{'message1':\"Add shipping successful.\"})\ndriver_ship = Driver.objects.all()\ncar_ship = Car.objects.all()\ncoolbox_ship = Coolbox.objects.all()\nreturn render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship})\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14123265/" ]
74,570,133
<p>I have a <a href="https://hardhat.org/" rel="nofollow noreferrer">Hardhat</a> script that queries the <a href="https://developers.rsk.co/rif/token/" rel="nofollow noreferrer">RIF token</a> balance on <a href="https://developers.rsk.co/" rel="nofollow noreferrer">Rootstock</a>. However the RIF address is hardcoded in my script: ​</p> <pre class="lang-js prettyprint-override"><code>const rifTokenAddress = '0x2aCc95758f8b5F583470bA265Eb685a8f45fC9D5'; ​ async function main() { const erc20 = await ethers.getContractAt( ['function balanceOf(address owner) view returns (uint)'], rifTokenAddress.toLowerCase(), ); const walletAddress = (await ethers.getSigner(0)).address; const rifBalance = await erc20.balanceOf(walletAddress); console.log(ethers.utils.formatEther(rifBalance)); } ​ main(); </code></pre> <p>​ Now I am using this command to run the script: ​</p> <pre class="lang-bash prettyprint-override"><code>npx hardhat run scripts/balances.js --network rskmainnet </code></pre> <p>​ I would like to be able to specify a token address in the command line like this: ​</p> <pre class="lang-bash prettyprint-override"><code>npx hardhat run scripts/balances.js --network rskmainnet --token 0x2d919f19D4892381d58EdEbEcA66D5642ceF1A1F </code></pre> <p>​ Is there a way to modify Hardhat script so that it could read token address from the command line, similar to how I select the network with <code>--network</code> parameter? ​ For reference, this is my <code>hardhat.config.js</code> file: ​</p> <pre class="lang-js prettyprint-override"><code>require('@nomicfoundation/hardhat-toolbox'); const { mnemonic } = require('./.secret.json'); ​ const accounts = { mnemonic, path: &quot;m/44'/60'/0'/0&quot;, }; ​ module.exports = { solidity: '0.8.9', networks: { hardhat: {}, rsktestnet: { chainId: 31, url: 'https://public-node.testnet.rsk.co/', accounts, }, rskmainnet: { chainId: 30, url: 'https://public-node.rsk.co/', accounts, }, }, }; </code></pre>
[ { "answer_id": 74570939, "author": "Rajesh Panda", "author_id": 6208805, "author_profile": "https://Stackoverflow.com/users/6208805", "pm_score": 2, "selected": false, "text": "\"hardhat-runner\": \"npx hardhat run --network rskmainnet scripts/balances.js\"\n npm run hardhat-runner --token=0x2d919f19D4892381d58EdEbEcA66D5642ceF1A1F\n process.env.npm_config_token\n" }, { "answer_id": 74581756, "author": "Aleks Shenshin", "author_id": 16695341, "author_profile": "https://Stackoverflow.com/users/16695341", "pm_score": 2, "selected": false, "text": "--network tasks/balance.js const { task } = require('hardhat/config');\n\nconst rifTokenAddress = '0x2aCc95758f8b5F583470bA265Eb685a8f45fC9D5';\n\nmodule.exports = task('balance', 'Displays token balance')\n .addOptionalParam('token', 'ERC20 token name')\n .setAction(async ({ token }) => {\n const erc20 = await ethers.getContractAt(\n ['function balanceOf(address owner) view returns (uint)'],\n token?.toLowerCase() || rifTokenAddress.toLowerCase(),\n );\n const walletAddress = (await ethers.getSigner(0)).address;\n const erc20Balance = await erc20.balanceOf(walletAddress);\n console.log(ethers.utils.formatEther(erc20Balance));\n });\n balance --token --token rifTokenAddress hardhat.config.js require('@nomicfoundation/hardhat-toolbox');\nrequire('./tasks/balance.js');\n\n # queries default token balance\nnpx hardhat balance\n --network rsktestnet\n # queries specified token balance\nnpx hardhat balance\n --network rsktestnet \\\n --token 0x19f64674D8a5b4e652319F5e239EFd3bc969a1FE\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12142981/" ]
74,570,140
<p>During debug sessions in <code>PyCharm</code> I need to set some environment variables to <code>None</code> value.</p> <p>There is good explanation on how to set Run/Debug configuration environment variables in <code>PyCharm</code> <a href="https://stackoverflow.com/questions/42708389/how-to-set-environment-variables-in-pycharm">How to set environment variables in PyCharm?</a>, but they set each variable to specific value.</p> <p>It is possible to delete environment variable from Run/Debug configuration setting it to <code>None</code>, but I would prefer to keep the variable's name inside <code>PyCharm</code> configuration settings for further use.</p> <p>So how I set it to python <code>None</code>?</p>
[ { "answer_id": 74570953, "author": "BoarGules", "author_id": 2084384, "author_profile": "https://Stackoverflow.com/users/2084384", "pm_score": 1, "selected": false, "text": "None SET MYVAR= #MYVAR MYVAR" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6194150/" ]
74,570,148
<p>I'm trying to return HTTP Status Code 410 (gone) alongside a custom simple HTML:</p> <pre><code> &lt;h1&gt;Error 410&lt;/h1&gt; &lt;h2&gt;Permanently deleted or Gone&lt;/h2&gt; &lt;p&gt;This page is not found and is gone from this server forever&lt;/p&gt; </code></pre> <p>Is it possible? Because I can't find a method on <a href="https://nextjs.org/docs/api-reference/next/server#nextresponse" rel="nofollow noreferrer">NextResponse</a> object.</p> <p>How can I return HTML from middleware?</p>
[ { "answer_id": 74579652, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 0, "selected": false, "text": "type NextApiResponse<T = any> = ServerResponse<IncomingMessage> & {\n send: Send<T>;\n json: Send<T>;\n status: (statusCode: number) => NextApiResponse<T>;\n redirect(url: string): NextApiResponse<T>;\n redirect(status: number, url: string): NextApiResponse<T>;\n setPreviewData: (data: object | string, options?: {\n maxAge?: number;\n path?: string;\n }) => NextApiResponse<T>;\n clearPreviewData: (options?: {\n path?: string;\n }) => NextApiResponse<T>;\n unstable_revalidate: () => void;\n revalidate: (urlPath: string, opts?: {\n unstable_onlyGenerated?: boolean;\n }) => Promise<void>;\n}\n express sendFile app.get(\"/\", (req, res) => {\n res.sendFile(__dirname + \"/index.html\");\n});\n NextApiResponse, and res.json(body) - Sends a JSON response. body must be a serializable object\nres.send(body) - Sends the HTTP response. body can be a string, an object or a Buffer\n" }, { "answer_id": 74681500, "author": "juliomalves", "author_id": 1870780, "author_profile": "https://Stackoverflow.com/users/1870780", "pm_score": 0, "selected": false, "text": "allowMiddlewareResponseBody next.config.js // next.config.js\nmodule.exports = {\n experimental: {\n allowMiddlewareResponseBody: true\n }\n}\n import { NextResponse } from 'next/server'\n\nexport function middleware(request) {\n return new NextResponse(\n `\n <h1>Error 410</h1>\n <h2>Permanently deleted or Gone</h2>\n <p>This page is not found and is gone from this server forever</p>\n `,\n { status: 410, headers: { 'content-type': 'text/html' } }\n )\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16473956/" ]
74,570,159
<p>I have a simple code that fetches data from url. I have executed same code in both Ubuntu(server-only) and Windows</p> <p>Code</p> <pre><code>import axios from &quot;axios&quot;; (async () =&gt; { const url = &quot;https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/inr/usd.json&quot;; fetch(url).then((res) =&gt; { return res.json(); }).then((data) =&gt; { console.log(&quot;fetch&quot;, data); }); axios.get(url).then((res) =&gt; { console.log(&quot;axios&quot;, res.data); }); })(); </code></pre> <p>OUTPUT:</p> <p>In windows: fetch { date: '2022-11-25', usd: 0.012218 } axios { date: '2022-11-25', usd: 0.012218 }</p> <p>In Ubuntu: axios 0D��_�XV��ؚ�!�I,�8�j��8��K9&quot;�2�wOvx�� fetch { date: '2022-11-25', usd: 0.012218 }</p> <p>It worked well before, but now its coming like this. Response codes are 200 in both the cases.</p> <p>I have tried updating axios and ubuntu but nothing worked.</p>
[ { "answer_id": 74571804, "author": "pierpy", "author_id": 7353417, "author_profile": "https://Stackoverflow.com/users/7353417", "pm_score": 0, "selected": false, "text": "(async () => {\nconst url = \"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/inr/usd.json\";\nfetch(url)\n.then(res => res.json())\n.then(data => console.log(data))\n})();\n" }, { "answer_id": 74598872, "author": "Kasun Shanaka", "author_id": 16056064, "author_profile": "https://Stackoverflow.com/users/16056064", "pm_score": 1, "selected": false, "text": "version 1.1.2 Accept-Encoding axios.get(url, { headers: { Accept: 'application/json', 'Accept-Encoding': 'identity' }, params: { trophies: true } })\n.then((res) => {\n console.log(\"axios\", res.data);\n});\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13151669/" ]
74,570,186
<p>I have text like this:</p> <pre><code>text = &lt;option value=&quot;tfa_4472&quot; id=&quot;tfa_4472&quot; class=&quot;&quot;&gt;helo 1&lt;/option&gt; &lt;option value=&quot;tfa_4473&quot; id=&quot;tfa_4473&quot; class=&quot;&quot;&gt;helo 2&lt;/option&gt; &lt;option value=&quot;tfa_4474&quot; id=&quot;tfa_4474&quot; class=&quot;&quot;&gt;helo 3&lt;/option&gt; &lt;option value=&quot;tfa_4475&quot; id=&quot;tfa_4475&quot; class=&quot;&quot;&gt;helo 4&lt;/option&gt; &lt;option value=&quot;tfa_4476&quot; id=&quot;tfa_4476&quot; class=&quot;&quot;&gt;helo 5&lt;/option&gt; </code></pre> <h2>i want get result like this: my_list = get_text(text)</h2> <p>helo 1 helo 2 helo 3 helo 4 helo 5</p> <p>Thank you</p> <p>To to remove html tag to get text</p>
[ { "answer_id": 74570434, "author": "Joel", "author_id": 20580580, "author_profile": "https://Stackoverflow.com/users/20580580", "pm_score": 0, "selected": false, "text": "$mylist = []\n$nodes = document.querySelectorAll('option')\n\n$nodes.forEach($node => {\n $mylist += $node.innerText\n});\n\nconsole.log($mylist)\n" }, { "answer_id": 74570906, "author": "Enrique Benito Casado", "author_id": 3844270, "author_profile": "https://Stackoverflow.com/users/3844270", "pm_score": 2, "selected": true, "text": "from bs4 import BeautifulSoup\n\n\nmyhtml = \"\"\"<option value=\"tfa_4472\" id=\"tfa_4472\" class=\"\">helo 1</option>\n<option value=\"tfa_4473\" id=\"tfa_4473\" class=\"\">helo 2</option>\n<option value=\"tfa_4474\" id=\"tfa_4474\" class=\"\">helo 3</option>\n<option value=\"tfa_4475\" id=\"tfa_4475\" class=\"\">helo 4</option>\n<option value=\"tfa_4476\" id=\"tfa_4476\" class=\"\">helo 5</option>\"\"\"\n\n\nsoup = BeautifulSoup(myhtml, 'html.parser')\n\nmy_text = []\nfor text_tag in soup.find_all(\"option\", {'class': ''}):\n my_text.append(text_tag.getText()) \n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14161240/" ]
74,570,195
<p>I try to upgrade minio version in my docker commpose(previously I used <code>image: minio/minio:RELEASE.2020-06-22T03-12-50Z</code> and it was working ) For now I have following docker-compose service:</p> <pre><code>version: '3.6' services: minio: container_name: minio image: minio/minio:RELEASE.2022-11-17T23-20-09Z.fips volumes: - minio-data:/data ports: - 9000:9000 environment: - MINIO_ROOT_USER=minio - MINIO_ROOT_PASSWORD=minio123 command: server /data healthcheck: test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;-f&quot;, &quot;http://localhost:9000/minio/health/live&quot;] interval: 30s timeout: 20s retries: 3 </code></pre> <p>When I try to start(<code>docker-compose up -d</code>) I see the following error in the minio container log:</p> <pre><code>2022-11-25 11:40:56 ERROR Unable to use the drive /data: Drive /data: found backend type fs, expected xl or xl-single - to migrate to a supported backend visit https://min.io/docs/minio/linux/operations/install-deploy-manage/migrate-fs-gateway.html: Invalid arguments specified </code></pre> <p>I've googled the following article <a href="https://min.io/docs/minio/linux/operations/install-deploy-manage/migrate-fs-gateway.html" rel="nofollow noreferrer">https://min.io/docs/minio/linux/operations/install-deploy-manage/migrate-fs-gateway.html</a></p> <p>But I still don't understand what shoud I change in my compose file to make it working.</p>
[ { "answer_id": 74601247, "author": "gstackoverflow", "author_id": 2674303, "author_profile": "https://Stackoverflow.com/users/2674303", "pm_score": 1, "selected": false, "text": " minio:\n container_name: minio\n image: bitnami/minio:2022.11.17-debian-11-r0\n volumes:\n - minio-data:/data\n ports:\n - 9000:9000\n - 9001:9001\n environment:\n - MINIO_ROOT_USER=minio\n - MINIO_ROOT_PASSWORD=minio123\n - MINIO_DEFAULT_BUCKETS=mybucket1,mybucket2\n healthcheck:\n test: [\"CMD\", \"curl\", \"-f\", \"http://localhost:9000/minio/health/live\"]\n interval: 30s\n timeout: 20s\n" }, { "answer_id": 74674606, "author": "Ryabchenko Alexander", "author_id": 6515755, "author_profile": "https://Stackoverflow.com/users/6515755", "pm_score": 0, "selected": false, "text": "volumes:\n minio-data:\n driver: local\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2674303/" ]
74,570,198
<p>Azure function throws &quot;Message processing error(Action=Complete)&quot; after calling deadletterasync with autocomplete not setting as False. But when I set &quot;Autocomplete=false&quot; even after processing successful messages it keeps retrying. What is the best way to receive message ,and deadletter when exception occurs?</p> <pre><code>public async Task Test( [ServiceBusTrigger( topicName: &quot;testTopic&quot;, subscriptionName: &quot;testSubsription&quot;, Connection = &quot;testConnectionString&quot;,Autocomplete = false)] Message message, MessageReceiver messageReceiver, [ServiceBus(&quot;SendTopic&quot;, EntityType.Topic, Connection = &quot;SendConnection&quot;)] IAsyncCollector&lt;Message&gt; output, CancellationToken cancellationToken) { try { var result = JsonConvert.DeserializeObject&lt;TestObject&gt;(Encoding.UTF8.GetString(message.Body)); foreach (var data in result.Data) { var convertedData= JsonConvert.SerializeObject(data); var byteArray = Encoding.UTF8.GetBytes(convertedData); Message outputMessages = new(byteArray); await output.AddAsync(outputMessages, cancellationToken); await messageReceiver.CompleteAsync(lockToken); } } catch (Exception ex) { await messageReceiver.DeadLetterAsync(lockToken); } } </code></pre>
[ { "answer_id": 74601247, "author": "gstackoverflow", "author_id": 2674303, "author_profile": "https://Stackoverflow.com/users/2674303", "pm_score": 1, "selected": false, "text": " minio:\n container_name: minio\n image: bitnami/minio:2022.11.17-debian-11-r0\n volumes:\n - minio-data:/data\n ports:\n - 9000:9000\n - 9001:9001\n environment:\n - MINIO_ROOT_USER=minio\n - MINIO_ROOT_PASSWORD=minio123\n - MINIO_DEFAULT_BUCKETS=mybucket1,mybucket2\n healthcheck:\n test: [\"CMD\", \"curl\", \"-f\", \"http://localhost:9000/minio/health/live\"]\n interval: 30s\n timeout: 20s\n" }, { "answer_id": 74674606, "author": "Ryabchenko Alexander", "author_id": 6515755, "author_profile": "https://Stackoverflow.com/users/6515755", "pm_score": 0, "selected": false, "text": "volumes:\n minio-data:\n driver: local\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13966637/" ]
74,570,201
<p>I'm writing a function in which one of the arguments is an array that can have strings or numbers:</p> <pre><code>function functionName(argumentOne: string, argumentTwo: string, argumentThree: string[] | number[]) { ... } </code></pre> <p>One instance of <code>argumentThree</code>: <code>[&quot;string1&quot;, 2, &quot;string3&quot;]</code></p> <p><code>string[]</code> is an array of strings and <code>number[]</code> is an array of numbers. Therefore my code is giving me an error.</p>
[ { "answer_id": 74570224, "author": "CollinD", "author_id": 5298696, "author_profile": "https://Stackoverflow.com/users/5298696", "pm_score": 4, "selected": true, "text": "// alternatively: Array<string | number>\nfunction myFunction(arr: (string | number)[]) {\n for (const element of arr) {\n // typeof element => string | number\n }\n}\n" }, { "answer_id": 74570248, "author": "Ryan Le", "author_id": 5122615, "author_profile": "https://Stackoverflow.com/users/5122615", "pm_score": 2, "selected": false, "text": "function functionName(argumentOne: string, argumentTwo: string, argumentThree: Array<string | number>) {\n ...\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13970434/" ]
74,570,220
<p>I am trying to make an app with a login function and I want to keep the user logged in. I'm using Firebase auth and android studio.</p> <p>This is what I tried:</p> <pre><code>auth.signInWithEmailAndPassword(txt_email, txt_password) .addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() { @Override public void onComplete(@NonNull Task&lt;AuthResult&gt; task) { if (task.isSuccessful()){ Intent intent = new Intent(login.this, sendForm.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } else { Toast.makeText(login.this, &quot;cant sing in&quot;, Toast.LENGTH_SHORT).show(); } } }); </code></pre>
[ { "answer_id": 74570224, "author": "CollinD", "author_id": 5298696, "author_profile": "https://Stackoverflow.com/users/5298696", "pm_score": 4, "selected": true, "text": "// alternatively: Array<string | number>\nfunction myFunction(arr: (string | number)[]) {\n for (const element of arr) {\n // typeof element => string | number\n }\n}\n" }, { "answer_id": 74570248, "author": "Ryan Le", "author_id": 5122615, "author_profile": "https://Stackoverflow.com/users/5122615", "pm_score": 2, "selected": false, "text": "function functionName(argumentOne: string, argumentTwo: string, argumentThree: Array<string | number>) {\n ...\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12136232/" ]
74,570,243
<p>I'm beginner in Symfony (6.1) and sometimes I need to get the current User in my controllers.</p> <p>The way I use for the moment is :</p> <pre><code>$user = $userRepository-&gt;find($this-&gt;getUser()-&gt;getId()); </code></pre> <p>But they are a better way ?</p> <p>Because <code>$this-&gt;getUser()</code> give me the UserInterface and I need the User entity. <a href="https://i.stack.imgur.com/CGj4Q.png" rel="nofollow noreferrer">screenshot example</a></p> <p>Thanks to read me</p>
[ { "answer_id": 74570810, "author": "Dirk J. Faber", "author_id": 9230154, "author_profile": "https://Stackoverflow.com/users/9230154", "pm_score": 2, "selected": false, "text": "$this->getUser() getUser() getUser() public function setUser(UserInterface $user) \n{\n //....\n}\n setUser(User $user) /** @var User $user */\n$user = $this->getUser();\n namespace App\\Controller;\n\nuse App\\Entity\\User;\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController;\n\nclass BaseController extends AbstractController\n{\n protected function getUser(): ?User\n {\n if (!$this->container->has('security.token_storage')) {\n throw new \\LogicException('The SecurityBundle is not registered in your application. Try running \"composer require symfony/security-bundle\".');\n }\n\n if (null === $token = $this->container->get('security.token_storage')->getToken()) {\n return null;\n }\n\n return $token->getUser();\n }\n}\n /**\n * @return User|null\n */\nprotected function getUser(): ?UserInterface\n{\n return parent::getUser();\n}\n" }, { "answer_id": 74571683, "author": "Lubna Altungi", "author_id": 18530022, "author_profile": "https://Stackoverflow.com/users/18530022", "pm_score": 0, "selected": false, "text": "$creditCard= new creditCard();\n$creditCard->setUser($this->getUser());\n $creditCard= $this->get('security.token_storage')->getToken()->getUser();\n" }, { "answer_id": 74574642, "author": "Cerad", "author_id": 1146363, "author_profile": "https://Stackoverflow.com/users/1146363", "pm_score": 1, "selected": false, "text": "use App\\Entity\\User; # or whetever the application defined user is\n\nclass MyController extends AbstractController \n{\n public function someMethod() \n {\n /** @var User */\n $user = $this->getUser();\n class AbstractController {\n protected function getUser(): ?UserInterface {\n User $user = $this->getUser();\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18419618/" ]
74,570,246
<p>I want to create a calculation that adds the dimensions current month and previous month to a Cognos Data Module. The Month format is 2022/11. This is what I tried. I do not get an error message, but the calculation does not return a result.</p> <pre><code>Case when (Month_Adj = #timestampMask(_add_months($current_timestamp,0),'yyyy')+'/'+timestampMask(_add_months($current_timestamp,0),'mm')#) then 'Last Month' when (Month_Adj = #timestampMask(_add_months($current_timestamp,-1),'yyyy')+'/'+timestampMask(_add_months($current_timestamp,-1),'mm')#) then 'Previous Month' else null end </code></pre> <p>Please find a screenshot for reference.<a href="https://i.stack.imgur.com/rVgvb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rVgvb.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74570810, "author": "Dirk J. Faber", "author_id": 9230154, "author_profile": "https://Stackoverflow.com/users/9230154", "pm_score": 2, "selected": false, "text": "$this->getUser() getUser() getUser() public function setUser(UserInterface $user) \n{\n //....\n}\n setUser(User $user) /** @var User $user */\n$user = $this->getUser();\n namespace App\\Controller;\n\nuse App\\Entity\\User;\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController;\n\nclass BaseController extends AbstractController\n{\n protected function getUser(): ?User\n {\n if (!$this->container->has('security.token_storage')) {\n throw new \\LogicException('The SecurityBundle is not registered in your application. Try running \"composer require symfony/security-bundle\".');\n }\n\n if (null === $token = $this->container->get('security.token_storage')->getToken()) {\n return null;\n }\n\n return $token->getUser();\n }\n}\n /**\n * @return User|null\n */\nprotected function getUser(): ?UserInterface\n{\n return parent::getUser();\n}\n" }, { "answer_id": 74571683, "author": "Lubna Altungi", "author_id": 18530022, "author_profile": "https://Stackoverflow.com/users/18530022", "pm_score": 0, "selected": false, "text": "$creditCard= new creditCard();\n$creditCard->setUser($this->getUser());\n $creditCard= $this->get('security.token_storage')->getToken()->getUser();\n" }, { "answer_id": 74574642, "author": "Cerad", "author_id": 1146363, "author_profile": "https://Stackoverflow.com/users/1146363", "pm_score": 1, "selected": false, "text": "use App\\Entity\\User; # or whetever the application defined user is\n\nclass MyController extends AbstractController \n{\n public function someMethod() \n {\n /** @var User */\n $user = $this->getUser();\n class AbstractController {\n protected function getUser(): ?UserInterface {\n User $user = $this->getUser();\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12853034/" ]
74,570,266
<p>I have a utility function defined in my <code>utils.tsx</code> file:</p> <pre class="lang-js prettyprint-override"><code>// resolveAxiosInstance creates an axios instance const createAxiosInstance = resolveAxiosInstance(); export const getItemList = params =&gt; { const axios = await createAxiosInstance; const res = await axios.get(&quot;/my-url&quot;, {params}); return res.data; } </code></pre> <p>And I am using the <code>getItemList</code> utility in my component <code>mycomponent.tsx</code>. It is invoked on click of a button but before calling that API the click event sets some states as well. Here's the code of my component:</p> <pre class="lang-js prettyprint-override"><code>export const MyComponent = () =&gt; { //rest of component code const clickMe = () =&gt; { setIsLoading(true); const data = { // item and price are vars whose values are filled by user through input text itemName: item, itemPrice: price, }; getItemList(data).then(res =&gt; { if (res) { setItemData({ itemName: name, itemPrice: price, itemDiscount: res.disc, }); } }, err =&gt; console.log(err)); } return ( //rest of the component code &lt;div&gt; &lt;Button onClick={clickMe} data-testid=&quot;update&quot;&gt;Click Me&lt;/Button&gt; &lt;/div&gt; ) } </code></pre> <p>I want to write a unit test case in Jasmine to test the on click functionality. I am able to invoke the on click function by using <code>simulate(&quot;click&quot;)</code> on the button element. But it doesn't execute the API call and that's understandable. To execute the API call I tried to use <code>spyOn</code> but it didn't help. It returns the error that <code>getItemList is not declared configurable</code>. Here's my test case:</p> <pre class="lang-js prettyprint-override"><code>it(&quot;should show data on click me&quot;, () =&gt; { const wrapper = mount(&lt;MyComponent /&gt;); let elem = wrapper.find(MyComponent); const mockSpy = Jasmine.createSpy(&quot;getItemList&quot;).and.returnValue(Promise.resolve(mockResp)) let btn = elem.find('[data-testid=&quot;update&quot;]'); btn.at(0).simulate(&quot;click&quot;); elem = elem.update(); expect(elem.find(&quot;table&quot;).length).toBe(1); }); </code></pre> <p>My question is how can I write a unit test for my use case where I trigger a button click and it calls a function which does something, and then calls an API and updates the table on my view as per the API response.</p>
[ { "answer_id": 74570810, "author": "Dirk J. Faber", "author_id": 9230154, "author_profile": "https://Stackoverflow.com/users/9230154", "pm_score": 2, "selected": false, "text": "$this->getUser() getUser() getUser() public function setUser(UserInterface $user) \n{\n //....\n}\n setUser(User $user) /** @var User $user */\n$user = $this->getUser();\n namespace App\\Controller;\n\nuse App\\Entity\\User;\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController;\n\nclass BaseController extends AbstractController\n{\n protected function getUser(): ?User\n {\n if (!$this->container->has('security.token_storage')) {\n throw new \\LogicException('The SecurityBundle is not registered in your application. Try running \"composer require symfony/security-bundle\".');\n }\n\n if (null === $token = $this->container->get('security.token_storage')->getToken()) {\n return null;\n }\n\n return $token->getUser();\n }\n}\n /**\n * @return User|null\n */\nprotected function getUser(): ?UserInterface\n{\n return parent::getUser();\n}\n" }, { "answer_id": 74571683, "author": "Lubna Altungi", "author_id": 18530022, "author_profile": "https://Stackoverflow.com/users/18530022", "pm_score": 0, "selected": false, "text": "$creditCard= new creditCard();\n$creditCard->setUser($this->getUser());\n $creditCard= $this->get('security.token_storage')->getToken()->getUser();\n" }, { "answer_id": 74574642, "author": "Cerad", "author_id": 1146363, "author_profile": "https://Stackoverflow.com/users/1146363", "pm_score": 1, "selected": false, "text": "use App\\Entity\\User; # or whetever the application defined user is\n\nclass MyController extends AbstractController \n{\n public function someMethod() \n {\n /** @var User */\n $user = $this->getUser();\n class AbstractController {\n protected function getUser(): ?UserInterface {\n User $user = $this->getUser();\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10416948/" ]
74,570,277
<p>Please help me on this, after an change of domain hosting, we are getting this error in the logs when we want to create a new customer.</p> <p>Start:</p> <pre><code>{&quot;time&quot;:&quot;2022-11-25T08:21:27+00:00&quot;, &quot;remote_addr&quot;:&quot;149.143.40.237&quot;, &quot;remote_user&quot;:&quot;&quot;, &quot;host&quot;:&quot;www.hydroseals.nl&quot;, &quot;request&quot;:&quot;POST /account/register HTTP/2.0&quot;, &quot;status&quot;:&quot;500&quot;, &quot;body_bytes_sent&quot;:&quot;93913&quot;, &quot;referer&quot;:&quot;https://www.hydroseals.nl/account/login&quot;, &quot;user_agent&quot;:&quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36&quot;, &quot;request_time&quot;:&quot;0.406&quot;, &quot;handler&quot;:&quot;phpfpm&quot;, &quot;country&quot;:&quot;US&quot;, &quot;server_name&quot;:&quot;www.hydroseals.nl&quot;, &quot;port&quot;:&quot;443&quot;, &quot;ssl_cipher&quot;:&quot;TLS_AES_256_GCM_SHA384&quot;, &quot;ssl_protocol&quot;:&quot;TLSv1.3&quot;} </code></pre> <p>Event:</p> <pre><code>[2022-11-25T08:23:11.598982+00:00] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\Exception\DriverException: &quot;An exception occurred while executing 'INSERT INTO `customer_address` (`id`, `customer_id`, `country_id`, `salutation_id`, `first_name`, `last_name`, `zipcode`, `city`, `street`, `created_at`) VALUES ('G�\0Â?M»�h��\&quot;R','[�(F�L�v��*                                                              e','���XM�@��i��&gt;G�','9\0\nL�vD:��#�-)3�','Tim','van Dijk','3911JB','Rhenen','Herenstraat 49A','2022-11-25 08:23:11.590');':  SQLSTATE[HY000]: General error: 1449 The user specified as a definer ('o9214241'@'%') does not exist&quot; at /data/web/application/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php line 128 {&quot;exception&quot;:&quot;[object] (Doctrine\\DBAL\\Exception\\DriverException(code: 0): An exception occurred while executing 'INSERT INTO `customer_address` (`id`, `customer_id`, `country_id`, `salutation_id`, `first_name`, `last_name`, `zipcode`, `city`, `street`, `created_at`) VALUES ('G�\\0Â?M»�h��\\\&quot;R','[�\u0006(F�L��\u0002v��*\fe','��XM�@��\u001di��&gt;G�','9\\0\\nL�vD:��#�-)3�','Tim','van Dijk','3911JB','Rhenen','Herenstraat 49A','2022-11-25 08:23:11.590');':\n\nSQLSTATE[HY000]: General error: 1449 The user specified as a definer ('o9214241'@'%') does not exist at /data/web/application/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:128)\n[previous exception] [object] (Doctrine\\DBAL\\Driver\\PDO\\Exception(code: HY000): SQLSTATE[HY000]: General error: 1449 The user specified as a definer ('o9214241'@'%') does not exist at /data/web/application/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDO/Exception.php:18)\n[previous exception] [object] (PDOException(code: HY000): SQLSTATE[HY000]: General error: 1449 The user specified as a definer ('o9214241'@'%') does not exist at /data/web/application/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:55)&quot;} [] </code></pre> <p>Does anyone have an idea because now we cannot create new customers in the backend nor in the frontend ofcourse.</p> <p>Thanks</p> <p>pim</p> <p>See what the isseu was, and locate the problem.</p> <p>but i am unable to solved it.</p>
[ { "answer_id": 74570925, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 1, "selected": false, "text": "UPDATE mysql.proc SET definer = 'existing_user@localhost' WHERE db = 'database_name';\n" }, { "answer_id": 74588702, "author": "Alex", "author_id": 288568, "author_profile": "https://Stackoverflow.com/users/288568", "pm_score": 0, "selected": false, "text": "mysqldump" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19388551/" ]
74,570,290
<p>I have below playbook that generates <code>stdout_lines</code> which has multi line output.</p> <pre class="lang-yaml prettyprint-override"><code> - name: Execute command: cbstats db-host:db-port -u User -p Password -b orders all register: count - name: Print debug: msg: &quot;{{ item }}&quot; with_items: &quot;{{ count.stdout_lines }}&quot; </code></pre> <p>Output of stdout_lines:</p> <pre><code>TASK [Print] **************************************************************************************************ok: [localhost] =&gt; { &quot;msg&quot;: [ &quot; accepting_conns: 1&quot;, &quot; auth_cmds: 0&quot;, &quot; auth_errors: 0&quot;, &quot; bytes: 3756475864&quot;, &quot; bytes_read: 2015848580&quot;, &quot; bytes_subdoc_lookup_extracted: 0&quot;, </code></pre> <p>Now I want to get only <code>bytes</code> from <code>stdout_lines</code>. Any idea how this can be achieved ?</p>
[ { "answer_id": 74570925, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 1, "selected": false, "text": "UPDATE mysql.proc SET definer = 'existing_user@localhost' WHERE db = 'database_name';\n" }, { "answer_id": 74588702, "author": "Alex", "author_id": 288568, "author_profile": "https://Stackoverflow.com/users/288568", "pm_score": 0, "selected": false, "text": "mysqldump" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2919863/" ]
74,570,314
<p>I am trying to read a CSV file whose header position numbers comes from a property file. I get the position number for the fields using @Value. But however I am unable to bind this value as the position for <code>@CsvBindByPosition</code>.</p> <p>Here is my code :</p> <pre><code>public class MyPojo { @Value(value = &quot;${csv.pojo.refNumber}&quot;) public static final int test; @CsvBindByPosition(position = test) private String id; } </code></pre> <p>This gives me this error:</p> <blockquote> <p>The value for annotation attribute <code>CsvBindByPosition.position</code> must be a constant expression</p> </blockquote> <p>Is there a way to resolve this as my position needs to be read from a property file itself?</p>
[ { "answer_id": 74591194, "author": "MWiesner", "author_id": 2849346, "author_profile": "https://Stackoverflow.com/users/2849346", "pm_score": 2, "selected": false, "text": "position test test test" }, { "answer_id": 74591582, "author": "samabcde", "author_id": 7928721, "author_profile": "https://Stackoverflow.com/users/7928721", "pm_score": 2, "selected": true, "text": "MappingStrategy ColumnPositionMappingStrategy import com.opencsv.CSVReader;\nimport com.opencsv.CSVReaderBuilder;\nimport com.opencsv.bean.ColumnPositionMappingStrategy;\nimport com.opencsv.bean.ColumnPositionMappingStrategyBuilder;\nimport com.opencsv.bean.CsvToBean;\nimport com.opencsv.bean.CsvToBeanBuilder;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.test.context.SpringBootTest;\n\nimport java.io.StringReader;\n\n@SpringBootTest(\n classes = CsvByPositionInRuntimeTest.Pojo.class,\n properties = {\"csv.pojo.refNumber=0\", \"csv.pojo.name=1\"}\n)\npublic class CsvByPositionInRuntimeTest {\n // assume 0\n @Value(\"${csv.pojo.refNumber}\")\n private Integer refNumberIndex;\n // assume 1\n @Value(\"${csv.pojo.name}\")\n private Integer nameIndex;\n\n // or specify column order like 'refNumber,name'\n // this is more readable and easy to maintain\n @Value(\"${csv.pojo.columnOrder}\")\n private String[] columnOrder;\n\n @Test\n public void parse() {\n CSVReader csvReader = new CSVReaderBuilder(\n new StringReader(\"\"\"\n 123,david\n 456,terry\n \"\"\")\n ).build();\n ColumnPositionMappingStrategy<Pojo> positionMappingStrategy = new ColumnPositionMappingStrategyBuilder<Pojo>().build();\n // this is just for demo, proper implementation is need for all column index\n positionMappingStrategy.setColumnMapping(refNumberIndex < nameIndex ? new String[]{\"refNumber\", \"name\"} : new String[]{\"name\", \"refNumber\"});\n // positionMappingStrategy.setColumnMapping(columnOrder);\n positionMappingStrategy.setType(Pojo.class);\n CsvToBean<Pojo> csvModelCsvToBean =\n new CsvToBeanBuilder<Pojo>(csvReader).withMappingStrategy(\n positionMappingStrategy\n ).build();\n csvModelCsvToBean.parse().forEach(m -> System.out.println(\"id:%s ,name:%s\".formatted(m.refNumber, m.name)));\n }\n\n public static class Pojo {\n private String refNumber;\n private String name;\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9399421/" ]
74,570,318
<p>I am trying to split column into mulitple column and insert into same table using snowflake query.</p> <p><strong>EMP Table</strong></p> <pre><code>ID NAME AGE 1 Ravi#Kumar 25 2 Virat#Singh 26 3 Rohit#Sharma 27 </code></pre> <p><strong>EMP Table after split</strong></p> <pre><code>ID NAME F_NAME L_NAME AGE 1 Ravi#Kumar Ravi Kumar 25 2 Virat#Singh Viart Singh 26 3 Rohit#Sharma Rohit Sharma 27 </code></pre> <p>I am able to select the data and spilt but I wanted to alter the existing table only.</p>
[ { "answer_id": 74591194, "author": "MWiesner", "author_id": 2849346, "author_profile": "https://Stackoverflow.com/users/2849346", "pm_score": 2, "selected": false, "text": "position test test test" }, { "answer_id": 74591582, "author": "samabcde", "author_id": 7928721, "author_profile": "https://Stackoverflow.com/users/7928721", "pm_score": 2, "selected": true, "text": "MappingStrategy ColumnPositionMappingStrategy import com.opencsv.CSVReader;\nimport com.opencsv.CSVReaderBuilder;\nimport com.opencsv.bean.ColumnPositionMappingStrategy;\nimport com.opencsv.bean.ColumnPositionMappingStrategyBuilder;\nimport com.opencsv.bean.CsvToBean;\nimport com.opencsv.bean.CsvToBeanBuilder;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.test.context.SpringBootTest;\n\nimport java.io.StringReader;\n\n@SpringBootTest(\n classes = CsvByPositionInRuntimeTest.Pojo.class,\n properties = {\"csv.pojo.refNumber=0\", \"csv.pojo.name=1\"}\n)\npublic class CsvByPositionInRuntimeTest {\n // assume 0\n @Value(\"${csv.pojo.refNumber}\")\n private Integer refNumberIndex;\n // assume 1\n @Value(\"${csv.pojo.name}\")\n private Integer nameIndex;\n\n // or specify column order like 'refNumber,name'\n // this is more readable and easy to maintain\n @Value(\"${csv.pojo.columnOrder}\")\n private String[] columnOrder;\n\n @Test\n public void parse() {\n CSVReader csvReader = new CSVReaderBuilder(\n new StringReader(\"\"\"\n 123,david\n 456,terry\n \"\"\")\n ).build();\n ColumnPositionMappingStrategy<Pojo> positionMappingStrategy = new ColumnPositionMappingStrategyBuilder<Pojo>().build();\n // this is just for demo, proper implementation is need for all column index\n positionMappingStrategy.setColumnMapping(refNumberIndex < nameIndex ? new String[]{\"refNumber\", \"name\"} : new String[]{\"name\", \"refNumber\"});\n // positionMappingStrategy.setColumnMapping(columnOrder);\n positionMappingStrategy.setType(Pojo.class);\n CsvToBean<Pojo> csvModelCsvToBean =\n new CsvToBeanBuilder<Pojo>(csvReader).withMappingStrategy(\n positionMappingStrategy\n ).build();\n csvModelCsvToBean.parse().forEach(m -> System.out.println(\"id:%s ,name:%s\".formatted(m.refNumber, m.name)));\n }\n\n public static class Pojo {\n private String refNumber;\n private String name;\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19571560/" ]
74,570,349
<p>I'm creating my own ELK dashboard to monitor my finances.</p> <p>I got completely wiped out this year, a combination of many things, but most likely just poor fiscal responsibility.</p> <p>Anyway;</p> <p>I'm a regex newb, and I'm having a hard time with this.</p> <p>Is there a way to quickly match strings with many trailing and leading whitespaces?</p> <p>Here are my characters:</p> <pre><code> Account: ************0000 Purchase Amount: $10.00 Transaction Date: November 10, 2022 Transaction Description: UBER *TRIP HELP.UBER.C </code></pre> <p>Here's what I am trying in regexr.com</p> <p><code>(?&lt;account&gt;(?&lt;=Account:)(.*)(?=\s*Pur)) </code> And my results contain a lot of whitespaces:</p> <pre><code> ************0000 </code></pre> <p>I'd like to have all the transaction $KEY:$VALUE pairs as named captures for grok filtering my bank transactions.</p> <p><strong>The results should be:</strong></p> <p><code>(?&lt;account&gt;($StackOverFlowSuperChargedRegex) </code></p> <pre><code>**************0000 </code></pre> <p><strong>Here is my regxr.com workspace link:</strong> <a href="https://www.stackoverflow.com/">regexr.com/736tg</a></p> <p>EDIT: I am applying this grok pattern to an elastic search ingest pipeline, but I am not opposed to using it for a logstash ingest.</p> <p>EDIT 2: @Paulo</p> <p>Here is the content field after applying trim and gsub (without the dissect processor applied)</p> <pre><code>&quot;content&quot;: &quot;View Online Hello, As requested, we’re letting you know that a purchase of $10.00 was made on your RBC Royal Bank credit card account ************0000 on November 12, 2022 towards UBER *TRIP HELP.UBER.C. If you don’t recognize this transaction, please call us at 1‑800‑769‑2512 (available 24/7) and we’ll be happy to help. Account: ************0000 Purchase Amount: $10.00 Transaction Date: November 12, 2022 Transaction Description: UBER *TRIP HELP.UBER.C Thank you! - Privacy &amp; Security | Legal - RBC Royal Bank | Royal Bank of Canada RBC WaterPark Place, 88 Queens Quay West, 12th Floor, Toronto, ON, M5J 0B8, Canada www.rbcroyalbank.com. ®/TM Trademark(s) of Royal Bank of Canada. RBC and Royal Bank are registered trademarks of Royal Bank of Canada. © Royal Bank of Canada 2022 - Communicating Safely Online Regular, unencrypted email is not secure. You should never include personal or confidential information in a regular email. Be careful when opening messages, links or attachments received through digital channels, including regular emails, text messages and social media messages. If you receive a message that appears to be from RBC that is suspicious please report it to us and then delete it. Do not provide personal information like passwords. Need Help? To discuss your personal information with us safely, visit our customer service page. Please note this email was sent from an unmonitored inbox. Do not reply. For current scam alerts and tips to protect yourself visit: RBC Cyber Security | Active Scam Alerts &quot; }, &quot;_ingest&quot;: { &quot;timestamp&quot;: &quot;2022-11-25T11:18:28.621402003Z&quot; } </code></pre>
[ { "answer_id": 74591194, "author": "MWiesner", "author_id": 2849346, "author_profile": "https://Stackoverflow.com/users/2849346", "pm_score": 2, "selected": false, "text": "position test test test" }, { "answer_id": 74591582, "author": "samabcde", "author_id": 7928721, "author_profile": "https://Stackoverflow.com/users/7928721", "pm_score": 2, "selected": true, "text": "MappingStrategy ColumnPositionMappingStrategy import com.opencsv.CSVReader;\nimport com.opencsv.CSVReaderBuilder;\nimport com.opencsv.bean.ColumnPositionMappingStrategy;\nimport com.opencsv.bean.ColumnPositionMappingStrategyBuilder;\nimport com.opencsv.bean.CsvToBean;\nimport com.opencsv.bean.CsvToBeanBuilder;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.test.context.SpringBootTest;\n\nimport java.io.StringReader;\n\n@SpringBootTest(\n classes = CsvByPositionInRuntimeTest.Pojo.class,\n properties = {\"csv.pojo.refNumber=0\", \"csv.pojo.name=1\"}\n)\npublic class CsvByPositionInRuntimeTest {\n // assume 0\n @Value(\"${csv.pojo.refNumber}\")\n private Integer refNumberIndex;\n // assume 1\n @Value(\"${csv.pojo.name}\")\n private Integer nameIndex;\n\n // or specify column order like 'refNumber,name'\n // this is more readable and easy to maintain\n @Value(\"${csv.pojo.columnOrder}\")\n private String[] columnOrder;\n\n @Test\n public void parse() {\n CSVReader csvReader = new CSVReaderBuilder(\n new StringReader(\"\"\"\n 123,david\n 456,terry\n \"\"\")\n ).build();\n ColumnPositionMappingStrategy<Pojo> positionMappingStrategy = new ColumnPositionMappingStrategyBuilder<Pojo>().build();\n // this is just for demo, proper implementation is need for all column index\n positionMappingStrategy.setColumnMapping(refNumberIndex < nameIndex ? new String[]{\"refNumber\", \"name\"} : new String[]{\"name\", \"refNumber\"});\n // positionMappingStrategy.setColumnMapping(columnOrder);\n positionMappingStrategy.setType(Pojo.class);\n CsvToBean<Pojo> csvModelCsvToBean =\n new CsvToBeanBuilder<Pojo>(csvReader).withMappingStrategy(\n positionMappingStrategy\n ).build();\n csvModelCsvToBean.parse().forEach(m -> System.out.println(\"id:%s ,name:%s\".formatted(m.refNumber, m.name)));\n }\n\n public static class Pojo {\n private String refNumber;\n private String name;\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949282/" ]
74,570,360
<p>I'm trying to remove the legend of lines, but I don't know why it can't remove, and I only want to keep the points of &quot;supp&quot;.</p> <pre><code>library(ggpubr) a&lt;-ggline(ToothGrowth, x = &quot;dose&quot;, y = &quot;len&quot;, add = c(&quot;mean_se&quot;, &quot;jitter&quot;), color = &quot;supp&quot;, palette = &quot;jco&quot;) b&lt;-ggline(ToothGrowth, x = &quot;dose&quot;, y = &quot;len&quot;, add = c(&quot;mean_se&quot;, &quot;jitter&quot;), color = &quot;supp&quot;, palette = &quot;jco&quot;) ggarrange(plot_grid(a + theme(legend.position=&quot;none&quot;)), b,common.legend = TRUE, labels = c(&quot;A&quot;, &quot;B&quot;),legend = &quot;right&quot;) </code></pre>
[ { "answer_id": 74591194, "author": "MWiesner", "author_id": 2849346, "author_profile": "https://Stackoverflow.com/users/2849346", "pm_score": 2, "selected": false, "text": "position test test test" }, { "answer_id": 74591582, "author": "samabcde", "author_id": 7928721, "author_profile": "https://Stackoverflow.com/users/7928721", "pm_score": 2, "selected": true, "text": "MappingStrategy ColumnPositionMappingStrategy import com.opencsv.CSVReader;\nimport com.opencsv.CSVReaderBuilder;\nimport com.opencsv.bean.ColumnPositionMappingStrategy;\nimport com.opencsv.bean.ColumnPositionMappingStrategyBuilder;\nimport com.opencsv.bean.CsvToBean;\nimport com.opencsv.bean.CsvToBeanBuilder;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.test.context.SpringBootTest;\n\nimport java.io.StringReader;\n\n@SpringBootTest(\n classes = CsvByPositionInRuntimeTest.Pojo.class,\n properties = {\"csv.pojo.refNumber=0\", \"csv.pojo.name=1\"}\n)\npublic class CsvByPositionInRuntimeTest {\n // assume 0\n @Value(\"${csv.pojo.refNumber}\")\n private Integer refNumberIndex;\n // assume 1\n @Value(\"${csv.pojo.name}\")\n private Integer nameIndex;\n\n // or specify column order like 'refNumber,name'\n // this is more readable and easy to maintain\n @Value(\"${csv.pojo.columnOrder}\")\n private String[] columnOrder;\n\n @Test\n public void parse() {\n CSVReader csvReader = new CSVReaderBuilder(\n new StringReader(\"\"\"\n 123,david\n 456,terry\n \"\"\")\n ).build();\n ColumnPositionMappingStrategy<Pojo> positionMappingStrategy = new ColumnPositionMappingStrategyBuilder<Pojo>().build();\n // this is just for demo, proper implementation is need for all column index\n positionMappingStrategy.setColumnMapping(refNumberIndex < nameIndex ? new String[]{\"refNumber\", \"name\"} : new String[]{\"name\", \"refNumber\"});\n // positionMappingStrategy.setColumnMapping(columnOrder);\n positionMappingStrategy.setType(Pojo.class);\n CsvToBean<Pojo> csvModelCsvToBean =\n new CsvToBeanBuilder<Pojo>(csvReader).withMappingStrategy(\n positionMappingStrategy\n ).build();\n csvModelCsvToBean.parse().forEach(m -> System.out.println(\"id:%s ,name:%s\".formatted(m.refNumber, m.name)));\n }\n\n public static class Pojo {\n private String refNumber;\n private String name;\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20597651/" ]
74,570,372
<p>I am trying to populate a JSON file from the user input. The <code>users.json</code> file is initially empty, and I was able to register the first user <code>(&quot;Doe_Joh&quot;)</code>. The problem was when I ran the program and registered for the second use. The data inside got replaced by the data. What I expected was to have the data saved incrementally. How can I achieve this?</p> <p>Here is my code.</p> <pre><code>import json class User: def register(): first = input(&quot;Name: &quot;) last = input(&quot;Last: &quot;) username = input(&quot;Username: &quot;) email = input(&quot;Email: &quot;) user_data = { username: [ { &quot;fname&quot;: first, &quot;lname&quot;: last, &quot;username&quot;: username, &quot;email&quot;: email } ] } with open(&quot;users.json&quot;, &quot;w&quot;) as outfile: json.dump(user_data, outfile, indent=4) user1 = User user1.register() </code></pre>
[ { "answer_id": 74570496, "author": "mighty_mike", "author_id": 4953409, "author_profile": "https://Stackoverflow.com/users/4953409", "pm_score": 2, "selected": true, "text": "import json\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass User:\n f_name: str\n l_name: str\n username: str\n email: str\n\n\ndef save_user(user: User) -> None:\n with open(\"users.json\", \"r\") as file:\n try:\n file_data = json.load(file)\n except JSONDecodeError:\n file_data = {}\n file_data[user.username] = [{\n \"fname\": user.f_name,\n \"lname\": user.l_name,\n \"username\": user.username,\n \"email\": user.email\n }]\n with open(\"users.json\", \"w\") as outfile:\n json.dump(file_data, outfile, indent=4)\n\n\ndef register():\n first = input(\"Name: \")\n last = input(\"Last: \")\n username = input(\"Username: \")\n email = input(\"Email: \")\n user_data = User(\n f_name=first,\n l_name=last,\n username=username,\n email=email\n )\n save_user(user=user_data)\n\n\nregister()\n import json\n\n\ndef save_user(user) -> None:\n with open(\"users.json\", \"r\") as file:\n try:\n file_data = json.load(file)\n except JSONDecodeError:\n file_data = {}\n file_data[user['username']] = [{\n \"fname\": user['f_name'],\n \"lname\": user['l_name'],\n \"username\": user['username'],\n \"email\": user['email']\n }]\n with open(\"users.json\", \"w\") as outfile:\n json.dump(file_data, outfile, indent=4)\n\n\ndef register():\n first = input(\"Name: \")\n last = input(\"Last: \")\n username = input(\"Username: \")\n email = input(\"Email: \")\n user_data = {\n \"f_name\": first,\n \"l_name\": last,\n \"username\": username,\n \"email\": email\n }\n save_user(user=user_data)\n\n\nregister()\n with open(\"users.json\", \"a\") as outfile:\n json.dump(user_data, outfile, indent=4)\n open()" }, { "answer_id": 74570776, "author": "Mogli141", "author_id": 15395276, "author_profile": "https://Stackoverflow.com/users/15395276", "pm_score": 0, "selected": false, "text": "load() import json\nimport os\n\ndata = {}\n\n\nclass User():\n\n def register(self):\n first = input(\"Name: \")\n last = input(\"Last: \")\n username = input(\"Username: \")\n email = input(\"Email: \")\n data[username] = [{\n \"fname\": first,\n \"lname\": last,\n \"username\": username,\n \"email\": email\n }\n ]\n with open(\"users.json\", \"w\") as outfile:\n json.dump(data, outfile, indent=4)\n\n def load(self):\n global data\n with open(\"users.json\", \"r\") as outfile:\n data = json.loads(outfile.read())\n print(data, type(data))\n return data\n\n\nuser1 = User()\n\nif os.path.isfile(\"users.json\"):\n user1.load()\nuser1.register()\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17701650/" ]
74,570,376
<p>I'm a bit lost here (maybe because it's Friday)</p> <p>I want to write a simple &quot;throw if null or empty&quot; extension helper that I can use in constructors like (e.g.)</p> <pre class="lang-cs prettyprint-override"><code>public class MyClass { public MyClass(params MyType[] parameters) { _parameters = parameters.ThrowIfNullOrEmpty(); } </code></pre> <p>So I was trying to write this method like:</p> <pre class="lang-cs prettyprint-override"><code>public static T ThrowIfNullOrEmpty&lt;T, V&gt;(this T? collection, [CallerArgumentExpression(&quot;collection&quot;)] string? paramName = null) where T : IReadOnlyCollection&lt;V&gt; { if (collection is null || collection.Count == 0) { throw new ArgumentException($&quot;{paramName} is null or empty&quot;); } return collection; } </code></pre> <p>But that doesn't work, as I get an &quot;Arguments cannot be inferred from usage&quot;.</p> <p>The issue here I that I have to use <code>ThrowIfNullOrEmpty&lt;T, V&gt;</code>, as <code>where T : IReadOnlyCollection&lt;V&gt;</code> requires a type parameter.</p> <p>Isn't there a way to say &quot;I don't care what <code>V</code> is, as long as <code>T</code> is a form of <code>IReadOnlyCollection</code>&quot;?</p>
[ { "answer_id": 74570822, "author": "shingo", "author_id": 6196568, "author_profile": "https://Stackoverflow.com/users/6196568", "pm_score": 0, "selected": false, "text": "parameters.ThrowIfNullOrEmpty(out _parameters);\n\npublic static void ThrowIfNullOrEmpty<TElem, TColl>(\n this IReadOnlyCollection<TElem>? collection,\n out TColl? output,\n [CallerArgumentExpression(\"collection\")] string? paramName = null\n) where TColl : IReadOnlyCollection<TElem>\n{\n if (collection is null || collection.Count == 0)\n {\n throw new ArgumentException($\"{paramName} is null or empty\");\n }\n\n output = (TColl)collection;\n}\n" }, { "answer_id": 74571055, "author": "CodeCaster", "author_id": 266143, "author_profile": "https://Stackoverflow.com/users/266143", "pm_score": 2, "selected": true, "text": "ICollection public static TCollection ThrowIfNullOrEmpty<TCollection>(this TCollection collection, [CallerArgumentExpression(\"collection\")] string? paramName = null)\n where TCollection : ICollection\n{\n if (collection is null || collection.Count == 0)\n {\n throw new ArgumentException($\"{paramName} is null or empty\");\n }\n\n return collection;\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6717178/" ]
74,570,393
<p>I want to change the font weight in TextView but i can't find the required method.</p> <p>How can i do it without creating a new font?</p>
[ { "answer_id": 74570822, "author": "shingo", "author_id": 6196568, "author_profile": "https://Stackoverflow.com/users/6196568", "pm_score": 0, "selected": false, "text": "parameters.ThrowIfNullOrEmpty(out _parameters);\n\npublic static void ThrowIfNullOrEmpty<TElem, TColl>(\n this IReadOnlyCollection<TElem>? collection,\n out TColl? output,\n [CallerArgumentExpression(\"collection\")] string? paramName = null\n) where TColl : IReadOnlyCollection<TElem>\n{\n if (collection is null || collection.Count == 0)\n {\n throw new ArgumentException($\"{paramName} is null or empty\");\n }\n\n output = (TColl)collection;\n}\n" }, { "answer_id": 74571055, "author": "CodeCaster", "author_id": 266143, "author_profile": "https://Stackoverflow.com/users/266143", "pm_score": 2, "selected": true, "text": "ICollection public static TCollection ThrowIfNullOrEmpty<TCollection>(this TCollection collection, [CallerArgumentExpression(\"collection\")] string? paramName = null)\n where TCollection : ICollection\n{\n if (collection is null || collection.Count == 0)\n {\n throw new ArgumentException($\"{paramName} is null or empty\");\n }\n\n return collection;\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593361/" ]
74,570,405
<p>I'm defining a component as:</p> <pre><code>&lt;HiChevronDown aria-hidden=&quot;true&quot; className= &quot;ml-2 h-5 w-5 ...&quot; /&gt; </code></pre> <p>However, the console warnings state that I am defining it camelCased.</p> <p>Anything I'm doing obviously wrong here?</p> <p>Console warning: <a href="https://i.stack.imgur.com/HX6yV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HX6yV.png" alt="invalid ARIA attribute" /></a></p>
[ { "answer_id": 74587178, "author": "AIMEUR Amin", "author_id": 5616238, "author_profile": "https://Stackoverflow.com/users/5616238", "pm_score": 1, "selected": false, "text": "react-icons/hi FaChevronDown IoChevronDownOutline" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13966698/" ]
74,570,461
<p>I can't figure out how to properly slice a string. There is a line: &quot;1, 2, 3, 4, 5, 6&quot;. The number of characters is unknown, numbers can be either one-digit or three-digit I need to get the last value up to the nearest comma, that means I need to get the value (6) from the string</p>
[ { "answer_id": 74570508, "author": "Lucas M. Uriarte", "author_id": 14543462, "author_profile": "https://Stackoverflow.com/users/14543462", "pm_score": 3, "selected": true, "text": "string = \"1, 2, 3, 4, 5, 6\"\nstring.split(',')[-1]\n>>> ' 6'\n string.split(',')[-1].strip(' ')\n>>> '6'\n" }, { "answer_id": 74570515, "author": "Álvaro Méndez Civieta", "author_id": 5413581, "author_profile": "https://Stackoverflow.com/users/5413581", "pm_score": 1, "selected": false, "text": "split string = '1, 2, 3, 4, 5, 6'\nlast_value = string.split(', ')[-1]\nprint(last_value)\n\nOut[3]: '6'\n" }, { "answer_id": 74570522, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "def get_last_number(s):\n return s.split(',')[-1].strip()\n s1 = \"1, 2, 3, 4, 5, 6\"\ns2 = \"123, 4, 785, 12\"\ns3 = \"1, 2, 789654 \" \n print (get_last_number(s1))\n# 6\nprint (get_last_number(s2))\n# 12\nprint (get_last_number(s3))\n# 789654\n" }, { "answer_id": 74570607, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "str.rsplit maxsplit=1 string = \"1, 2, 3, 4, 5, 6\"\nlast = string.rsplit(', ', 1)[-1]\n '6'" }, { "answer_id": 74571343, "author": "azzzoto", "author_id": 19676081, "author_profile": "https://Stackoverflow.com/users/19676081", "pm_score": 0, "selected": false, "text": "string = '1, 2, 3, 4, 5, 6'\nsplitted_str = string.split(',')\n last_elem = splitted_str[-1]\n last_number_str = last_elem.strip()\n last_elem_int = int(last_elem_str)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19628591/" ]
74,570,472
<p>Im using react-redux, and in my saga file where I have implemented logic for new/edit page, I need to implement an API for getting some codes for customer.</p> <pre><code>const getCodesById = (Id) =&gt; get(`${BASE_URL}/${companyId}/codes`); export function* getTableById(action) { const Id = yield select(getCurrentCustomeId); getEarningCodesForCompany(companyId).then((response) =&gt; { console.log(response) //It shows correct array of objects from api return response; }); } </code></pre> <p>in <code>console.log(response)</code> I can see the data properly. However, I dont know how can I extract that response in some variable outside that function to be able to use it along in the function <code>getTableById</code>.</p> <p>I tried with <code>const request = yield call(getCodesById(Id));</code> but with yield my program is crashing.</p> <p>How can I do this to, get response and use it elsewhere?</p>
[ { "answer_id": 74570508, "author": "Lucas M. Uriarte", "author_id": 14543462, "author_profile": "https://Stackoverflow.com/users/14543462", "pm_score": 3, "selected": true, "text": "string = \"1, 2, 3, 4, 5, 6\"\nstring.split(',')[-1]\n>>> ' 6'\n string.split(',')[-1].strip(' ')\n>>> '6'\n" }, { "answer_id": 74570515, "author": "Álvaro Méndez Civieta", "author_id": 5413581, "author_profile": "https://Stackoverflow.com/users/5413581", "pm_score": 1, "selected": false, "text": "split string = '1, 2, 3, 4, 5, 6'\nlast_value = string.split(', ')[-1]\nprint(last_value)\n\nOut[3]: '6'\n" }, { "answer_id": 74570522, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "def get_last_number(s):\n return s.split(',')[-1].strip()\n s1 = \"1, 2, 3, 4, 5, 6\"\ns2 = \"123, 4, 785, 12\"\ns3 = \"1, 2, 789654 \" \n print (get_last_number(s1))\n# 6\nprint (get_last_number(s2))\n# 12\nprint (get_last_number(s3))\n# 789654\n" }, { "answer_id": 74570607, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "str.rsplit maxsplit=1 string = \"1, 2, 3, 4, 5, 6\"\nlast = string.rsplit(', ', 1)[-1]\n '6'" }, { "answer_id": 74571343, "author": "azzzoto", "author_id": 19676081, "author_profile": "https://Stackoverflow.com/users/19676081", "pm_score": 0, "selected": false, "text": "string = '1, 2, 3, 4, 5, 6'\nsplitted_str = string.split(',')\n last_elem = splitted_str[-1]\n last_number_str = last_elem.strip()\n last_elem_int = int(last_elem_str)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3918121/" ]
74,570,485
<p>I have problems with getting a css file places behind a razor component to work</p> <p>I have 3 files:</p> <ul> <li>Index.razor</li> <li>Index.razor.cs</li> <li>Index.razor.css</li> </ul> <p>but the css in the .css file is not used in the Index.razor page</p> <p>Do I need to switch anything one or how do i make it work?</p> <p>Indexfile content:</p> <pre><code>@page &quot;/&quot; @namespace TestCSSIsolation.Pages &lt;h1&gt;Hello, world!&lt;/h1&gt; &lt;input value=&quot;@value&quot; /&gt; &lt;button @onclick=&quot;@OnClick_Button&quot;&gt;Click&lt;/button&gt; </code></pre> <p>.cs file content:</p> <pre><code>namespace TestCSSIsolation.Pages; public partial class Index { private string value = string.Empty; private void OnClick_Button() { if (value.Trim().Length &gt; 0) { value = string.Empty; } else { value = &quot;Test&quot;; } } } </code></pre> <p>.css file content:</p> <pre><code>body { border: solid 10px red; } button { background-color: pink; } input { background-color: lightblue; } </code></pre> <p>Unfortunately I not allowed to post pictures here, but the result when I run the application is that the styling in the css file is not used on the component.</p>
[ { "answer_id": 74570508, "author": "Lucas M. Uriarte", "author_id": 14543462, "author_profile": "https://Stackoverflow.com/users/14543462", "pm_score": 3, "selected": true, "text": "string = \"1, 2, 3, 4, 5, 6\"\nstring.split(',')[-1]\n>>> ' 6'\n string.split(',')[-1].strip(' ')\n>>> '6'\n" }, { "answer_id": 74570515, "author": "Álvaro Méndez Civieta", "author_id": 5413581, "author_profile": "https://Stackoverflow.com/users/5413581", "pm_score": 1, "selected": false, "text": "split string = '1, 2, 3, 4, 5, 6'\nlast_value = string.split(', ')[-1]\nprint(last_value)\n\nOut[3]: '6'\n" }, { "answer_id": 74570522, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "def get_last_number(s):\n return s.split(',')[-1].strip()\n s1 = \"1, 2, 3, 4, 5, 6\"\ns2 = \"123, 4, 785, 12\"\ns3 = \"1, 2, 789654 \" \n print (get_last_number(s1))\n# 6\nprint (get_last_number(s2))\n# 12\nprint (get_last_number(s3))\n# 789654\n" }, { "answer_id": 74570607, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "str.rsplit maxsplit=1 string = \"1, 2, 3, 4, 5, 6\"\nlast = string.rsplit(', ', 1)[-1]\n '6'" }, { "answer_id": 74571343, "author": "azzzoto", "author_id": 19676081, "author_profile": "https://Stackoverflow.com/users/19676081", "pm_score": 0, "selected": false, "text": "string = '1, 2, 3, 4, 5, 6'\nsplitted_str = string.split(',')\n last_elem = splitted_str[-1]\n last_number_str = last_elem.strip()\n last_elem_int = int(last_elem_str)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18528148/" ]
74,570,569
<p>I want to clearly understand what is the difference between the following XPath expressions <code>&quot;//*[contains(.,'sometext')]&quot;</code> and <code>&quot;//*[contains(text(),'sometext')]&quot;</code>.<br /> From <a href="https://stackoverflow.com/a/41862373/3485434">this great answer</a> I understand, that <code>text()</code> returns a set of individual nodes, while <code>.</code> in a predicate evaluates to the string concatenation of all text nodes.<br /> OK, but when I'm using <code>[contains(.,'sometext')]</code> or <code>[contains(text(),'sometext')]</code> this should return the same amount of elements matching those XPaths since here we checking for nodes <strong>containing</strong> <code>someText</code> content in itself or in some of their children. Right? And it doesn't matter if we are checking whether any of the text nodes of an element contains <code>sometext</code> or string concatenation of all text nodes contains the <code>sometext</code> text. This should give the same amount of matches.<br /> However if we test this for example on <a href="https://stackoverflow.com/questions/tagged/selenium%2Bor%2Bwebdriver%2Bor%2Bxpath%2Bor%2Bselenium-webdriver%2Bor%2Bselenium-chromedriver?tab=Newest">this page</a> I see 104 matches for <code>//*[contains(text(),'selenium')]</code> XPath while <code>//*[contains(.,'selenium')]</code> XPath is giving 442 matches.<br /> So, what causes this difference?</p>
[ { "answer_id": 74570508, "author": "Lucas M. Uriarte", "author_id": 14543462, "author_profile": "https://Stackoverflow.com/users/14543462", "pm_score": 3, "selected": true, "text": "string = \"1, 2, 3, 4, 5, 6\"\nstring.split(',')[-1]\n>>> ' 6'\n string.split(',')[-1].strip(' ')\n>>> '6'\n" }, { "answer_id": 74570515, "author": "Álvaro Méndez Civieta", "author_id": 5413581, "author_profile": "https://Stackoverflow.com/users/5413581", "pm_score": 1, "selected": false, "text": "split string = '1, 2, 3, 4, 5, 6'\nlast_value = string.split(', ')[-1]\nprint(last_value)\n\nOut[3]: '6'\n" }, { "answer_id": 74570522, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "def get_last_number(s):\n return s.split(',')[-1].strip()\n s1 = \"1, 2, 3, 4, 5, 6\"\ns2 = \"123, 4, 785, 12\"\ns3 = \"1, 2, 789654 \" \n print (get_last_number(s1))\n# 6\nprint (get_last_number(s2))\n# 12\nprint (get_last_number(s3))\n# 789654\n" }, { "answer_id": 74570607, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "str.rsplit maxsplit=1 string = \"1, 2, 3, 4, 5, 6\"\nlast = string.rsplit(', ', 1)[-1]\n '6'" }, { "answer_id": 74571343, "author": "azzzoto", "author_id": 19676081, "author_profile": "https://Stackoverflow.com/users/19676081", "pm_score": 0, "selected": false, "text": "string = '1, 2, 3, 4, 5, 6'\nsplitted_str = string.split(',')\n last_elem = splitted_str[-1]\n last_number_str = last_elem.strip()\n last_elem_int = int(last_elem_str)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3485434/" ]
74,570,573
<p>I have a web application which is linked to an API. Usually I launch the API and it works. And now, for no reason ( I change nothing in my code and in the API ), it does not work anymore and I can a ton of error like the one I shared on my web application. What can I do ? `</p> <pre><code>at callWithErrorHandling (vue.runtime.esm-bundler.js?ebac:123) at setupStatefulComponent (vue.runtime.esm-bundler.js?ebac:1242) at setupComponent (vue.runtime.esm-bundler.js?ebac:1238) at mountComponent (vue.runtime.esm-bundler.js?ebac:838) at processComponent (vue.runtime.esm-bundler.js?ebac:834) at patch (vue.runtime.esm-bundler.js?ebac:755) at ReactiveEffect.componentUpdateFn [as fn] (vue.runtime.esm-bundler.js?ebac:856) at ReactiveEffect.run (vue.runtime.esm-bundler.js?ebac:67) at setupRenderEffect (vue.runtime.esm-bundler.js?ebac:881) </code></pre> <p>`</p> <p>I tried to relaunch the web application but same problem.</p>
[ { "answer_id": 74570747, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "axios.js src/boot/ import { boot } from 'quasar/wrappers'\n import axios from 'axios'\n\n // example: const RESTURL = \"http://172.26.117.16:3000/api\"\n const RESTURL = \"http://localhost:3000/api\"\n \n const api = axios.create({\n baseURL: RESTURL,\n headers:{ \"Content-type\" : \"application/json\" }\n })\n\n export default boot(({ app }) => {\n \n app.config.globalProperties.$axios = axios\n \n app.config.globalProperties.$api = api\n \n app.config.globalProperties.$RESTURL = RESTURL\n })\n\n export { api, RESTURL }\n this.$api.post(\"/customer/login\", data)\n .then(res => {\n if (res.status == 200){\n this.errorMessage = \"\"\n this.store.loggedUser = res.data\n this.$router.push('/')\n }\n })\n .catch((err) => {\n this.errorMessage = \"Wrong Mail / Password\"\n })\n const sql = require(\"./db\");\n\n //Constructor\n const Customer = function (customer) {\n this.name = customer.name;\n this.mail = customer.mail;\n this.password = customer.password;\n this.address = customer.address;\n this.postCode = customer.postCode;\n this.city = customer.city;\n };\n\n Customer.getAllRecords = (result) => {\n sql.query(\"SELECT * FROM Customer\", (err, res) => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n result(null, res);\n });\n };\n\n Customer.create = ( newCustomer, result ) => {\n sql.query(\"INSERT INTO Customer SET ?\", newCustomer, (err, res) \n => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n console.log(\"Created Customer: \", {\n id: res.insertId,\n ...newCustomer\n });\n result(null, {\n id: res.insertId,\n ...newCustomer\n });\n })\n }\n\n Customer.updateByID = (id, data, result) => {\n sql.query(\n \"UPDATE Customer SET name=?, mail=?, password=?, address=?, \n postCode=?, city=? WHERE id=?\",\n [data.name, data.mail, data.password, data.address, \n data.postCode, data.city, id],\n (err, res) => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n if (res.affectedRows == 0) {\n //this id not found\n result({ kind: \"not_found\" }, null);\n return;\n }\n console.log(\"Updated Customer: \", { id: id, ...data });\n result(null, { id: id, ...data });\n }\n );\n };\n\n Customer.delete = ( id, result ) => {\n sql.query(\"DELETE FROM Customer WHERE id = ?\", id, (err, res) \n => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n } if(res.affectedRows == 0){\n result({kind: \"not_found\"}, null)\n return;\n }\n console.log(\"Deleted Customer id: \", id)\n result(null, {id: id})\n });\n }\n\n Customer.login = (account, result) => {\n sql.query(\n \"SELECT * FROM Customer WHERE mail = ?\", account.mail,\n (err, res) => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n if (res.length) {\n const validPassword = account.password == \n res[0].password\n\n if (validPassword) {\n result(null, res[0]);\n return;\n } else {\n console.log(\"Password invalid.\");\n result({ kind: \"invalid_pass\" }, null);\n return;\n }\n }\n result({ kind: \"not_found\" }, null);\n }\n );\n };\n\n module.exports = Customer\n" }, { "answer_id": 74570795, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "const routes = [\n {\n path: '/',\n component: () => import('layouts/MainLayout.vue'),\n children: [\n { path: '', component: () => import('pages/IndexPage.vue') },\n { path: 'signin', component: () => import('pages/SigninPage.vue') \n},\n { path: 'signup', component: () => import('pages/SignupPage.vue') \n},\n ]\n },\n {\n path: '/:catchAll(.*)*',\n component: () => import('pages/ErrorNotFound.vue')\n }\n]\n\nexport default routes\n module.exports = (app) => {\n const customer_controller = \nrequire(\"../controllers/customer.controller\")\n var router = require(\"express\").Router();\n router.post(\"/add\", customer_controller.createNewCustomer);\n router.get(\"/all\", customer_controller.getAllCustomer);\n router.put(\"/:id\", customer_controller.updateCustomer);\n router.delete(\"/:id\", customer_controller.deleteCustomer);\n router.post(\"/login\", customer_controller.loginCustomer);\n\n app.use(\"/api/customer\", router);\n};\n" }, { "answer_id": 74570964, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "import { defineStore } from \"pinia\";\n\nexport const useGlobalStateStore = defineStore(\"global\", {\n state: () => ({\n globalSell: 0,\n whateverarray: [...],\n }),\n getters: {\n doubleCount(state) {\n return state.globalSell * 2;\n },\n },\n\nactions: {\n incrementGlobalSell() {\n this.globalSell++;\n },\n deleteCategory(id) {\n this.categories = this.categories.filter((element) => {\n return element.id != id;\n });\n },\n <script>\n -> import {useGlobalStateStore} from \"stores/globalState\";\n import NavComponent from \"components/NavComponent\";\n data() {\n return {\n -> store : useGlobalStateStore(),\n email: \"\",\n" }, { "answer_id": 74571260, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "module.exports = {\n HOST:\"sql12.freemysqlhosting.net\",\n USER:\"user\",\n PASSWORD:\"pass\",\n DB:\"nameOfDB\"\n}\n const Customer = require(\"../models/customer.model.js\");\n\nconst getAllCustomer = (req, res) => {\n Customer.getAllRecords((err, data) => {\n if (err) {\n res.status(500).send({\n message: err.message || \"Some error occured while \nretriveing data.\",\n });\n } else res.send(data);\n });\n};\n\nconst createNewCustomer = (req, res) => {\n if (!req.body) {\n res.status(400).send({\n message: \"Content can not be empty.\",\n });\n}\n\nconst customerObj = new Customer({\n name: req.body.name,\n mail: req.body.mail,\n password: req.body.password,\n address: req.body.address,\n postCode: req.body.postCode,\n city: req.body.city\n});\n\nCustomer.create(customerObj, (err, data) => {\n console.log(req.body)\n if (err) {\n res.status(500).send({\n message: err.message || \"Some error occured while \ncreating.\",\n });\n } else {\n res.send(data);\n }\n });\n};\n\nconst updateCustomer = (req, res) =>{\n if(!req.body){\n res.status(400).send({ message: \"Content can not be \n empty.\"});\n }\nconst data = {\n name: req.body.name,\n mail: req.body.mail,\n password: req.body.password,\n address: req.body.address,\n postCode: req.body.postCode,\n city: req.body.city\n};\nCustomer.updateByID(req.params.id, data, (err, result)=>{\n if(err){\n if(err.kind == \"not_found\"){\n res.status(401).send({\n message: \"Not found Customer id: \" + \nreq.params.id\n });\n } else{\n res.status(500).send({\n message: \"Error update Customer id: \" + \nreq.params.id\n });\n }\n } else res.send(result);\n });\n};\n\nconst deleteCustomer = (req, res) =>{\n Customer.delete(req.params.id, (err, result)=>{\n if(err){\n if(err.kind == \"not_found\"){\n res.status(401).send({\n message: \"Not found Customer id: \" + \n req.params.id\n });\n }else{\n res.status(500).send({\n message: \"Error delete Customer id: \" + \n req.params.id\n });\n }\n }\n else res.send(result);\n });\n};\n\nconst loginCustomer = (req, res) => {\n if (!req.body) {\n res.status(400).send({\n message: \"Content can not be empty.\",\n });\n}\n\nconst account = new Customer({\n mail: req.body.mail,\n password: req.body.password\n});\n\nCustomer.login(account, (err, data)=>{\n if(err){\n if(err.kind == \"not_found\"){\n res.status(401).send({\n message: \"Not found \" + req.body.mail\n });\n } else if (err.kind == \"invalid_pass\"){\n res.status(401).send({\n message: \"Invalid Password\"\n });\n } else{\n res.status(500).send({\n message: \"Error retriveing \" + req.body.mail\n });\n }\n }else res.send(data);\n });\n};\n\nmodule.exports = {\ngetAllCustomer,\ncreateNewCustomer,\nupdateCustomer,\ndeleteCustomer,\nloginCustomer\n};\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20597728/" ]
74,570,587
<p>I am trying to change the color of a button pressed from a dynamic json list using useRef. But when I use the useRef it is only aiming at the last value of the list.But if I add array in the list then how would the main component know which element was pressed ?</p> <p><a href="https://i.stack.imgur.com/d8fuc.png" rel="nofollow noreferrer">Need to make the background of the selected item colored and rest white</a></p> <p>// Parent Element ==&gt; InvoiceTitle is the child component</p> <p>const Usage = () =&gt; {</p> <pre><code>const data = UsageDataMock const invoiceTitleRef = useRef('') const onChange = () =&gt; { console.log('Selected Title =&gt; ',invoiceTitleRef?.current?.getSelectedTitle()) } return ( &lt;View style = {{flexDirection : 'row', marginTop : 50}}&gt; {data.map((item, index) =&gt; ( &lt;InvoiceTitle ref = {invoiceTitleRef} key = {item.id} title = {item.title} onChange = {onChange} /&gt; ))} &lt;/View&gt; ) </code></pre> <p>}</p> <p>//Child Component</p> <pre><code>const InvoiceTitle = forwardRef(({ title, onChange, ...props }: InvoiceTitleProps, ref) =&gt; { const[selectedTitle, setSelectedTitle] = useState('') useImperativeHandle(ref, () =&gt; ({ getSelectedTitle : () =&gt; selectedTitle })) const onClick = (title : string) =&gt; { onChange(selectedTitle) } console.log('default title', selectedTitle) return ( &lt;Pressable onPress={() =&gt; onChange(setSelectedTitle(title))} style = {({pressed}) =&gt; [styles.titleContainer, {backgroundColor : 'red', opacity : pressed ? 0.5 : 1}]}&gt; &lt;AppText&gt;{title}&lt;/AppText&gt; &lt;/Pressable&gt; ) }) </code></pre> <p>Updated 28th Nov</p> <p>Getting selected items but now it is changing color of every button . const Usage = () =&gt; {</p> <pre><code>const [data, setData] = useState(UsageDataMock1); const invoiceTitleRef = []; const onChange = (index, selectedTitle) =&gt; { // console.log('Selected Title =&gt; ', invoiceTitleRef[index].getSelectedTitle()) const tempSelection = invoiceTitleRef[index].getSelectedTitle() const temp = data.map((item, index) =&gt; { if(item.title == tempSelection) { return ({...item, isSelected : 'true'}) } else return ({...item, isSelected : 'false'}) }) setData(temp) } </code></pre> <p>console.log('123', data)</p> <pre><code>return ( &lt;AppBackground&gt; &lt;View style = {{flexDirection : 'row', marginTop : 50}}&gt; {data.map((item, index) =&gt; ( &lt;&gt; {console.log('asd', item)} &lt;InvoiceTitle ref={(element) =&gt; invoiceTitleRef[index] = element} key={item.id} title={item.title} selected = {item?.isSelected} onChange={onChange} index={index} /&gt; &lt;/&gt; ))} &lt;/View&gt; &lt;/AppBackground&gt; ) </code></pre> <p>}</p> <p>const styles = StyleSheet.create({ container : { flexDirection : 'row', marginTop : 40, }, titleContainer : { marginHorizontal : 10, alignSelf : 'flex-start', paddingHorizontal : 10, paddingVertical : 8, borderRadius : 12, } })</p> <p>export default Usage</p> <p>Child Component const InvoiceTitle = forwardRef(({ title, onChange, index, key, selected = false, ...props }: InvoiceTitleProps, ref) =&gt; {</p> <pre><code>useImperativeHandle(ref, () =&gt; ({ getSelectedTitle : () =&gt; title })) // console.log('ASD title', title, selected) // const [color, setColor] = useState('white') const [color , setColor] = useState('white') const onClick = () =&gt; { onChange(index, title) } return ( &lt;Pressable key = {key} onPress={() =&gt; onClick()} style = {({pressed}) =&gt; [styles.titleContainer, {backgroundColor : selected ? 'red' : 'blue', opacity : pressed ? 0.5 : 1}]}&gt; &lt;AppText&gt;{title}&lt;/AppText&gt; &lt;/Pressable&gt; ) </code></pre> <p>})</p> <p>const styles = StyleSheet.create({ container : { flexDirection : 'row', marginTop : 40, }, titleContainer : { marginHorizontal : 10, alignSelf : 'flex-start', paddingHorizontal : 10, paddingVertical : 8, borderRadius : 12, } })</p> <p>export default InvoiceTitle</p> <p>interface InvoiceTitleProps { title : string, onChange : Function, index : number, selected : boolean, key? : number }</p>
[ { "answer_id": 74570747, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "axios.js src/boot/ import { boot } from 'quasar/wrappers'\n import axios from 'axios'\n\n // example: const RESTURL = \"http://172.26.117.16:3000/api\"\n const RESTURL = \"http://localhost:3000/api\"\n \n const api = axios.create({\n baseURL: RESTURL,\n headers:{ \"Content-type\" : \"application/json\" }\n })\n\n export default boot(({ app }) => {\n \n app.config.globalProperties.$axios = axios\n \n app.config.globalProperties.$api = api\n \n app.config.globalProperties.$RESTURL = RESTURL\n })\n\n export { api, RESTURL }\n this.$api.post(\"/customer/login\", data)\n .then(res => {\n if (res.status == 200){\n this.errorMessage = \"\"\n this.store.loggedUser = res.data\n this.$router.push('/')\n }\n })\n .catch((err) => {\n this.errorMessage = \"Wrong Mail / Password\"\n })\n const sql = require(\"./db\");\n\n //Constructor\n const Customer = function (customer) {\n this.name = customer.name;\n this.mail = customer.mail;\n this.password = customer.password;\n this.address = customer.address;\n this.postCode = customer.postCode;\n this.city = customer.city;\n };\n\n Customer.getAllRecords = (result) => {\n sql.query(\"SELECT * FROM Customer\", (err, res) => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n result(null, res);\n });\n };\n\n Customer.create = ( newCustomer, result ) => {\n sql.query(\"INSERT INTO Customer SET ?\", newCustomer, (err, res) \n => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n console.log(\"Created Customer: \", {\n id: res.insertId,\n ...newCustomer\n });\n result(null, {\n id: res.insertId,\n ...newCustomer\n });\n })\n }\n\n Customer.updateByID = (id, data, result) => {\n sql.query(\n \"UPDATE Customer SET name=?, mail=?, password=?, address=?, \n postCode=?, city=? WHERE id=?\",\n [data.name, data.mail, data.password, data.address, \n data.postCode, data.city, id],\n (err, res) => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n if (res.affectedRows == 0) {\n //this id not found\n result({ kind: \"not_found\" }, null);\n return;\n }\n console.log(\"Updated Customer: \", { id: id, ...data });\n result(null, { id: id, ...data });\n }\n );\n };\n\n Customer.delete = ( id, result ) => {\n sql.query(\"DELETE FROM Customer WHERE id = ?\", id, (err, res) \n => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n } if(res.affectedRows == 0){\n result({kind: \"not_found\"}, null)\n return;\n }\n console.log(\"Deleted Customer id: \", id)\n result(null, {id: id})\n });\n }\n\n Customer.login = (account, result) => {\n sql.query(\n \"SELECT * FROM Customer WHERE mail = ?\", account.mail,\n (err, res) => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n if (res.length) {\n const validPassword = account.password == \n res[0].password\n\n if (validPassword) {\n result(null, res[0]);\n return;\n } else {\n console.log(\"Password invalid.\");\n result({ kind: \"invalid_pass\" }, null);\n return;\n }\n }\n result({ kind: \"not_found\" }, null);\n }\n );\n };\n\n module.exports = Customer\n" }, { "answer_id": 74570795, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "const routes = [\n {\n path: '/',\n component: () => import('layouts/MainLayout.vue'),\n children: [\n { path: '', component: () => import('pages/IndexPage.vue') },\n { path: 'signin', component: () => import('pages/SigninPage.vue') \n},\n { path: 'signup', component: () => import('pages/SignupPage.vue') \n},\n ]\n },\n {\n path: '/:catchAll(.*)*',\n component: () => import('pages/ErrorNotFound.vue')\n }\n]\n\nexport default routes\n module.exports = (app) => {\n const customer_controller = \nrequire(\"../controllers/customer.controller\")\n var router = require(\"express\").Router();\n router.post(\"/add\", customer_controller.createNewCustomer);\n router.get(\"/all\", customer_controller.getAllCustomer);\n router.put(\"/:id\", customer_controller.updateCustomer);\n router.delete(\"/:id\", customer_controller.deleteCustomer);\n router.post(\"/login\", customer_controller.loginCustomer);\n\n app.use(\"/api/customer\", router);\n};\n" }, { "answer_id": 74570964, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "import { defineStore } from \"pinia\";\n\nexport const useGlobalStateStore = defineStore(\"global\", {\n state: () => ({\n globalSell: 0,\n whateverarray: [...],\n }),\n getters: {\n doubleCount(state) {\n return state.globalSell * 2;\n },\n },\n\nactions: {\n incrementGlobalSell() {\n this.globalSell++;\n },\n deleteCategory(id) {\n this.categories = this.categories.filter((element) => {\n return element.id != id;\n });\n },\n <script>\n -> import {useGlobalStateStore} from \"stores/globalState\";\n import NavComponent from \"components/NavComponent\";\n data() {\n return {\n -> store : useGlobalStateStore(),\n email: \"\",\n" }, { "answer_id": 74571260, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "module.exports = {\n HOST:\"sql12.freemysqlhosting.net\",\n USER:\"user\",\n PASSWORD:\"pass\",\n DB:\"nameOfDB\"\n}\n const Customer = require(\"../models/customer.model.js\");\n\nconst getAllCustomer = (req, res) => {\n Customer.getAllRecords((err, data) => {\n if (err) {\n res.status(500).send({\n message: err.message || \"Some error occured while \nretriveing data.\",\n });\n } else res.send(data);\n });\n};\n\nconst createNewCustomer = (req, res) => {\n if (!req.body) {\n res.status(400).send({\n message: \"Content can not be empty.\",\n });\n}\n\nconst customerObj = new Customer({\n name: req.body.name,\n mail: req.body.mail,\n password: req.body.password,\n address: req.body.address,\n postCode: req.body.postCode,\n city: req.body.city\n});\n\nCustomer.create(customerObj, (err, data) => {\n console.log(req.body)\n if (err) {\n res.status(500).send({\n message: err.message || \"Some error occured while \ncreating.\",\n });\n } else {\n res.send(data);\n }\n });\n};\n\nconst updateCustomer = (req, res) =>{\n if(!req.body){\n res.status(400).send({ message: \"Content can not be \n empty.\"});\n }\nconst data = {\n name: req.body.name,\n mail: req.body.mail,\n password: req.body.password,\n address: req.body.address,\n postCode: req.body.postCode,\n city: req.body.city\n};\nCustomer.updateByID(req.params.id, data, (err, result)=>{\n if(err){\n if(err.kind == \"not_found\"){\n res.status(401).send({\n message: \"Not found Customer id: \" + \nreq.params.id\n });\n } else{\n res.status(500).send({\n message: \"Error update Customer id: \" + \nreq.params.id\n });\n }\n } else res.send(result);\n });\n};\n\nconst deleteCustomer = (req, res) =>{\n Customer.delete(req.params.id, (err, result)=>{\n if(err){\n if(err.kind == \"not_found\"){\n res.status(401).send({\n message: \"Not found Customer id: \" + \n req.params.id\n });\n }else{\n res.status(500).send({\n message: \"Error delete Customer id: \" + \n req.params.id\n });\n }\n }\n else res.send(result);\n });\n};\n\nconst loginCustomer = (req, res) => {\n if (!req.body) {\n res.status(400).send({\n message: \"Content can not be empty.\",\n });\n}\n\nconst account = new Customer({\n mail: req.body.mail,\n password: req.body.password\n});\n\nCustomer.login(account, (err, data)=>{\n if(err){\n if(err.kind == \"not_found\"){\n res.status(401).send({\n message: \"Not found \" + req.body.mail\n });\n } else if (err.kind == \"invalid_pass\"){\n res.status(401).send({\n message: \"Invalid Password\"\n });\n } else{\n res.status(500).send({\n message: \"Error retriveing \" + req.body.mail\n });\n }\n }else res.send(data);\n });\n};\n\nmodule.exports = {\ngetAllCustomer,\ncreateNewCustomer,\nupdateCustomer,\ndeleteCustomer,\nloginCustomer\n};\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20597762/" ]
74,570,599
<p>I use Firebase Authentication for my app. I can log / register correctly except when another user was log previously.</p> <p>Exemple : I am log, and I want to signout. Like this :</p> <pre><code> final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; signOut() async { await _firebaseAuth.signOut(); } </code></pre> <pre><code>IconButton( onPressed: () { signOut(); Navigator.of(context, rootNavigator: true) .pushAndRemoveUntil( MaterialPageRoute( builder: (BuildContext context) { return const OnBoardingPage(); }, ), (_) =&gt; false, ); }, icon: const Icon(Icons.logout)) </code></pre> <p>So I came back to my onboarding page but I'm not fully disconnected.</p> <p>I know it because I can display my email on the onboarding page (where normally no one can be connected)<a href="https://i.stack.imgur.com/izQBO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/izQBO.jpg" alt="exemple" /></a></p> <p>So, I need to restart the app, and then, I am no longer connected and user mail can't be displayed. I think it is something about cache but not sure.</p> <p>I want to know how to fully disconnected my account of my app. and avoid persistent session after logout.</p>
[ { "answer_id": 74570747, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "axios.js src/boot/ import { boot } from 'quasar/wrappers'\n import axios from 'axios'\n\n // example: const RESTURL = \"http://172.26.117.16:3000/api\"\n const RESTURL = \"http://localhost:3000/api\"\n \n const api = axios.create({\n baseURL: RESTURL,\n headers:{ \"Content-type\" : \"application/json\" }\n })\n\n export default boot(({ app }) => {\n \n app.config.globalProperties.$axios = axios\n \n app.config.globalProperties.$api = api\n \n app.config.globalProperties.$RESTURL = RESTURL\n })\n\n export { api, RESTURL }\n this.$api.post(\"/customer/login\", data)\n .then(res => {\n if (res.status == 200){\n this.errorMessage = \"\"\n this.store.loggedUser = res.data\n this.$router.push('/')\n }\n })\n .catch((err) => {\n this.errorMessage = \"Wrong Mail / Password\"\n })\n const sql = require(\"./db\");\n\n //Constructor\n const Customer = function (customer) {\n this.name = customer.name;\n this.mail = customer.mail;\n this.password = customer.password;\n this.address = customer.address;\n this.postCode = customer.postCode;\n this.city = customer.city;\n };\n\n Customer.getAllRecords = (result) => {\n sql.query(\"SELECT * FROM Customer\", (err, res) => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n result(null, res);\n });\n };\n\n Customer.create = ( newCustomer, result ) => {\n sql.query(\"INSERT INTO Customer SET ?\", newCustomer, (err, res) \n => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n console.log(\"Created Customer: \", {\n id: res.insertId,\n ...newCustomer\n });\n result(null, {\n id: res.insertId,\n ...newCustomer\n });\n })\n }\n\n Customer.updateByID = (id, data, result) => {\n sql.query(\n \"UPDATE Customer SET name=?, mail=?, password=?, address=?, \n postCode=?, city=? WHERE id=?\",\n [data.name, data.mail, data.password, data.address, \n data.postCode, data.city, id],\n (err, res) => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n if (res.affectedRows == 0) {\n //this id not found\n result({ kind: \"not_found\" }, null);\n return;\n }\n console.log(\"Updated Customer: \", { id: id, ...data });\n result(null, { id: id, ...data });\n }\n );\n };\n\n Customer.delete = ( id, result ) => {\n sql.query(\"DELETE FROM Customer WHERE id = ?\", id, (err, res) \n => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n } if(res.affectedRows == 0){\n result({kind: \"not_found\"}, null)\n return;\n }\n console.log(\"Deleted Customer id: \", id)\n result(null, {id: id})\n });\n }\n\n Customer.login = (account, result) => {\n sql.query(\n \"SELECT * FROM Customer WHERE mail = ?\", account.mail,\n (err, res) => {\n if (err) {\n console.log(\"Query error: \" + err);\n result(err, null);\n return;\n }\n if (res.length) {\n const validPassword = account.password == \n res[0].password\n\n if (validPassword) {\n result(null, res[0]);\n return;\n } else {\n console.log(\"Password invalid.\");\n result({ kind: \"invalid_pass\" }, null);\n return;\n }\n }\n result({ kind: \"not_found\" }, null);\n }\n );\n };\n\n module.exports = Customer\n" }, { "answer_id": 74570795, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "const routes = [\n {\n path: '/',\n component: () => import('layouts/MainLayout.vue'),\n children: [\n { path: '', component: () => import('pages/IndexPage.vue') },\n { path: 'signin', component: () => import('pages/SigninPage.vue') \n},\n { path: 'signup', component: () => import('pages/SignupPage.vue') \n},\n ]\n },\n {\n path: '/:catchAll(.*)*',\n component: () => import('pages/ErrorNotFound.vue')\n }\n]\n\nexport default routes\n module.exports = (app) => {\n const customer_controller = \nrequire(\"../controllers/customer.controller\")\n var router = require(\"express\").Router();\n router.post(\"/add\", customer_controller.createNewCustomer);\n router.get(\"/all\", customer_controller.getAllCustomer);\n router.put(\"/:id\", customer_controller.updateCustomer);\n router.delete(\"/:id\", customer_controller.deleteCustomer);\n router.post(\"/login\", customer_controller.loginCustomer);\n\n app.use(\"/api/customer\", router);\n};\n" }, { "answer_id": 74570964, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "import { defineStore } from \"pinia\";\n\nexport const useGlobalStateStore = defineStore(\"global\", {\n state: () => ({\n globalSell: 0,\n whateverarray: [...],\n }),\n getters: {\n doubleCount(state) {\n return state.globalSell * 2;\n },\n },\n\nactions: {\n incrementGlobalSell() {\n this.globalSell++;\n },\n deleteCategory(id) {\n this.categories = this.categories.filter((element) => {\n return element.id != id;\n });\n },\n <script>\n -> import {useGlobalStateStore} from \"stores/globalState\";\n import NavComponent from \"components/NavComponent\";\n data() {\n return {\n -> store : useGlobalStateStore(),\n email: \"\",\n" }, { "answer_id": 74571260, "author": "okayforhim79", "author_id": 20597611, "author_profile": "https://Stackoverflow.com/users/20597611", "pm_score": 0, "selected": false, "text": "module.exports = {\n HOST:\"sql12.freemysqlhosting.net\",\n USER:\"user\",\n PASSWORD:\"pass\",\n DB:\"nameOfDB\"\n}\n const Customer = require(\"../models/customer.model.js\");\n\nconst getAllCustomer = (req, res) => {\n Customer.getAllRecords((err, data) => {\n if (err) {\n res.status(500).send({\n message: err.message || \"Some error occured while \nretriveing data.\",\n });\n } else res.send(data);\n });\n};\n\nconst createNewCustomer = (req, res) => {\n if (!req.body) {\n res.status(400).send({\n message: \"Content can not be empty.\",\n });\n}\n\nconst customerObj = new Customer({\n name: req.body.name,\n mail: req.body.mail,\n password: req.body.password,\n address: req.body.address,\n postCode: req.body.postCode,\n city: req.body.city\n});\n\nCustomer.create(customerObj, (err, data) => {\n console.log(req.body)\n if (err) {\n res.status(500).send({\n message: err.message || \"Some error occured while \ncreating.\",\n });\n } else {\n res.send(data);\n }\n });\n};\n\nconst updateCustomer = (req, res) =>{\n if(!req.body){\n res.status(400).send({ message: \"Content can not be \n empty.\"});\n }\nconst data = {\n name: req.body.name,\n mail: req.body.mail,\n password: req.body.password,\n address: req.body.address,\n postCode: req.body.postCode,\n city: req.body.city\n};\nCustomer.updateByID(req.params.id, data, (err, result)=>{\n if(err){\n if(err.kind == \"not_found\"){\n res.status(401).send({\n message: \"Not found Customer id: \" + \nreq.params.id\n });\n } else{\n res.status(500).send({\n message: \"Error update Customer id: \" + \nreq.params.id\n });\n }\n } else res.send(result);\n });\n};\n\nconst deleteCustomer = (req, res) =>{\n Customer.delete(req.params.id, (err, result)=>{\n if(err){\n if(err.kind == \"not_found\"){\n res.status(401).send({\n message: \"Not found Customer id: \" + \n req.params.id\n });\n }else{\n res.status(500).send({\n message: \"Error delete Customer id: \" + \n req.params.id\n });\n }\n }\n else res.send(result);\n });\n};\n\nconst loginCustomer = (req, res) => {\n if (!req.body) {\n res.status(400).send({\n message: \"Content can not be empty.\",\n });\n}\n\nconst account = new Customer({\n mail: req.body.mail,\n password: req.body.password\n});\n\nCustomer.login(account, (err, data)=>{\n if(err){\n if(err.kind == \"not_found\"){\n res.status(401).send({\n message: \"Not found \" + req.body.mail\n });\n } else if (err.kind == \"invalid_pass\"){\n res.status(401).send({\n message: \"Invalid Password\"\n });\n } else{\n res.status(500).send({\n message: \"Error retriveing \" + req.body.mail\n });\n }\n }else res.send(data);\n });\n};\n\nmodule.exports = {\ngetAllCustomer,\ncreateNewCustomer,\nupdateCustomer,\ndeleteCustomer,\nloginCustomer\n};\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19904553/" ]
74,570,604
<p>I use the <code>memoise</code> package to cache queries to an <code>arrow</code> dataset but I sometimes get mismatches/&quot;collisions&quot; in hashes and therefore the wrong values are returned.</p> <p>I have isolated the problem and replicated it in the MWE below. The issue is that the <code>rlang::hash()</code> (which <code>memoise</code> uses) of an arrow query that first filters then summarises does not depend on the filter.</p> <p>My question is: is this something that I can fix (because I used it wrongly) or is this a bug in the one of the packages (I am happy to create an issue), if so, should this be reported to <code>arrow</code>, <code>rlang::hash()</code>, or even <code>R6</code>?</p> <h2>MWE</h2> <p>For example, all three queries below have the same hash but <strong>they should be different</strong> (and looking at the results, the results obviously are...)</p> <pre class="lang-r prettyprint-override"><code>library(arrow) library(dplyr) ds_file &lt;- file.path(tempdir(), &quot;mtcars&quot;) write_dataset(mtcars, ds_file) ds &lt;- open_dataset(ds_file) # 1) Create three different queries ======= # Query 1 with mpg &gt; 25 ---- query1 &lt;- ds |&gt; filter(mpg &gt; 25) |&gt; group_by(vs) |&gt; summarise(n = n(), mean_mpg = mean(mpg)) # Query 2 with mpg &gt; 0 ---- query2 &lt;- ds |&gt; filter(mpg &gt; 0) |&gt; group_by(vs) |&gt; summarise(n = n(), mean_mpg = mean(mpg)) # Query 3 with filter on cyl ---- query3 &lt;- ds |&gt; filter(cyl == 4) |&gt; group_by(vs) |&gt; summarise(n = n(), mean_mpg = mean(mpg)) # 2) Lets compare the hashes: the main issue ====== rlang::hash(query1) #&gt; [1] &quot;f505339fd65df6ef53728fcc4b0e55f7&quot; rlang::hash(query2) #&gt; [1] &quot;f505339fd65df6ef53728fcc4b0e55f7&quot; rlang::hash(query3) #&gt; [1] &quot;f505339fd65df6ef53728fcc4b0e55f7&quot; # ERROR HERE: they should be different as the queries are different! # 3) Lets also compare the results: clearly different ===== query1 |&gt; collect() #&gt; # A tibble: 2 × 3 #&gt; vs n mean_mpg #&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; #&gt; 1 1 5 30.9 #&gt; 2 0 1 26 query2 |&gt; collect() #&gt; # A tibble: 2 × 3 #&gt; vs n mean_mpg #&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; #&gt; 1 0 18 16.6 #&gt; 2 1 14 24.6 query3 |&gt; collect() #&gt; # A tibble: 2 × 3 #&gt; vs n mean_mpg #&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; #&gt; 1 1 10 26.7 #&gt; 2 0 1 26 </code></pre> <p>Note that the same error happens when I use <code>digest</code>.</p> <p>When I print the queries, they are printed as if they were identical... (I reported this bug <a href="https://github.com/apache/arrow/issues/14732" rel="nofollow noreferrer">here</a> to arrow)</p> <pre><code>query1 #&gt; FileSystemDataset (query) #&gt; vs: double #&gt; n: int32 #&gt; mean_mpg: double #&gt; #&gt; See $.data for the source Arrow object query2 #&gt; FileSystemDataset (query) #&gt; vs: double #&gt; n: int32 #&gt; mean_mpg: double #&gt; #&gt; See $.data for the source Arrow object query3 #&gt; FileSystemDataset (query) #&gt; vs: double #&gt; n: int32 #&gt; mean_mpg: double #&gt; #&gt; See $.data for the source Arrow object </code></pre> <p>but when I query the <code>$.data</code> argument of the query, I see that they are in fact different</p> <pre><code>query1$.data #&gt; FileSystemDataset (query) #&gt; mpg: double #&gt; vs: double #&gt; #&gt; * Aggregations: #&gt; n: sum(1) #&gt; mean_mpg: mean(mpg) #&gt; * Filter: (mpg &gt; 25) #&lt;========= #&gt; * Grouped by vs #&gt; See $.data for the source Arrow object query2$.data #&gt; FileSystemDataset (query) #&gt; mpg: double #&gt; vs: double #&gt; #&gt; * Aggregations: #&gt; n: sum(1) #&gt; mean_mpg: mean(mpg) #&gt; * Filter: (mpg &gt; 0) #&lt;========= #&gt; * Grouped by vs #&gt; See $.data for the source Arrow object query3$.data #&gt; FileSystemDataset (query) #&gt; mpg: double #&gt; vs: double #&gt; #&gt; * Aggregations: #&gt; n: sum(1) #&gt; mean_mpg: mean(mpg) #&gt; * Filter: (cyl == 4) #&lt;========= #&gt; * Grouped by vs #&gt; See $.data for the source Arrow object </code></pre> <p>but again <code>rlang::hash()</code> cannot find a difference:</p> <pre><code>rlang::hash(query1$.data) #&gt; [1] &quot;b7f743cd635f7dc06356b827a6974df8&quot; rlang::hash(query2$.data) #&gt; [1] &quot;b7f743cd635f7dc06356b827a6974df8&quot; rlang::hash(query3$.data) #&gt; [1] &quot;b7f743cd635f7dc06356b827a6974df8&quot; </code></pre> <p>If it helps, the query objects are <code>R6</code> objects with class <code>arrow_dplyr_query</code> (see also its <a href="https://github.com/apache/arrow/blob/5e53978b56aa13f9c033f2e849cc22f2aed6e2d3/r/R/dplyr.R" rel="nofollow noreferrer">source code in apache/arrow</a>)</p> <h2>Memoise use case</h2> <p>For completeness sake and to put the problem into perspective, I use the following to cache the results, which should return different values (see above) but doesn't!</p> <pre class="lang-r prettyprint-override"><code>library(arrow) library(memoise) library(dplyr) ds_file &lt;- file.path(tempdir(), &quot;mtcars&quot;) write_dataset(mtcars, ds_file) ds &lt;- open_dataset(ds_file) collect_cached &lt;- memoise::memoise(dplyr::collect, cache = cachem::cache_mem(logfile = stdout())) # Query 1 with mpg &gt; 25 ---- ds |&gt; filter(mpg &gt; 25) |&gt; group_by(vs) |&gt; summarise(n = n(), mean_mpg = mean(mpg)) |&gt; collect_cached() #&gt; [2022-11-25 09:16:28.586] cache_mem get: key &quot;2edd901226498414056dcc54eaa49415&quot; #&gt; [2022-11-25 09:16:28.586] cache_mem get: key &quot;2edd901226498414056dcc54eaa49415&quot; is missing #&gt; [2022-11-25 09:16:28.705] cache_mem set: key &quot;2edd901226498414056dcc54eaa49415&quot; #&gt; [2022-11-25 09:16:28.706] cache_mem prune #&gt; # A tibble: 2 × 3 #&gt; vs n mean_mpg #&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; #&gt; 1 1 5 30.9 #&gt; 2 0 1 26 # Query 2 with mpg &gt; 0 ---- # this is wrongly matched to the first query and returns wrong results... ds |&gt; filter(mpg &gt; 0) |&gt; group_by(vs) |&gt; summarise(n = n(), mean_mpg = mean(mpg)) |&gt; collect_cached() #&gt; [2022-11-25 09:16:28.820] cache_mem get: key &quot;2edd901226498414056dcc54eaa49415&quot; #&gt; [2022-11-25 09:16:28.820] cache_mem get: key &quot;2edd901226498414056dcc54eaa49415&quot; found #&lt; ERROR HERE! as the hash is identical #&gt; # A tibble: 2 × 3 #&gt; vs n mean_mpg #&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; #&gt; 1 1 5 30.9 #&gt; 2 0 1 26 </code></pre> <p>Note that we get the same result although the queries are different (yet their hashes are identical, hence this question).</p>
[ { "answer_id": 74573497, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 3, "selected": true, "text": "show_query hash= memoise hashfun <- function(x) {\n x$x <- capture.output(show_query(x$x))\n rlang::hash(x)\n}\ncollect_cached <- memoise::memoise(\n dplyr::collect,\n cache = cachem::cache_mem(logfile = stdout()),\n hash = hashfun)\n\nds |> \n filter(mpg > 25) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg)) |> \n collect_cached()\n# [2022-11-25 08:14:56.596] cache_mem get: key \"e6184e282e05875139e8afd2a071f329\"\n# [2022-11-25 08:14:56.596] cache_mem get: key \"e6184e282e05875139e8afd2a071f329\" is missing\n# [2022-11-25 08:14:56.616] cache_mem set: key \"e6184e282e05875139e8afd2a071f329\"\n# [2022-11-25 08:14:56.616] cache_mem prune\n# # A tibble: 2 x 3\n# vs n mean_mpg\n# <dbl> <int> <dbl>\n# 1 1 5 30.9\n# 2 0 1 26 \n\n#### different filter, should be a \"miss\"\nds |> \n filter(mpg > 0) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg)) |> \n collect_cached()\n# [2022-11-25 08:15:06.745] cache_mem get: key \"88312b31b29050ff029900f4dfc58a9f\"\n# [2022-11-25 08:15:06.745] cache_mem get: key \"88312b31b29050ff029900f4dfc58a9f\" is missing\n# [2022-11-25 08:15:06.767] cache_mem set: key \"88312b31b29050ff029900f4dfc58a9f\"\n# [2022-11-25 08:15:06.767] cache_mem prune\n# # A tibble: 2 x 3\n# vs n mean_mpg\n# <dbl> <int> <dbl>\n# 1 0 18 16.6\n# 2 1 14 24.6\n\n#### repeat of filter `mpg > 0`, should be a \"hit\"\nds |> \n filter(mpg > 0) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg)) |> \n collect_cached()\n# . + > \n# [2022-11-25 08:15:24.825] cache_mem get: key \"88312b31b29050ff029900f4dfc58a9f\"\n# [2022-11-25 08:15:24.825] cache_mem get: key \"88312b31b29050ff029900f4dfc58a9f\" found\n# # A tibble: 2 x 3\n# vs n mean_mpg\n# <dbl> <int> <dbl>\n# 1 0 18 16.6\n# 2 1 14 24.6\n hashfun collect x= ...= debugonce(hashfun)\nds |> \n filter(mpg > 0) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg)) |> \n collect_cached()\n# debugging in: encl$`_hash`(c(encl$`_f_hash`, args, lapply(encl$`_additional`, \n# function(x) eval(x[[2L]], environment(x)))))\n# debug at #1: {\n# x$x <- capture.output(show_query(x$x))\n# rlang::hash(x)\n# }\n\nx\n# [[1]]\n# [1] \"1e4b92a7ebe8b4bcb1afbd44c9a72a72\"\n# \n# $x\n# FileSystemDataset (query)\n# vs: double\n# n: int32\n# mean_mpg: double\n# \n# See $.data for the source Arrow object\n\nshow_query(x$x)\n# ExecPlan with 6 nodes:\n# 5:SinkNode{}\n# 4:ProjectNode{projection=[vs, n, mean_mpg]}\n# 3:GroupByNode{keys=[\"vs\"], aggregates=[\n# hash_sum(n, {skip_nulls=true, min_count=1}),\n# hash_mean(mean_mpg, {skip_nulls=false, min_count=0}),\n# ]}\n# 2:ProjectNode{projection=[\"n\": 1, \"mean_mpg\": mpg, vs]}\n# 1:FilterNode{filter=(mpg > 0)}\n# 0:SourceNode{}\n x$x show_query(x$x) print rlang::hash capture.output" }, { "answer_id": 74573843, "author": "assignUser", "author_id": 19933286, "author_profile": "https://Stackoverflow.com/users/19933286", "pm_score": 1, "selected": false, "text": "library(arrow)\nlibrary(dplyr)\n\nds_file <- file.path(tempdir(), \"mtcars\")\n\nwrite_dataset(mtcars, ds_file)\nds <- open_dataset(ds_file)\n\n# 1) Create three different queries =======\n\n# Query 1 with mpg > 25 ----\nquery1 <- ds |> \n filter(mpg > 25) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg))\n\n# Query 2 with mpg > 0 ----\nquery2 <- ds |> \n filter(mpg > 0) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg))\n\n# Query 3 with filter on cyl ----\nquery3 <- ds |> \n filter(cyl == 4) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg))\n\nquery1$.data\n#> FileSystemDataset (query)\n#> mpg: double\n#> vs: double\n#> \n#> * Aggregations:\n#> n: sum(1)\n#> mean_mpg: mean(mpg)\n#> * Filter: (mpg > 25)\n#> * Grouped by vs\n#> See $.data for the source Arrow object\nexplain(query2)\n#> ExecPlan with 6 nodes:\n#> 5:SinkNode{}\n#> 4:ProjectNode{projection=[vs, n, mean_mpg]}\n#> 3:GroupByNode{keys=[\"vs\"], aggregates=[\n#> hash_sum(n, {skip_nulls=true, min_count=1}),\n#> hash_mean(mean_mpg, {skip_nulls=false, min_count=0}),\n#> ]}\n#> 2:ProjectNode{projection=[\"n\": 1, \"mean_mpg\": mpg, vs]}\n#> 1:FilterNode{filter=(mpg > 0)}\n#> 0:SourceNode{}\n# 2) Lets compare the hashes: the main issue ======\nrlang::hash(query1)\n#> [1] \"8bbf29208ccbc95fc1bc46f2f2dfe10d\"\nrlang::hash(query2)\n#> [1] \"ae5c80b8ed0cc884df40926f3a985b27\"\nrlang::hash(query3)\n#> [1] \"3826d824e4c9be046ac5f09dcb60959d\"\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048453/" ]
74,570,616
<p><a href="https://i.stack.imgur.com/BDrdz.png" rel="nofollow noreferrer">enter image description here</a>I have a problem when inserting dynamic ng-select in a table ,</p> <p>when I select one dropdown the next one takes the same value and I couldn't find where is the probleme ? Any one can help me please ? (<a href="https://i.stack.imgur.com/Af33N.png" rel="nofollow noreferrer">https://i.stack.imgur.com/Af33N.png</a>)</p> <pre><code>&lt;ng-container *ngFor=&quot;let label of natureSaisie; index as i&quot;&gt; &lt;tr&gt; &lt;td&gt;{{label.NO_DPTG}}&lt;/td&gt; &lt;td class=&quot;text-align&quot;&gt;{{label.LIB_DPTG}}&lt;/td&gt; &lt;td *ngFor=&quot;let val of label.LIB_VALEUR ;let index = index;&quot;&gt; &lt;ng-select notFoundText=&quot;{{ 'lg_liste_vide' | translatePipe }}&quot; class=&quot;selector-metier&quot; [searchable]=&quot;false&quot; [(ngModel)]=&quot;label.LIB_VALEUR[index]&quot; id=&quot;index&quot; [items]=&quot;natures&quot; [clearable]=&quot;false&quot; bindValue=&quot;index&quot; bindLabel=&quot;val&quot; (change)=&quot;selectMetier($event,label.NO_DPTG)&quot; &gt; &lt;/ng-select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/ng-container&gt; </code></pre>
[ { "answer_id": 74573497, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 3, "selected": true, "text": "show_query hash= memoise hashfun <- function(x) {\n x$x <- capture.output(show_query(x$x))\n rlang::hash(x)\n}\ncollect_cached <- memoise::memoise(\n dplyr::collect,\n cache = cachem::cache_mem(logfile = stdout()),\n hash = hashfun)\n\nds |> \n filter(mpg > 25) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg)) |> \n collect_cached()\n# [2022-11-25 08:14:56.596] cache_mem get: key \"e6184e282e05875139e8afd2a071f329\"\n# [2022-11-25 08:14:56.596] cache_mem get: key \"e6184e282e05875139e8afd2a071f329\" is missing\n# [2022-11-25 08:14:56.616] cache_mem set: key \"e6184e282e05875139e8afd2a071f329\"\n# [2022-11-25 08:14:56.616] cache_mem prune\n# # A tibble: 2 x 3\n# vs n mean_mpg\n# <dbl> <int> <dbl>\n# 1 1 5 30.9\n# 2 0 1 26 \n\n#### different filter, should be a \"miss\"\nds |> \n filter(mpg > 0) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg)) |> \n collect_cached()\n# [2022-11-25 08:15:06.745] cache_mem get: key \"88312b31b29050ff029900f4dfc58a9f\"\n# [2022-11-25 08:15:06.745] cache_mem get: key \"88312b31b29050ff029900f4dfc58a9f\" is missing\n# [2022-11-25 08:15:06.767] cache_mem set: key \"88312b31b29050ff029900f4dfc58a9f\"\n# [2022-11-25 08:15:06.767] cache_mem prune\n# # A tibble: 2 x 3\n# vs n mean_mpg\n# <dbl> <int> <dbl>\n# 1 0 18 16.6\n# 2 1 14 24.6\n\n#### repeat of filter `mpg > 0`, should be a \"hit\"\nds |> \n filter(mpg > 0) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg)) |> \n collect_cached()\n# . + > \n# [2022-11-25 08:15:24.825] cache_mem get: key \"88312b31b29050ff029900f4dfc58a9f\"\n# [2022-11-25 08:15:24.825] cache_mem get: key \"88312b31b29050ff029900f4dfc58a9f\" found\n# # A tibble: 2 x 3\n# vs n mean_mpg\n# <dbl> <int> <dbl>\n# 1 0 18 16.6\n# 2 1 14 24.6\n hashfun collect x= ...= debugonce(hashfun)\nds |> \n filter(mpg > 0) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg)) |> \n collect_cached()\n# debugging in: encl$`_hash`(c(encl$`_f_hash`, args, lapply(encl$`_additional`, \n# function(x) eval(x[[2L]], environment(x)))))\n# debug at #1: {\n# x$x <- capture.output(show_query(x$x))\n# rlang::hash(x)\n# }\n\nx\n# [[1]]\n# [1] \"1e4b92a7ebe8b4bcb1afbd44c9a72a72\"\n# \n# $x\n# FileSystemDataset (query)\n# vs: double\n# n: int32\n# mean_mpg: double\n# \n# See $.data for the source Arrow object\n\nshow_query(x$x)\n# ExecPlan with 6 nodes:\n# 5:SinkNode{}\n# 4:ProjectNode{projection=[vs, n, mean_mpg]}\n# 3:GroupByNode{keys=[\"vs\"], aggregates=[\n# hash_sum(n, {skip_nulls=true, min_count=1}),\n# hash_mean(mean_mpg, {skip_nulls=false, min_count=0}),\n# ]}\n# 2:ProjectNode{projection=[\"n\": 1, \"mean_mpg\": mpg, vs]}\n# 1:FilterNode{filter=(mpg > 0)}\n# 0:SourceNode{}\n x$x show_query(x$x) print rlang::hash capture.output" }, { "answer_id": 74573843, "author": "assignUser", "author_id": 19933286, "author_profile": "https://Stackoverflow.com/users/19933286", "pm_score": 1, "selected": false, "text": "library(arrow)\nlibrary(dplyr)\n\nds_file <- file.path(tempdir(), \"mtcars\")\n\nwrite_dataset(mtcars, ds_file)\nds <- open_dataset(ds_file)\n\n# 1) Create three different queries =======\n\n# Query 1 with mpg > 25 ----\nquery1 <- ds |> \n filter(mpg > 25) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg))\n\n# Query 2 with mpg > 0 ----\nquery2 <- ds |> \n filter(mpg > 0) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg))\n\n# Query 3 with filter on cyl ----\nquery3 <- ds |> \n filter(cyl == 4) |> \n group_by(vs) |> \n summarise(n = n(), mean_mpg = mean(mpg))\n\nquery1$.data\n#> FileSystemDataset (query)\n#> mpg: double\n#> vs: double\n#> \n#> * Aggregations:\n#> n: sum(1)\n#> mean_mpg: mean(mpg)\n#> * Filter: (mpg > 25)\n#> * Grouped by vs\n#> See $.data for the source Arrow object\nexplain(query2)\n#> ExecPlan with 6 nodes:\n#> 5:SinkNode{}\n#> 4:ProjectNode{projection=[vs, n, mean_mpg]}\n#> 3:GroupByNode{keys=[\"vs\"], aggregates=[\n#> hash_sum(n, {skip_nulls=true, min_count=1}),\n#> hash_mean(mean_mpg, {skip_nulls=false, min_count=0}),\n#> ]}\n#> 2:ProjectNode{projection=[\"n\": 1, \"mean_mpg\": mpg, vs]}\n#> 1:FilterNode{filter=(mpg > 0)}\n#> 0:SourceNode{}\n# 2) Lets compare the hashes: the main issue ======\nrlang::hash(query1)\n#> [1] \"8bbf29208ccbc95fc1bc46f2f2dfe10d\"\nrlang::hash(query2)\n#> [1] \"ae5c80b8ed0cc884df40926f3a985b27\"\nrlang::hash(query3)\n#> [1] \"3826d824e4c9be046ac5f09dcb60959d\"\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19957077/" ]
74,570,621
<p>I have two related tables where I need to update and set a column based on count from the other table. I have an agents table where each agent has a level which is to be computed based on the number of booked slots. The system has the Agent details where each Agent has different levels of dealer namely bronze, silver and gold. The Agent’s level is determined based on the number of bookings, where if an Agent have, equal or more than, 10 bookings, it is categorised as Gold, more than 4, but less then, 10 as Silver, and Bronze otherwise. How can I update the level column to display this. Below are the agents table and booked slots table. Thanks in advance.</p> <p><a href="https://i.stack.imgur.com/GhnwV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GhnwV.png" alt="Agents table" /></a></p> <p><a href="https://i.stack.imgur.com/jw6SR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jw6SR.png" alt="Booked slots table" /></a></p>
[ { "answer_id": 74572065, "author": "Henrik", "author_id": 20598225, "author_profile": "https://Stackoverflow.com/users/20598225", "pm_score": 1, "selected": false, "text": "UPDATE customers \nSET customers.level = (SELECT IF(count(*) > 10, \"Gold\", IF(count(*) > 4, \"SILVER\", \"Bronze\"))\n FROM bookings \n WHERE bookings.customer_tbl_id = customers.id)\n" }, { "answer_id": 74572528, "author": "nnichols", "author_id": 1191247, "author_profile": "https://Stackoverflow.com/users/1191247", "pm_score": 0, "selected": false, "text": "UPDATE `agents` `a`\nINNER JOIN (\n SELECT\n `agents_tbl_id`,\n CASE\n WHEN COUNT(*) >= 10 THEN 'Gold'\n WHEN COUNT(*) > 4 THEN 'Silver'\n ELSE 'Bronze'\n END `level`\n FROM `bookings`\n GROUP BY `agents_tbl_id`\n) `b`\n ON `a`.`id` = `b`.`agents_tbl_id`\nSET `a`.`level` = `b`.`level`;\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14020878/" ]
74,570,672
<p>Trying to find a document by ObjectId in mongoose. The query returns an empty result but when applying the same query in the &quot;MongoDB Compass&quot; - it returns the document.</p> <pre><code>const mongoose = require(&quot;mongoose&quot;); await CollectionModel.find({ &quot;_id&quot;: new mongoose.Types.ObjectId(DOCUMENT_ID)}); </code></pre> <p><a href="https://i.stack.imgur.com/iDzfk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iDzfk.png" alt="MongoDB Compass" /></a></p> <p>What are the possible reasons for the issue?</p> <p>Note: searching with other properties except the &quot;_id&quot; works fine.</p>
[ { "answer_id": 74572065, "author": "Henrik", "author_id": 20598225, "author_profile": "https://Stackoverflow.com/users/20598225", "pm_score": 1, "selected": false, "text": "UPDATE customers \nSET customers.level = (SELECT IF(count(*) > 10, \"Gold\", IF(count(*) > 4, \"SILVER\", \"Bronze\"))\n FROM bookings \n WHERE bookings.customer_tbl_id = customers.id)\n" }, { "answer_id": 74572528, "author": "nnichols", "author_id": 1191247, "author_profile": "https://Stackoverflow.com/users/1191247", "pm_score": 0, "selected": false, "text": "UPDATE `agents` `a`\nINNER JOIN (\n SELECT\n `agents_tbl_id`,\n CASE\n WHEN COUNT(*) >= 10 THEN 'Gold'\n WHEN COUNT(*) > 4 THEN 'Silver'\n ELSE 'Bronze'\n END `level`\n FROM `bookings`\n GROUP BY `agents_tbl_id`\n) `b`\n ON `a`.`id` = `b`.`agents_tbl_id`\nSET `a`.`level` = `b`.`level`;\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3384985/" ]
74,570,681
<p>I am trying to add a new column &quot;profile_type&quot; to a dataframe &quot;df_new&quot; which contains the string <strong>&quot;Decision Maker&quot;</strong> if the &quot;job_title&quot; has any one of the following words: (Head or VP or COO or CEO or CMO or CLO or Chief or Partner or Founder or Owner or CIO or CTO or President or Leaders),</p> <p><strong>&quot;Key Influencer&quot;</strong> if the &quot;job_title&quot; has any one of the following words: (Senior or Consultant or Manager or Learning or Training or Talent or HR or Human Resources or Consultant or L&amp;D or Lead), and</p> <p><strong>&quot;Influencer&quot;</strong> for all other fields in &quot;job_title&quot;.</p> <p>For example, if the 'job_title' includes a row &quot;Learning and Development Specialist&quot;, the code has to pull out just the word 'Learning' and segregate it as 'Key Influencer' under 'profile_type'.</p>
[ { "answer_id": 74570821, "author": "butterflyknife", "author_id": 8790507, "author_profile": "https://Stackoverflow.com/users/8790507", "pm_score": -1, "selected": false, "text": "'Decision Maker' job_title def is_key_worker(row):\n if (row[\"job_title\"] == \"CTO\" or row[\"job_title\"]==\"Founder\") # add more here.\n df_new[\"Key influencer\"] = df_new.apply(is_key_worker, axis=1)\n" }, { "answer_id": 74570882, "author": "Hobanator", "author_id": 15324493, "author_profile": "https://Stackoverflow.com/users/15324493", "pm_score": 0, "selected": false, "text": "import numpy as np\n\ndm_titles = ['Head', 'VP', 'COO', ...]\nki_titles = ['Senior ', 'Consultant', 'Manager', ...]\n\n\nconditions = [\n(any([word in new_df['job_title'] for word in dm_titles])),\n(any([word in new_df['job_title'] for word in ki_titles])),\n(all([word not in new_df['job_title'] for word in dm_titles] + [word not in new_df['job_title'] for word in ki_titles]))\n]\n\nvalues = [\"Decision Maker\", \"Key Influencer\", \"Influencer\"]\n\ndf_new['profile_type'] = np.select(conditions, values)\n\n" }, { "answer_id": 74597691, "author": "Alisha A", "author_id": 20578623, "author_profile": "https://Stackoverflow.com/users/20578623", "pm_score": 1, "selected": true, "text": "import re\ns1 = pd.Series(df['job_title'])\n\ncondition1 = s1.str.contains('Director|Head|VP|COO|CEO...', flags=re.IGNORECASE, regex=True)\n\ncondition2 = s1.str.contains('Senior|Consultant|Manager|Learning...', flags=re.IGNORECASE, regex=True)\n\ndf_new['profile_type'] = np.where(condition1 == True, 'Decision Maker', \n (np.where(condition2 == True, 'Key Influencer', 'Influencer')))\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20578623/" ]
74,570,699
<p>I have output of API request in given below. From each atom:entry I need to extract</p> <pre><code>&lt;c:series href=&quot;http://company.com/series/product/123&quot;/&gt; &lt;c:series-order&gt;2020-09-17T00:00:00Z&lt;/c:series-order&gt; &lt;f:assessment-low precision=&quot;0&quot;&gt;980&lt;/f:assessment-low&gt; </code></pre> <p>I tried to extract them to different list with BeautifulSoup, but that wasn't successful because in some entries there are dates but there isn't price (I've shown example below). How could I conditionally extract it? at least put N/A for entries where price is ommited.</p> <pre><code>soup = BeautifulSoup(request.text, &quot;html.parser&quot;) date = soup.find_all('c:series-order') value = soup.find_all('f:assessment-low') quot=soup.find_all('c:series') p_day = [] p_val = [] q_val=[] for i in date: p_day.append(i.text) for j in value: p_val.append(j.text) for j in quot: q_val.append(j.get('href')) d2={'date': p_day, 'price': p_val, 'quote': q_val } </code></pre> <p>and</p> <pre><code>&lt;atom:feed xmlns:atom=&quot;http://www.w3.org/2005/Atom&quot; xmlns:a=&quot;http://company.com/ns/assets&quot; xmlns:c=&quot;http://company.com/ns/core&quot; xmlns:f=&quot;http://company.com/ns/fields&quot; xmlns:s=&quot;http://company.com/ns/search&quot;&gt; &lt;atom:id&gt;http://company.com/search&lt;/atom:id&gt; &lt;atom:title&gt; COMPANYSearch Results&lt;/atom:title&gt; &lt;atom:updated&gt;2022-11-24T19:36:19.104414Z&lt;/atom:updated&gt; &lt;atom:author&gt;COMPANY atom:author&gt; &lt;atom:generator&gt; COMPANY/search Endpoint&lt;/atom:generator&gt; &lt;atom:link href=&quot;/search&quot; rel=&quot;self&quot; type=&quot;application/atom&quot;/&gt; &lt;s:first-result&gt;1&lt;/s:first-result&gt; &lt;s:max-results&gt;15500&lt;/s:max-results&gt; &lt;s:selected-count&gt;212&lt;/s:selected-count&gt; &lt;s:returned-count&gt;212&lt;/s:returned-count&gt; &lt;s:query-time&gt;PT0.036179S&lt;/s:query-time&gt; &lt;s:request version=&quot;1.0&quot;&gt; &lt;s:scope&gt; &lt;s:series&gt;http://company.com/series/product/123&lt;/s:series&gt; &lt;/s:scope&gt; &lt;s:constraints&gt; &lt;s:compare field=&quot;c:series-order&quot; op=&quot;ge&quot; value=&quot;2018-10-01&quot;/&gt; &lt;s:compare field=&quot;c:series-order&quot; op=&quot;le&quot; value=&quot;2022-11-18&quot;/&gt; &lt;/s:constraints&gt; &lt;s:options&gt; &lt;s:first-result&gt;1&lt;/s:first-result&gt; &lt;s:max-results&gt;15500&lt;/s:max-results&gt; &lt;s:order-by key=&quot;commodity-name&quot; direction=&quot;ascending&quot; xml:lang=&quot;en&quot;/&gt; &lt;s:no-currency-rate-scheme&gt;no-element&lt;/s:no-currency-rate-scheme&gt; &lt;s:precision&gt;embed&lt;/s:precision&gt; &lt;s:include-last-commit-time&gt;false&lt;/s:include-last-commit-time&gt; &lt;s:include-result-types&gt;live&lt;/s:include-result-types&gt; &lt;s:relevance-score algorithm=&quot;score-logtfidf&quot;/&gt; &lt;s:lang-data-missing-scheme&gt;show-available-language-content&lt;/s:lang-data-missing-scheme&gt; &lt;/s:options&gt; &lt;/s:request&gt; &lt;s:facets/&gt; &lt;atom:entry&gt; &lt;atom:title&gt;http://company.com/series-item/product/123-pricehistory-20200917000000&lt;/atom:title&gt; &lt;atom:id&gt;http://company.com/series-item/product/123-pricehistory-20200917000000&lt;/atom:id&gt; &lt;atom:updated&gt;2020-09-17T17:09:43.55243Z&lt;/atom:updated&gt; &lt;atom:relevance-score&gt;60800&lt;/atom:relevance-score&gt; &lt;atom:content type=&quot;application/vnd.icis.iddn.entity+xml&quot;&gt;&lt;a:price-range&gt; &lt;c:id&gt;http://company.com/series-item/product/123-pricehistory-20200917000000&lt;/c:id&gt; &lt;c:version&gt;1&lt;/c:version&gt; &lt;c:type&gt;series-item&lt;/c:type&gt; &lt;c:created-on&gt;2020-09-17T17:09:43.55243Z&lt;/c:created-on&gt; &lt;c:descriptor href=&quot;http://company.com/descriptor/price-range&quot;/&gt; &lt;c:domain href=&quot;http://company.com/domain/product&quot;/&gt; &lt;c:released-on&gt;2020-09-17T21:30:00Z&lt;/c:released-on&gt; &lt;c:series href=&quot;http://company.com/series/product/123&quot;/&gt; &lt;c:series-order&gt;2020-09-17T00:00:00Z&lt;/c:series-order&gt; &lt;f:assessment-low precision=&quot;0&quot;&gt;980&lt;/f:assessment-low&gt; &lt;f:assessment-high precision=&quot;0&quot;&gt;1020&lt;/f:assessment-high&gt; &lt;f:mid precision=&quot;1&quot;&gt;1000&lt;/f:mid&gt; &lt;f:assessment-low-delta&gt;0&lt;/f:assessment-low-delta&gt; &lt;f:assessment-high-delta&gt;+20&lt;/f:assessment-high-delta&gt; &lt;f:delta-type href=&quot;http://company.com/ref-data/delta-type/regular&quot;/&gt; &lt;/a:price-range&gt;&lt;/atom:content&gt; &lt;/atom:entry&gt; &lt;atom:entry&gt; &lt;atom:title&gt;http://company.com/series-item/product/123-pricehistory-20200910000000&lt;/atom:title&gt; &lt;atom:id&gt;http://company.com/series-item/product/123-pricehistory-20200910000000&lt;/atom:id&gt; &lt;atom:updated&gt;2020-09-10T18:57:55.128308Z&lt;/atom:updated&gt; &lt;atom:relevance-score&gt;60800&lt;/atom:relevance-score&gt; &lt;atom:content type=&quot;application/vnd.icis.iddn.entity+xml&quot;&gt;&lt;a:price-range&gt; &lt;c:id&gt;http://company.com/series-item/product/123-pricehistory-20200910000000&lt;/c:id&gt; &lt;c:version&gt;1&lt;/c:version&gt; &lt;c:type&gt;series-item&lt;/c:type&gt; &lt;c:created-on&gt;2020-09-10T18:57:55.128308Z&lt;/c:created-on&gt; &lt;c:descriptor href=&quot;http://company.com/descriptor/price-range&quot;/&gt; &lt;c:domain href=&quot;http://company.com/domain/product&quot;/&gt; &lt;c:released-on&gt;2020-09-10T21:30:00Z&lt;/c:released-on&gt; &lt;c:series href=&quot;http://company.com/series/product/123&quot;/&gt; &lt;c:series-order&gt;2020-09-10T00:00:00Z&lt;/c:series-order&gt; for example here is no price &lt;f:delta-type href=&quot;http://company.com/ref-data/delta-type/regular&quot;/&gt; &lt;/a:price-range&gt;&lt;/atom:content&gt; &lt;/atom:entry&gt; </code></pre>
[ { "answer_id": 74570821, "author": "butterflyknife", "author_id": 8790507, "author_profile": "https://Stackoverflow.com/users/8790507", "pm_score": -1, "selected": false, "text": "'Decision Maker' job_title def is_key_worker(row):\n if (row[\"job_title\"] == \"CTO\" or row[\"job_title\"]==\"Founder\") # add more here.\n df_new[\"Key influencer\"] = df_new.apply(is_key_worker, axis=1)\n" }, { "answer_id": 74570882, "author": "Hobanator", "author_id": 15324493, "author_profile": "https://Stackoverflow.com/users/15324493", "pm_score": 0, "selected": false, "text": "import numpy as np\n\ndm_titles = ['Head', 'VP', 'COO', ...]\nki_titles = ['Senior ', 'Consultant', 'Manager', ...]\n\n\nconditions = [\n(any([word in new_df['job_title'] for word in dm_titles])),\n(any([word in new_df['job_title'] for word in ki_titles])),\n(all([word not in new_df['job_title'] for word in dm_titles] + [word not in new_df['job_title'] for word in ki_titles]))\n]\n\nvalues = [\"Decision Maker\", \"Key Influencer\", \"Influencer\"]\n\ndf_new['profile_type'] = np.select(conditions, values)\n\n" }, { "answer_id": 74597691, "author": "Alisha A", "author_id": 20578623, "author_profile": "https://Stackoverflow.com/users/20578623", "pm_score": 1, "selected": true, "text": "import re\ns1 = pd.Series(df['job_title'])\n\ncondition1 = s1.str.contains('Director|Head|VP|COO|CEO...', flags=re.IGNORECASE, regex=True)\n\ncondition2 = s1.str.contains('Senior|Consultant|Manager|Learning...', flags=re.IGNORECASE, regex=True)\n\ndf_new['profile_type'] = np.where(condition1 == True, 'Decision Maker', \n (np.where(condition2 == True, 'Key Influencer', 'Influencer')))\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19761341/" ]
74,570,714
<p><a href="https://i.stack.imgur.com/uLOLZ.jpg" rel="nofollow noreferrer">enter image description here</a>I'm working on a form that patients can use to make an appointment at a hospital.</p> <ul> <li>In the first dropdown patients have to select a department</li> <li>Based on the selected department, the second dropdown should display the doctors assigned to the department</li> </ul> <p><a href="https://i.stack.imgur.com/Hyeh7.jpg" rel="nofollow noreferrer">This screenshot shows my html-code</a></p> <p><a href="https://i.stack.imgur.com/LMboI.jpg" rel="nofollow noreferrer">This screenshot shows the relevant typescript-code</a></p> <p>When the user selects a department, <code>changeDept()</code> should be triggered. In <code>changeDept()</code> the corresponding doctor-objects should be fetched from the API and used as input of my doctor-dropdown.</p>
[ { "answer_id": 74571483, "author": "Mukesh Soni", "author_id": 11556649, "author_profile": "https://Stackoverflow.com/users/11556649", "pm_score": 0, "selected": false, "text": "Choose doctor \npublic doctorListAsync$: BehaviorSubject<Array<[IDoc]>> = new BehaviorSubject([]);\n\n\nchangeDept(event:object)\n{\n // here reset $doctorListAsync value\n this.doctorListAsync$.next([]);\n this.userService.showDoc(deptId).pipe(take(1))\n .subscribe((docData:IDoc[])=>{\n this.doctorListAsync$.next(docData);\n })\n}\n <ng-container *ngIf=\"(doctorListAsync$ | async).length > 0\">\n <option *ngFor=\"let item of doctorListAsync\"></option>\n</ng-container>\n" }, { "answer_id": 74572264, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 1, "selected": false, "text": "onSelect() departments: Department[];\n doctors: Doctor[];\n\n selectedDepartment: Department = null;\n selectedDoctor: Doctor = null;\n\n constructor(private selectService: SelectService) {}\n\n ngOnInit() {\n this.departments = this.selectService.getDepartments();\n // Select the first department as default (optional):\n this.selectedDepartment = this.departments[0];\n this.onSelect(this.selectedDepartment);\n }\n\n onSelect(department: Department) {\n this.doctors = this.selectService\n .getDoctors()\n .filter((item) => item.departmentId == department.id);\n }\n <div>\n <label>Department:</label>\n <select\n [(ngModel)]=\"selectedDepartment\"\n (change)=\"onSelect($event.target.value)\">\n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let department of departments\" [ngValue]=\"department\">\n {{ department.name }}\n </option>\n </select>\n</div>\n\n<br /><br />\n\n<div>\n <label>Doctor:</label>\n <select \n [(ngModel)]=\"selectedDoctor\"> \n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let doctor of doctors\" [ngValue]=\"doctor\">\n {{ doctor.name }}\n </option>\n </select>\n</div>\n export class SelectService {\n getDepartments() {\n return [\n new Department(1, 'Department A'),\n new Department(2, 'Department B'),\n ];\n }\n\n getDoctors() {\n return [\n new Doctor(1, 1, 'Dr. Khan'),\n new Doctor(2, 1, 'Dr. Peters'),\n new Doctor(3, 1, 'Dr. Keller'),\n new Doctor(4, 1, 'Dr. Suter'),\n new Doctor(5, 2, 'Ronaldo'),\n new Doctor(6, 2, 'Messi'),\n new Doctor(7, 2, 'Shakiri'),\n ];\n }\n}\n export class Department {\n constructor(public id: number, public name: string) {}\n}\n\nexport class Doctor {\n constructor(\n public id: number,\n public departmentId: number,\n public name: string\n ) {}\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20340209/" ]
74,570,721
<p>Some Win32 API function documentation (for example <a href="https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformationex" rel="nofollow noreferrer">this</a> and <a href="https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getnumanodeprocessormask" rel="nofollow noreferrer">this</a>) contains the following note:</p> <blockquote> <p>Starting with <strong>TBD Release Iron</strong>, the behavior of this and other NUMA functions has been modified to better support systems with nodes containing more that 64 processors. For more information about this change, including information about enabling the old behavior of this API, see NUMA Support.</p> </blockquote> <ol> <li>What exactly is the &quot;TBD Release Iron&quot;?</li> <li>Which Windows versions does it support?</li> <li>What modifications does the note refer to?</li> </ol>
[ { "answer_id": 74571483, "author": "Mukesh Soni", "author_id": 11556649, "author_profile": "https://Stackoverflow.com/users/11556649", "pm_score": 0, "selected": false, "text": "Choose doctor \npublic doctorListAsync$: BehaviorSubject<Array<[IDoc]>> = new BehaviorSubject([]);\n\n\nchangeDept(event:object)\n{\n // here reset $doctorListAsync value\n this.doctorListAsync$.next([]);\n this.userService.showDoc(deptId).pipe(take(1))\n .subscribe((docData:IDoc[])=>{\n this.doctorListAsync$.next(docData);\n })\n}\n <ng-container *ngIf=\"(doctorListAsync$ | async).length > 0\">\n <option *ngFor=\"let item of doctorListAsync\"></option>\n</ng-container>\n" }, { "answer_id": 74572264, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 1, "selected": false, "text": "onSelect() departments: Department[];\n doctors: Doctor[];\n\n selectedDepartment: Department = null;\n selectedDoctor: Doctor = null;\n\n constructor(private selectService: SelectService) {}\n\n ngOnInit() {\n this.departments = this.selectService.getDepartments();\n // Select the first department as default (optional):\n this.selectedDepartment = this.departments[0];\n this.onSelect(this.selectedDepartment);\n }\n\n onSelect(department: Department) {\n this.doctors = this.selectService\n .getDoctors()\n .filter((item) => item.departmentId == department.id);\n }\n <div>\n <label>Department:</label>\n <select\n [(ngModel)]=\"selectedDepartment\"\n (change)=\"onSelect($event.target.value)\">\n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let department of departments\" [ngValue]=\"department\">\n {{ department.name }}\n </option>\n </select>\n</div>\n\n<br /><br />\n\n<div>\n <label>Doctor:</label>\n <select \n [(ngModel)]=\"selectedDoctor\"> \n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let doctor of doctors\" [ngValue]=\"doctor\">\n {{ doctor.name }}\n </option>\n </select>\n</div>\n export class SelectService {\n getDepartments() {\n return [\n new Department(1, 'Department A'),\n new Department(2, 'Department B'),\n ];\n }\n\n getDoctors() {\n return [\n new Doctor(1, 1, 'Dr. Khan'),\n new Doctor(2, 1, 'Dr. Peters'),\n new Doctor(3, 1, 'Dr. Keller'),\n new Doctor(4, 1, 'Dr. Suter'),\n new Doctor(5, 2, 'Ronaldo'),\n new Doctor(6, 2, 'Messi'),\n new Doctor(7, 2, 'Shakiri'),\n ];\n }\n}\n export class Department {\n constructor(public id: number, public name: string) {}\n}\n\nexport class Doctor {\n constructor(\n public id: number,\n public departmentId: number,\n public name: string\n ) {}\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/220425/" ]
74,570,722
<p>i am working on an android studio project, when i run the project it crashes immedietly, i tried to debug and i found that the problem is in the methods i use from the android libraries as in the pic here (<a href="https://i.stack.imgur.com/a6bKI.png" rel="nofollow noreferrer">https://i.stack.imgur.com/a6bKI.png</a>)</p> <p>i updated the android SDK repaired the IDE added the depencencies needed to the build.gradle file but the problem is not solved</p> <p>bellow is the build.gradle</p> <pre><code>plugins { id 'com.android.application' } android { namespace 'com.example.readerapp' compileSdk 33 defaultConfig { applicationId &quot;com.example.readerapp&quot; minSdk 21 targetSdk 33 versionCode 1 versionName &quot;1.0&quot; testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot; } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'androidx.appcompat:appcompat:1.5.1' implementation &quot;androidx.annotation:annotation:1.5.0&quot; implementation &quot;androidx.constraintlayout:constraintlayout:2.1.4&quot; implementation &quot;androidx.constraintlayout:constraintlayout-compose:1.0.1&quot; implementation 'com.google.android.material:material:1.5.0' implementation files('libs\\uhfcom13_eu_v15.jar') implementation files('libs\\SerialPort.jar') } </code></pre>
[ { "answer_id": 74571483, "author": "Mukesh Soni", "author_id": 11556649, "author_profile": "https://Stackoverflow.com/users/11556649", "pm_score": 0, "selected": false, "text": "Choose doctor \npublic doctorListAsync$: BehaviorSubject<Array<[IDoc]>> = new BehaviorSubject([]);\n\n\nchangeDept(event:object)\n{\n // here reset $doctorListAsync value\n this.doctorListAsync$.next([]);\n this.userService.showDoc(deptId).pipe(take(1))\n .subscribe((docData:IDoc[])=>{\n this.doctorListAsync$.next(docData);\n })\n}\n <ng-container *ngIf=\"(doctorListAsync$ | async).length > 0\">\n <option *ngFor=\"let item of doctorListAsync\"></option>\n</ng-container>\n" }, { "answer_id": 74572264, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 1, "selected": false, "text": "onSelect() departments: Department[];\n doctors: Doctor[];\n\n selectedDepartment: Department = null;\n selectedDoctor: Doctor = null;\n\n constructor(private selectService: SelectService) {}\n\n ngOnInit() {\n this.departments = this.selectService.getDepartments();\n // Select the first department as default (optional):\n this.selectedDepartment = this.departments[0];\n this.onSelect(this.selectedDepartment);\n }\n\n onSelect(department: Department) {\n this.doctors = this.selectService\n .getDoctors()\n .filter((item) => item.departmentId == department.id);\n }\n <div>\n <label>Department:</label>\n <select\n [(ngModel)]=\"selectedDepartment\"\n (change)=\"onSelect($event.target.value)\">\n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let department of departments\" [ngValue]=\"department\">\n {{ department.name }}\n </option>\n </select>\n</div>\n\n<br /><br />\n\n<div>\n <label>Doctor:</label>\n <select \n [(ngModel)]=\"selectedDoctor\"> \n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let doctor of doctors\" [ngValue]=\"doctor\">\n {{ doctor.name }}\n </option>\n </select>\n</div>\n export class SelectService {\n getDepartments() {\n return [\n new Department(1, 'Department A'),\n new Department(2, 'Department B'),\n ];\n }\n\n getDoctors() {\n return [\n new Doctor(1, 1, 'Dr. Khan'),\n new Doctor(2, 1, 'Dr. Peters'),\n new Doctor(3, 1, 'Dr. Keller'),\n new Doctor(4, 1, 'Dr. Suter'),\n new Doctor(5, 2, 'Ronaldo'),\n new Doctor(6, 2, 'Messi'),\n new Doctor(7, 2, 'Shakiri'),\n ];\n }\n}\n export class Department {\n constructor(public id: number, public name: string) {}\n}\n\nexport class Doctor {\n constructor(\n public id: number,\n public departmentId: number,\n public name: string\n ) {}\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20597616/" ]
74,570,738
<p>I'm trying to migrate a legacy app into a new .net 6 version, the issue that I have is that this app has a 3rd party library with keys that will be looked up in the <code>appsettings.json</code> file.</p> <p>Something like this(note the dots in the key):</p> <pre><code>{ &quot;one.special.key&quot;:&quot;one value&quot; } </code></pre> <p>The issue that I'm facing now is that my new app will be running inside a container and the keys will be injected using environment variables and I don't think that containers environments (aka - linux) accept environment variables with dots, only the convention with one/double underscore like this: <em>one_special_key</em>.</p> <p>How can I override an <code>appsetting.json</code> that has a key with dots in it like <code>some.key.with.dots=hello</code> instead of the traditional <code>some_key_without_dots=hello</code>?</p>
[ { "answer_id": 74571483, "author": "Mukesh Soni", "author_id": 11556649, "author_profile": "https://Stackoverflow.com/users/11556649", "pm_score": 0, "selected": false, "text": "Choose doctor \npublic doctorListAsync$: BehaviorSubject<Array<[IDoc]>> = new BehaviorSubject([]);\n\n\nchangeDept(event:object)\n{\n // here reset $doctorListAsync value\n this.doctorListAsync$.next([]);\n this.userService.showDoc(deptId).pipe(take(1))\n .subscribe((docData:IDoc[])=>{\n this.doctorListAsync$.next(docData);\n })\n}\n <ng-container *ngIf=\"(doctorListAsync$ | async).length > 0\">\n <option *ngFor=\"let item of doctorListAsync\"></option>\n</ng-container>\n" }, { "answer_id": 74572264, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 1, "selected": false, "text": "onSelect() departments: Department[];\n doctors: Doctor[];\n\n selectedDepartment: Department = null;\n selectedDoctor: Doctor = null;\n\n constructor(private selectService: SelectService) {}\n\n ngOnInit() {\n this.departments = this.selectService.getDepartments();\n // Select the first department as default (optional):\n this.selectedDepartment = this.departments[0];\n this.onSelect(this.selectedDepartment);\n }\n\n onSelect(department: Department) {\n this.doctors = this.selectService\n .getDoctors()\n .filter((item) => item.departmentId == department.id);\n }\n <div>\n <label>Department:</label>\n <select\n [(ngModel)]=\"selectedDepartment\"\n (change)=\"onSelect($event.target.value)\">\n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let department of departments\" [ngValue]=\"department\">\n {{ department.name }}\n </option>\n </select>\n</div>\n\n<br /><br />\n\n<div>\n <label>Doctor:</label>\n <select \n [(ngModel)]=\"selectedDoctor\"> \n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let doctor of doctors\" [ngValue]=\"doctor\">\n {{ doctor.name }}\n </option>\n </select>\n</div>\n export class SelectService {\n getDepartments() {\n return [\n new Department(1, 'Department A'),\n new Department(2, 'Department B'),\n ];\n }\n\n getDoctors() {\n return [\n new Doctor(1, 1, 'Dr. Khan'),\n new Doctor(2, 1, 'Dr. Peters'),\n new Doctor(3, 1, 'Dr. Keller'),\n new Doctor(4, 1, 'Dr. Suter'),\n new Doctor(5, 2, 'Ronaldo'),\n new Doctor(6, 2, 'Messi'),\n new Doctor(7, 2, 'Shakiri'),\n ];\n }\n}\n export class Department {\n constructor(public id: number, public name: string) {}\n}\n\nexport class Doctor {\n constructor(\n public id: number,\n public departmentId: number,\n public name: string\n ) {}\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2001723/" ]
74,570,748
<p>I am new to Jekyll and I have the following error</p> <p>So I have a Jekyll project which has an index.html file, the html file has content in yaml format in the front matter. I would like to add an <code>&lt;a href=&quot;&quot;&gt;</code> tag to a word, to make it clickable and work as a link but upon adding the tag I get the following error</p> <p>&quot;YAML Exception reading /Users/yapsody/Desktop/campaigns.yapsody.com/faq/index.html: (): did not find expected key while parsing a block mapping at line 38 column 5&quot;</p> <p>this is my YAML content in index.html file, the content is at the top of the page, I would like to enclose &quot;Dashboard overview&quot; in the anchor tag</p> <p><a href="https://i.stack.imgur.com/xb6Wd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xb6Wd.png" alt="enter image description here" /></a></p> <p>this is how I call my yaml content:</p> <p><a href="https://i.stack.imgur.com/6QFAG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6QFAG.png" alt="enter image description here" /></a></p> <p>what I would like to do is the following or something that gives me the same output (dashboard overview ) but its giving me the following error (yellow text)</p> <p><a href="https://i.stack.imgur.com/QNXOG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QNXOG.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74571483, "author": "Mukesh Soni", "author_id": 11556649, "author_profile": "https://Stackoverflow.com/users/11556649", "pm_score": 0, "selected": false, "text": "Choose doctor \npublic doctorListAsync$: BehaviorSubject<Array<[IDoc]>> = new BehaviorSubject([]);\n\n\nchangeDept(event:object)\n{\n // here reset $doctorListAsync value\n this.doctorListAsync$.next([]);\n this.userService.showDoc(deptId).pipe(take(1))\n .subscribe((docData:IDoc[])=>{\n this.doctorListAsync$.next(docData);\n })\n}\n <ng-container *ngIf=\"(doctorListAsync$ | async).length > 0\">\n <option *ngFor=\"let item of doctorListAsync\"></option>\n</ng-container>\n" }, { "answer_id": 74572264, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 1, "selected": false, "text": "onSelect() departments: Department[];\n doctors: Doctor[];\n\n selectedDepartment: Department = null;\n selectedDoctor: Doctor = null;\n\n constructor(private selectService: SelectService) {}\n\n ngOnInit() {\n this.departments = this.selectService.getDepartments();\n // Select the first department as default (optional):\n this.selectedDepartment = this.departments[0];\n this.onSelect(this.selectedDepartment);\n }\n\n onSelect(department: Department) {\n this.doctors = this.selectService\n .getDoctors()\n .filter((item) => item.departmentId == department.id);\n }\n <div>\n <label>Department:</label>\n <select\n [(ngModel)]=\"selectedDepartment\"\n (change)=\"onSelect($event.target.value)\">\n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let department of departments\" [ngValue]=\"department\">\n {{ department.name }}\n </option>\n </select>\n</div>\n\n<br /><br />\n\n<div>\n <label>Doctor:</label>\n <select \n [(ngModel)]=\"selectedDoctor\"> \n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let doctor of doctors\" [ngValue]=\"doctor\">\n {{ doctor.name }}\n </option>\n </select>\n</div>\n export class SelectService {\n getDepartments() {\n return [\n new Department(1, 'Department A'),\n new Department(2, 'Department B'),\n ];\n }\n\n getDoctors() {\n return [\n new Doctor(1, 1, 'Dr. Khan'),\n new Doctor(2, 1, 'Dr. Peters'),\n new Doctor(3, 1, 'Dr. Keller'),\n new Doctor(4, 1, 'Dr. Suter'),\n new Doctor(5, 2, 'Ronaldo'),\n new Doctor(6, 2, 'Messi'),\n new Doctor(7, 2, 'Shakiri'),\n ];\n }\n}\n export class Department {\n constructor(public id: number, public name: string) {}\n}\n\nexport class Doctor {\n constructor(\n public id: number,\n public departmentId: number,\n public name: string\n ) {}\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11760701/" ]
74,570,802
<p>I'm currently doing research and collecting a ranked-choice data. Basically people choosing their preferences in a topic. E.g., people ranking their preference on fruits: orange, mango, apple, avocado</p> <p>The clean data frame looks like this:</p> <pre><code> Fruits Color 1 orange;apple;banana;avocado blue;yellow;red;green 2 avocado;apple;banana;orange red;green;blue;yellow 3 apple;banana;orange;avocado yellow;red;green;blue 4 banana;orange;apple;avocado green;blue;red;yellow 5 apple;avocado;banana;orange yellow;blue;green;red </code></pre> <p>The first person put orange as their first preference, then apple, banana, and avocado as the last preference. and so on</p> <p><strong>Scoring:</strong> 1st preference = 4; 2nd preference = 3; 3rd preference = 2; 4th preference = 1</p> <p><strong>Desired result</strong></p> <pre><code> apple avocado banana orange blue green red yellow 1 3 1 2 4 4 1 2 3 2 3 4 2 1 2 3 4 1 3 4 1 3 2 1 2 3 4 4 2 1 4 3 3 4 2 1 5 4 3 2 1 3 2 1 4 </code></pre> <p>The part that I confused is to figure out how to give score for each column -&gt; turn from semicolon separated string into column with numeric value. If I can pass this, I can create the desired output dataframe.</p> <p>I've found <code>pmr</code> package, but the documentation only a few. Moreover, that package is too advance. I don't really need that for current state, just need simple scores for each preferences</p> <p>Please help me at the scoring stage</p>
[ { "answer_id": 74571483, "author": "Mukesh Soni", "author_id": 11556649, "author_profile": "https://Stackoverflow.com/users/11556649", "pm_score": 0, "selected": false, "text": "Choose doctor \npublic doctorListAsync$: BehaviorSubject<Array<[IDoc]>> = new BehaviorSubject([]);\n\n\nchangeDept(event:object)\n{\n // here reset $doctorListAsync value\n this.doctorListAsync$.next([]);\n this.userService.showDoc(deptId).pipe(take(1))\n .subscribe((docData:IDoc[])=>{\n this.doctorListAsync$.next(docData);\n })\n}\n <ng-container *ngIf=\"(doctorListAsync$ | async).length > 0\">\n <option *ngFor=\"let item of doctorListAsync\"></option>\n</ng-container>\n" }, { "answer_id": 74572264, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 1, "selected": false, "text": "onSelect() departments: Department[];\n doctors: Doctor[];\n\n selectedDepartment: Department = null;\n selectedDoctor: Doctor = null;\n\n constructor(private selectService: SelectService) {}\n\n ngOnInit() {\n this.departments = this.selectService.getDepartments();\n // Select the first department as default (optional):\n this.selectedDepartment = this.departments[0];\n this.onSelect(this.selectedDepartment);\n }\n\n onSelect(department: Department) {\n this.doctors = this.selectService\n .getDoctors()\n .filter((item) => item.departmentId == department.id);\n }\n <div>\n <label>Department:</label>\n <select\n [(ngModel)]=\"selectedDepartment\"\n (change)=\"onSelect($event.target.value)\">\n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let department of departments\" [ngValue]=\"department\">\n {{ department.name }}\n </option>\n </select>\n</div>\n\n<br /><br />\n\n<div>\n <label>Doctor:</label>\n <select \n [(ngModel)]=\"selectedDoctor\"> \n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let doctor of doctors\" [ngValue]=\"doctor\">\n {{ doctor.name }}\n </option>\n </select>\n</div>\n export class SelectService {\n getDepartments() {\n return [\n new Department(1, 'Department A'),\n new Department(2, 'Department B'),\n ];\n }\n\n getDoctors() {\n return [\n new Doctor(1, 1, 'Dr. Khan'),\n new Doctor(2, 1, 'Dr. Peters'),\n new Doctor(3, 1, 'Dr. Keller'),\n new Doctor(4, 1, 'Dr. Suter'),\n new Doctor(5, 2, 'Ronaldo'),\n new Doctor(6, 2, 'Messi'),\n new Doctor(7, 2, 'Shakiri'),\n ];\n }\n}\n export class Department {\n constructor(public id: number, public name: string) {}\n}\n\nexport class Doctor {\n constructor(\n public id: number,\n public departmentId: number,\n public name: string\n ) {}\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14767090/" ]
74,570,840
<p>I have a bigquery table with a column as time_created. The data type of this column is TIMESTAMP. Now I want to know if the column containss invalid values like &quot;&quot;,&quot; &quot;, &quot;some_string&quot;,&quot;++--&quot;. How can I check that?</p>
[ { "answer_id": 74571483, "author": "Mukesh Soni", "author_id": 11556649, "author_profile": "https://Stackoverflow.com/users/11556649", "pm_score": 0, "selected": false, "text": "Choose doctor \npublic doctorListAsync$: BehaviorSubject<Array<[IDoc]>> = new BehaviorSubject([]);\n\n\nchangeDept(event:object)\n{\n // here reset $doctorListAsync value\n this.doctorListAsync$.next([]);\n this.userService.showDoc(deptId).pipe(take(1))\n .subscribe((docData:IDoc[])=>{\n this.doctorListAsync$.next(docData);\n })\n}\n <ng-container *ngIf=\"(doctorListAsync$ | async).length > 0\">\n <option *ngFor=\"let item of doctorListAsync\"></option>\n</ng-container>\n" }, { "answer_id": 74572264, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 1, "selected": false, "text": "onSelect() departments: Department[];\n doctors: Doctor[];\n\n selectedDepartment: Department = null;\n selectedDoctor: Doctor = null;\n\n constructor(private selectService: SelectService) {}\n\n ngOnInit() {\n this.departments = this.selectService.getDepartments();\n // Select the first department as default (optional):\n this.selectedDepartment = this.departments[0];\n this.onSelect(this.selectedDepartment);\n }\n\n onSelect(department: Department) {\n this.doctors = this.selectService\n .getDoctors()\n .filter((item) => item.departmentId == department.id);\n }\n <div>\n <label>Department:</label>\n <select\n [(ngModel)]=\"selectedDepartment\"\n (change)=\"onSelect($event.target.value)\">\n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let department of departments\" [ngValue]=\"department\">\n {{ department.name }}\n </option>\n </select>\n</div>\n\n<br /><br />\n\n<div>\n <label>Doctor:</label>\n <select \n [(ngModel)]=\"selectedDoctor\"> \n <option [ngValue]=\"null\">--Select--</option>\n <option *ngFor=\"let doctor of doctors\" [ngValue]=\"doctor\">\n {{ doctor.name }}\n </option>\n </select>\n</div>\n export class SelectService {\n getDepartments() {\n return [\n new Department(1, 'Department A'),\n new Department(2, 'Department B'),\n ];\n }\n\n getDoctors() {\n return [\n new Doctor(1, 1, 'Dr. Khan'),\n new Doctor(2, 1, 'Dr. Peters'),\n new Doctor(3, 1, 'Dr. Keller'),\n new Doctor(4, 1, 'Dr. Suter'),\n new Doctor(5, 2, 'Ronaldo'),\n new Doctor(6, 2, 'Messi'),\n new Doctor(7, 2, 'Shakiri'),\n ];\n }\n}\n export class Department {\n constructor(public id: number, public name: string) {}\n}\n\nexport class Doctor {\n constructor(\n public id: number,\n public departmentId: number,\n public name: string\n ) {}\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19114283/" ]
74,570,863
<p>I have certain forms in my Django project and I want to get a different data with a button on this form with a pop-up window and save it to the database. But here, how can I make the previously entered data come back when the page is reloaded so that my background data is not lost?</p> <p>Thanks in advance to everyone who helps.</p>
[ { "answer_id": 74571002, "author": "GouriSankar", "author_id": 7235140, "author_profile": "https://Stackoverflow.com/users/7235140", "pm_score": 0, "selected": false, "text": "localStorage.setItem(\"name\", \"Smith\");\nlocalStorage.getItem(\"name\");\nlocalStorage.removeItem(\"name\");\n" }, { "answer_id": 74571110, "author": "Dream Bold", "author_id": 12743692, "author_profile": "https://Stackoverflow.com/users/12743692", "pm_score": 2, "selected": true, "text": "setItem var inputEmail= document.getElementById(\"email\");\nlocalStorage.setItem(\"email\", inputEmail.value);\n var storedValue = localStorage.getItem(\"email\");\n <button onclick=\"store()\" type=\"button\">StoreEmail</button>\n\n<script type=\"text/javascript\">\n function store(){\n var inputEmail= document.getElementById(\"email\");\n localStorage.setItem(\"email\", inputEmail.value);\n }\n</script>\n cookie" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20563061/" ]
74,570,912
<p>I am trying to export a report from SSRS into CSV and just have no data rows or blank lines at the end.</p> <p>I have already added the following to the config file:</p> <pre><code>&lt;Extension Name=&quot;CSV (No Header)&quot; Type=&quot;Microsoft.ReportingServices.Rendering.DataRenderer.CsvReport,Microsoft.ReportingServices.DataRendering&quot;&gt; &lt;OverrideNames&gt; &lt;Name Language=&quot;en-us&quot;&gt; CSV No Header&lt;/Name&gt; &lt;/OverrideNames&gt; &lt;Configuration&gt; &lt;DeviceInfo&gt; &lt;NoHeader&gt;true&lt;/NoHeader&gt; &lt;ExcelMode&gt;False&lt;/ExcelMode&gt; &lt;/DeviceInfo&gt; &lt;/Configuration&gt; &lt;/Extension&gt; </code></pre> <p>The header section works, but only one of the two blank lines is removed. how do i remove the other blank line?</p> <p>Thanks</p>
[ { "answer_id": 74571002, "author": "GouriSankar", "author_id": 7235140, "author_profile": "https://Stackoverflow.com/users/7235140", "pm_score": 0, "selected": false, "text": "localStorage.setItem(\"name\", \"Smith\");\nlocalStorage.getItem(\"name\");\nlocalStorage.removeItem(\"name\");\n" }, { "answer_id": 74571110, "author": "Dream Bold", "author_id": 12743692, "author_profile": "https://Stackoverflow.com/users/12743692", "pm_score": 2, "selected": true, "text": "setItem var inputEmail= document.getElementById(\"email\");\nlocalStorage.setItem(\"email\", inputEmail.value);\n var storedValue = localStorage.getItem(\"email\");\n <button onclick=\"store()\" type=\"button\">StoreEmail</button>\n\n<script type=\"text/javascript\">\n function store(){\n var inputEmail= document.getElementById(\"email\");\n localStorage.setItem(\"email\", inputEmail.value);\n }\n</script>\n cookie" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688277/" ]
74,570,926
<p>I am trying to automate some API endpoints, but the JSON response is an array of data. How can I assert a specific user with all his data inside that JSON array?</p> <p>I am trying with:</p> <pre><code>assert { &quot;user&quot;: &quot;test1&quot;, &quot;userName&quot;: &quot;John Berner&quot;, &quot;userid&quot;: &quot;1&quot; } in response.json() </code></pre> <p>The JSON response is:</p> <pre><code>{ &quot;data&quot;: [ { &quot;user&quot;: &quot;test1&quot;, &quot;userName&quot;: &quot;John Berner&quot;, &quot;userid&quot;: &quot;1&quot; }, { &quot;user&quot;: &quot;test2&quot;, &quot;userName&quot;: &quot;Nick Morris&quot;, &quot;userid&quot;: &quot;2&quot; } ], &quot;metadata&quot;: { &quot;current_page&quot;: 1, &quot;pages&quot;: 1, &quot;per_page&quot;: 100, &quot;total&quot;: 2 } } </code></pre>
[ { "answer_id": 74571002, "author": "GouriSankar", "author_id": 7235140, "author_profile": "https://Stackoverflow.com/users/7235140", "pm_score": 0, "selected": false, "text": "localStorage.setItem(\"name\", \"Smith\");\nlocalStorage.getItem(\"name\");\nlocalStorage.removeItem(\"name\");\n" }, { "answer_id": 74571110, "author": "Dream Bold", "author_id": 12743692, "author_profile": "https://Stackoverflow.com/users/12743692", "pm_score": 2, "selected": true, "text": "setItem var inputEmail= document.getElementById(\"email\");\nlocalStorage.setItem(\"email\", inputEmail.value);\n var storedValue = localStorage.getItem(\"email\");\n <button onclick=\"store()\" type=\"button\">StoreEmail</button>\n\n<script type=\"text/javascript\">\n function store(){\n var inputEmail= document.getElementById(\"email\");\n localStorage.setItem(\"email\", inputEmail.value);\n }\n</script>\n cookie" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20597969/" ]
74,570,974
<p>I have an original dataframe <code>df0</code> with a number of values, based on this dataframe I have a second dateframe where some the original values are <code>NaN</code>, <code>df1</code>.</p> <pre><code>import pandas as pd df0 = pd.DataFrame({'col1': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]}) df1 = pd.DataFrame({'col1': [1,2,None,4,5,6,None,8,None,10,11,None,13,None,None]}) </code></pre> <p>I need a <code>df2</code> to be the inverse of <code>df1</code> in terms of rows with <code>NaN</code>. Every row which is <code>NaN</code> in df1 should get its original value back from <code>df0</code> and rows which are not <code>NaN</code> must become <code>NaN</code> such that I get the following dataframe:</p> <pre><code>df2 = pd.DataFrame({'col1': [None,None,3,None,None,None,7,None,9,None,None,12,None,14,15]}) </code></pre> <p>What is the best way to go about this if it were a larger dataset?</p>
[ { "answer_id": 74570987, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "mask notna where isna df2 = df0.mask(df1['col1'].notna())\n# or\ndf2 = df0.where(df1['col1'].isna())\n col1\n0 NaN\n1 NaN\n2 3.0\n3 NaN\n4 NaN\n5 NaN\n6 7.0\n7 NaN\n8 9.0\n9 NaN\n10 NaN\n11 12.0\n12 NaN\n13 14.0\n14 15.0\n assign Series.mask df2 = df0.assign(col1=df0['col1'].mask(df1['col1'].notna()))\n" }, { "answer_id": 74570990, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 1, "selected": false, "text": "Series.where Series.isna df0['col1'] = df0['col1'].where(df1['col1'].isna())\nprint (df0)\n col1\n0 NaN\n1 NaN\n2 3.0\n3 NaN\n4 NaN\n5 NaN\n6 7.0\n7 NaN\n8 9.0\n9 NaN\n10 NaN\n11 12.0\n12 NaN\n13 14.0\n14 15.0\n DataFrame.loc Series.notna df0.loc[df1['col1'].notna(), 'col1'] = np.nan\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16002179/" ]
74,570,995
<p>Will <code>aws s3 sync s3://myBucket/this_folder/object_file C:\\Users\Desktop</code> create also the &quot;this_folder&quot; in C:\Users\Desktop? If not, what would be the solution to copy/sync including the folder structure of S3? I mean I have many files in different S3 bucket folders sorted by year, month, day. I would like to copy them locally with the folder structure/tree to be created locally as it is in the S3 bucket. Thank you.</p>
[ { "answer_id": 74571044, "author": "baduker", "author_id": 6106791, "author_profile": "https://Stackoverflow.com/users/6106791", "pm_score": 1, "selected": false, "text": "aws cli --recursive aws s3 cp --recursive s3://your_bucket/your_folder_named_x path/to/your/destination\n" }, { "answer_id": 74571217, "author": "Paolo", "author_id": 3390419, "author_profile": "https://Stackoverflow.com/users/3390419", "pm_score": 2, "selected": false, "text": "aws s3 sync --delete C:\\Users\\Desktop" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12176490/" ]
74,570,999
<p>Good morning, I'm doing a job where I have to show some information from a database in cmd, I search the internet and only find in Tables DataGrid do not understand how I will do, I have the following code:</p> <pre><code>public class atm { public static void Main() { string connectionString; SqlConnection cnn; connectionString = @&quot;Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;&quot;; cnn = new SqlConnection(connectionString); try { using (SqlCommand cmd = cnn.CreateCommand()) { cnn.Open(); Console.WriteLine(&quot;Is working&quot;); var sqlQuery = &quot;SELECT FirstName FROM tblATM&quot;; using (SqlDataAdapter da = new SqlDataAdapter(sqlQuery, cnn)) { using (DataTable dt = new DataTable()) { da.Fill(dt); Console.WriteLine(dt); } } } } catch (SqlException erro) { Console.WriteLine(&quot;Is not working&quot; + erro); } finally { cnn.Close(); } } } </code></pre> <p>When I open it says it's working, then I think the connection is working but it doesn't show the database data I'm asking for. If anyone knows how to help me, i'd appreciate it.</p>
[ { "answer_id": 74571044, "author": "baduker", "author_id": 6106791, "author_profile": "https://Stackoverflow.com/users/6106791", "pm_score": 1, "selected": false, "text": "aws cli --recursive aws s3 cp --recursive s3://your_bucket/your_folder_named_x path/to/your/destination\n" }, { "answer_id": 74571217, "author": "Paolo", "author_id": 3390419, "author_profile": "https://Stackoverflow.com/users/3390419", "pm_score": 2, "selected": false, "text": "aws s3 sync --delete C:\\Users\\Desktop" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74570999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20571251/" ]
74,571,034
<p>As the title suggests, I am somewhat unable to figure out the correct syntax for this function.</p> <p>Currently, I have an event listener on a map that fires a function when the map is clicked as seen below:</p> <pre><code>map.on(&quot;click&quot;,(event)=&gt;addMarker(event,parameter)) </code></pre> <p>This is fine, but I want to combine the function fired into one complete function. I am aware it can be done such that I don't have to define the event outside of the <code>addMarker</code> function. Rather, I want to define the event within the <code>addMarker</code> function such that I only have the single function that is fired once the map is clicked.</p> <p>Below is what I am trying to achieve (it's not the correct syntax):</p> <pre><code>map.on(&quot;click&quot;,addMarker(map)) </code></pre> <p>and the addMarker function is:</p> <pre><code>const addMarker = (event) =&gt; (parameter) =&gt;{ new mapboxgl.addMarker({}).setLngLat(coords).addTo(parameter) } </code></pre> <p>can anyone help with the proper syntax of the proposed addMarker function? When I do it this way I get the error <code>&quot;Cannot read properties of undefined (reading:&quot;lng&quot;)&quot;</code></p>
[ { "answer_id": 74571044, "author": "baduker", "author_id": 6106791, "author_profile": "https://Stackoverflow.com/users/6106791", "pm_score": 1, "selected": false, "text": "aws cli --recursive aws s3 cp --recursive s3://your_bucket/your_folder_named_x path/to/your/destination\n" }, { "answer_id": 74571217, "author": "Paolo", "author_id": 3390419, "author_profile": "https://Stackoverflow.com/users/3390419", "pm_score": 2, "selected": false, "text": "aws s3 sync --delete C:\\Users\\Desktop" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11970486/" ]
74,571,071
<p>I recently started working with spark and was eager to know if I have to perform queries which would be better spark sql or databricks sql and why?</p>
[ { "answer_id": 74574573, "author": "Alex Ott", "author_id": 18627, "author_profile": "https://Stackoverflow.com/users/18627", "pm_score": 2, "selected": false, "text": "CREATE TABLE CLONE" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19006871/" ]
74,571,072
<p>I have a list of Map items. From this i want to modify a key value of an item by using it's id. The below is the List of map.</p> <pre><code>List items = [{'id':'01','name':'Rahul'},{'id':'02','name':'John'},{'id':'03','name':'Marry'}]; </code></pre> <p>From this list when i press a button i want to update the name of that item based on id.</p> <p>For eg,</p> <pre><code>void editName(String id,String name){ //Here i want to edit the name based on that id } </code></pre> <p>if i pass <code>editName('02','Rose')</code> i want the result</p> <pre><code>[{'id':'01','name':'Rahul'},{'id':'02','name':'Rose'},{'id':'03','name':'Marry'}]; </code></pre>
[ { "answer_id": 74571283, "author": "Murali Krishnan", "author_id": 12094009, "author_profile": "https://Stackoverflow.com/users/12094009", "pm_score": 0, "selected": false, "text": "void main() {\nList items = [{'id':'01','name':'Rahul'},{'id':'02','name':'John'},{'id':'03','name':'Marry'}];\nvar result = items.firstWhere((element) => element['id'] == '02');\nprint(result);\nvar index = items.indexWhere((element) => element['id'] == '02');\nprint(index);\nresult['name'] = 'Rose';\nprint(result);\nitems.removeAt(index);\nitems.insert(index, result);\nprint(items);\n}\n\n" }, { "answer_id": 74571349, "author": "Ska Lee", "author_id": 14695961, "author_profile": "https://Stackoverflow.com/users/14695961", "pm_score": 2, "selected": false, "text": "void main() {\n List<Map<String, String>> items = [\n {'id': '01', 'name': 'Rahul'},\n {'id': '02', 'name': 'John'},\n {'id': '03', 'name': 'Marry'}\n ];\n\n void editName(String id, String name) {\n for (var item in items) {\n if (id == item['id']) {\n item['name'] = name;\n }\n }\n }\n\n editName('02', 'Rose');\n print('items: $items');\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12094009/" ]
74,571,076
<p><strong>Table 1</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>item</th> <th style="text-align: right;">unit sold</th> <th>item - 2</th> <th style="text-align: right;">unit sold</th> </tr> </thead> <tbody> <tr> <td>x</td> <td style="text-align: right;">1000</td> <td>y</td> <td style="text-align: right;">500</td> </tr> </tbody> </table> </div> <p><strong>Table 2</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>bundle items</th> <th>items in bundle</th> </tr> </thead> <tbody> <tr> <td>a</td> <td>['x,y']</td> </tr> <tr> <td>b</td> <td>['x,y,z']</td> </tr> </tbody> </table> </div> <p>I need to join Table 1 &amp; 2. If Item and item-2 match with items in bundle.</p> <p>Desired result</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>item</th> <th style="text-align: right;">unit sold</th> <th>item - 2</th> <th style="text-align: right;">unit sold</th> <th>bundle items</th> <th>items in bundle</th> </tr> </thead> <tbody> <tr> <td>x</td> <td style="text-align: right;">1000</td> <td>y</td> <td style="text-align: right;">500</td> <td>a</td> <td>[x,y]</td> </tr> <tr> <td>x</td> <td style="text-align: right;">1000</td> <td>y</td> <td style="text-align: right;">500</td> <td>b</td> <td>[x,y,z]</td> </tr> </tbody> </table> </div> <p>I tried using unnest with no luck.</p> <pre><code>Left join ( select b_sku, array_agg(c_sku) as children from p group by p.b_sku ) y ON i.sku = unnest(y.children) </code></pre>
[ { "answer_id": 74571283, "author": "Murali Krishnan", "author_id": 12094009, "author_profile": "https://Stackoverflow.com/users/12094009", "pm_score": 0, "selected": false, "text": "void main() {\nList items = [{'id':'01','name':'Rahul'},{'id':'02','name':'John'},{'id':'03','name':'Marry'}];\nvar result = items.firstWhere((element) => element['id'] == '02');\nprint(result);\nvar index = items.indexWhere((element) => element['id'] == '02');\nprint(index);\nresult['name'] = 'Rose';\nprint(result);\nitems.removeAt(index);\nitems.insert(index, result);\nprint(items);\n}\n\n" }, { "answer_id": 74571349, "author": "Ska Lee", "author_id": 14695961, "author_profile": "https://Stackoverflow.com/users/14695961", "pm_score": 2, "selected": false, "text": "void main() {\n List<Map<String, String>> items = [\n {'id': '01', 'name': 'Rahul'},\n {'id': '02', 'name': 'John'},\n {'id': '03', 'name': 'Marry'}\n ];\n\n void editName(String id, String name) {\n for (var item in items) {\n if (id == item['id']) {\n item['name'] = name;\n }\n }\n }\n\n editName('02', 'Rose');\n print('items: $items');\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17497166/" ]
74,571,088
<p>In my android project I got very intericting task My company wants to hide all mintions about her in code (variables names, packages and etc) But only for one flavour, so I cannot do it once for all project.</p> <p>My first idea, was writing a simple gradle task, that will replace all strings that fit in code, but in this case package names will remain unchanged.</p> <p>Secondly, since we have ci on Jenkins, I thought about jenkins script, that will rename all files and its content, if it has keyword. But this solution looks very bulky for me.</p> <p>Maybe there is another, elegant way?</p>
[ { "answer_id": 74643848, "author": "ycr", "author_id": 2627018, "author_profile": "https://Stackoverflow.com/users/2627018", "pm_score": 1, "selected": false, "text": "grep sed sh '''\ngrep -rl ${PACKAGE_NAME_TO_REPLACE} ${DESTINATION_DIR} | xargs sed -i \"s&${PACKAGE_NAME_TO_REPLACE}&${PACKAGE_NAME_NEW}&g\"\n'''\n def dirToSearchIn = \"/where/to/replace\"\n\n// Change the content on specific files. You can improve the regex pattern below to fine-tune it. With the following pattern only files with extensions .java and .md will be changed. \ndef filterFilePattern = ~/.*\\.java|.*\\.md$/\n\ndef oldString = \"replaceme\"\ndef newString = \"newme\"\n\nnew File(dirToSearchIn).traverse(type: groovy.io.FileType.FILES, nameFilter: filterFilePattern) { file ->\n println \"Processing file: \" + file.getPath()\n def fileContent = file.text;\n if (fileContent.contains(oldString)) {\n println \"Replacing the content of the file: \" + file.getPath()\n file.write(fileContent.replaceAll(oldString, newString));\n } else {\n println \"Skipping file: \" + file.getPath()\n }\n}\n" }, { "answer_id": 74677916, "author": "Begging", "author_id": 16606223, "author_profile": "https://Stackoverflow.com/users/16606223", "pm_score": 0, "selected": false, "text": "#!/bin/bash\n\n# Replace all instances of \"old_string\" with \"new_string\" in the current directory and subdirectories\nfind . -type f -exec sed -i \"s/old_string/new_string/g\" {} +\n" }, { "answer_id": 74681227, "author": "Chriki", "author_id": 1797912, "author_profile": "https://Stackoverflow.com/users/1797912", "pm_score": 0, "selected": false, "text": "build.gradle def duplicateProjDirName = 'duplicateProj'\ndef duplicateProjDir = project.layout.buildDirectory.dir(duplicateProjDirName)\n\ndef duplicateProj = tasks.register('createDuplicateProject', Copy) {\n enabled = (projectDir.name != duplicateProjDirName)\n\n from(project.layout.projectDirectory)\n into(duplicateProjDir)\n exclude('build', '.gradle')\n\n def acmePattern = /(?i)acme/\n def newCompanyName = 'foobar'\n eachFile { it.path = it.sourcePath.replaceAll(acmePattern, newCompanyName) }\n filter { it.replaceAll(acmePattern, newCompanyName) }\n includeEmptyDirs = false\n}\n\ndef duplicateBuild = tasks.register('buildDuplicateProject', GradleBuild) {\n enabled = (projectDir.name != duplicateProjDirName)\n\n dependsOn(duplicateProj)\n\n dir = duplicateProjDir\n tasks = ['build']\n}\n\ntasks.named('build').configure {\n dependsOn(duplicateBuild)\n}\n createDuplicateProject build/duplicateProj/ buildDuplicateProject \"AC\" + \"ME\"" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1474925/" ]
74,571,107
<p>I have a dataframe with two related columns that needs to be merged into a single <code>dictionary</code> column.</p> <p>Sample Data:</p> <pre><code> skuId coreAttributes.price coreAttributes.amount 0 100 price 8.84 1 102 price 12.99 2 103 price 9.99 </code></pre> <p>Expected output:</p> <pre><code>skuId coreAttributes 100 {'price': 8.84} 102 {'price': 12.99} 103 {'price': 9.99} </code></pre> <p>What I've tried:</p> <pre><code>planProducts_T = planProducts.filter(regex = 'coreAttributes').T planProducts_T.columns = planProducts_T.iloc[0] planProducts_T.iloc[1:].to_dict(orient = 'records') </code></pre> <p>I get <code>UserWarning: DataFrame columns are not unique, some columns will be omitted.</code> and this output:</p> <pre><code>[{'price': 9.99}] </code></pre> <p>Could you someone please help me on this.</p>
[ { "answer_id": 74571150, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "zip df['coreAttributes'] = [{k: v} for k,v in\n zip(df['coreAttributes.price'],\n df['coreAttributes.amount'])]\n skuId coreAttributes.price coreAttributes.amount coreAttributes\n0 100 price 8.84 {'price': 8.84}\n1 102 price 12.99 {'price': 12.99}\n2 103 price 9.99 {'price': 9.99}\n pop df['coreAttributes'] = [{k: v} for k,v in\n zip(df.pop('coreAttributes.price'),\n df.pop('coreAttributes.amount'))]\n skuId coreAttributes\n0 100 {'price': 8.84}\n1 102 {'price': 12.99}\n2 103 {'price': 9.99}\n" }, { "answer_id": 74571261, "author": "Lucas M. Uriarte", "author_id": 14543462, "author_profile": "https://Stackoverflow.com/users/14543462", "pm_score": 1, "selected": false, "text": "df[\"coreAttributes\"] = df.apply(lambda row: {row[\"coreAttributes.price\"]: row[\"coreAttributes.amount\"]}, axis=1)\ndf.drop([\"coreAttributes.price\",\"coreAttributes.amount\"], axis=1)\n skuId coreAttributes\n0 100 {'price': 8.84}\n1 102 {'price': 12.99}\n2 103 {'price': 9.99}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10722752/" ]
74,571,118
<p>I have multiple state variables, that contains data entered in a form by the user. Since this form is only meant to update the existing values, I have to pass in only those values that have changed from its initial value (the one returned from the GET request).</p> <p>State:</p> <pre><code>const [name, setName] = useState(props.user?.name ?? null); const [lang, setLang] = useState(props.user?.lang ?? null); const [enableChecks, setEnableChecks] = useState(props.user?.checkEnabled ?? false) </code></pre> <p>In the event that the user only changed the name, how can I pass in only name in the request body?</p> <p>What I have tried: I have the user props, so I have multiple if statements that check if the props matches the state. If it doesn't, then I add it to the request payload. This works, but when there's a lot of state, there will be a lot of if statements, which isn't nice to look at.</p> <p>Is there a better way to do this?</p>
[ { "answer_id": 74571150, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "zip df['coreAttributes'] = [{k: v} for k,v in\n zip(df['coreAttributes.price'],\n df['coreAttributes.amount'])]\n skuId coreAttributes.price coreAttributes.amount coreAttributes\n0 100 price 8.84 {'price': 8.84}\n1 102 price 12.99 {'price': 12.99}\n2 103 price 9.99 {'price': 9.99}\n pop df['coreAttributes'] = [{k: v} for k,v in\n zip(df.pop('coreAttributes.price'),\n df.pop('coreAttributes.amount'))]\n skuId coreAttributes\n0 100 {'price': 8.84}\n1 102 {'price': 12.99}\n2 103 {'price': 9.99}\n" }, { "answer_id": 74571261, "author": "Lucas M. Uriarte", "author_id": 14543462, "author_profile": "https://Stackoverflow.com/users/14543462", "pm_score": 1, "selected": false, "text": "df[\"coreAttributes\"] = df.apply(lambda row: {row[\"coreAttributes.price\"]: row[\"coreAttributes.amount\"]}, axis=1)\ndf.drop([\"coreAttributes.price\",\"coreAttributes.amount\"], axis=1)\n skuId coreAttributes\n0 100 {'price': 8.84}\n1 102 {'price': 12.99}\n2 103 {'price': 9.99}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8845766/" ]
74,571,119
<p>I need to repeat a value x time in rows. when it is done repeat another value n time. I found <code>SEQUENCE()</code> but it works only for the first value.</p> <p>EXAMPLE:</p> <pre><code>Repeat in rows starting from C1 Repeat A1 value: 42 N time A2 value: 3 then Repeat B1 value: 67 M time B2 value: 5 </code></pre> <p>In C8 I should have the last 67 value</p> <p>Is there a way to concatenate the =SEQUENCE?</p> <p>Thanks <a href="https://i.stack.imgur.com/uv4QB.png" rel="nofollow noreferrer">enter image description here</a></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> </tr> </thead> <tbody> <tr> <td>42</td> <td>67</td> </tr> <tr> <td>3</td> <td>5</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74571150, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "zip df['coreAttributes'] = [{k: v} for k,v in\n zip(df['coreAttributes.price'],\n df['coreAttributes.amount'])]\n skuId coreAttributes.price coreAttributes.amount coreAttributes\n0 100 price 8.84 {'price': 8.84}\n1 102 price 12.99 {'price': 12.99}\n2 103 price 9.99 {'price': 9.99}\n pop df['coreAttributes'] = [{k: v} for k,v in\n zip(df.pop('coreAttributes.price'),\n df.pop('coreAttributes.amount'))]\n skuId coreAttributes\n0 100 {'price': 8.84}\n1 102 {'price': 12.99}\n2 103 {'price': 9.99}\n" }, { "answer_id": 74571261, "author": "Lucas M. Uriarte", "author_id": 14543462, "author_profile": "https://Stackoverflow.com/users/14543462", "pm_score": 1, "selected": false, "text": "df[\"coreAttributes\"] = df.apply(lambda row: {row[\"coreAttributes.price\"]: row[\"coreAttributes.amount\"]}, axis=1)\ndf.drop([\"coreAttributes.price\",\"coreAttributes.amount\"], axis=1)\n skuId coreAttributes\n0 100 {'price': 8.84}\n1 102 {'price': 12.99}\n2 103 {'price': 9.99}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11642253/" ]
74,571,128
<p>I'm new at the MQ topic.</p> <p>How do I Test/Unit-Test my Java Services, which do actions against a real Queue. My classes do connections, deletes etc.</p> <p>Is there any way to test these services without performing actions against the productive Queues?</p> <pre><code>@Service public class QueueConnectionService { private final MQConfigMapping configMapping; private MQQueueManager queueManager; @Autowired public QueueConnectionService(MQConfigMapping configMapping) { this.configMapping = configMapping; } MQQueue connect(String queuePropertyTitle, int openOptions, String queueName) throws MQException { MQEnvironment.hostname = configMapping.getNamed().get(queuePropertyTitle).getHostname(); MQEnvironment.channel = configMapping.getNamed().get(queuePropertyTitle).getChannel(); MQEnvironment.port = configMapping.getNamed().get(queuePropertyTitle).getPort(); MQEnvironment.userID = configMapping.getNamed().get(queuePropertyTitle).getUser(); MQEnvironment.password = configMapping.getNamed().get(queuePropertyTitle).getPassword(); queueManager = new MQQueueManager(configMapping.getNamed().get(queuePropertyTitle).getQueueManager()); return queueManager.accessQueue(queueName, openOptions); } } </code></pre> <p>This is my QueueConnectionService, but I have no clue how to use this one at local tests.</p>
[ { "answer_id": 74575223, "author": "Étienne Miret", "author_id": 1867549, "author_profile": "https://Stackoverflow.com/users/1867549", "pm_score": 1, "selected": false, "text": "MQQueueManager new MqQueueManagerFactory QueueConnectionService @ExtendWith(MockitoExtension.class)\nclass QueueConnectionServiceTest {\n\n private static final String TITLE = \"Some random string\";\n private static final String QUEUE_MANAGER = \"Actual value does not matter\";\n private static final String NAME = \"Really. Those constants are magic strings.\";\n private static final int OPTIONS = 42;\n\n @InjectMock\n private QueueConnectionService service;\n\n @Mock(answer = RETURNS_DEEP_STUBS)\n private MQConfigMapping configMapping;\n\n @Mock\n private MqConnectionManagerFactory connectionManagerFactory;\n\n @Mock\n private MQConnectionManager connectionManager;\n\n @Mock\n private MQQueue queue;\n\n @Test\n void should_provide_queue() {\n when(configMapping.getNamed().get(TITLE).getQueueManager()).thenReturn(QUEUE_MANAGER);\n // repeat above line for each configuration parameter.\n // Alternatively, create a config object and:\n when(configMapping.getNamed().get(TITLE)).thenReturn(config);\n\n when(connectionManagerFactory.create(QUEUE_MANAGER)).thenReturn(connectionManager);\n when(connectionManager.accessQueue(NAME, OPTIONS)).thenReturn(queue);\n\n var actual = service.connect(TITLE, OPTIONS, NAME);\n\n assertSame(actual, queue);\n }\n\n}\n @PostConstruct" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598157/" ]
74,571,142
<p>I'm looking for a person to explain this code to me and tell why I'm getting this error.</p> <blockquote> <p>C:\Users\04albjoh\Downloads\VS code\app\Program.cs(20,30): error CS0103: The name 'customers' does not exist in the current context [C:\Users\04albjoh\Downloads\VS code\app\app.csproj]</p> </blockquote> <pre><code>*// Example #1: var is optional when // the select clause specifies a string string[] words = { &quot;apple&quot;, &quot;strawberry&quot;, &quot;grape&quot;, &quot;peach&quot;, &quot;banana&quot; }; var wordQuery = from word in words where word[0] == 'g' select word; // Because each element in the sequence is a string, // not an anonymous type, var is optional here also. foreach (string s in wordQuery) { Console.WriteLine(s); } // Example #2: var is required because // the select clause specifies an anonymous type var custQuery = from cust in customers where cust.City == &quot;Phoenix&quot; select new { cust.Name, cust.Phone }; // var must be used because each item // in the sequence is an anonymous type foreach (var item in custQuery) { Console.WriteLine(&quot;Name={0}, Phone={1}&quot;, item.Name, item.Phone); }* </code></pre> <p><strong>I tried adding</strong></p> <pre><code>this: customers = {} </code></pre> <p><strong>above</strong></p> <pre><code>var custQuery = from cust in customers where cust.City == &quot;Phoenix&quot; select new { cust.Name, cust.Phone }; </code></pre>
[ { "answer_id": 74571239, "author": "CodeCaster", "author_id": 266143, "author_profile": "https://Stackoverflow.com/users/266143", "pm_score": 2, "selected": false, "text": "customers City Name Phone select var" }, { "answer_id": 74571721, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "Customer customers Customer List<Customer> customers" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598084/" ]
74,571,191
<p>I updated to Spring Boot 3 in a project that uses the Keycloak Spring Adapter. Unfortunately it doesn't start because the KeycloakWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter which was first deprecated in Spring Security and then removed. Is there currently another way to implement security with Keycloak? Or to put it in other words: How can I use Spring Boot 3 in combination with the keycloak adapter?</p> <p>I searched the internet but couldn't find any other version of the adapter.</p>
[ { "answer_id": 74571452, "author": "lathspell", "author_id": 2356160, "author_profile": "https://Stackoverflow.com/users/2356160", "pm_score": 2, "selected": false, "text": "SecurityFilterChain WebSecurityAdapter @Configuration\n@EnableWebSecurity\n@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true)\nclass OAuth2SecurityConfig {\n\n@Bean\nfun customOauth2FilterChain(http: HttpSecurity): SecurityFilterChain {\n log.info(\"Configure HttpSecurity with OAuth2\")\n\n http {\n oauth2ResourceServer {\n jwt { jwtAuthenticationConverter = CustomBearerJwtAuthenticationConverter() }\n }\n oauth2Login {}\n\n csrf { disable() }\n\n authorizeRequests {\n // Kubernetes\n authorize(\"/readiness\", permitAll)\n authorize(\"/liveness\", permitAll)\n authorize(\"/actuator/health/**\", permitAll)\n // ...\n // everything else needs at least a valid login, roles are checked at method level\n authorize(anyRequest, authenticated)\n }\n }\n\n return http.build()\n}\n application.yml spring:\n security:\n oauth2:\n client:\n provider:\n abc:\n issuer-uri: https://keycloak.../auth/realms/foo\n registration:\n abc:\n client-secret: ...\n provider: abc\n client-id: foo\n scope: [ openid, profile, email ]\n resourceserver:\n jwt:\n issuer-uri: https://keycloak.../auth/realms/foo\n" }, { "answer_id": 74572732, "author": "ch4mp", "author_id": 619830, "author_profile": "https://Stackoverflow.com/users/619830", "pm_score": 3, "selected": true, "text": "spring-boot-starter-oauth2-client WebClient @FeignClient RestTemplate spring-boot-starter-oauth2-resource-server @Configuration\n@EnableWebSecurity\n@EnableMethodSecurity\npublic class WebSecurityConfig {\n\n public interface Jwt2AuthoritiesConverter extends Converter<Jwt, Collection<? extends GrantedAuthority>> {\n }\n\n @SuppressWarnings(\"unchecked\")\n @Bean\n public Jwt2AuthoritiesConverter authoritiesConverter() {\n // This is a converter for roles as embedded in the JWT by a Keycloak server\n // Roles are taken from both realm_access.roles & resource_access.{client}.roles\n return jwt -> {\n final var realmAccess = (Map<String, Object>) jwt.getClaims().getOrDefault(\"realm_access\", Map.of());\n final var realmRoles = (Collection<String>) realmAccess.getOrDefault(\"roles\", List.of());\n\n final var resourceAccess = (Map<String, Object>) jwt.getClaims().getOrDefault(\"resource_access\", Map.of());\n // We assume here you have \"spring-addons-confidential\" and \"spring-addons-public\" clients configured with \"client roles\" mapper in Keycloak\n final var confidentialClientAccess = (Map<String, Object>) resourceAccess.getOrDefault(\"spring-addons-confidential\", Map.of());\n final var confidentialClientRoles = (Collection<String>) confidentialClientAccess.getOrDefault(\"roles\", List.of());\n final var publicClientAccess = (Map<String, Object>) resourceAccess.getOrDefault(\"spring-addons-public\", Map.of());\n final var publicClientRoles = (Collection<String>) publicClientAccess.getOrDefault(\"roles\", List.of());\n\n return Stream.concat(realmRoles.stream(), Stream.concat(confidentialClientRoles.stream(), publicClientRoles.stream()))\n .map(SimpleGrantedAuthority::new).toList();\n };\n }\n\n public interface Jwt2AuthenticationConverter extends Converter<Jwt, AbstractAuthenticationToken> {\n }\n\n @Bean\n public Jwt2AuthenticationConverter authenticationConverter(Jwt2AuthoritiesConverter authoritiesConverter) {\n return jwt -> new JwtAuthenticationToken(jwt, authoritiesConverter.convert(jwt));\n }\n\n @Bean\n public SecurityFilterChain apiFilterChain(HttpSecurity http, Converter<JWT, AbstractAuthenticationToken> authenticationConverter, ServerProperties serverProperties)\n throws Exception {\n\n // Enable OAuth2 with custom authorities mapping\n http.oauth2ResourceServer().jwt().jwtAuthenticationConverter(authenticationConverter);\n\n // Enable anonymous\n http.anonymous();\n\n // Enable and configure CORS\n http.cors().configurationSource(corsConfigurationSource());\n\n // State-less session (state in access-token only)\n http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);\n\n // Disable CSRF because of disabled sessions\n http.csrf().disable();\n\n // Return 401 (unauthorized) instead of 302 (redirect to login) when authorization is missing or invalid\n http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {\n response.addHeader(HttpHeaders.WWW_AUTHENTICATE, \"Basic realm=\\\"Restricted Content\\\"\");\n response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());\n });\n\n // If SSL enabled, disable http (https only)\n if (serverProperties.getSsl() != null && serverProperties.getSsl().isEnabled()) {\n http.requiresChannel().anyRequest().requiresSecure();\n } else {\n http.requiresChannel().anyRequest().requiresInsecure();\n }\n\n // Route security: authenticated to all routes but actuator and Swagger-UI\n // @formatter:off\n http.authorizeRequests()\n .antMatchers(\"/actuator/health/readiness\", \"/actuator/health/liveness\", \"/v3/api-docs/**\").permitAll()\n .anyRequest().authenticated();\n // @formatter:on\n\n return http.build();\n }\n\n private CorsConfigurationSource corsConfigurationSource() {\n // Very permissive CORS config...\n final var configuration = new CorsConfiguration();\n configuration.setAllowedOrigins(Arrays.asList(\"*\"));\n configuration.setAllowedMethods(Arrays.asList(\"*\"));\n configuration.setAllowedHeaders(Arrays.asList(\"*\"));\n configuration.setExposedHeaders(Arrays.asList(\"*\"));\n\n // Limited to API routes (neither actuator nor Swagger-UI)\n final var source = new UrlBasedCorsConfigurationSource();\n source.registerCorsConfiguration(\"/greet/**\", configuration);\n\n return source;\n }\n}\n spring.security.oauth2.resourceserver.jwt.issuer-uri=https://localhost:8443/realms/master\nspring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://localhost:8443/realms/master/protocol/openid-connect/certs\n <dependency>\n <groupId>com.c4-soft.springaddons</groupId>\n <!-- replace \"webmvc\" with \"weblux\" if your app is reactive -->\n <!-- replace \"jwt\" with \"introspecting\" to use token introspection instead of JWT decoding -->\n <artifactId>spring-addons-webmvc-jwt-resource-server</artifactId>\n <!-- this version is to be used with spring-boot 3.0.0, use 5.x for spring-boot 2.6.x or before -->\n <version>6.0.7</version>\n</dependency>\n @Configuration\n@EnableMethodSecurity\npublic static class WebSecurityConfig { }\n com.c4-soft.springaddons.security.issuers[0].location=https://localhost:8443/realms/realm1\ncom.c4-soft.springaddons.security.issuers[0].authorities.claims=realm_access.roles,ressource_access.some-client.roles,ressource_access.other-client.roles\n\n\ncom.c4-soft.springaddons.security.cors[0].path=/some-api\n issuers <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-oauth2-client</artifactId>\n </dependency>\n SecurityFilterChain securityMatcher SecurityFilterChain @Order(Ordered.HIGHEST_PRECEDENCE)\n @Bean\n SecurityFilterChain uiFilterChain(HttpSecurity http, ServerProperties serverProperties) throws Exception {\n\n // @formatter:off\n http.securityMatcher(new OrRequestMatcher(\n // add path to your UI elements instead\n new AntPathRequestMatcher(\"/ui/**\"),\n // those two are required to access Spring generated login page\n // and OAuth2 client callback endpoints\n new AntPathRequestMatcher(\"/login/**\"),\n new AntPathRequestMatcher(\"/oauth2/**\")));\n\n http.oauth2Login();\n http.authorizeHttpRequests()\n .requestMatchers(\"/ui/index.html\").permitAll()\n .requestMatchers(\"/login/**\").permitAll()\n .requestMatchers(\"/oauth2/**\").permitAll()\n .anyRequest().authenticated();\n // @formatter:on\n\n // If SSL enabled, disable http (https only)\n if (serverProperties.getSsl() != null && serverProperties.getSsl().isEnabled()) {\n http.requiresChannel().anyRequest().requiresSecure();\n } else {\n http.requiresChannel().anyRequest().requiresInsecure();\n }\n\n // Many defaults are kept compared to API filter-chain:\n // - sessions (and CSRF protection) are enabled\n // - unauthorized requests to secured resources will be redirected to login (302 to login is Spring's default response when access is denied)\n\n return http.build();\n }\n spring.security.oauth2.client.provider.keycloak.issuer-uri=https://localhost:8443/realms/master\n\nspring.security.oauth2.client.registration.spring-addons-public.provider=keycloak\nspring.security.oauth2.client.registration.spring-addons-public.client-name=spring-addons-public\nspring.security.oauth2.client.registration.spring-addons-public.client-id=spring-addons-public\nspring.security.oauth2.client.registration.spring-addons-public.scope=openid,offline_access,profile\nspring.security.oauth2.client.registration.spring-addons-public.authorization-grant-type=authorization_code\nspring.security.oauth2.client.registration.spring-addons-public.redirect-uri=http://bravo-ch4mp:8080/login/oauth2/code/spring-addons-public\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598202/" ]
74,571,192
<p>Hi I am sick of searching I could not find the exact code for my question. I need to code the sum of the odd numbers from 1 to 100 and sum of the even numbers from 2 to 100. This is what i have so far.</p> <p>Thank you so much</p> <pre><code>// 1) using for statement to Sum Up a Range of values using Interactive Console.WriteLine(&quot; Sum Up a Range of values entered by User &quot;); Console.WriteLine(); // 2) Declare the Variables to be used in the Project string strFromNumber, strToNumber; int fromNumber, toNumber; int sum = 0; int i, even = 0, odd = 0; int[] array = new int[10]; // 3) Prompt the User to Enter the From Number to Sum From Console.Write(&quot;Enter the From Number to Sum From: &quot;); strFromNumber = Console.ReadLine(); fromNumber = Convert.ToInt32(strFromNumber); // 4) Prompt the User to Enter the To Number to Sum To Console.Write(&quot;Enter the To Number to Sum To: &quot;); strToNumber = Console.ReadLine(); toNumber = Convert.ToInt32(strToNumber); // 5) Use for statement to Sum up the Range of Numbers for (i = fromNumber; i &lt;= toNumber; ++i) { sum += i; } if //(array[i] % 2 == 0) //here if condition to check number { // is divided by 2 or not even = even + array[i]; //here sum of even numbers will be stored in even } else { odd = odd + array[i]; //here sum of odd numbers will be stored in odd. } Console.WriteLine(&quot;The Sum of Values from {0} till {1} = {2}&quot;, fromNumber, toNumber, sum); Console.ReadLine(); </code></pre>
[ { "answer_id": 74571537, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 1, "selected": false, "text": "Sn = n/2[2a + (n − 1) × d] a n d Sn= n^2 n(n+1)" }, { "answer_id": 74571572, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "fromNumber .. toNumber number // long : since sum of int's can be large (beyond int.MaxValue) let's use long\nlong evenSum = 0;\nlong oddSum = 0;\n\nfor (int number = fromNumber; number <= toNumber; ++number) {\n if (number % 2 == 0)\n evenSum += number;\n else\n oddSum += number;\n}\n\nConsole.WriteLine($\"The Sum of Values from {fromNumber} till {toNumber}\");\nConsole.WriteLine($\"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).\");\n private static (long even, long odd) ComputeSums(long from, long to) {\n if (to < from)\n return (0, 0); // Or throw ArgumentOutOfRangeException\n\n long total = (to + from) * (to - from + 1) / 2;\n\n from = from / 2 * 2 + 1;\n to = (to + 1) / 2 * 2 - 1;\n\n long odd = (to + from) / 2 * ((to - from) / 2 + 1);\n\n return (total - odd, odd);\n}\n (long evenSum, long oddSum) = ComputeSums(fromNumber, toNumber);\n\nConsole.WriteLine($\"The Sum of Values from {fromNumber} till {toNumber}\");\nConsole.WriteLine($\"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).\");\n" }, { "answer_id": 74571738, "author": "pankaj_m05", "author_id": 12058318, "author_profile": "https://Stackoverflow.com/users/12058318", "pm_score": 0, "selected": false, "text": "f(n) = n^2 g(n) = n(n + 1) (l, r) = f(r) - f(l - 1) (l, r) = g(r) - g(l - 1)" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598174/" ]
74,571,201
<p>I'm a new rustacean and I try to pass a function as argument in another function in order to create threads with the function pass as argument.</p> <p>Here the code:</p> <pre><code>use std::os::unix::net::{UnixListener, UnixStream}; use std::thread; use std::io::Read; use anyhow::Context; pub struct SocketServer { path: String, listener: UnixListener, } impl SocketServer { pub fn new(path: &amp;str) -&gt; anyhow::Result&lt;SocketServer&gt;{ if std::fs::metadata(path).is_ok() { println!(&quot;A socket is already present. Deleting...&quot;); std::fs::remove_file(path).with_context(|| { format!(&quot;could not delete previous socket at {:?}&quot;, path) })?; } let socket_listener = UnixListener::bind(path).context(&quot;Could not create the unix socket&quot;)?; let path = path.to_string(); Ok(SocketServer{ path, listener: socket_listener }) } pub fn start(&amp;self, f: &amp;dyn Fn(UnixStream)) -&gt; anyhow::Result&lt;()&gt;{ for stream in self.listener.incoming() { match stream { Ok(stream) =&gt; { thread::spawn(||f(stream)); } Err(err) =&gt; {break;} } } Ok(()) } } pub fn handle_stream(mut unix_stream: UnixStream) -&gt; anyhow::Result&lt;()&gt; { let mut message = String::new(); unix_stream .read_to_string(&amp;mut message) .context(&quot;Failed at reading the unix stream&quot;)?; println!(&quot;We received this message: {}&quot;, message); Ok(()) } </code></pre> <p>Here the error I get when in try to compile:</p> <pre><code>error[E0277]: `dyn Fn(UnixStream)` cannot be shared between threads safely --&gt; src/socket.rs:34:35 | 34 | thread::spawn(||f(stream)); | ------------- ^^^^^^^^^^^ `dyn Fn(UnixStream)` cannot be shared between threads safely | | | required by a bound introduced by this call | = help: the trait `Sync` is not implemented for `dyn Fn(UnixStream)` = note: required for `&amp;dyn Fn(UnixStream)` to implement `Send` </code></pre> <p>I got some information in the Rust book but I still don't understand which function need to implement what. Can you give me some hints? (Advice on other parts are welcome too)</p> <p>I tried to remove closure but it goes to another error:</p> <pre><code>error[E0277]: expected a `FnOnce&lt;()&gt;` closure, found `()` --&gt; src/socket.rs:34:35 | 34 | thread::spawn(f(stream)); | ------------- ^^^^^^^^^ expected an `FnOnce&lt;()&gt;` closure, found `()` | | | required by a bound introduced by this call | = help: the trait `FnOnce&lt;()&gt;` is not implemented for `()` = note: wrap the `()` in a closure with no arguments: `|| { /* code */ }` note: required by a bound in `spawn` --&gt; /rust/lib/rustlib/src/rust/library/std/src/thread/mod.rs:661:8 | 661 | F: FnOnce() -&gt; T, | ^^^^^^^^^^^^^ required by this bound in `spawn` </code></pre>
[ { "answer_id": 74571537, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 1, "selected": false, "text": "Sn = n/2[2a + (n − 1) × d] a n d Sn= n^2 n(n+1)" }, { "answer_id": 74571572, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "fromNumber .. toNumber number // long : since sum of int's can be large (beyond int.MaxValue) let's use long\nlong evenSum = 0;\nlong oddSum = 0;\n\nfor (int number = fromNumber; number <= toNumber; ++number) {\n if (number % 2 == 0)\n evenSum += number;\n else\n oddSum += number;\n}\n\nConsole.WriteLine($\"The Sum of Values from {fromNumber} till {toNumber}\");\nConsole.WriteLine($\"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).\");\n private static (long even, long odd) ComputeSums(long from, long to) {\n if (to < from)\n return (0, 0); // Or throw ArgumentOutOfRangeException\n\n long total = (to + from) * (to - from + 1) / 2;\n\n from = from / 2 * 2 + 1;\n to = (to + 1) / 2 * 2 - 1;\n\n long odd = (to + from) / 2 * ((to - from) / 2 + 1);\n\n return (total - odd, odd);\n}\n (long evenSum, long oddSum) = ComputeSums(fromNumber, toNumber);\n\nConsole.WriteLine($\"The Sum of Values from {fromNumber} till {toNumber}\");\nConsole.WriteLine($\"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).\");\n" }, { "answer_id": 74571738, "author": "pankaj_m05", "author_id": 12058318, "author_profile": "https://Stackoverflow.com/users/12058318", "pm_score": 0, "selected": false, "text": "f(n) = n^2 g(n) = n(n + 1) (l, r) = f(r) - f(l - 1) (l, r) = g(r) - g(l - 1)" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18502921/" ]
74,571,215
<p>I need to find out all numbers with exactly one comma. I've got this regex,</p> <pre><code>[\d ,]+ </code></pre> <p>but it matches all numbers no matter how much commas is in the number.</p> <p>So, in this text</p> <pre><code>lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222 </code></pre> <p>it should match only first and last number:</p> <pre><code>49 877 989 888,33 1,222 </code></pre> <p>and NOT this</p> <pre><code>1,2,3 </code></pre>
[ { "answer_id": 74571286, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 1, "selected": false, "text": "\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n const text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nconsole.log(text.match(/\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g)); \\b (?<!\\d,) (?: \\d{1,3} (?: \\d{3})* \\s | \\d+ , \\d+ \\b (?!,\\d) (\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n var text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar regex = /(\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g;\nvar results = [], m;\nwhile (m = regex.exec(text)) {\n if (m[1] === undefined) results.push(m[0])\n}\nconsole.log(results);" }, { "answer_id": 74571379, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "\\b\\d+(?:[ ,]?\\d+)*\\b\n var input = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar nums = input.match(/\\b\\d+(?:[ ,]?\\d+)*\\b/g)\n .filter(x => !x.match(/,.*,/));\nconsole.log(nums);" }, { "answer_id": 74571475, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 0, "selected": false, "text": "(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)\n (?<!\\d\\s*,?) \\d+(?:\\s\\d+)*,\\d+ (?!,?\\s*\\d) var s_in = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar s_out = s_in.match(/(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)/g);\nconsole.log(s_out);" }, { "answer_id": 74571591, "author": "ZiTAL", "author_id": 454827, "author_profile": "https://Stackoverflow.com/users/454827", "pm_score": 0, "selected": false, "text": "let input = 'lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222'\n\nlet numbers = []\nlet words = input.split(/\\s+/)\nwords.forEach(function(w)\n{\n let nums = w.match(/\\d+(?:[,\\d]+)?/)\n if(nums)\n {\n let commas = nums[0].match(/,/g)\n if(commas)\n commas = commas.length\n else\n commas = 0\n if(commas<2)\n numbers.push(nums[0])\n }\n})\n\nconsole.log(numbers)\n [ '49', '877', '989', '888,33', '1,222' ]\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9125984/" ]
74,571,240
<pre class="lang-py prettyprint-override"><code>import openpyxl i=2 workbook= openpyxl.load_workbook() sheet = workbook.active for i, cellObj in enumerate (sheet['I'],2): cellObj.value = '=IF(ISNUMBER(A2)*(A2&lt;&gt;0),A2,IF(ISNUMBER(F2)*(F2&lt;&gt;0),F2,IF(ISBLANK(A2)*ISBLANK(F2)*ISBLANK(H2),0,H2)))' workbook.save() </code></pre> <p>Using openpxl, I tried to apply formula to entire column 'I' its not working as per the formula, I wanted formula to start from I2 but its start from I1 and wrong output as well.</p> <p>I have attached a screenshot.</p> <p><img src="https://i.stack.imgur.com/MXAY3.png" alt="output result in column I" />.</p> <p>Can someone please correct the code?</p> <p>Output of <code>print(list(enumerate(sheet['I'])))</code>:</p> <p><img src="https://i.stack.imgur.com/DEKDh.png" alt="Output" /></p>
[ { "answer_id": 74571286, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 1, "selected": false, "text": "\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n const text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nconsole.log(text.match(/\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g)); \\b (?<!\\d,) (?: \\d{1,3} (?: \\d{3})* \\s | \\d+ , \\d+ \\b (?!,\\d) (\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n var text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar regex = /(\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g;\nvar results = [], m;\nwhile (m = regex.exec(text)) {\n if (m[1] === undefined) results.push(m[0])\n}\nconsole.log(results);" }, { "answer_id": 74571379, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "\\b\\d+(?:[ ,]?\\d+)*\\b\n var input = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar nums = input.match(/\\b\\d+(?:[ ,]?\\d+)*\\b/g)\n .filter(x => !x.match(/,.*,/));\nconsole.log(nums);" }, { "answer_id": 74571475, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 0, "selected": false, "text": "(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)\n (?<!\\d\\s*,?) \\d+(?:\\s\\d+)*,\\d+ (?!,?\\s*\\d) var s_in = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar s_out = s_in.match(/(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)/g);\nconsole.log(s_out);" }, { "answer_id": 74571591, "author": "ZiTAL", "author_id": 454827, "author_profile": "https://Stackoverflow.com/users/454827", "pm_score": 0, "selected": false, "text": "let input = 'lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222'\n\nlet numbers = []\nlet words = input.split(/\\s+/)\nwords.forEach(function(w)\n{\n let nums = w.match(/\\d+(?:[,\\d]+)?/)\n if(nums)\n {\n let commas = nums[0].match(/,/g)\n if(commas)\n commas = commas.length\n else\n commas = 0\n if(commas<2)\n numbers.push(nums[0])\n }\n})\n\nconsole.log(numbers)\n [ '49', '877', '989', '888,33', '1,222' ]\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598085/" ]
74,571,274
<p>Im trying to make the inner html of a div to change colors. My div looks like this</p> <pre><code>&lt;div class = 'child'&gt; &lt;span class=&quot;color&quot;&gt;F&lt;/span&gt; &lt;span class=&quot;color&quot;&gt;u&lt;/span&gt; &lt;span class=&quot;color&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;color&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;color&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;color&quot;&gt; &lt;/span&gt; &lt;span class=&quot;color&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;color&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;color&quot;&gt;o&lt;/span&gt; &lt;span class=&quot;color&quot;&gt;k&lt;/span&gt; &lt;/div&gt; </code></pre> <p>and my javascript looks like this</p> <pre><code>var value = document.getElementsByClassName(&quot;child&quot;)[0].innerHTML; bannerArray = value.split(&quot;&quot;); var colourArray = [ &quot;rgb(248, 116, 138)&quot;, &quot;rgb(248, 125, 145)&quot;, &quot;rgb(248, 140, 160)&quot;, &quot;rgb(248, 160, 180)&quot;, &quot;rgb(248, 175, 195)&quot;, &quot;pink&quot;, &quot;rgb(248, 195, 215)&quot;, &quot;rgb(248, 205, 235)&quot;, &quot;rgb(248, 225, 225)&quot;, ]; for ( let i = 0; i &lt; colourArray.length; i++) { for ( let j = 0; j &lt; bannerArray.length; j++) { document.getElementsByClassName(&quot;color&quot;)[j].style.color = colourArray[i]; } } </code></pre> <p>the result of that code is basically every letter in the banner array gets the first color from the color array, then the second color, until i end up with all the letters being the last color ie rgb(248, 225, 225). What id like is the first color to pass through the first letter, then move to the second letter, then have the first letter take the second color in the color array, then the second color to move to the second letter, then the first letter to take the third color in the array and so on and so forth like marque for lack of a better description, So very sorry for the wall of text.</p>
[ { "answer_id": 74571286, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 1, "selected": false, "text": "\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n const text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nconsole.log(text.match(/\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g)); \\b (?<!\\d,) (?: \\d{1,3} (?: \\d{3})* \\s | \\d+ , \\d+ \\b (?!,\\d) (\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n var text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar regex = /(\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g;\nvar results = [], m;\nwhile (m = regex.exec(text)) {\n if (m[1] === undefined) results.push(m[0])\n}\nconsole.log(results);" }, { "answer_id": 74571379, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "\\b\\d+(?:[ ,]?\\d+)*\\b\n var input = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar nums = input.match(/\\b\\d+(?:[ ,]?\\d+)*\\b/g)\n .filter(x => !x.match(/,.*,/));\nconsole.log(nums);" }, { "answer_id": 74571475, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 0, "selected": false, "text": "(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)\n (?<!\\d\\s*,?) \\d+(?:\\s\\d+)*,\\d+ (?!,?\\s*\\d) var s_in = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar s_out = s_in.match(/(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)/g);\nconsole.log(s_out);" }, { "answer_id": 74571591, "author": "ZiTAL", "author_id": 454827, "author_profile": "https://Stackoverflow.com/users/454827", "pm_score": 0, "selected": false, "text": "let input = 'lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222'\n\nlet numbers = []\nlet words = input.split(/\\s+/)\nwords.forEach(function(w)\n{\n let nums = w.match(/\\d+(?:[,\\d]+)?/)\n if(nums)\n {\n let commas = nums[0].match(/,/g)\n if(commas)\n commas = commas.length\n else\n commas = 0\n if(commas<2)\n numbers.push(nums[0])\n }\n})\n\nconsole.log(numbers)\n [ '49', '877', '989', '888,33', '1,222' ]\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13713975/" ]
74,571,275
<p>I have been struggling with z-index . On clicking on a div , I'm trying to show a popup that should come over other elements . But it's not working as expected</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.popup-container { height: 1000px; position: relative; } .popup-trigger { width: 100%; height: 30px; color: #fff; background-color: blue; } .popup { position: absolute; z-index: 5; top: 0; right: -8%; height: 100px; width: 100px; background-color: green; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="popup-container"&gt; &lt;div class="popup-trigger"&gt;Popup trigger!!&lt;/div&gt; &lt;div class="popup"&gt; &lt;p&gt;I'm a popup and I want to come over column-2&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I have attached my <a href="https://stackblitz.com/edit/web-platform-p8a5x7?file=styles.css" rel="nofollow noreferrer">Stackblitz</a> here that I have tried . Please help</p>
[ { "answer_id": 74571286, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 1, "selected": false, "text": "\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n const text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nconsole.log(text.match(/\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g)); \\b (?<!\\d,) (?: \\d{1,3} (?: \\d{3})* \\s | \\d+ , \\d+ \\b (?!,\\d) (\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n var text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar regex = /(\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g;\nvar results = [], m;\nwhile (m = regex.exec(text)) {\n if (m[1] === undefined) results.push(m[0])\n}\nconsole.log(results);" }, { "answer_id": 74571379, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "\\b\\d+(?:[ ,]?\\d+)*\\b\n var input = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar nums = input.match(/\\b\\d+(?:[ ,]?\\d+)*\\b/g)\n .filter(x => !x.match(/,.*,/));\nconsole.log(nums);" }, { "answer_id": 74571475, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 0, "selected": false, "text": "(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)\n (?<!\\d\\s*,?) \\d+(?:\\s\\d+)*,\\d+ (?!,?\\s*\\d) var s_in = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar s_out = s_in.match(/(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)/g);\nconsole.log(s_out);" }, { "answer_id": 74571591, "author": "ZiTAL", "author_id": 454827, "author_profile": "https://Stackoverflow.com/users/454827", "pm_score": 0, "selected": false, "text": "let input = 'lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222'\n\nlet numbers = []\nlet words = input.split(/\\s+/)\nwords.forEach(function(w)\n{\n let nums = w.match(/\\d+(?:[,\\d]+)?/)\n if(nums)\n {\n let commas = nums[0].match(/,/g)\n if(commas)\n commas = commas.length\n else\n commas = 0\n if(commas<2)\n numbers.push(nums[0])\n }\n})\n\nconsole.log(numbers)\n [ '49', '877', '989', '888,33', '1,222' ]\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12306627/" ]
74,571,281
<p>We have been asked to check if files exists in a SFTP remote directory, on a server outside our organisation, and send an email if it does exist.</p> <p>I have the IP address, an account, and a password.</p> <p>I found this powershell script <a href="https://www.tech2tech.fr/powershell-surveiller-des-fichiers-avec-envoi-de-mail/" rel="nofollow noreferrer">https://www.tech2tech.fr/powershell-surveiller-des-fichiers-avec-envoi-de-mail/</a> , but... How can i make it work on a remote directory, using credential to access it?</p> <p>I also try using ftp command, but can't find a way to check if many files exist, and not only one.</p> <p>Does anyone have a solution or a way to help me?</p> <p>Thanks in advance !</p>
[ { "answer_id": 74571286, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 1, "selected": false, "text": "\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n const text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nconsole.log(text.match(/\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g)); \\b (?<!\\d,) (?: \\d{1,3} (?: \\d{3})* \\s | \\d+ , \\d+ \\b (?!,\\d) (\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n var text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar regex = /(\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g;\nvar results = [], m;\nwhile (m = regex.exec(text)) {\n if (m[1] === undefined) results.push(m[0])\n}\nconsole.log(results);" }, { "answer_id": 74571379, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "\\b\\d+(?:[ ,]?\\d+)*\\b\n var input = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar nums = input.match(/\\b\\d+(?:[ ,]?\\d+)*\\b/g)\n .filter(x => !x.match(/,.*,/));\nconsole.log(nums);" }, { "answer_id": 74571475, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 0, "selected": false, "text": "(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)\n (?<!\\d\\s*,?) \\d+(?:\\s\\d+)*,\\d+ (?!,?\\s*\\d) var s_in = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar s_out = s_in.match(/(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)/g);\nconsole.log(s_out);" }, { "answer_id": 74571591, "author": "ZiTAL", "author_id": 454827, "author_profile": "https://Stackoverflow.com/users/454827", "pm_score": 0, "selected": false, "text": "let input = 'lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222'\n\nlet numbers = []\nlet words = input.split(/\\s+/)\nwords.forEach(function(w)\n{\n let nums = w.match(/\\d+(?:[,\\d]+)?/)\n if(nums)\n {\n let commas = nums[0].match(/,/g)\n if(commas)\n commas = commas.length\n else\n commas = 0\n if(commas<2)\n numbers.push(nums[0])\n }\n})\n\nconsole.log(numbers)\n [ '49', '877', '989', '888,33', '1,222' ]\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20447697/" ]
74,571,292
<p>I want to change the following variable to false using the onclick method of a button in my shared navbar.</p> <p><strong>Variable</strong></p> <pre><code>public static bool LoginStatus { get; set; } = true; </code></pre> <p>What I have so far which does not work:</p> <p><strong>Html button</strong></p> <pre><code>&lt;button type=&quot;button&quot; class=&quot;btn btn-primary&quot; onclick=@Apex_Leaderboard_Website.Models.LoginViewModel.LoginStatus = false&gt;Log Out&lt;/button&gt; </code></pre> <p>I have tried a form but with the button in the shared navbar it makes it difficult to submit it to the appropriate handler.</p>
[ { "answer_id": 74571286, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 1, "selected": false, "text": "\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n const text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nconsole.log(text.match(/\\b(?<!\\d,)(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g)); \\b (?<!\\d,) (?: \\d{1,3} (?: \\d{3})* \\s | \\d+ , \\d+ \\b (?!,\\d) (\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)\n var text = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar regex = /(\\d,)?\\b(?:\\d{1,3}(?: \\d{3})*|\\d+),\\d+\\b(?!,\\d)/g;\nvar results = [], m;\nwhile (m = regex.exec(text)) {\n if (m[1] === undefined) results.push(m[0])\n}\nconsole.log(results);" }, { "answer_id": 74571379, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "\\b\\d+(?:[ ,]?\\d+)*\\b\n var input = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar nums = input.match(/\\b\\d+(?:[ ,]?\\d+)*\\b/g)\n .filter(x => !x.match(/,.*,/));\nconsole.log(nums);" }, { "answer_id": 74571475, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 0, "selected": false, "text": "(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)\n (?<!\\d\\s*,?) \\d+(?:\\s\\d+)*,\\d+ (?!,?\\s*\\d) var s_in = \"lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222\";\nvar s_out = s_in.match(/(?<!\\d\\s*,?)\\d+(?:\\s\\d+)*,\\d+(?!,?\\s*\\d)/g);\nconsole.log(s_out);" }, { "answer_id": 74571591, "author": "ZiTAL", "author_id": 454827, "author_profile": "https://Stackoverflow.com/users/454827", "pm_score": 0, "selected": false, "text": "let input = 'lorem 49 877 989 888,33 ipsum 1,2,3 dfgdfgdf 1,222'\n\nlet numbers = []\nlet words = input.split(/\\s+/)\nwords.forEach(function(w)\n{\n let nums = w.match(/\\d+(?:[,\\d]+)?/)\n if(nums)\n {\n let commas = nums[0].match(/,/g)\n if(commas)\n commas = commas.length\n else\n commas = 0\n if(commas<2)\n numbers.push(nums[0])\n }\n})\n\nconsole.log(numbers)\n [ '49', '877', '989', '888,33', '1,222' ]\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598285/" ]
74,571,312
<p>I try to go to a speific page on initComplete:</p> <pre><code>var table = $('#example').dataTable( {   &quot;initComplete&quot;: function( settings, json ) {     table.page(5).draw(false);   } } ); </code></pre> <p>But it is not working. My page is still at page 1.</p>
[ { "answer_id": 74571490, "author": "john Smith", "author_id": 1712905, "author_profile": "https://Stackoverflow.com/users/1712905", "pm_score": 0, "selected": false, "text": "table var table = $('#example').DataTable( {\n \"initComplete\": function( settings, json ) {\n settings.oInstance.api().page(5).draw(false);\n }\n});\n" }, { "answer_id": 74571510, "author": "freedomn-m", "author_id": 2181514, "author_profile": "https://Stackoverflow.com/users/2181514", "pm_score": 2, "selected": true, "text": ".DataTable dataTable initComplete .DataTable({}) table \"initComplete\": function (settings, json) {\n console.log(table);\n //table.page(5).draw(false);\n }\n initComplete this table .DataTable this $('#example').DataTable({\n \"pageLength\": 2,\n \"initComplete\": function(settings, json) {\n $(this).DataTable().page(5).draw(false);\n }\n}); <link href=\"https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css\" rel=\"stylesheet\">\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js\"></script>\n\n<table id=\"example\" class=\"display\">\n <thead>\n <tr>\n <th>Company name</th>\n <th>Address</th>\n <th>Town</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Emkay Entertainments</td>\n <td>Nobel House, Regent Centre</td>\n <td>Lothian</td>\n </tr>\n <tr>\n <td>The Empire</td>\n <td>Milton Keynes Leisure Plaza</td>\n <td>Buckinghamshire</td>\n </tr>\n <tr>\n <td>Emkay Entertainments</td>\n <td>Nobel House, Regent Centre</td>\n <td>Lothian</td>\n </tr>\n <tr>\n <td>The Empire</td>\n <td>Milton Keynes Leisure Plaza</td>\n <td>Buckinghamshire</td>\n </tr>\n <tr>\n <td>Emkay Entertainments</td>\n <td>Nobel House, Regent Centre</td>\n <td>Lothian</td>\n </tr>\n <tr>\n <td>The Empire</td>\n <td>Milton Keynes Leisure Plaza</td>\n <td>Buckinghamshire</td>\n </tr>\n <tr>\n <td>Emkay Entertainments</td>\n <td>Nobel House, Regent Centre</td>\n <td>Lothian</td>\n </tr>\n <tr>\n <td>The Empire</td>\n <td>Milton Keynes Leisure Plaza</td>\n <td>Buckinghamshire</td>\n </tr>\n <tr>\n <td>Emkay Entertainments</td>\n <td>Nobel House, Regent Centre</td>\n <td>Lothian</td>\n </tr>\n <tr>\n <td>The Empire</td>\n <td>Milton Keynes Leisure Plaza</td>\n <td>Buckinghamshire</td>\n </tr>\n <tr>\n <td>Emkay Entertainments</td>\n <td>Nobel House, Regent Centre</td>\n <td>Lothian</td>\n </tr>\n <tr>\n <td>The Empire</td>\n <td>Milton Keynes Leisure Plaza</td>\n <td>Buckinghamshire</td>\n </tr>\n <tr>\n <td>Emkay Entertainments</td>\n <td>Nobel House, Regent Centre</td>\n <td>Lothian</td>\n </tr>\n <tr>\n <td>The Empire</td>\n <td>Milton Keynes Leisure Plaza</td>\n <td>Buckinghamshire</td>\n </tr>\n <tr>\n <td>Emkay Entertainments</td>\n <td>Nobel House, Regent Centre</td>\n <td>Lothian</td>\n </tr>\n <tr>\n <td>The Empire</td>\n <td>Milton Keynes Leisure Plaza</td>\n <td>Buckinghamshire</td>\n </tr>\n <tr>\n <td>Emkay Entertainments</td>\n <td>Nobel House, Regent Centre</td>\n <td>Lothian</td>\n </tr>\n <tr>\n <td>The Empire</td>\n <td>Milton Keynes Leisure Plaza</td>\n <td>Buckinghamshire</td>\n </tr>\n </tbody>\n</table>" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5024157/" ]
74,571,318
<p>My supplier entity has enum property notifyType. Any idea how translate the enum this way?</p> <pre><code>{{ supplier.notifyType|trans }} </code></pre> <p>Unfortunately, use __toString method in Enum is not possible.</p> <pre class="lang-php prettyprint-override"><code>// error - Enum may not include __toString public function __toString(): string { return 'supplier.notify.'.$this-&gt;name; } </code></pre> <p>Then I just tried this:</p> <pre class="lang-php prettyprint-override"><code>use Symfony\Contracts\Translation\TranslatableInterface; use Symfony\Contracts\Translation\TranslatorInterface; enum NotifyType: int implements TranslatableInterface { case EMAIL = 1; case WEBHOOK = 2; case PUNCH_OUT = 4; public function trans(TranslatorInterface $translator, string $locale = null): string { return $translator-&gt;trans('supplier.notify.'.$this-&gt;name, locale: $locale); } } </code></pre> <p>But it's not possible pass translatable object to trans method. String only accepted.</p> <pre class="lang-php prettyprint-override"><code>$this-&gt;translator-&gt;trans(NotifyType::EMAIL); // error: must be of type string </code></pre>
[ { "answer_id": 74626011, "author": "hugo schweitzer", "author_id": 9284519, "author_profile": "https://Stackoverflow.com/users/9284519", "pm_score": 0, "selected": false, "text": "|trans TranslatorExtension trans string|\\Stringable|TranslatableInterface|null |trans TranslatorExtension getTransString 'supplier.notify.'. $this->name {{ supplier.notifyType.getTransString|trans }} class EnumTranslationService\n{\n public function __construct(private readonly TranslatorInterface $translator)\n {\n }\n\n public function translateNotifyType(NotifyType $notifyType): string\n {\n return $this->translator->trans('supplier.notify.' . $notifyType->name);\n }\n}\n class AppExtension extends AbstractExtension\n{\n public function getFilters(): array\n {\n return [\n new TwigFilter('transNotifyType', [EnumTranslationService::class, 'translateNotifyType'])\n ];\n }\n}\n {{ supplier.notifyType|transNotifyType }}\n" }, { "answer_id": 74642943, "author": "CAVASIN Florian", "author_id": 6409747, "author_profile": "https://Stackoverflow.com/users/6409747", "pm_score": 3, "selected": true, "text": "NotifyType::EMAIL->trans($this->translator) TranslatableInterface translation:extract trans id match PHP >= 8.1 enum NotifyType: int implements TranslatableInterface\n{\n case EMAIL = 1;\n case WEBHOOK = 2;\n case PUNCH_OUT = 4;\n\n public function trans(TranslatorInterface $translator, string $locale = null): string\n {\n return match ($this) {\n self::EMAIL => $translator->trans('supplier.notify.email'),\n self::WEBHOOK => $translator->trans('supplier.notify.webhook'),\n self::PUNCH_OUT => $translator->trans('supplier.notify.punch_out'),\n };\n }\n}\n NotifyType::EMAIL->trans($this->translator) {{ supplier.notifyType | trans }} {{ supplier.notifyType.value | trans }} {{ supplier.notifyType.name | trans }}" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2999149/" ]
74,571,338
<p><a href="https://i.stack.imgur.com/VakFl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VakFl.png" alt="values" /></a></p> <p>i create an array with the information above.</p> <pre><code>Dim arr As Variant arr = ActiveSheet.Range(&quot;F2:F&quot; &amp; Range(&quot;F1&quot;).End(xlDown).Row).Value </code></pre> <p>Now i want to look in a range, if a value from array is in the range. if yes than change the color for this matching cell.</p> <pre><code>Set ws = Workbooks(&quot;test.xlsx&quot;).Worksheets(&quot;test&quot;) For i = 2 To Range(&quot;A2&quot;).End(xlDown).Row For j = 1 To UBound(arr, 1) If arr(j) = Cells(i, 7).Value Then Cells(i, 7).Interior.color = RGB(180, 198, 231) Next Next </code></pre> <p>i get a type mismatch error when starting the second loop</p>
[ { "answer_id": 74626011, "author": "hugo schweitzer", "author_id": 9284519, "author_profile": "https://Stackoverflow.com/users/9284519", "pm_score": 0, "selected": false, "text": "|trans TranslatorExtension trans string|\\Stringable|TranslatableInterface|null |trans TranslatorExtension getTransString 'supplier.notify.'. $this->name {{ supplier.notifyType.getTransString|trans }} class EnumTranslationService\n{\n public function __construct(private readonly TranslatorInterface $translator)\n {\n }\n\n public function translateNotifyType(NotifyType $notifyType): string\n {\n return $this->translator->trans('supplier.notify.' . $notifyType->name);\n }\n}\n class AppExtension extends AbstractExtension\n{\n public function getFilters(): array\n {\n return [\n new TwigFilter('transNotifyType', [EnumTranslationService::class, 'translateNotifyType'])\n ];\n }\n}\n {{ supplier.notifyType|transNotifyType }}\n" }, { "answer_id": 74642943, "author": "CAVASIN Florian", "author_id": 6409747, "author_profile": "https://Stackoverflow.com/users/6409747", "pm_score": 3, "selected": true, "text": "NotifyType::EMAIL->trans($this->translator) TranslatableInterface translation:extract trans id match PHP >= 8.1 enum NotifyType: int implements TranslatableInterface\n{\n case EMAIL = 1;\n case WEBHOOK = 2;\n case PUNCH_OUT = 4;\n\n public function trans(TranslatorInterface $translator, string $locale = null): string\n {\n return match ($this) {\n self::EMAIL => $translator->trans('supplier.notify.email'),\n self::WEBHOOK => $translator->trans('supplier.notify.webhook'),\n self::PUNCH_OUT => $translator->trans('supplier.notify.punch_out'),\n };\n }\n}\n NotifyType::EMAIL->trans($this->translator) {{ supplier.notifyType | trans }} {{ supplier.notifyType.value | trans }} {{ supplier.notifyType.name | trans }}" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598301/" ]
74,571,369
<p>I am trying to merge a few PDFs and keep the nested bookmarks all pdfs have a content parent in common when only one is needed, when i use the code below only the bookmarks of the last pdf in the folder are present in the merge, can anyone advise on what i need to change to have all the bookmarks preserved and a shared contents parent? content bookmark bookmark bookmark</p> <pre><code>from PyPDF2 import PdfFileMerger, PdfFileReader import os from os import listdir from os.path import isfile, join os.chdir('filepath') source_dir = 'filepath' onlyfiles = [f for f in listdir('filepath') if isfile(join('filepath', f))] for file in source_dir: fileReader = PdfFileReader(open(file,'rb')) outlines = fileReader.getOutlines() merger = PdfFileMerger(strict=False) for item in os.listdir(source_dir): if item.endswith('pdf'): merger.bookmarks = outlines merger.append(item) merger.write('merged.pdf') merger.close() </code></pre>
[ { "answer_id": 74626011, "author": "hugo schweitzer", "author_id": 9284519, "author_profile": "https://Stackoverflow.com/users/9284519", "pm_score": 0, "selected": false, "text": "|trans TranslatorExtension trans string|\\Stringable|TranslatableInterface|null |trans TranslatorExtension getTransString 'supplier.notify.'. $this->name {{ supplier.notifyType.getTransString|trans }} class EnumTranslationService\n{\n public function __construct(private readonly TranslatorInterface $translator)\n {\n }\n\n public function translateNotifyType(NotifyType $notifyType): string\n {\n return $this->translator->trans('supplier.notify.' . $notifyType->name);\n }\n}\n class AppExtension extends AbstractExtension\n{\n public function getFilters(): array\n {\n return [\n new TwigFilter('transNotifyType', [EnumTranslationService::class, 'translateNotifyType'])\n ];\n }\n}\n {{ supplier.notifyType|transNotifyType }}\n" }, { "answer_id": 74642943, "author": "CAVASIN Florian", "author_id": 6409747, "author_profile": "https://Stackoverflow.com/users/6409747", "pm_score": 3, "selected": true, "text": "NotifyType::EMAIL->trans($this->translator) TranslatableInterface translation:extract trans id match PHP >= 8.1 enum NotifyType: int implements TranslatableInterface\n{\n case EMAIL = 1;\n case WEBHOOK = 2;\n case PUNCH_OUT = 4;\n\n public function trans(TranslatorInterface $translator, string $locale = null): string\n {\n return match ($this) {\n self::EMAIL => $translator->trans('supplier.notify.email'),\n self::WEBHOOK => $translator->trans('supplier.notify.webhook'),\n self::PUNCH_OUT => $translator->trans('supplier.notify.punch_out'),\n };\n }\n}\n NotifyType::EMAIL->trans($this->translator) {{ supplier.notifyType | trans }} {{ supplier.notifyType.value | trans }} {{ supplier.notifyType.name | trans }}" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20242302/" ]
74,571,370
<p>I have this struct in my server and client</p> <pre><code>typedef struct email{ unsigned char * message; }mail; </code></pre> <p>And I want to send it through TCP sockets in C. But I have problems when the struct contains a pointer. I want to send all together, not parameter by parameter</p> <p>I have this code for server and client:</p> <p>Client:</p> <pre><code> mail messageServer; printf(&quot;Choose message: &quot;); scanf(&quot;%s&quot;,messageServer.message); printf(&quot;Message: %s\n&quot;, messageServer.message); send(fd, &amp;messageServer, sizeof(struct email), 0); </code></pre> <p>Server:</p> <pre><code>mail messageServer; printf(&quot;Before recv\n&quot;); recv(fd2, &amp;messageServer, sizeof(struct email), 0); printf(&quot;After recv&quot;); printf(&quot;Message: %s\n&quot;,messageServer.message); </code></pre> <p>But when I execute it, I have a segmentation fault on server</p>
[ { "answer_id": 74626011, "author": "hugo schweitzer", "author_id": 9284519, "author_profile": "https://Stackoverflow.com/users/9284519", "pm_score": 0, "selected": false, "text": "|trans TranslatorExtension trans string|\\Stringable|TranslatableInterface|null |trans TranslatorExtension getTransString 'supplier.notify.'. $this->name {{ supplier.notifyType.getTransString|trans }} class EnumTranslationService\n{\n public function __construct(private readonly TranslatorInterface $translator)\n {\n }\n\n public function translateNotifyType(NotifyType $notifyType): string\n {\n return $this->translator->trans('supplier.notify.' . $notifyType->name);\n }\n}\n class AppExtension extends AbstractExtension\n{\n public function getFilters(): array\n {\n return [\n new TwigFilter('transNotifyType', [EnumTranslationService::class, 'translateNotifyType'])\n ];\n }\n}\n {{ supplier.notifyType|transNotifyType }}\n" }, { "answer_id": 74642943, "author": "CAVASIN Florian", "author_id": 6409747, "author_profile": "https://Stackoverflow.com/users/6409747", "pm_score": 3, "selected": true, "text": "NotifyType::EMAIL->trans($this->translator) TranslatableInterface translation:extract trans id match PHP >= 8.1 enum NotifyType: int implements TranslatableInterface\n{\n case EMAIL = 1;\n case WEBHOOK = 2;\n case PUNCH_OUT = 4;\n\n public function trans(TranslatorInterface $translator, string $locale = null): string\n {\n return match ($this) {\n self::EMAIL => $translator->trans('supplier.notify.email'),\n self::WEBHOOK => $translator->trans('supplier.notify.webhook'),\n self::PUNCH_OUT => $translator->trans('supplier.notify.punch_out'),\n };\n }\n}\n NotifyType::EMAIL->trans($this->translator) {{ supplier.notifyType | trans }} {{ supplier.notifyType.value | trans }} {{ supplier.notifyType.name | trans }}" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74571370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18770252/" ]