Saturday, June 19, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


std([0,3]) in Matlab doesn't give the standard deviation

Posted: 19 Jun 2021 10:10 AM PDT

I'm trying to compute the standard deviation of the vector [0,3] in Matlab but std(0,3]) doesn't yield the right result, please see the snippet below.

enter image description here

How to make social media share link

Posted: 19 Jun 2021 10:10 AM PDT

I want to generate a share link for Quora. And add it as HTML into a button so that on clicking to the button webiste directly share to that app.

For example this HTML trigges link sharing for whatsapp.

<a class='whatsapp' expr:href='&quot;https://api.whatsapp.com/send?text=&quot; + data:blog.url.canonical' rel='nofollow noreferrer' role='button' target='_blank'>  

In the very same way I want it from Quora. Anyone help please

"sharing" token cookie when using several http clients

Posted: 19 Jun 2021 10:09 AM PDT

I'm writing a VueJS application (so it runs on browser!)

I'm using Axios for a lot of rest api calls but when it comes to streaming, Axios does only provide some file streaming feature, not a feature like the one provided by stream-http. So I'm trying to use stream-http to manage long rest api calls in a somewhat stream mode.

Now the issue:

When I login, I do it with axios and receives the token cookie from the server. Subsequent calls to axios (using the withCredential option) send back the cookie to the server ==> it works. Traces on server side:

>headers { host: 'localhost:4000',    'user-agent':     'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0',    accept: 'application/json, text/plain, */*',    'accept-language': 'fr-FR,fr;q=0.5',    'accept-encoding': 'gzip, deflate',    'access-control-allow-origin': '*',    origin: 'http://localhost:8080',    dnt: '1',    connection: 'keep-alive',    referer: 'http://localhost:8080/',    cookie:     'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MjQxMjExMjEsImV4cCI6MTYyNDEyNDcyMX0.YaBZGlEC1MT-bMaDunHIEHTzLA4R9DLmq1WCk45cs9I',    pragma: 'no-cache',    'cache-control': 'no-cache' }   

But when I call a rest endpoint with stream-http, the cookie is not sent. Traces:

>headers { host: 'localhost:4000',    'user-agent':     'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0',    accept: '*/*',    'accept-language': 'fr-FR,fr;q=0.5',    'accept-encoding': 'gzip, deflate',    'access-control-request-method': 'POST',    'access-control-request-headers': 'access-control-allow-origin,content-type,set-cookie',    referer: 'http://localhost:8080/',    origin: 'http://localhost:8080',    dnt: '1',    connection: 'keep-alive',    pragma: 'no-cache',    'cache-control': 'no-cache' }   

As it's impossible to access the token in javascript in the browser (secure mode prevent it), I can't force it in stream-http calls. How to deal with this?

How to render a page which have data comming from controller to javascript in thymeleaf

Posted: 19 Jun 2021 10:09 AM PDT

I have made a simple login page and showing success message with the help of sweetalert2 but the page in which I have written the script getting errors

There was an unexpected error (type=Internal Server Error, status=500).  An error happened during template parsing (template: "class path resource [templates/home.html]")  org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/home.html]")      at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)      at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100)      at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666)      at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)      at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072)      at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:366)      at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:190)      at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1396)      at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1141)      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080)      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)      at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)      at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)      at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)      at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)      at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)      at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)      at java.base/java.lang.Thread.run(Thread.java:834)  Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "swalf.text" (template: "home" - line 50, col 14)      at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)      at org.attoparser.MarkupParser.parse(MarkupParser.java:257)      at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)      ... 48 more  Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "swalf.text" (template: "home" - line 50, col 14)      at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:292)      at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)      at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)      at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)      at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)      at org.thymeleaf.standard.processor.AbstractStandardExpressionAttributeTagProcessor.doProcess(AbstractStandardExpressionAttributeTagProcessor.java:144)      at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)      at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)      at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)      at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314)      at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleOpenElementEnd(TemplateHandlerAdapterMarkupHandler.java:304)      at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleOpenElementEnd(InlinedOutputExpressionMarkupHandler.java:278)      at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.performInlining(OutputExpressionInlinePreProcessorHandler.java:440)      at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleText(OutputExpressionInlinePreProcessorHandler.java:146)      at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleText(InlinedOutputExpressionMarkupHandler.java:80)      at org.attoparser.HtmlMarkupHandler.handleText(HtmlMarkupHandler.java:208)      at org.attoparser.AbstractChainedMarkupHandler.handleText(AbstractChainedMarkupHandler.java:203)      at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:557)      at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)      ... 50 more  Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'text' cannot be found on null      at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:213)      at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104)      at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:51)      at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:406)      at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:92)      at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:112)      at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:337)      at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:265)      ... 68 more  

HTML page is-

    <!doctype html>  <html lang="en" xmlns:th="http://www.thymeleaf.com">  <head>  <!-- Required meta tags -->  <meta charset="utf-8">  <meta name="viewport"      content="width=device-width, initial-scale=1, shrink-to-fit=no">    <!-- Bootstrap CSS -->     <title>Hello, world!</title>  </head>  <body>      <form class="container mt-5" th:action="@{/saveuser}" th:object="${user}" method="post">      <div class="form-group">              <label for="name">Name</label> <input                  type="text" class="form-control" id="name" th:field="*{name}"                  aria-describedby="emailHelp">          </div>          <div class="form-group">              <label for="exampleInputEmail1">Email address</label> <input                  type="email" class="form-control" id="exampleInputEmail1" th:field="*{email}"                  aria-describedby="emailHelp">          </div>          <div class="form-group">              <label for="exampleInputPassword1">Password</label> <input th:field="*{password}"                  type="text" class="form-control" id="exampleInputPassword1">           </div>                <button type="submit" class="btn btn-primary">Submit</button>      </form>        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"          integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"          crossorigin="anonymous"></script>      <script          src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"          integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"          crossorigin="anonymous"></script>      <script          src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"          integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF"          crossorigin="anonymous"></script>               <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>           <script>      var text="[[${swalf.text}]]";      var content="[[${swalf.content}]]";          var type="[[${swalf.type}]]";          console.log(text+",  "+content+",  "+type);      console.log(text+" "+content+" "+type);      Swal.fire(              text,                content,                type              )       </script>    </body>  </html>  

Help me out how can I normal render my page and showing success message with the same page with sweetalert js which is sending data from controller.

how disable Excel Errore in vba?

Posted: 19 Jun 2021 10:09 AM PDT

how disable excel error in vba , (error dialog)

enter image description here

Pine Script code for timestamp on Trading View does not filter through the dates that I want it to view. How can I adjust this?

Posted: 19 Jun 2021 10:09 AM PDT

I am trying to run this script on Pinescript in Trading View. However, when I try to add in timestamp, it does not work. Can someone help with this?

strategy("My Strategy", overlay=true)    start = timestamp(2007, 1, 1, 0, 0)  end = timestamp(2009, 3, 31, 0, 0)    // Indicators  SMA50 = sma(close, 50)  SMA100 = sma(close, 100)  rsi = rsi(close, 14)  atr = atr(14)    // Crossover conditions   longCondition = crossover(SMA50, SMA100)    if (longCondition)      stopLoss = low - atr * 2      takeProfit = high + atr * 6      strategy.entry("long", strategy.long, 100, when = rsi > 30)      strategy.exit ("exit", "long", stop=stopLoss, limit=takeProfit)              // Plotting SMAs in the chart.  plot(SMA50)  plot(SMA100,color=color.black)```  

How to fix layouts to the top when scrolling?

Posted: 19 Jun 2021 10:08 AM PDT

I need to make layout as shown in the image below. I could achieve the layout but when scrolling I need to attach the Search and TabBar at the top. I had used buttons_tabbar to create the tabbar. I tried using TabBarView to achieve such Tabbar but could not succeed. How can I attach the Search and TabBar at the top when scrolling. I have tried as follows:

enter image description here

 body:              DefaultTabController(                length: 5,                child: Container(                  padding: const EdgeInsets.all(10),                    margin: EdgeInsets.fromLTRB(0, 0, 0, 0),                  child: Column(children: [                    Material(                      borderRadius: BorderRadius.circular(25.0),                      elevation: 2,                      child: Container(                        height:60,                        clipBehavior: Clip.antiAlias,                        decoration: BoxDecoration(                            borderRadius: BorderRadius.circular(30.0)                        ),                        child: TextFormField(                            expands: false,                            controller: searchController,                            textAlign: TextAlign.left,                          textAlignVertical: TextAlignVertical.center,                          keyboardType: TextInputType.emailAddress,                          maxLines: 1,                            decoration: InputDecoration(                                                            fillColor: Colors.white,                            filled: true,                            border: OutlineInputBorder(                              gapPadding: 0,                              borderSide: BorderSide(color: Colors.white),                              borderRadius: BorderRadius.circular(30.0),                            ),                            focusedBorder: OutlineInputBorder(                              gapPadding: 0,                              borderSide: BorderSide(color: Colors.white),                              borderRadius: BorderRadius.circular(30.0),                            ),                            errorBorder: OutlineInputBorder(                              gapPadding: 0,                              borderSide: BorderSide(color: Colors.white),                              borderRadius: BorderRadius.circular(30.0),                            ),                            enabledBorder: OutlineInputBorder(                              gapPadding: 0,                              borderSide: BorderSide(color: Colors.white),                              borderRadius: BorderRadius.circular(30.0),                            ),                            focusedErrorBorder: OutlineInputBorder(                              borderSide: BorderSide(color: Colors.white),                              borderRadius: BorderRadius.circular(30.0),                            ),                            disabledBorder: OutlineInputBorder(                              gapPadding: 0,                              borderSide: BorderSide(color: Colors.white),                              borderRadius: BorderRadius.circular(30.0),                            ),                            suffixIcon: InkWell(                              onTap: () {                                unFocus();                                  presenter.gotoSearchView();                                },                              child: Container(                                child: Icon(Icons.search),                              ),                            ),                            hintText: "Search Books",                            hintStyle: TextStyle(                                fontSize: 14, color: Colors.grey),                          ),                          onFieldSubmitted: (String val) {                            unFocus();                              presenter.gotoSearchView();                            },                        ),                      ),                    ),                    SizedBox(height: 20),                    GridView.count(                      crossAxisCount: 3,                      crossAxisSpacing: 10.0,                      mainAxisSpacing: 10.0,                      physics: NeverScrollableScrollPhysics(),                      childAspectRatio: MediaQuery.of(context).size.width /                          (MediaQuery.of(context).size.height / 2.2),                      shrinkWrap: true,                      children: [                        _buildGridItems(                          "Books",                          "assets/books.svg",                          "1",                        ),                        _buildGridItems(                          "Stationery",                          "assets/stationery.svg",                          "2",                        ),                        _buildGridItems(                          "Office Supplies",                          "assets/supplies.svg",                          "3",                        ),                        _buildGridItems(                          "Sports",                          "assets/sport.svg",                          "4",                        ),                        _buildGridItems(                          "Literary Gift",                          'assets/gift.svg',                          "5",                        ),                      ],                    ),                      ButtonsTabBar(                      height: 65,                      radius: 15,                      contentPadding:                          const EdgeInsets.only(left: 10, right: 25),                      backgroundColor: CustomColor.themeColor,                      unselectedBackgroundColor: Colors.grey[100],                      unselectedLabelStyle: TextStyle(color: Colors.grey),                      labelStyle: TextStyle(                          color: Colors.white, fontWeight: FontWeight.bold),                      tabs: [                        Tab(                          icon: Padding(                            padding: const EdgeInsets.all(8.0),                            child: FaIcon(                              FontAwesomeIcons.book,                            ),                          ),                          text: "Books",                        ),                        Tab(                          icon: Padding(                            padding: const EdgeInsets.all(8.0),                            child: FaIcon(                              FontAwesomeIcons.highlighter,                            ),                          ),                          text: "Stationery",                        ),                        Tab(                          icon: Padding(                            padding: const EdgeInsets.all(8.0),                            child: FaIcon(                              FontAwesomeIcons.calculator,                            ),                          ),                          text: "Office Supplies",                        ),                        Tab(                          icon: Padding(                            padding: const EdgeInsets.all(8.0),                            child: FaIcon(                              FontAwesomeIcons.futbol,                            ),                          ),                          text: "Sports",                        ),                        Tab(                          icon: FaIcon(                            FontAwesomeIcons.gifts,                          ),                          text: "Literary Gift Items",                        ),                      ],                    ),                    Expanded(                      child: TabBarView(                        children: <Widget>[                          BooksTab(presenter),                          CatCommonItemsView(                              catId: "2", updateCart: widget.updateCart),                          CatCommonItemsView(                              catId: "3", updateCart: widget.updateCart),                          CatCommonItemsView(                              catId: "4", updateCart: widget.updateCart),                          CatCommonItemsView(                              catId: "5", updateCart: widget.updateCart),                        ],                      ),                    )                  ]),                ),              ))  

capturar img por js y mostrarlas en js [closed]

Posted: 19 Jun 2021 10:09 AM PDT

enter image description here

buenas tardes estoy capturando las src de las imagenes por medio de js, pero al momento de mostrarlas en un INNETJOIN me sale ese error, soy nuevo me podrian ayudar por favor

How do convert specific String format to DateTime in Flutter?

Posted: 19 Jun 2021 10:09 AM PDT

I have this string '11:59 pm'. I would like to parse it as todays date and time.

String time = '11:59 pm';  

I tried this: DateFormat('HH:mm').parse(time) and I get 1970-01-01 11:59:00.000 as answer which I believe is 'am' time and also the wrong date.

How do it get it as today date and correct am/pm type time? Thanks

ANDROID - ImageButton

Posted: 19 Jun 2021 10:09 AM PDT

so im new in android developing and im trying to make ImageButton just toast to test it, but i cant get it to work :/ I tried more things but nothing was working.

MorningFragment.xml

<?xml version="1.0" encoding="utf-8"?>  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:background="@android:color/holo_blue_bright"      android:id="@+id/myToolbar">        <ImageButton          android:id="@+id/test_product"          android:layout_width="223dp"          android:layout_height="232dp"          android:background="@null"          android:scaleType="fitXY"          android:src="@drawable/test_product"></ImageButton>        <TextView          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_alignBottom="@+id/test_product"          android:layout_gravity="center"          android:layout_marginBottom="3dp"          android:layout_marginLeft="3dp"          android:clickable="true"          android:text="2x McMuffin Menu"          android:textColor="@color/black"          android:textSize="15dp"          android:textStyle="bold"></TextView>    </RelativeLayout>  

MorningActivity.java

package com.example.mcdonaldscoupons;    import android.app.Activity;  import android.os.Bundle;  import android.widget.ImageButton;  import android.widget.Toast;    public class MorningActivity extends Activity {      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.fragment_morning);            ImageButton imageButton = (ImageButton) findViewById(R.id.test_product);          imageButton.setOnClickListener(v -> Toast.makeText(getApplicationContext(), "Click!", Toast.LENGTH_SHORT).show());      }  }  

compiler error: class,interface or enum expected in java

Posted: 19 Jun 2021 10:10 AM PDT

How can I find the data which written with for loop in Flask

Posted: 19 Jun 2021 10:09 AM PDT

I'm trying to make a database project using with MYSQL and I'm new in Flask. In this project, the user should be able to increase and decrease the number of the products in the database. I print the items in my product table with for loop. The problem is I couldn't select the item which the user selected.

Html:

{% for mydata in data %}        <div class="items filterDiv {{ mydata[1] }}">          <img src="../static/foto/atayumurta.png" alt="">          <br><br>          <label for="item"> {{ mydata[3] }}</label>          <br><br>          <label class="Number">Number: <input class="numb" min="1" name="number" type="number"></label>          <br><br>          <input class="addbutton" type="submit" name="submit_button" value="Add">          <input class="removebutton" type="submit" name="removebutton" value="Remove">        </div>    {% endfor %}  

Flask:

@app.route('/mainpage', methods=['POST','GET'])  def mainpage():      cursor.execute("SELECT * FROM product")      fetchdata = cursor.fetchall()      if request.method == 'POST':          if request.form['submit_button'] == 'Add':              number = request.form.get("number")              print(number)              return render_template('main.html', data=fetchdata)      else:          return render_template('main.html', data = fetchdata)  

First, I wanted to see the number that the user has selected. So tried to print it but it prints null. As I said im new in flask, open for your suggestions.

How filter data and show order by date. order by date desc not working in second filter query

Posted: 19 Jun 2021 10:09 AM PDT

{https://caddaclk.blogspot.com/2021/06/blog-post.html this is my code first query declared. How filter data and show order by date. order by date desc not working in second filter query. first query declared. so view- user A all post then, user B all post as like that. if user A have posted 100 posts we need past all 100 posts of user A -to view User B posts}

500 - Internal Server Error in Scala Test

Posted: 19 Jun 2021 10:09 AM PDT

i want to test my create client route. when i hit the route through postman it works fine but when i test my create client unit test it gives internal server error. i am new to this.

this is my create client unit test code

 class CreateClient extends ScalaFutures with AnyWordSpecLike with Matchers     with BeforeAndAfterAll with ScalatestRouteTest with JsonSupport{       val adminInjector = Guice.createInjector(new AdminMockModule)     val adminService = adminInjector.getInstance(classOf[AdminService])       val createNewClientActor = (f: ActorRefFactory) => f.actorOf(Props[CreateNewClientActor], "CreateNewClientActor")       val clientManagerActorsList: List[ActorRefFactory => ActorRef] = List(createNewClientActor)     val clientManagerActor = (f: ActorRefFactory) => f.actorOf(Props(new ClientManagerActor(clientManagerActorsList)), "ClientManagerActor")         val adminManagerActorsList: List[ActorRefFactory => ActorRef] = List(clientManagerActor)       val adminManagerActor = (f: ActorRefFactory) => f.actorOf(Props(new AdminManagerActor(adminManagerActorsList, adminService)), "AdminManagerActor")       val actorsList: List[ActorRefFactory => ActorRef] = List(adminManagerActor)     val actorManager: ActorRef = system.actorOf(Props(new ActorManager(actorsList)), name = "ActorManager")         val adminController = new AdminController(system,actorManager)       override protected def createActorSystem(): ActorSystem = ActorSystem("test-interpret-auth")       val routeResponseMessage = new RouteResponseMessage       val realmName ="testRealm"     val clientName="mom"       val wrealmName ="testReam"     val wclientName="momj"         val token = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJNdDVzbzBSSTNzWWIxa3ZodjRYZDBpMkRHRVg4cFE2RG9YbkxhVlFDOU1VIn0.eyJleHAiOjE2MjQwODA3ODMsImlhdCI6MTYyNDA4MDcyMywianRpIjoiNzA5MDJiYmEtYWNkYi00MDY0LTg3NDctMTdlYmNjMGQ4N2JlIiwiaXNzIjoiaHR0cDovLzAuMC4wLjA6ODA4MC9hdXRoL3JlYWxtcy9tYXN0ZXIiLCJzdWIiOiJlMGU3OWQwMy0xZjMyLTQ5ZWEtOWU5ZS1mNDI1MjRmYjIxYTUiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZG1pbi1jbGkiLCJzZXNzaW9uX3N0YXRlIjoiY2M4MmYxMjUtNjFkYy00ZDQzLWEzNDUtZmRjYTgxNzNjNTJhIiwiYWNyIjoiMSIsInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWRtaW4ifQ.G7rDMCyUcquMLzu00lhJkyhdLdkpaJ9bWOxD13BK_IXt9-dpKKKtsZhbtmwRKUTmV9cvwy6yMjt0vNCi3RaRSGTbUFXHZZ33kkowriFJ8ZrUVLFeKjJuOI2eQbNU2-W8URvsWOvMNWXKBjFREQO9XlZCAKl_XzK9OVu5q1nSbtQQfc7Mxk85Qq7zYcvbQvOct3PnxtvnUJa-UnDWfKpQMNs2l-TsmiaqLFoC_uqayhEf3RvpSBujmqcqlMSRfDeeBMAEQb-NYE_wXSa_v0CpmajAvfwYBgX1n_PRExWHjlk9zpVznTdlpRlyJQwKqISYObVaxVICD9UYfM5s0CpNRw"     val t1="eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJNdDVzbzBSSTNzWWIxa3ZodjRYZDBpMkRHRVg4cFE2RG9YbkxhVlFDOU1VIn0.eyJleHAiOjE2MjQwODQ1NDMsImlhdCI6MTYyNDA4NDQ4MywianRpIjoiNTMwMjlkNWQtN2FmOS00M2EyLWJhMTktNGMwZjU3NGE2ODVjIiwiaXNzIjoiaHR0cDovLzAuMC4wLjA6ODA4MC9hdXRoL3JlYWxtcy9tYXN0ZXIiLCJzdWIiOiJlMGU3OWQwMy0xZjMyLTQ5ZWEtOWU5ZS1mNDI1MjRmYjIxYTUiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZG1pbi1jbGkiLCJzZXNzaW9uX3N0YXRlIjoiNTA2OGRiNmItZjEwNC00NjQ5LTlmMDAtZDE4NjRlMDE5MzRmIiwiYWNyIjoiMSIsInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWRtaW4ifQ.U_9QLi2Ue5EM9zs-joPXSruVnsU5j5hBdErfS3-JJjpLtn8qmBfnWAC8P7n0o9R8ZkmCh7xsc0w93UsejyQzMSSPgAZGV9D_zOoNZjn_epS128nTpfZAsC04yqkIHEUZj3vc1LMVGgohv-uAUuxBiP5bFa32AN-u6DFqEsynj1XxZVj8uHcIm9zvj52JYNYzKZNebXTsOSjE2q3njhGhZD2wSIRt5uXs2vaJ5uU3LUUQBJGb4VXZUUa_vGXd14Zk2Ebh7_ppbS7VL7HtwyaMwtjs_qlQR0FxG1dXHZSvGS5_KnBYDdlyigNvm0gPfKum6sIMtm6Pn2OHRTz5P4P75g"       "pass route /create client" in {         val probe = TestProbe()       implicit val timeoutlimit = Timeout(10, SECONDS)       val routeResponseMessage = new RouteResponseMessage       val adminController = new AdminController(system, actorManager)         val expectedValuesresp= ClientResponseDetails(         clientCreated = true,         error = None,         statusCode = 201)         val tokenJsonRequest: ByteString =         ByteString(           s"""              |{              |   "realmName":"${realmName}",              |   "clientName":"${clientName}"              |}          """.stripMargin)             val httpPostGetToken = HttpRequest(         uri = "http://0.0.0.0:8083/admin/create-new-client",         method = HttpMethods.POST,         headers = List(Authorization(OAuth2BearerToken(token))),         entity = HttpEntity(MediaTypes.`application/json`, tokenJsonRequest)       )       val jsonResponse = JsObject("ClientCreated" -> JsBoolean(expectedValuesresp.clientCreated))       val response = routeResponseMessage.getResponse(StatusCodes.Created.intValue,ServerMessages.ADMIN_KEYCLOAK_CLIENT_CREATED,jsonResponse)       httpPostGetToken ~> adminController.route ~> check {        status shouldEqual StatusCodes.Created         info("status is " + status)         responseAs[String] shouldEqual response.toString()         info("response is " + response.toString())       }     }   }  

this is my AdminMockModule

class AdminMockModule extends AbstractModule{    override protected def configure(): Unit = {      }        @Provides  def adminRepository:AdminRepository = new AdminRepositoryMockImpl    @Provides def adminService: AdminService = new AdminService(adminRepository)      }  

this is my AdminRepositoryMockImpl

class AdminRepositoryMockImpl extends AdminRepository{    val log = LoggerFactory.getLogger(this.getClass)    log.info("i am mock impl class")      var verifiedAdminMap: Map[String,ClientResponseDetails] = Map[String,ClientResponseDetails]()      def this(verifiedAdminMap: Map[String,ClientResponseDetails]) {      this()      this.verifiedAdminMap = verifiedAdminMap    }  //existing client error    val keyCloakex = KeyCloakErrorMessage(error= "Client abc already exists",error_description="",statusCode= 409)  //realm not found error    val keyCloakrm= KeyCloakErrorMessage(error= "Realm not found.",error_description="",statusCode= 404)    // new client created response    val clientResponse=ClientResponseDetails(      clientCreated =true,    error =None,    statusCode =201)    //err1 response    val clientResponseErr1 = ClientResponseDetails(   error = Some(keyCloakex))      //err2 response    val clientResponseErr2 = ClientResponseDetails(      error = Some(keyCloakrm))      //existing client    val createClientDetailsex = CreateClientDetails(clientName = "abc",realmName ="testRealm")      //new client    val createClientDetailsnew = CreateClientDetails(clientName = "new",realmName ="testRealm")      //wrong realm    val createClientDetailswr = CreateClientDetails(clientName = "abc",realmName ="testReam")      val t1="eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJNdDVzbzBSSTNzWWIxa3ZodjRYZDBpMkRHRVg4cFE2RG9YbkxhVlFDOU1VIn0.eyJleHAiOjE2MjQwODQ1NDMsImlhdCI6MTYyNDA4NDQ4MywianRpIjoiNTMwMjlkNWQtN2FmOS00M2EyLWJhMTktNGMwZjU3NGE2ODVjIiwiaXNzIjoiaHR0cDovLzAuMC4wLjA6ODA4MC9hdXRoL3JlYWxtcy9tYXN0ZXIiLCJzdWIiOiJlMGU3OWQwMy0xZjMyLTQ5ZWEtOWU5ZS1mNDI1MjRmYjIxYTUiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZG1pbi1jbGkiLCJzZXNzaW9uX3N0YXRlIjoiNTA2OGRiNmItZjEwNC00NjQ5LTlmMDAtZDE4NjRlMDE5MzRmIiwiYWNyIjoiMSIsInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWRtaW4ifQ.U_9QLi2Ue5EM9zs-joPXSruVnsU5j5hBdErfS3-JJjpLtn8qmBfnWAC8P7n0o9R8ZkmCh7xsc0w93UsejyQzMSSPgAZGV9D_zOoNZjn_epS128nTpfZAsC04yqkIHEUZj3vc1LMVGgohv-uAUuxBiP5bFa32AN-u6DFqEsynj1XxZVj8uHcIm9zvj52JYNYzKZNebXTsOSjE2q3njhGhZD2wSIRt5uXs2vaJ5uU3LUUQBJGb4VXZUUa_vGXd14Zk2Ebh7_ppbS7VL7HtwyaMwtjs_qlQR0FxG1dXHZSvGS5_KnBYDdlyigNvm0gPfKum6sIMtm6Pn2OHRTz5P4P75g"      var returnedClientResponse: ClientResponseDetails= null      override def importNewRealmInKeyCloak(username: String, userPwd: String, realmName: String, actorManagersenderRef: Option[ActorRef], adminManagerActorself: ActorRef, realmActor: ActorRef): Unit = ???      override def createRealmRoleInKeyCloak(accessToken: String, realmRoleDetails: RealmRoleDetails, actorManagersenderRef: Option[ActorRef], adminManagerActorself: ActorRef, clientManagerActor: ActorRef): Unit = ???      override def createClientRoleInKeyCloak(accessToken: String, clientRoleDetails: ClientRoleDetails, actorManagersenderRef: Option[ActorRef], adminManagerActorself: ActorRef, clientManagerActor: ActorRef): Unit = ???    override def createClientInKeyCloak(accessToken: String,createClientDetails: CreateClientDetails,actorManagersenderRef: Option[akka.actor.ActorRef],adminManagerActorself:ActorRef,clientManagerActor:ActorRef): Unit = {      if(accessToken!=null || accessToken.equals(t1)) {        if (createClientDetails.equals(createClientDetailsnew)        )        {          verifiedAdminMap.put(createClientDetailsnew.clientName,clientResponse)        }        else if (createClientDetails.equals(createClientDetailsex)) {          verifiedAdminMap.put(createClientDetailsnew.clientName,clientResponseErr1)        }        else if (createClientDetails.equals(createClientDetailswr)){          verifiedAdminMap.put(createClientDetailsnew.clientName,clientResponseErr2)        }      }      for ((verifiedClientResponseKey, verifiedClientResponseValue) <- verifiedAdminMap) {          if (verifiedClientResponseKey.equals(createClientDetailsnew) && accessToken!=null) {          if (verifiedClientResponseValue.equals(clientResponse)) {            returnedClientResponse = clientResponse          }        }        else if (verifiedClientResponseKey.equals(createClientDetailsex) && accessToken!=null) {          if (verifiedClientResponseValue.equals(clientResponseErr1)) {            returnedClientResponse = clientResponseErr1          }        }        else  if (verifiedClientResponseKey.equals(createClientDetailswr) && accessToken!=null) {          if (verifiedClientResponseValue.equals(clientResponseErr2)) {            returnedClientResponse = clientResponseErr2          }        }      }        import scala.concurrent.{ExecutionContextExecutor, Future}      import scala.concurrent.ExecutionContext.Implicits.global      import akka.pattern.{ask, pipe}        actorManagersenderRef match {        case Some(actorMangerRef) =>          log.info("AdminRepositoryMock Impl: actor ref is {}", actorMangerRef)          Future{returnedClientResponse}.pipeTo(actorMangerRef)          case None => log.info("AdminRepositoryImpl: Actor ref is empty")      }    }  }  

this is my admincontroller route for create client

 def createClient: server.Route =        pathPrefix("admin") {        path("create-new-client") {          post {            entity(as[CreateClientDetails]) {              createClientDetails =>                bearerToken { adminToken =>                  adminToken match {                    case Some(token) =>                      val future = ask(actorManager, CreateNewClient(token, createClientDetails)).mapTo[ClientResponseDetails]                      onComplete(future) {                        case Success(value) =>                          value.error match {                            case Some(kcMsg) =>                              log.info("kc error")                              val jsonResponse = JsObject("Error" -> kcMsg.toJson)                              complete(kcMsg.statusCode, routeResponseMessage.getResponse(kcMsg.statusCode.intValue, ServerMessages.KEYCLOAK_ERROR, jsonResponse))                            case None =>                              log.info("client created")                              val jsonResponse = JsObject("ClientCreated" -> JsBoolean(value.clientCreated))                              complete(value.statusCode, routeResponseMessage.getResponse(value.statusCode, ServerMessages.ADMIN_KEYCLOAK_CLIENT_CREATED, jsonResponse))                          }                        case Failure(ex) =>                          failWith(ex)                      }                    case None => reject(AuthorizationFailedRejection)                  }                }            }          }        }      }  

this my actor manager

class ActorManager(childMaker: List[ActorRefFactory => ActorRef]) extends Actor {    val log = LoggerFactory.getLogger(this.getClass)    val seconds = 10    implicit val timeout = Timeout(ReadTimeIntervalValue.getInterval(), SECONDS)      val managerActor: ActorRef = childMaker(0)(context)    val adminManagerActor: ActorRef = childMaker(1)(context)      override val supervisorStrategy = OneForOneStrategy(      maxNrOfRetries = seconds, withinTimeRange = seconds seconds) {      case tokenNotActiveException: TokenNotActiveException =>        log.error(s"Got some tokenNotActiveException: TokenNotActiveException :$tokenNotActiveException, Supervision Strategy says Resume for Actor $sender()")        Resume      case tsEx: TokenSignatureInvalidException =>        log.error(s"Got some TokenSignatureInvalidExceptio :$tsEx, Supervision Strategy says Resume for Actor $sender()")        Resume      case vEx: VerificationException =>        log.error(s"Got some VerificationException :$vEx, Supervision Strategy says Resume for Actor $sender()")        Resume      case aEx: akka.stream.StreamTcpException =>        log.error(s"Got some StreamTcpException :$aEx, Supervision Strategy says Resume for Actor $sender()")        Resume        case wEx: javax.ws.rs.WebApplicationException =>        log.error(s"Got some StreamTcpException :$wEx, Supervision Strategy says Resume for Actor $sender()")        Resume      case e: Exception =>        log.error(s"Got some Exception, $e Supervision Strategy says Resume for the actor $sender()")        Resume    }      /**      * Actor receive method      *      * @return PartialFunction[Any, Unit]      */      def receive: PartialFunction[Any, Unit] = {      case GetUserDetails(userName, userPwd, realmName, clientName, clientSecret) =>        log.debug("Actor ActorManger: received message : GetUserDetails with params username {}", userName)        managerActor.forward(AuthenticateUser(userName, userPwd, realmName, clientName, clientSecret))        case GetKeycloakAdminUserDetails(userName, userPwd) =>        log.debug("Actor ActorManger: received message : GetKeycloakAdminUserDetails with params username {}", userName)        managerActor.forward(AuthenticateKeycloakAdminUser(userName, userPwd))        case VerifyAccessToken(accessToken, realmName) =>        log.debug("Actor ActorManger: received message : VerifyAccessToken with params token {}", accessToken)        managerActor.forward(VerifyUserToken(accessToken, realmName))        case VerifyRpt(rpt, realmName) =>        log.debug("Actor ActorManger: received message : VerifyRpt with params token {}", rpt)        managerActor.forward(VerifyRptToken(rpt, realmName))        /*case CreateRealm(userName, userPwd) =>        log.debug("Actor ActorManger: received message : CreateRealm with params username {}", userName)        adminManagerActor.forward(CreateKeycloakRealm(userName, userPwd))  */      case ImportNewRealm(accessToken, realmName) =>        log.debug("Actor ActorManger: received message : ImportNewRealm")        adminManagerActor.forward(ImportKeycloakNewRealm(accessToken, realmName))        case CreateNewClient(accessToken, createClientDetails) =>        log.debug("Actor ActorManger: received message : CreateNewClient")        adminManagerActor.forward(CreateClientInKeycloakRealm(accessToken, createClientDetails))        case CreateNewClientRole(accessToken, clientRoleDetails) =>        log.debug("Actor ActorManger: received message : CreateNewClient")        adminManagerActor.forward(CreateClientRoleInKeycloakRealm(accessToken, clientRoleDetails))        case CreateNewRealmRole(accessToken, realmRoleDetails) =>        log.debug("Actor ActorManger: received message : CreateNewRealmRole")        adminManagerActor.forward(CreateRealmRoleInKeycloakRealm(accessToken, realmRoleDetails))        case CreateNewUser(accessToken, keycloakUserDetails) =>        log.debug("Actor ActorManger: received message : CreateNewUser")        adminManagerActor.forward(CreateNewUserInKeycloak(accessToken, keycloakUserDetails))        case MapClientLevelRoleToUser(accessToken, clientLevelRoleMappingToUser) =>        log.debug("Actor ActorManger: received message : MapClientLevelRoleToUser")        adminManagerActor.forward(MapClientLevelRoleToUserInKeycloak(accessToken, clientLevelRoleMappingToUser))        case MapRealmLevelRoleToUser(accessToken, realmLevelRoleMappingToUser) =>        log.debug("Actor ActorManger: received message : MapRealmLevelRoleToUser")        adminManagerActor.forward(MapRealmLevelRoleToUserInKeycloak(accessToken, realmLevelRoleMappingToUser))        case CreateNewUserGroup(accessToken, createUserGroup) =>        log.debug("Actor ActorManger: received message : CreateNewUserGroup")        adminManagerActor.forward(CreateNewUserGroupInKeycloak(accessToken, createUserGroup))        case MapRealmLevelRoleToUserGroup(accessToken, realmLevelRoleMappingToGroup)=>        log.debug("Actor ActorManger: received message : MapRealmLevelRoleToUserGroup")        adminManagerActor.forward(MapRealmLevelRoleToUserGroupInKeycloak(accessToken, realmLevelRoleMappingToGroup))        case MapClientLevelRoleToUserGroup(accessToken, clientLevelRoleMappingToGroup) =>        log.debug("Actor ActorManger: received message : MapClientLevelRoleToUserGroup")        adminManagerActor.forward(MapClientLevelRoleToUserGroupInKeycloak(accessToken, clientLevelRoleMappingToGroup))        case AddUserToGroup(accessToken,addUserToGroupDetails)=>        log.debug("Actor ActorManger: received message : AddUserToGroup")        adminManagerActor.forward(AddUserToGroupInKeycloak(accessToken, addUserToGroupDetails))        case CreateNewUserSubGroup(accessToken, createUserSubGroup) =>        log.debug("Actor ActorManger: received message : CreateNewUserSubGroup")        adminManagerActor.forward(CreateNewUserSubGroupInKeycloak(accessToken, createUserSubGroup))        case message =>        log.warn("Actor ActorManger: Unhandled message received : {}", message)        unhandled(message)    }  }  

when i hit the route without bearer token, my request is going to b rejected as show below

ERROR] [06/19/2021 20:57:32.802] [test-interpret-auth-akka.actor.internal-dispatcher-2] [akka://test-interpret-auth/user/ActorManager] 1  akka.actor.ActorInitializationException: akka://test-interpret-auth/user/ActorManager: exception during creation          at akka.actor.ActorInitializationException$.apply(Actor.scala:196)          at akka.actor.ActorCell.create(ActorCell.scala:661)          at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:513)          at akka.actor.ActorCell.systemInvoke(ActorCell.scala:535)          at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:295)          at akka.dispatch.Mailbox.run(Mailbox.scala:230)          at akka.dispatch.Mailbox.exec(Mailbox.scala:243)          at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)          at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)          at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)          at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)          at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)  Caused by: java.lang.IndexOutOfBoundsException: 1          at scala.collection.LinearSeqOps.apply(LinearSeq.scala:117)          at scala.collection.LinearSeqOps.apply$(LinearSeq.scala:114)          at scala.collection.immutable.List.apply(List.scala:79)          at com.lufz.authentication.actors.parent.ActorManager.<init>(ActorManager.scala:71)          at CreateClient.$anonfun$actorManager$1(CreateClient.scala:71)          at akka.actor.TypedCreatorFunctionConsumer.produce(IndirectActorProducer.scala:91)          at akka.actor.Props.newActor(Props.scala:226)          at akka.actor.ActorCell.newActor(ActorCell.scala:613)          at akka.actor.ActorCell.create(ActorCell.scala:640)          ... 10 more    [info] CreateClient:  [info] - pass route /create client *** FAILED ***  [info]   Request was rejected with rejection AuthorizationFailedRejection (CreateClient.scala:122)  [info] Run completed in 3 seconds, 192 milliseconds.  [info] Total number of tests run: 1  [info] Suites: completed 1, aborted 0  [info] Tests: succeeded 0, failed 1, canceled 0, ignored 0, pending 0  [info] *** 1 TEST FAILED ***  [error] Failed tests:  [error]         CreateClient  [error] (Test / testOnly) sbt.TestsFailedException: Tests unsuccessful  [error] Total time: 12 s, completed 19 Jun. 2021, 8:57:35 pm  sbt:interpret-auth>   

and when i hit the route with bearer token,it gives internal server error as show below

sbt:interpret-auth> testOnly CreateClient  [info] Compiling 1 Scala source to /home/mehveen/Downloads/interpret-auth/target/scala-2.13/test-classes ...  [info] Done compiling.  21:00:38.370 [pool-17-thread-4] INFO com.lufz.admin.mock.auth.AdminRepositoryMockImpl - i am mock impl class  [ERROR] [06/19/2021 21:00:38.409] [test-interpret-auth-akka.actor.internal-dispatcher-2] [akka://test-interpret-auth/user/ActorManager] 1  akka.actor.ActorInitializationException: akka://test-interpret-auth/user/ActorManager: exception during creation          at akka.actor.ActorInitializationException$.apply(Actor.scala:196)          at akka.actor.ActorCell.create(ActorCell.scala:661)          at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:513)          at akka.actor.ActorCell.systemInvoke(ActorCell.scala:535)          at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:295)          at akka.dispatch.Mailbox.run(Mailbox.scala:230)          at akka.dispatch.Mailbox.exec(Mailbox.scala:243)          at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)          at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)          at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)          at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)          at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)  Caused by: java.lang.IndexOutOfBoundsException: 1          at scala.collection.LinearSeqOps.apply(LinearSeq.scala:117)          at scala.collection.LinearSeqOps.apply$(LinearSeq.scala:114)          at scala.collection.immutable.List.apply(List.scala:79)          at com.lufz.authentication.actors.parent.ActorManager.<init>(ActorManager.scala:71)          at CreateClient.$anonfun$actorManager$1(CreateClient.scala:71)          at akka.actor.TypedCreatorFunctionConsumer.produce(IndirectActorProducer.scala:91)          at akka.actor.Props.newActor(Props.scala:226)          at akka.actor.ActorCell.newActor(ActorCell.scala:613)          at akka.actor.ActorCell.create(ActorCell.scala:640)          ... 10 more    [INFO] [akkaDeadLetter][06/19/2021 21:00:38.914] [test-interpret-auth-akka.actor.default-dispatcher-5] [akka://test-interpret-auth/user/ActorManager] Message [com.lufz.authentication.actors.parent.CreateNewClient] to Actor[akka://test-interpret-auth/user/ActorManager#-184987743] was not delivered. [1] dead letters encountered. If this is not an expected behavior then Actor[akka://test-interpret-auth/user/ActorManager#-184987743] may have terminated unexpectedly. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.  21:00:38.954 [pool-17-thread-4-ScalaTest-running-CreateClient] ERROR com.lufz.authentication.controllers.AdminController - Request to http://0.0.0.0:8083/admin/create-new-client could not be handled normally  akka.pattern.AskTimeoutException: Recipient [Actor[akka://test-interpret-auth/user/ActorManager#-184987743]] had already been terminated. Message of type [com.lufz.authentication.actors.parent.CreateNewClient].  [info] CreateClient:  [info] - pass route /create client *** FAILED ***  [info]   500 Internal Server Error did not equal 201 Created (CreateClient.scala:122)  [info]   Analysis:  [info]   StatusCodes$ServerError(allowsEntity: -> true, defaultMessage: "The[re was an internal server error]." -> "The[ request has been fulfilled and resulted in a new resource being created].", intValue: 500 -> 201, reason: "[Internal Server Error]" -> "[Created]")  [info] Run completed in 1 second, 758 milliseconds.  [info] Total number of tests run: 1  [info] Suites: completed 1, aborted 0  [info] Tests: succeeded 0, failed 1, canceled 0, ignored 0, pending 0  [info] *** 1 TEST FAILED ***  [error] Failed tests:  [error]         CreateClient  [error] (Test / testOnly) sbt.TestsFailedException: Tests unsuccessful  [error] Total time: 5 s, completed 19 Jun. 2021, 9:00:40 pm  sbt:interpret-auth>   

Line graph with linear timescale in Chart.js

Posted: 19 Jun 2021 10:09 AM PDT

I'm trying to use Chart.js 3.3.2 to display some a line graph with an equally spaced x date axis. Like the example they give here.

I cannot get a simple version of this example working (see below snippet) as it outputs the error:

Error: This method is not implemented: Check that a complete date adapter is provided.

I did not try to implement the whole example given it depends on externally defined functions and values.

I asked a similar question long ago (Chart.js creating a line graph using dates) but having re-read through answers there, it has not helped me here (notably most answers here also focus on Chart.js 2 rather than 3).

I would greatly appreciate any help here (I find the documentation here hard to understand).

const data = {    labels: [      new Date(86400000), // Day 1      new Date(2*86400000), // Day 2      new Date(3*86400000), // Day 3      new Date(4*86400000), // Day 4      new Date(6*86400000), // Day 6      new Date(7*86400000), // Day 7      new Date(13*86400000) // Day 13    ],    datasets: [{      label: 'My First dataset',      data: [1,3,4,5,6,7,8]    }]  };    const config = {    type: 'line',    data: data,    options: {      scales: {        x: {          type: 'time'        }      }    }  };    let ctx = document.querySelector("canvas").getContext("2d");  let chart = new Chart(ctx,config);
<!DOCTYPE html>  <html>    <head>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width">      <title>repl.it</title>      <link href="style.css" rel="stylesheet" type="text/css" />      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.min.js"></script>    </head>    <body>      <canvas></canvas>      <script src="script.js"></script>    </body>  </html>

Adding all elements together in a matrix

Posted: 19 Jun 2021 10:09 AM PDT

Say, if there is an input matrix whose dimension N is unknown (it could be 2D, 3D, or some D.) to the receiving end:

import tensorflow as tf  m = tf.keras.backend.random_normal([2, 3,4], mean=6, stddev=0.1, seed = 1) # a 3D matrix  

or

m = tf.keras.backend.random_normal([3], mean=6, stddev=0.1, seed = 1) # a 1D matrix  

or

m = tf.keras.backend.random_normal([3,7], mean=6, stddev=0.1, seed = 1). # a 2D matrix  

On the receiving end, I need to add all the elements in the matrix. How do I do that?

I was thinking of some sort of for loop

for n in N # N is the dimension of the matrix   sum = tf.reduce_sum(m, axis=-1)  

I am not sure how to get N on the receiving end, or should it be done differently? In MATLAB, it'd be like

sum_of_a_m = sum(m(:));  

Thanks a lot. A couple of lines code is highly appreciated.

how to ignore charset errors while parsing pdf with pdf miner

Posted: 19 Jun 2021 10:09 AM PDT

Hi folks I got an encoding error while parsing a pdf file using pdf miner.

from pdfminer import layout    from pdfminer.high_level import extract_pages  from pdfminer.layout import LTTextBoxHorizontal, LTTextContainer  from pdfminer.pdfparser import PDFParser  from pdfminer.pdfdocument import PDFDocument  from pdfminer.pdfpage import PDFPage  from pdfminer.pdfpage import PDFTextExtractionNotAllowed  from pdfminer.pdfinterp import PDFResourceManager  from pdfminer.pdfinterp import PDFPageInterpreter  from pdfminer.pdfdevice import PDFDevice  from pdfminer.layout import LAParams  from pdfminer.converter import PDFPageAggregator  import pdfminer    #pageno=0  #for page_layout in extract_pages("./Statements/Manoj Kotak.pdf"):  #    pageno+=1  #    print(str(len(page_layout))+" page No:"+str(pageno))  #    for element in page_layout:  #        if(isinstance(element,LTTextBoxHorizontal)):  #              #            print(element.get_text())  #    if pageno==2:  #        break      #Open Pdf   fp=open("../pathto/pdffile.pdf")    #Pdf Parser Instantiation  parser =PDFParser(fp)    #Reading Parsed Document    document=PDFDocument(parser)    #Text Extraction is Implementable    if not document.is_extractable:      raise PDFTextExtractionNotAllowed    #Initiating Resource Manager to store Shared Objects in Pdf document  rsrmgr=PDFResourceManager()    #Begining Page Layout Analysis  # Parameters for analysis  laparams=LAParams()    #Device Initialsation  device=PDFPageAggregator(rsrmgr,laparams=laparams)      # PDF interpreter Initialisation  interpreter=PDFPageInterpreter(rsrmgr,device)    #Function to Parse Parsed Pdf Object  def parse_obj(layout_objs):          # looping Through the Pdf           for obj in layout_objs:              if isinstance(obj,pdfminer.layout.LTTextBoxHorizontal):                  print ("%6 %6 %s".format(obj.bbox[0],obj.bbox[1],obj.get_text()))    for page in PDFPage.create_pages(document):          interpreter.process_page(page)          layout=device.get_result()            parse_obj(layout.objs)    

Above is the source code I have been used for parsing pdf in python

Traceback (most recent call last): File "bin\statementparser.py", line 37, in document=PDFDocument(parser) File "D:\python\lib\site-packages\pdfminer\pdfdocument.py", line 571, in init pos = self.find_xref(parser) File "D:\python\lib\site-packages\pdfminer\pdfdocument.py", line 788, in find_xref for line in parser.revreadlines(): File "D:\python\lib\site-packages\pdfminer\psparser.py", line 267, in revreadlines s = self.fp.read(prevpos-pos) File "D:\python\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 1803: character maps to

Thank You

Methods with certain functions

Posted: 19 Jun 2021 10:09 AM PDT

Is there any way to write these two class methods, without using loops, lambda functions, and other additional functions? I only want to use the functions and functors from libraries algorithm and functional. I have tried to use while loop and recursion to fugure something out, but still couldn't solve this. I didn't want to post the whole code since it is too long.

(I don't have to use these libraries for << operator, if there is a way to solve this without them, and min and max are lists) My main goal is not using loops, lambda functions and any additional functions outside the two libraries. EraseNegativeTemperatures is the method which should only erase the registered pairs of temperatures where both of them are negative (I wrote the method in the part which I didn't post, and that method makes pairs where one temperature is from min and the other one from max)

Operator << outputs all the registered temperatures, the min ones in one row and the max ones in the second row; the temperatures in one row are separates by space.

void Temperatures::EraseNegativeTemperatures() {    for (auto it = max.begin(); it != max.end(); it++) {      if (*it < 0) {        auto it1 = it;        auto it2 = min.begin();        while (it1 != max.begin()) {          it2++;          it1--;        }        min.erase(it2);        it = max.erase(it);      }    }    // std::remove_if(min.begin(), min.end(), std::bind(std::less<int>(),              max.begin() + std::placeholders::_1 - min.begin(), 0));  }    // second method  std::ostream &operator<<(std::ostream &flow, const Temperatures &t) {    std::for_each(t.min.begin(), t.min.end(),                  [&flow](int x) { flow << x << " "; });    flow << std::endl;    std::for_each(t.max.begin(), t.max.end(),                  [&flow](int x) { flow << x << " "; });    flow << std::endl;    return flow;  }  

Error when formatting a document on VSCode using LaTeX Workshop on Windows 10 due to missing perl module

Posted: 19 Jun 2021 10:09 AM PDT

I have the latest version of LaTeX Workshop installed on Visual Studio Code and, MikTex's latest version and ActivePerl:

This is perl 5, version 28, subversion 1 (v5.28.1) built for MSWin32-x64-multi-thread  (with 1 registered patch, see perl -V for more detail)  Copyright 1987-2018, Larry Wall  Binary build 0000 [25391a6d] provided by ActiveState http://www.ActiveState.com  Built Oct 28 2020 18:24:51  

On a Windows 10 Pro 20H2 machine. I also have an IEEE Scientific Document project and it builds correctly, but when I try to format the document I get this error:`

[13:58:18] Start formatting with latexindent.  [13:58:18] Formatting with command latexindent -c,c:/Users/user/Desktop/path/,c:/Users/user/Desktop/path/__latexindent_temp.tex,-y=defaultIndent: '    '   [13:58:18] Formatting failed with exit code 2  [13:58:18] stderr: Can't locate YAML/Tiny.pm in u/INC     (you may need to install the YAML::Tiny module)     (@INC contains: C:/Users/user/AppData/Local/Programs/MiKTeX/scripts/latexindent C:/Perl64/site/lib C:/Perl64/lib)     at C:/Users/user/AppData/Local/Programs/MiKTeX/scripts/latexindent/LatexIndent/GetYamlSettings.pm line 20.  

(Line breaks added for readability.)

I have searched for instructions on how to install the missing YAML::Tiny module but with no success. I've seen a tool called ppm but that seems to not be available anymore, how can I install this and other missing packages? Thank you a lot.

How can I make the Lux package work in Python?

Posted: 19 Jun 2021 10:09 AM PDT

I was trying to use the package called LUX for Python. I followed this tutorial. So it was pretty simple, I just had to import some csv and when I called my data, I would be able to see multiple graphs. The problem is that I do everything and nothing shows up for me.

I was using Melbourne House Market data, and this is my script so far:

# firstly, we install package and extensions  !pip install lux-api  !jupyter nbextension install --py luxwidget  !jupyter nbextension enable --py luxwidget    # then, load the packages  import lux  import pandas as pd    # load data  melb_data = pd.read_csv("melb_data.csv")  

So far so good... at least, I thought so. After doing these things, when we see the tutorial mentioned in the begining of this question, it mentions that if we call the dataframe now, instead of appearing only the dataset, we would be able to see some graphics as well. But that didn't happen to me. I know screenshots are not the best choice, but this is what I see:

enter image description here

As you can see, there is the Toggle button, but it is only working to hide the table. there isn't the graphs I saw in the tutorial. I also tried to follow this tutorial as well, but there isn't anything new there.

Any ideas on what I'm missing here? Why I can't find a way to make this package work?

How to convert three lists to json?

Posted: 19 Jun 2021 10:09 AM PDT

I have a three lists which I need to convert to json using python, It should be in a specific order, each item of a should be key in which it should have four keys of each item of b and there values should be every four items of c corresponding to it. If you don't understand, please see the example.

a = ["a","b","c"]  b = ["m","n","o","p"]  c = [1,2,3,4,"z","y","x","w","aa","ab","ac","ad"]  

convert the above data into this

dic = {      "a": {          "m": 1,          "n": 2,          "o":3,          "p":4      },      "b": {          "m": "z",          "n": "y",          "o":"x",          "p":"w"             },      "c":{          "m": "aa",          "n": "ab",          "o":"ac",          "p":"ad"      }  }  

any suggestions will be strongly appreciated.

Regex in vb.net get all A elements in a string [duplicate]

Posted: 19 Jun 2021 10:09 AM PDT

WHY THE I***TS AT SOVERFLOW SAY THIS QUESTIONS WA ASKED, THATS NOT TRUE, I ASK FOR VB.NET AND THE QUESTION LINKED BY ADMINS IS IN C#

Say I have a string consisting of HTML, in a string

Dim HtmlString as string = "<html><body>bla bla <a href='bla '>bla</a> blala <a href='bla2'>bla22</a></body></html>"  

I need to get an array of string containing all the A elements found in the HtmlString

say

Dim AElementsInHtmlString as String()  

How can I get ?

Join 2 parquet files with different columns but common key(id) column in Athena

Posted: 19 Jun 2021 10:10 AM PDT

I'm wondering is there a way in AWS Athena to "merge" 2 parquet files into a one single table in Athena just leveraging the columnar model of parquet, meaning without do any joins or post-processing?

For example:

File 1:

id first_name
1 Jonh
2 Joe

File 2:

id last_name status
1 Doe 1
2 Smith 0

Athena Final Table result:

id first_name last_name status
1 Jonh Doe 1
2 Joe Smith 0

I know I can do a join in both files, but I was wondering since I'm using Parquet can this be achieved without a sql command for join?

Thanks!

Federated Learning for Image Classification in colab

Posted: 19 Jun 2021 10:09 AM PDT

I'm new in Federated learning, I tried to implement the code of FL for Image Classification, but I can't understand this line

I am confused in some detail parts. I am trying to build a sequential model in Keras, but when I train the model, I am getting this error, How may I fix it?

please guide me thank you.

iterative_process = tff.learning.build_federated_averaging_process(model_fn)    TypeError                                 Traceback (most recent call last)  <ipython-input-50-0fdb188570d0> in <module>()  ----> 1 iterative_process = tff.learning.build_federated_averaging_process(model_fn)    TypeError: build_federated_averaging_process() missing 1 required positional argument: 'client_optimizer_fn'  

https://colab.research.google.com/github/tensorflow/federated/blob/v0.12.0/docs/tutorials/federated_learning_for_image_classification.ipynb#scrollTo=sk6mjOfycX5N

Select Option not working along with Search Filter

Posted: 19 Jun 2021 10:09 AM PDT

I'm to trying to get search filter and with category wise filter, My probelem is when i use search filter and select option alone it's working when i try to get these both together with one search button it's not working

here is some of my code, actual code is too big so i share some important here and i do have jsfiddle link below which is having whole code.

Jsfiddle : https://jsfiddle.net/JOHN_748/8dpg3y51/2/

enter image description here

$(function() {            //Search Filter (search form)          var flexiblePagination = $('#content').flexiblePagination({              itemsPerPage : 4,              displayedPages: 4,              itemSelector : 'div.result:visible',              pagingControlsContainer : '#pagingControls',              showingInfoSelector : '#showingInfo',              css: {                  btnNumberingClass: 'btn btn-sm btn-success',                  btnFirstClass: 'btn btn-sm btn-success',                  btnLastClass: 'btn btn-sm btn-success',                  btnNextClass: 'btn btn-sm btn-success',                  btnPreviousClass: 'btn btn-sm btn-success'              },              searchBox: {                  onClick: true,                    onClickSelector: '#search'              }          });          flexiblePagination.getController().onPageClick = function(pageNum, e){              console.log('You Clicked Page: '+pageNum)          };        });      // Search Category Wise  (select form)      $(function() {          const $sels = $("select");        const $boxes = $(".box");        $("#search").on("click", function() {          const vals = $sels.map(function() { return this.value }).get()          $boxes.each(function() {             const show = $(this).hasClass(vals[0]) && $(this).hasClass(vals[1]) && $(this).hasClass(vals[2]);            $(this).toggle(show)           });        }).click();      });
.details{      min-height: 20px;      padding: 19px;      margin-top: 20px;      background-color: #ecf0f1;      border: 1px solid transparent;      border-radius: 4px;      -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);      box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);  }    #pagingControls{    margin-top: 20px;    text-align: center;  }    #showingInfo{      margin-top: 20px;      margin-bottom: 20px;      text-align: center;  }
<div class="row mt-4">          <div class="col-9">              <input class="searchBox form-control" placeholder="Search Something...">                    </div>          <div class="col-3">              <button id="search" class="btn btn-primary w-100">Search</button>                  </div>      </div>      <div class="row mt-3">        <div class="col-3">          <select class="form-control">            <option value="all">Quality</option>            <option value="720">720p</option>            <option value="1080">1080p</option>            <option value="2160">2160p</option>          </select>        </div>        <div class="col-3">          <select class="form-control">            <option value="all">Genre</option>            <option value="action">Action</option>            <option value="thriller">Thriller</option>            <option value="drama">Drama</option>          </select>        </div>        <div class="col-3">          <select class="form-control">            <option value="all">Rating</option>            <option value="9">9</option>            <option value="8">8</option>            <option value="7">7</option>            <option value="6">7</option>          </select>        </div>        <div class="col-3">          <select class="form-control">            <option value="all">OrderBy</option>            <option value="dateasc">Date Asc</option>            <option value="datedesc">Date Desc</option>            <option value="highrate">Highest Rating</option>          </select>        </div>      </div>                  <div class="container">        <div id="content" class="row">        <div class="result box 1080 thriller 9 datedesc col-6">        <div class="details">          <p>Movie : Avatar</p>          <p>Actor : Jake Sully</p>          <p>Rating : 9</p>          <p>Info : Avatar is a 2009 science fiction film directed, written, produced, and co-edited by James Cameron.</p>        </div>      </div>              <div class="result box 720 action 9 dateasc col-6">        <div class="details">          <p>Movie : TENET</p>          <p>Actor : John David</p>          <p>Rating : 9</p>          <p>Info : Directed by Christopher Nolan. With Juhan Ulfsak, Jefferson Hall, Ivo Uukkivi, Andrew Howard.</p>        </div>      </div>    </div>    </div>    <div id="pagingControls"></div>  <div id="showingInfo"></div>

Got ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor

Posted: 19 Jun 2021 10:10 AM PDT

When I tried to run a colab notebook on 2021 June, which was created on 2020 december and ran fine I got an error. So I changed

baseModel = tf.keras.applications.VGG16(weights="imagenet",                                        include_top= False,                                       input_tensor=Input(shape=(224, 224, 3)))  

to

baseModel = tf.keras.applications.VGG19(weights="imagenet",                                        include_top= False,                                       input_shape=(224, 224, 3))  

However when I continued to execute the notebook I got an error "ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor." in a later stage.

Code:

import numpy as np  from tqdm import tqdm  import math  import os    import keras  from keras.models import *  from keras.layers import *  from keras.layers.core import Dense, Flatten  from keras.optimizers import Adam  from keras.metrics import categorical_crossentropy  from keras.preprocessing.image import ImageDataGenerator  from keras.layers.normalization import BatchNormalization  from keras.layers.convolutional import Conv2D  from sklearn.metrics import confusion_matrix  from keras.applications.densenet import DenseNet121  from keras.callbacks import *  from keras import backend as K  K.clear_session()  import itertools  import matplotlib.pyplot as plt  import cv2  import matplotlib.cm as cm    from tensorflow.keras.utils import to_categorical  from sklearn.preprocessing import LabelBinarizer,LabelEncoder  from sklearn.model_selection import train_test_split  from sklearn.metrics import classification_report  from sklearn.metrics import confusion_matrix      import tensorflow as tf  baseModel = tf.keras.applications.VGG19(weights="imagenet",                                        include_top= False,                                       input_shape=(224, 224, 3))    headModel = baseModel.output  headModel = AveragePooling2D(pool_size=(4, 4))(headModel)  headModel = Flatten(name="flatten")(headModel)  headModel = Dense(64, activation="relu")(headModel)  headModel = Dropout(0.4)(headModel)  headModel = Dense(3, activation="softmax")(headModel)  model = Model(inputs=baseModel.input, outputs=headModel)    model.summary()  

Error:

---------------------------------------------------------------------------  ValueError                                Traceback (most recent call last)  <ipython-input-18-6695ac43a942> in <module>()        1 headModel = baseModel.output        2 headModel = AveragePooling2D(pool_size=(4, 4))(headModel)  ----> 3 headModel = Flatten(name="flatten")(headModel)        4 headModel = Dense(64, activation="relu")(headModel)        5 headModel = Dropout(0.4)(headModel)    5 frames  /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)       96       dtype = dtypes.as_dtype(dtype).as_datatype_enum       97   ctx.ensure_initialized()  ---> 98   return ops.EagerTensor(value, ctx.device_name, dtype)       99       100     ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.  

Updated imports:

import numpy as np  from tqdm import tqdm  import math  import os    import tensorflow as tf    import tensorflow.keras  from tensorflow.keras.models import *  from tensorflow.keras.layers import *  from tensorflow.keras.layers import Dense, Flatten  from tensorflow.keras.optimizers import Adam  from tensorflow.keras.metrics import categorical_crossentropy  from tensorflow.keras.preprocessing.image import ImageDataGenerator  from tensorflow.keras.layers import BatchNormalization  from tensorflow.keras.layers import Conv2D  from sklearn.metrics import confusion_matrix  from tensorflow.keras.applications.densenet import DenseNet121  from tensorflow.keras.callbacks import *  from tensorflow.keras import backend as K  K.clear_session()  import itertools  import matplotlib.pyplot as plt  import cv2  import matplotlib.cm as cm    from tensorflow.keras.utils import to_categorical  from sklearn.preprocessing import LabelBinarizer,LabelEncoder  from sklearn.model_selection import train_test_split  from sklearn.metrics import classification_report  from sklearn.metrics import confusion_matrix  

Could not find com.google.firebase:firebase-ml-vision

Posted: 19 Jun 2021 10:09 AM PDT

When I added flutter_camera_ml_vision to an existing project, I got the following error.

Execution failed for task ':app:checkDebugAarMetadata'.                   > Could not resolve all files for configuration ':app:debugRuntimeClasspath'.     > Could not find com.google.firebase:firebase-ml-vision:.                   Required by:                                                                  project :app > project :firebase_ml_vision  

I didn't know what caused it, so I copied the code (from the official website). After that, I tried to link firebase and added only flutter_camera_ml_vision, but I got the same error as above.

The main.dart is the same as the URL above, and the other files that I changed are as follows. The version of flutter_camera_ml_vision is 3.0.1. As a supplement, the ./gradlew command succeeds.

//android/app/src/main/AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.example.association_firebase">     <application          android:label="association_firebase"          android:icon="@mipmap/ic_launcher">          <activity              android:name=".MainActivity"              android:launchMode="singleTop"              android:theme="@style/LaunchTheme"              android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"              android:hardwareAccelerated="true"              android:windowSoftInputMode="adjustResize">                <meta-data                android:name="io.flutter.embedding.android.NormalTheme"                android:resource="@style/NormalTheme"                />                <meta-data                android:name="io.flutter.embedding.android.SplashScreenDrawable"                android:resource="@drawable/launch_background"                />              <intent-filter>                  <action android:name="android.intent.action.MAIN"/>                  <category android:name="android.intent.category.LAUNCHER"/>              </intent-filter>          </activity>            <meta-data              android:name="flutterEmbedding"              android:value="2" />          <!-- add -->          <meta-data              android:name="com.google.firebase.ml.vision.DEPENDENCIES"              android:value="ocr" />      </application>  </manifest>  

//android/app/build.gradle

def localProperties = new Properties()  def localPropertiesFile = rootProject.file('local.properties')  if (localPropertiesFile.exists()) {      localPropertiesFile.withReader('UTF-8') { reader ->          localProperties.load(reader)      }  }    def flutterRoot = localProperties.getProperty('flutter.sdk')  if (flutterRoot == null) {      throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")  }    def flutterVersionCode = localProperties.getProperty('flutter.versionCode')  if (flutterVersionCode == null) {      flutterVersionCode = '1'  }    def flutterVersionName = localProperties.getProperty('flutter.versionName')  if (flutterVersionName == null) {      flutterVersionName = '1.0'  }    apply plugin: 'com.android.application'  // add  apply plugin: 'com.google.gms.google-services'  apply plugin: 'kotlin-android'  apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"    android {      compileSdkVersion 30        sourceSets {          main.java.srcDirs += 'src/main/kotlin'      }        defaultConfig {          applicationId "com.example.association_firebase"          minSdkVersion 21   // changed to 21          targetSdkVersion 30          versionCode flutterVersionCode.toInteger()          versionName flutterVersionName      }        buildTypes {          release {              signingConfig signingConfigs.debug          }      }      // add      dependencies {          api 'com.google.firebase:firebase-ml-vision-image-label-model:19.0.0'      }  }    flutter {      source '../..'  }    dependencies {      implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"      //add      implementation platform('com.google.firebase:firebase-bom:28.0.1')      //add      implementation 'com.google.firebase:firebase-analytics'  }  

//android/build.gradle

buildscript {      ext.kotlin_version = '1.3.50'      repositories {          google()          jcenter()      }        dependencies {          classpath 'com.android.tools.build:gradle:4.1.0'          classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"          //add          classpath 'com.google.gms:google-services:4.3.8'      }  }    allprojects {      repositories {          google()          jcenter()      }  }    rootProject.buildDir = '../build'  subprojects {      project.buildDir = "${rootProject.buildDir}/${project.name}"  }  subprojects {      project.evaluationDependsOn(':app')  }    task clean(type: Delete) {      delete rootProject.buildDir  }  

My WordPress site can't sent email like woocommerce check out

Posted: 19 Jun 2021 10:09 AM PDT

I have an WordPress site Last night I saw this problem after checkout customer can't get the mail and after table reservation customer can't get the mail

I think it's hosting configuration error So what can I do it on host

How can I access a child method in an ArrayList of parent type?

Posted: 19 Jun 2021 10:09 AM PDT

I am working on a problem wherein I need to create a virtual Dessert Shoppe with Java classes. I need to print a sort of receipt that is formatted in a certain way, and I have a class Sundae. I also have an ArrayList of type DessertItem (superclass to Ice Cream, which is superclass to Sundae). I want to access a method in Sundae from this ArrayList, but it won't let me as the ArrayList type is of DessertItem.

Here is the DessertItem class:

public abstract class DessertItem {        protected String name;        public DessertItem() {      this("");    }      public DessertItem(String name) {      if (name.length() <= DessertShoppe.MAX_ITEM_NAME_SIZE)        this.name = name;      else         this.name = name.substring(0,DessertShoppe.MAX_ITEM_NAME_SIZE);    }      public final String getName() {      return name;    }      public abstract int getCost();  }  

The Checkout class (which has the receipt):

import java.util.ArrayList;    public class Checkout {            ArrayList<DessertItem> dessertItems = new ArrayList<DessertItem>();        public int cost;        public void clear() {          dessertItems.clear();      }        public void enterItem(DessertItem item) {          dessertItems.add(item);      }        public int numberOfItems() {          return dessertItems.size();      }        @Override      public String toString() {          String reciept = "      " + DessertShoppe.STORE_NAME + "\n" +                          "      --------------------\n" +                          " \n";          cost = 0;            for (int i = 0; i < dessertItems.size(); i++) {              if (dessertItems.get(i) instanceof IceCream) {                  reciept = reciept + " " + dessertItems.get(i).getName() + "       " + Integer.toString(dessertItems.get(i).getCost()) + "\n";              } else if (dessertItems.get(i) instanceof Sundae) {                  reciept = reciept + (" Unfinished\n");  //              string.concat(" " + dessertItems.get(i).getName()).concat("       " + Integer.toString(dessertItems.get(i).getCost())).concat("\n");              } else if (dessertItems.get(i) instanceof Candy) {  //              string.concat(" " + dessertItems.get(i).getName()).concat("       " + Integer.toString(dessertItems.get(i).getCost())).concat("\n");              } else if (dessertItems.get(i) instanceof Cookie) {                  reciept = reciept + (" Unfinished\n");  //              string.concat(" " + dessertItems.get(i).getName()).concat("       " + Integer.toString(dessertItems.get(i).getCost())).concat("\n");              }                cost += dessertItems.get(i).getCost();          }            double taxRate = DessertShoppe.TAX_RATE;          double tax = taxRate / 100;            reciept.concat(" \n");          reciept.concat(" Tax                         " + tax + "\n");          reciept.concat(" Total Cost                " + (cost * (1 + tax)) + "\n");                    return reciept;      }        public int totalCost() {          cost = 0;            for (int i = 0; i < dessertItems.size(); i++) {              cost += dessertItems.get(i).getCost();          }            return cost;      }        public int totalTax() {          cost = 0;            for (int i = 0; i < dessertItems.size(); i++) {              cost += dessertItems.get(i).getCost();          }          double taxRate = DessertShoppe.TAX_RATE;          double tax = taxRate / 100;            return (int) Math.round(cost * tax);      }  }  

The Sundae class:

public class Sundae extends IceCream {        public String toppingName;      public int cost;      public int toppingCost;        public Sundae() {          this("", 0, "", 0);      }        public Sundae(String newName, int newCost, String newToppingName, int newToppingCost) {          if (newName.length() <= DessertShoppe.MAX_ITEM_NAME_SIZE)              this.name = newName;          else              this.name = newName.substring(0,DessertShoppe.MAX_ITEM_NAME_SIZE);                   if (newToppingName.length() <= DessertShoppe.MAX_ITEM_NAME_SIZE)              this.toppingName = newToppingName;          else              this.toppingName = newToppingName.substring(0,DessertShoppe.MAX_ITEM_NAME_SIZE);            this.cost = newCost;          this.toppingCost = newToppingCost;      }        @Override      public int getCost() {          return cost + toppingCost;      }        public String getToppingName() {          return toppingName;      }  }  

Can I use StackExchange.Redis to store a Null value in Redis?

Posted: 19 Jun 2021 10:09 AM PDT

Is there any way to use the StackExchange.Redis client to store a Null value in Redis?

If you use IDatabase.StringGet(key) then the returning of Null is used to signify that there "was no result". Therefore if you use IDatabase.StringSet(key, null) then the result is you don't know whether there is a Null value or No value!

Is there any mechanism for catering for this? - i.e. you want to cache a negative.

I was rather hoping to avoid any nasty sentinel values (like value ?? new byte[] {1}) that could later cause issues if a value happened to match!

I had a look at RedisValue.Null but that just yields a Null which has the same issues as above.

No comments:

Post a Comment