Thursday, June 24, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How do I make SwiftUI show entire vertical content on iPad?

Posted: 24 Jun 2021 08:12 AM PDT

I have a SwiftUI application that was laid out using an iPhone. Now when I run it on an iPad, it appears to fill the entire width of the screen, but much of the view content is cutoff on the top and bottom. The top level view contains a container (which can hold any number of different views, based on navigation) and a splash view, which times out after the animation. Is there a way to tell it to honor the size required to fit all of the vertical views, and auto-size the width? This is the top level view. I can post more, but that is a lot of code.

import SwiftUI  struct ContentView: View {        @State var showSplash = true        var body: some View {          ZStack() {              ContainerView()              SplashView()                .opacity(showSplash ? 1 : 0)                .onAppear {                  DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {                    withAnimation() {                      self.showSplash = false                      splashDidFinish()                    }                  }              }            }.onAppear {              NSLog(".onAppear()")          }      }      func splashDidFinish() {          NotificationCenter.default.post(name: NSNotification.Name(rawValue: "checkApplicationReady"), object: nil)      }  }  

Determine the region of overlap after stitching in OpenCV

Posted: 24 Jun 2021 08:12 AM PDT

I am trying to stitching images using this blog Image Panorama Stitching with OpenCV

enter image description here

enter image description here

# Apply panorama correction  width = trainImg.shape[1] + queryImg.shape[1]  height = trainImg.shape[0] + queryImg.shape[0]    result = cv2.warpPerspective(trainImg, H, (width, height))  result[0:queryImg.shape[0], 0:queryImg.shape[1]] = queryImg  

Here's Thalles Silva complete code for Image Panorama Stitching with OpenCV

I would like to know how much of the area of the images actual overlap like in this post OpenCV determine area of intersect/overlap

enter image description here

enter image description here

Where and how should I alter Thalles Silva complete code to get the area of intersection, confused?

FFMPEG Recording Audio from Adafruit I2S MEMS Microphone Having Issues

Posted: 24 Jun 2021 08:12 AM PDT

I am attempting to use FFMPEG to record and stream video off a Raspberry Pi Zero using the pi camera and the Adafruit I2S MEMS Microphone. I have successfully gotten video recording, but I am having trouble getting the audio correctly added on.

I followed the directions at https://learn.adafruit.com/adafruit-i2s-mems-microphone-breakout/raspberry-pi-wiring-test and using their command of arecord -D dmic_sv -c2 -r 44100 -f S32_LE -t wav -V mono -v file.wav I do get a correct audio recording with no issues.

However with my FFMPEG command of ffmpeg -f alsa -ar 44100 -ac 2 -c:a pcm_s32le -i default:CARD=sndrpii2scard -vcodec h264 -framerate 30 -i - -pix_fmt yuv420p -preset ultrafast -crf 0 -vcodec copy -codec:a aac -f segment -segment_time 1800 -segment_start_number 1 /RPICRecord%04d.mkv (The last bit starting at -f segment varies depending on recording vs streaming) I get audio that sorta just has a blip and then sounds like it's resetting. The actual recorded video also seems to not play correctly locally, however it does on YouTube. Testing with streaming the video and audio does the same, but it produces a consistent pattern on the audio blips. In the stream video I also finger snap 5 or so times, but you only ever hear 2, so it's for sure not recoding everything.

My limited knowledge of FFMPEG has failed me here to understand why this happens or how to debug this further to work towards a fix. Let me know if there is any additional info or logs that would be beneficial.

Artifactory 7.x - pypi proxy errror

Posted: 24 Jun 2021 08:12 AM PDT

I have a local Pypi repository with simple-default layout. It has anonymous read access granted. I am using this repository to store my libraries. After the upgrade from Artifactory 6.x to 7.x it is not possible to install any library using pip; it worked in 6.x. Following errors are returned on pip install my-python-lib:

Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after   connection broken by 'ReadTimeoutError("HTTPConnectionPool(host='host', port=8081):   Read timed out. (read timeout=30.0)")': /artifactory/api/pypi/my-python-repo/simple/my-python-lib/    Could not install packages due to an EnvironmentError: HTTPConnectionPool(host='host', port=8081):   Max retries exceeded with url: /artifactory/api/pypi/my-python-repo/simple/my-python-lib/ (Caused by   ReadTimeoutError("HTTPConnectionPool(host='host', port=8081): Read timed out. (read timeout=30.0)"))  

Setting longer --default-timeout doesn't work as well.

When I try to open host/artifactory/api/pypi/my-python-repo/simple/my-python-lib/ in the browser, it returns following error (after about 2 minutes):

502 Proxy Error The proxy server received an invalid response from an upstream server. The proxy server could not handle the request GET /artifactory/api/pypi/my-python-repo/simple/my-python-lib/. Reason: Error reading from remote server

Malvika is peculiar about color of balloons

Posted: 24 Jun 2021 08:12 AM PDT

This is a problem of codechef   

Little Malvika is very peculiar about colors. On her birthday, her mom wanted to buy balloons for decorating the house. So she asked her about her color preferences. The sophisticated little person that Malvika is, she likes only two colors — amber and brass. Her mom bought n balloons, each of which was either amber or brass in color. You are provided this information in a string s consisting of characters 'a' and 'b' only, where 'a' denotes that the balloon is amber, where 'b' denotes it being brass colored.

When Malvika saw the balloons, she was furious with anger as she wanted all the balloons of the same color. In her anger, she painted some of the balloons with the opposite color (i.e., she painted some amber ones brass and vice versa) to make all balloons appear to be the same color. As she was very angry, it took her a lot of time to do this, but you can probably show her the right way of doing so, thereby teaching her a lesson to remain calm in difficult situations, by finding out the minimum number of balloons needed to be painted in order to make all of them the same color.

#include <iostream>      using namespace std;      int main() {         string s;                 int n;         cin >> n;                  while (n--)         {             cin >> s;                  int count = 0;         int c = 0;         for(int i = 0; s[i] != '\0'; i++) {            if(s[i] == 'a'){            count++;            }         else if (s[i] == 'b')         {             c++;         }         }          if (c == count)          {              cout << "1" <<endl;                        }else if (c > count )          {              cout << count << endl;                        }else if (c < count)          {              cout << c << endl;          }else if (c == 0 )          {              cout << count << endl;          } else if (count == 0)          {              cout << c << endl;          }         }         return 0;      }           My sample output is correct but the code is failing while submission.  

The sample INPUT/OUTPUT are:

Input: 3 ab bb baaba

Output: 1 0 2

Linux System Call Implementation - Linux Kernel

Posted: 24 Jun 2021 08:12 AM PDT

I am trying to add a new system call that returns the total number of system calls made so far. I can find the count of system calls by writing the below command in terminal.

cat /proc/kallsyms |grep _x64_sys |grep -v _eil* |wc -l  

But i don't know how to implement this command in my new system call's C code. Any help is appreciated.

When is the Github Projects beta slated for general release?

Posted: 24 Jun 2021 08:12 AM PDT

This is the feature that builds on the existing Project implementation but which adds support for custom metadata fields. E.g. Story Points and Priority, so it's a pretty big deal.

Having some idea of when it's due would give me a clue as to how much effort to put into exploring other options in the meantime.

must convert dd-mm-yyyy to yyyy-mm-dd in input type date

Posted: 24 Jun 2021 08:12 AM PDT

code

<tr>     <th>DOB</th>     <td><input type="date" value="{{ results.DOB }}" class="form-field" ng-model="results.DOB"></td>  </tr>  

error

Error: [ngModel:datefmt] http://errors.angularjs.org/1.8.2/ngModel/datefmt?p0=2000-11-07      at angular.js:99      at Array.<anonymous> (angular.js:26870)      at Object.$$format (angular.js:31244)      at Object.$processModelValue (angular.js:31224)      at Object.$$setModelValue (angular.js:31256)      at angular.js:31295      at m.$digest (angular.js:19262)      at m.$apply (angular.js:19630)      at k (angular.js:13473)      at v (angular.js:13730)  

warning The specified value "{{ results.DOB }}" does not conform to the required format, "yyyy-MM-dd". input type="date" format should be yyyy-mm-dd how to change it.

Laravel "where" clause with "like" comparator

Posted: 24 Jun 2021 08:12 AM PDT

I have an array:

$box = implode(',', $ch);     dd($box)  

That returns:

"windows,linux,ios,android"  

(array can contain 1, 2, 3 or 4 elements like that)

I have this eloquent query:

  $vpns = Vpns::where('systemes', 'like', '%'.$box.'%')->get();  

My problem is that only works if the array contains only one element. If it contains more, it returns nothing.

why the image doesn't follow mousemove

Posted: 24 Jun 2021 08:12 AM PDT

I tried many times to find out where is the problem and I can't I followed the instructor his code was running and my code is the same but doesn't run

var move = document.getElementById('move')    document.addEventListener('mousemove', function(e) {      move.style.left = e.clientX      move.style.top = e.clientY    })
<img id="move" src="img.jpg" alt="PIC" />

The incrementing here continues to return a 0 value

Posted: 24 Jun 2021 08:11 AM PDT

I was writing the solution to this codewars problem however I've ran into a bit of an issue.

Problem statement:

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit, e.g.:

persistence(39) # returns 3, because 39=27, 27=14, 1*4=4 and 4 has only one digit

def persistence(n, t=1, x=0):      if len(str(n)) > 1:          number = [int(i) for i in str(n)]          for i in number:              t = t * i          if len(str(t)) > 1:              x += 1              return(persistence(t,x))          else:              return(x)      else:          return 0  

I can't quite figure out what the error is in this code. My hunch is that it's either a parameter error or the way the return() value is placed.

In essence, the code for distilling an integer to it's multiples is correct, so I just added an extra parameter to persistence; setting x = 0 and making it so that each time the if condition was fulfilled it would increment that exact x value. Once the number was distilled, simply output x. Yet it continues to simply output 0 as the final answer. What's the problem here?

RuntimeError: Working outside of request context Flask

Posted: 24 Jun 2021 08:12 AM PDT

I am trying out a web application that captures video from the client, processes it at the server-side and prints appropriate message. I was able to capture the video in frames and process every frame. For displaying the frames back to the client, I used a code from the internet that yields the frame and renders it. However, there needs to be an if condition before yielding the frame.

def gen(camera):      while True:          frame, persons = camera.get_frame()          if persons == 2:              flash('2 people detected.')          yield(b'--frame\r\n'                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')      @app.route('/video_feed')  def video_feed():      return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')  

The if-condition needs to be evaluated and display a flash message. But, whenever there are 2 persons in the frame, the server crashes with the error:

Debugging middleware caught exception in streamed response at a point where response headers were already sent.  Traceback (most recent call last):    File "/Users/nitin/Desktop/cheating detection system/venv/lib/python3.8/site-packages/werkzeug/wsgi.py", line 462, in __next__      return self._next()    File "/Users/nitin/Desktop/cheating detection system/venv/lib/python3.8/site-packages/werkzeug/wrappers/response.py", line 49, in _iter_encoded      for item in iterable:    File "/Users/nitin/Desktop/cheating detection system/system/routes.py", line 273, in gen      flash('2 people detected.')    File "/Users/nitin/Desktop/cheating detection system/venv/lib/python3.8/site-packages/flask/helpers.py", line 389, in flash      flashes = session.get("_flashes", [])    File "/Users/nitin/Desktop/cheating detection system/venv/lib/python3.8/site-packages/werkzeug/local.py", line 422, in __get__      obj = instance._get_current_object()    File "/Users/nitin/Desktop/cheating detection system/venv/lib/python3.8/site-packages/werkzeug/local.py", line 544, in _get_current_object      return self.__local()  # type: ignore    File "/Users/nitin/Desktop/cheating detection system/venv/lib/python3.8/site-packages/flask/globals.py", line 33, in _lookup_req_object      raise RuntimeError(_request_ctx_err_msg)  RuntimeError: Working outside of request context.    This typically means that you attempted to use functionality that needed  an active HTTP request.  Consult the documentation on testing for  information about how to avoid this problem.  

I am new to flask and any help is appreciated.

c# how to get enum name with value

Posted: 24 Jun 2021 08:11 AM PDT

I'm trying to get enum from value

like here

but I get value 2 instead of 35001 or as I want sdirt

public enum material{      dirt = 2  }  public enum sprite{      sdirt = 35002  }  sprite s = (sprite)material.dirt;  

output is 2 instead of sdirt

full code here

how to get sprite enum

How to query from "any"/"map" data type on Tarantool?

Posted: 24 Jun 2021 08:11 AM PDT

Following example from this answer. If I created map without index, how to query the inner value of the map?

box.schema.create_space('x', {format = {[1] = {'id', 'unsigned'}, [2] = {'obj', 'map'}}})  box.space.x:create_index('pk', {parts = {[1] = {field = 1, type = 'unsigned'}}})  box.space.x:insert({2, {text = 'second', timestamp = 123}}  box.execute [[ SELECT * FROM "x" ]]  -- [2, {'timestamp': 123, 'text': 'second'}]  

How to fetch timestamp or text column directly from SQL without creating index?

Tried these but didn't work:

SELECT "obj.text" FROM "x"  SELECT "obj"."text" FROM "x"  SELECT "obj"["text"] FROM "x"  SELECT "obj"->"text" FROM "x"  

how does a function changes the value of a variable outside its scope? Python

Posted: 24 Jun 2021 08:12 AM PDT

i was coding this code and noticed something weird, after my function has been called on the variable, the value of the variable gets changed although its outside of the functions scope, how exactly is this happening?

def test(my_list):    if 11 in my_list and sum(my_list) > 21:      my_list.remove(11)      my_list.append(1)    return sum(my_list)      ca = [11,11]  print(test(ca))  print(ca)  

the above code results to:

12  [11, 1]  

Read/write file only if it exists using fstream

Posted: 24 Jun 2021 08:12 AM PDT

I'm handling a file using fstream, and I need to read and write to it. However, even using std::ios:in, the file continues to be created if it does not exist:

std::fstream file("myfile.txt", std::ios::in | std::ios::out | std::ios::app);    

Any thoughts?

Thanks in advance!

Export PDF file from Excel template with Qt and QAxObject

Posted: 24 Jun 2021 08:12 AM PDT

The project I am currently working on is to export an Excel file to PDF.

The Excel file is a "Template" that allows the generation of graphs. The goal is to fill some cells of the Excel file so that the graphs are generated and then to export the file in PDF.

I use Qt in C++ with the QAxObject class and all the data writing process works well but it's the PDF export part that doesn't.

The problem is that the generated PDF file also contains the data of the graphs while these data are not included in the print area of the Excel template.

The PDF export is done with the "ExportAsFixedFormat" function which has as a parameter the possibility to ignore the print area that is "IgnorePrintAreas" at position 5. Even if I decide to set this parameter to "false", so not to ignore the print area and therefore to take into account the print area, this does not solve the problem and it produces the same result as if this parameter was set to "true".

I tried to vary the other parameters, to change the type of data passed in parameter or not to use any parameter but it does not change anything to the obtained result which is always the same.

Here is the link to the "documentation" of the export command "ExportAsFixedFormat": https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.exportasfixedformat

I give you a simplified version of the command suite that is executed in the code:

Rapport::Rapport(QObject *parent) : QObject(parent)  {          //Create the template from excel file          QString pathTemplate = "/ReportTemplate_FR.xlsx"          QString pathReporter = "/Report"          this->path = QDir(QDir::currentPath() + pathReporter + pathTemplate);          QString pathAbsolute(this->path.absolutePath().replace("/", "\\\\"));             //Create the output pdf file path          fileName = QString("_" + QDateTime::currentDateTime().toString("yyyyMMdd-HHmmssff") + "_Report");          QString pathDocument = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation).append("/").replace("/", "\\\\");          QString exportName(pathDocument + fileName + ".pdf");            //Create the QAxObjet that is linked to the excel template          this->excel = new QAxObject("Excel.Application");            //Create the QAxObject « sheet » who can accepte measure data          QAxObject* workbooks = this->excel->querySubObject("Workbooks");          QAxObject* workbook = workbooks->querySubObject("Add(const QString&)", pathAbsolute);          QAxObject* sheets = workbook->querySubObject("Worksheets");          QAxObject* sheet = sheets->querySubObject("Item(int)", 3);            //Get some data measure to a list of Inner class Measurement          QList<Measurement*> actuMeasure = this->getSomeMeasure() ; //no need to know how it's work…            //Create a 2 dimentional QVector to be able to place data on the table where we want (specific index)           QVector<QVector<QVariant>> vCells(actuMeasure.size());          for(int i = 0; i < vCells.size(); i++)                  vCells[i].resize(6);            //Fill the 2 dimentional QVector with data measure          int row = 0;          foreach(Measurement* m, actuMeasure)          {                  vCells[row][0] = QVariant(m->x);                  vCells[row][1] = QVariant(m->y1);                  vCells[row][2] = QVariant(m->y2);                  vCells[row][3] = QVariant(m->y3);                  vCells[row][4] = QVariant(m->y4);                  vCells[row][5] = QVariant(m->y5);                  row++;          }            //Transform the 2 dimentional QVector on a QVariant object          QVector<QVariant> vvars;          QVariant var;          for(int i = 0; i < actuMeasure.size(); i++)                  vvars.append(QVariant(vCells[i].toList()));          var = QVariant(vvars.toList());            //Set the QVariant object that is the data measure on the excel file          sheet->querySubObject("Range(QString)", "M2:AB501")->setProperty("Value", var);            //Set the fileName on the page setup (not relevant for this example)          sheet->querySubObject("PageSetup")->setProperty("LeftFooter", QVariant(fileName));            //Export to PDF file with options – NOT WORKING !!!          workbook->dynamicCall("ExportAsFixedFormat(const QVariant&, const QVariant&, const QVariant&, const QVariant&, const QVariant&)", QVariant(0), QVariant(exportName), QVariant(0), QVariant(false), QVariant(false));            //Close          workbooks->dynamicCall("Close()");          this->excel->dynamicCall("Quit()");  }  

A this point I really need help to find a way to solve this problem.

I also wonder if this is not a bug of the QAxObject class.

How to get all the matching groups in a file using regex in python

Posted: 24 Jun 2021 08:12 AM PDT

Say I have a file that looks like this:

'2021-06-23T08:02:08Z UTC [ db=dev LOG: BEGIN;  '2021-06-23T08:02:08Z UTC [ db=dev LOG: SET datestyle TO ISO;  '2021-06-23T08:02:08Z UTC [ db=dev LOG: SET TRANSACTION READ ONLY;  '2021-06-23T08:02:08Z UTC [ db=dev LOG: SET STATEMENT_TIMEOUT TO 300000;  '2021-06-23T08:02:08Z UTC [ LOG: /* hash: 8d9692aa66628f2ea5b0b9de8e4ea59b */    SELECT action,         status,         COUNT(*) AS num_req  FROM stl_datashare_changes_consumer  WHERE actiontime > getdate() - INTERVAL '1 day'  GROUP BY 1,2;  '2021-06-23T08:02:08Z UTC [ LOG: SELECT pg_catalog.stll_datashare_changes_consumer.action AS action, pg_catalog.stll_datashare_changes_consumer.status AS status, COUNT(*) AS num_req FROM pg_catalog.stll_datashare_changes_consumer WHERE pg_catalog.stll_datashare_changes_consumer.actiontime > getdate() - interval '1 day'::Interval GROUP BY 1, 2;  '2021-06-23T08:02:08Z UTC [ LOG: COMMIT;  '2021-06-23T08:02:08Z UTC [ LOG: SET query_group to ''  '2021-06-23T08:02:22Z UTC [ LOG: SELECT 1  '2021-06-23T08:02:30Z UTC [ LOG: /* hash: 64f5dca78e917617f51632257854cb2f */  WITH per_commit_info AS  (           SELECT   date_trunc('day', startwork) AS day,                    c.xid,                    SUM(num_metadata_blocks_retained) AS sum_retained,                    SUM(total_metadata_blocks)        AS sum_total,                    AVG(num_metadata_blocks_retained) AS avg_retained,                    AVG(total_metadata_blocks)        AS avg_total           FROM     stl_commit_stats c,                    stl_commit_internal_stats i           WHERE    c.xid = i.xid           < ...even more sql >;  '2021-06-23T08:02:30Z UTC [ LOG: SELECT per_commit_info.day AS day, COUNT(*) AS commits,  

and I want to eventually get a data store that looks like this:

[  {     'timestamp': '2021-06-23T08:02:08Z UTC',      'db': 'dev',     'query': 'LOG: BEGIN;',  },  {     'timestamp': '2021-06-23T08:02:08Z UTC',      'db': 'dev',     'query': 'LOG: <Extremely long query string',  },    ]  

Some of the problems here are that the queries can be multiline and so newlines are not nec

So I have a regex pattern that looks like this:

"(?P<query_date>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z UTC) \[ db=(?P<db>\w*) LOG:(?P<query_text>.*)",  

which I think is close to right. How do I use this to capture all of the matching groups in this file. Can anyone help with this code?

Is the code something like this:

import re  pattern = re.compile(<my pattenr>)    for i, line in enumerate(open(<my file>)):      for match in re.finditer(pattern, line):         <add matching group to empty array after making a dictionary>  

Is it something like that?

How to center "hue" coloring using seaborn stripplot

Posted: 24 Jun 2021 08:12 AM PDT

This is my plot: Plot

I would like the coloring to be centered at 0 within the plot. While I managed to have the legend centered at 0, this does not apply to the dots in the plot (i.e. I would expect them to be gray at the zero value).

This is my code which generates the plots:

import matplotlib.colors as mcolors  import matplotlib.cm as cm  import seaborn as sns    def plot_jitter(df):        plot = sns.stripplot(x='category', y='overall_margin', hue='overall_margin', data=df,                     palette='coolwarm_r',                     jitter=True, edgecolor='none', alpha=.60)      plot.get_legend().set_visible(False)      sns.despine()      plt.axhline(0, 0,1,color='grey').set_linestyle("--")        #Drawing the side color bar      normalize = mcolors.TwoSlopeNorm(vcenter=0, vmin=df['overall_margin'].min(), vmax=df['overall_margin'].max())      colormap = cm.coolwarm_r            [plt.plot(color=colormap(normalize(x))) for x in df['overall_margin']]        scalarmappaple = cm.ScalarMappable(norm=normalize, cmap=colormap)      scalarmappaple.set_array(df['overall_margin'])      plt.colorbar(scalarmappaple)  

why am I getting null pointer in here?

Posted: 24 Jun 2021 08:12 AM PDT

Hello Please help me figure out the problem here. I've looked up it on the StackOverFlow I found some similar questions but not really helped me figure it out.

    if(result.isPresent() && result.get() == ButtonType.OK) {          DialogController dialogController = new DialogController();         dialogController.processResult(); //Line 90          System.out.println("Ok was pressed");      }      else {          System.out.println("Cancel was pressed");      }   

this piece of code is from my main controller.java class and it refers to a dialog by pressing OK in the dialog it runs DialogController.proccessResult() which is supposed to call the proccessResult and print out the content entered in my dialog textArea and textField: SCREENSHOT OF MY DIALOG

    public class DialogController {        @FXML      private TextArea longDescription;      @FXML      private TextField shortDescription;         public void processResult () {          String ld = longDescription.getText().trim(); //Line 24          String sd = shortDescription.getText().trim();          System.Out.PrintLn (ld);          System.Out.PrintLn (sd);      }  }  

but it throws a null pointer exception, what seems to be the problem? I'm new to coding though.

Caused by: java.lang.NullPointerException at untitled18/ir.sepich.todolist.DialogController.processResult(DialogController.java:24) at untitled18/ir.sepich.todolist.controller.showItemNewDialog(controller.java:90) ... 54 more

error: A value of type 'User?' can't be returned from the method 'signInWithGoogle' because it has a return type of 'Future<void>'

Posted: 24 Jun 2021 08:11 AM PDT

I was trying to build a firebase google signin in my flutter project

here is the code of authentication

`https://pastebin.com/1ntBnBSe`  

and the terminal said

error: A value of type 'User?' can't be returned from the method 'signInWithGoogle' because it has a return type of 'Future'. (return_of_invalid_type at [teledentistry_baksos] lib\dummy\authentication.dart:19)

Im new in flutter, Please help me guys

Sleuth traceId and spanId not logged in activeMQ Listener

Posted: 24 Jun 2021 08:12 AM PDT

I'm trying to configure a microservice with Sleuth and ActiveMQ. When starting a request I can properly see appName, traceId and spanId in logs of producer, but after dequeuing the message in listener I find only appName, without traceId and spanId. How can I get this fields filled?

Right now I'm working with spring.sleuth.messaging.jms.enabled=false to avoid this exception at startup:

  • Bean named 'connectionFactory' is expected to be of type 'org.apache.activemq.ActiveMQConnectionFactory' but was actually of type 'org.springframework.cloud.sleuth.instrument.messaging.LazyConnectionFactory'

My dependencies:

  • org.springframework.boot.spring-boot-starter-activemq 2.5.1

  • org.springframework.cloud.spring-cloud-sleuth 3.0.3

Thank you all!

how to send an authentication mail using android studio

Posted: 24 Jun 2021 08:12 AM PDT

I created a signup page for my app and in that it only checks if the email pattern is correct but I want to create a method to check if the mail really exist or if the person is using someone else mail. For that I will need to send a mail to user and verify maybe by asking to click in the link or sending an OTP but idk how to do that this is my code

public class SignUp extends AppCompatActivity implements AdapterView.OnItemSelectedListener {      ActivitySignUpBinding binding;      private FirebaseAuth mAuth;      FirebaseDatabase database;      ProgressDialog progressdialog;      private Spinner spinner;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          binding=ActivitySignUpBinding.inflate(getLayoutInflater());          setContentView(binding.getRoot());          spinner=findViewById(R.id.spinner3);          ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.Options, android.R.layout.simple_spinner_item);          adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);          spinner.setAdapter(adapter);          spinner.setOnItemSelectedListener(this);          mAuth = FirebaseAuth.getInstance();          database=FirebaseDatabase.getInstance();          progressdialog=new ProgressDialog(SignUp.this);          progressdialog.setTitle("Creating Account");          progressdialog.setMessage("please wait while we create your account");          binding.SignUp.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  progressdialog.show();                  mAuth.createUserWithEmailAndPassword(binding.Email.getText().toString()                          ,binding.Password.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>()                  {                      @Override                      public void onComplete(@NonNull  Task<AuthResult> task) {                                                    progressdialog.dismiss();                          if (task.isSuccessful() && !binding.Username.getText().toString().equals("") && !binding.Username.getText().toString().contains("")) {                              Users user=new Users(binding.Username.getText().toString(),binding.Email.getText().toString(),binding.Password.getText().toString());                              String id=task.getResult().getUser().getUid();                              String selectedOption  =  spinner.getSelectedItem().toString();                              database.getReference().child("Users").child(selectedOption).child(id).setValue(user);                              Intent intent;                              if(selectedOption.contains("Driver")){                                  intent = new Intent(SignUp.this, HomePage.class);                              }                              else{                                  intent = new Intent(SignUp.this, Custhomepage.class);                              }                              startActivity(intent);                            }                          else {                              Toast.makeText(SignUp.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();                          }                        }                  });//to check if value match              }          });        }                @Override      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {          String text=parent.getItemAtPosition(position).toString();      }        @Override      public void onNothingSelected(AdapterView<?> parent) {        }  }  

Python - Matrix Identity multiplication

Posted: 24 Jun 2021 08:12 AM PDT

I have a a dataframe a which is

a = [[3],       [12],       [15]]  

and I want to turn it into

b = [[3, 0, 0],       [0, 12,0],       [0, 0, 15]]  

It has been a while since high school and my matrix multiplication is a little off. Any help would be great.

How to secure NIFI site-to-site with basic auth

Posted: 24 Jun 2021 08:12 AM PDT

My purpose is to collect some changed data of remote database to a nifi instance via site-to-site and internet. How could I protect the input port on the internet via user/password ? I'm not meaning ssl connection but prevent unauthorized invokation.

Is site-to-site suitable for this situation ? or use http processors instead of s2s ?

Float graphic figure and caption around text in rmarkdown for hmtl output

Posted: 24 Jun 2021 08:12 AM PDT

I am trying to build an html report using knitr where there is text description with some figures mixed in. If possible, I would like to be able to float a figure to the side and have text in the unused space. I am part of the way there, but my problem is that the figure caption is now dissociated from the figure itself. See image below for example. Here is reproducible code:

---  title: "caption_testing"  author: "Me"  date: "6/23/2021"  output: html_document  ---        ```{r setup, include=FALSE}      knitr::opts_chunk$set(echo = TRUE)      ```  Est pellentesque elit ullamcorper dignissim cras. Turpis egestas maecenas pharetra convallis posuere. Iaculis urna id volutpat lacus laoreet. Id volutpat lacus laoreet non. Vulputate dignissim suspendisse in est ante in. Elit eget gravida cum sociis natoque penatibus. Bibendum at varius vel pharetra vel turpis    ### An uninteresting heading that spans the width of the page.        ```{r echo=FALSE, fig.cap="**Figure 1**. This figure caption to ideally be placed underneath the figure where it will have many words and explain great things. As a bonus, the caption margins will match up with that of the figure.", out.width='60%', out.extra='style="float:right; padding:10px"', fig.align='right'}      knitr::include_graphics('darwinBubble.png')      ```  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Vel eros donec ac odio tempor orci dapibus ultrices in. Auctor augue mauris augue neque. Ornare arcu odio ut sem nulla pharetra diam. Enim blandit volutpat maecenas volutpat. Nisi quis eleifend quam adipiscing vitae proin sagittis nisl. Mi ipsum faucibus vitae aliquet nec ullamcorper. Cursus euismod quis viverra nibh cras pulvinar. Eget nunc scelerisque viverra mauris. Pharetra convallis posuere morbi leo. Elit scelerisque mauris pellentesque pulvinar pellentesque.    Semper risus in hendrerit gravida rutrum quisque non tellus. Massa vitae tortor condimentum lacinia quis vel eros donec. Ultrices gravida dictum fusce ut placerat orci nulla pellentesque dignissim. Nec ultrices dui sapien eget mi proin sed libero. Ac tortor vitae purus faucibus ornare suspendisse sed nisi lacus. Ultrices mi tempus imperdiet nulla. Magna ac placerat vestibulum lectus mauris ultrices. Amet dictum sit amet justo donec enim diam. Neque viverra justo nec ultrices dui sapien. Enim nulla aliquet porttitor lacus luctus accumsan tortor. Etiam non quam lacus suspendisse faucibus interdum posuere lorem. Id velit ut tortor pretium viverra suspendisse potenti nullam ac.    

Here is that same r chunk, but with only the essentials. I don't believe fig.align is doing any or much of the work here, but I got the idea to use out.extra from another SO post that I cannot find right now.

{r echo=FALSE, fig.cap="caption", out.width='60%', out.extra='style="float:right; padding:10px"', fig.align='right'}  knitr::include_graphics('darwinBubble.png')  

And here is what this produces for me.

enter image description here

Thanks in advance, any help appreciated!

Why does this SwiftUI code show "Empty" in the destination screen?

Posted: 24 Jun 2021 08:12 AM PDT

struct ContentView: View {      @State var showModal = false      @State var text = "Empty"      var body: some View {          Button("show text") {              text = "Filled"              showModal = true          }          .sheet(isPresented: $showModal) {              VStack {                  Text(text)                  Button("print text") {                      print(text)                  }                }          }      }  }  

I thought that when the "show text" button was tapped, the value of text would be set to "Filled" and showModal would be set to true, so that the screen specified in sheet would be displayed and the word "Filled" would be shown on that screen.

I thought it would show "Filled", but it actually showed "Empty".

Furthermore, when I printed the text using the print text button, the console displayed "Filled".

Why does it work like this?

What am I missing to display the value I set when I tap the button on the destination screen?

using Xcode12.4, Xcode12.5


Add the code for the new pattern.

struct ContentView: View {      @State var number = 0      @State var showModal = false            var body: some View {          VStack {              Button("set number 1") {                   number = 1                   showModal = true                  print("set number = \(number)")               }                Button("set number 2") {                   number = 2                   showModal = true                  print("set number = \(number)")               }                Button("add number") {                  number += 1                  showModal = true                  print("add number = \(number)")               }          }          .sheet(isPresented: $showModal) {              VStack {                  let _ = print("number = \(number)")                  Text("\(number)")              }          }      }  }  

In the above code, when I first tap "set number 1" or "set number 2", the destination screen shows "0". No matter how many times you tap the same button, "0" will be displayed.

However, if you tap "set number 2" after tapping "set number 1", it will work correctly and display "2". If you continue to tap "set number 1", "1" will be displayed and the app will work correctly.

When you tap "add number" for the first time after the app is launched, "0" will still be displayed, but if you tap "add number" again, "2" will be displayed and the app will count up correctly.

This shows that the rendering of the destination screen can be started even when the @State variable is updated, but only when the @State variable is referenced first in the destination screen, it does not seem to be referenced properly.

Can anyone explain why it behaves this way?

Or does this look like a bug in SwiftUI?

SQL / Postgresql count multiple columns with conditions

Posted: 24 Jun 2021 08:12 AM PDT

I have a simple table of the form:

id gender a_feature (bool) b_feature (bool) ... xyz_feature (bool)

and I want to sum over all feature columns dependent on gender.

metric male female
a_feature 345 3423
b_feature 65 143
... ... ...
xyz_feature 133 5536

Is there a simple way to do this, e.g. using the information_schema.

I found only the solution below, but this is very ugly:

select         'a_feature' as feature_name,         count(case a_feature and gender = 'male') as male,         count(case a_feature and gender = 'female') as female  from table  union  select         b_feature as feature_name,         count(case b_feature and gender = 'male') as male,         count(case b_feature and gender = 'female') as female  from table  .  .  .  select         xyz_feature as feature_name,         count(case xyz_feature and gender = 'male') as male,         count(case xyz_feature and gender = 'female') as female  from table  

Change rectangular Qt button to round

Posted: 24 Jun 2021 08:12 AM PDT

I'm trying to create a round button in Qt. A simple form with a single button QPushButton was created in designer. I'm attempting to turn this into a round button using setMask(). As soon as setMask() is applied the button disappeares. Does a custom widget need to be created to make a round button?

#include "mainwindow.h"  #include "ui_mainwindow.h"  #include <QMessageBox>  #include <QtGui/QPushButton>      MainWindow::MainWindow(QWidget *parent) :      QMainWindow(parent),      ui(new Ui::MainWindow)  {      ui->setupUi(this);        ui->pushButton->setText("Test Text");      ui->pushButton->setFixedHeight(200);      ui->pushButton->setFixedWidth(200);        //Set Starting point of region 5 pixels inside , make region width & height      //values same and less than button size so that we obtain a pure-round shape        QRegion* region = new QRegion(*(new QRect(ui->pushButton->x()+5,ui->pushButton->y()+5,190,190)),QRegion::Ellipse);      ui->pushButton->setMask(*region);      ui->pushButton->show();      }    MainWindow::~MainWindow()  {      delete ui;  }    void MainWindow::on_pushButton_clicked()  {      QMessageBox msgbox;      msgbox.setText("Text was set");      msgbox.show();    }  

Note: If the button is created in code and applied to a window before the window is displayed, the button is displayed. I would like to use the WYSIWIG capabilities of the Qt Designer rather than creating the entire form in code.

Truncate number to two decimal places without rounding

Posted: 24 Jun 2021 08:12 AM PDT

Suppose I have a value of 15.7784514, I want to display it 15.77 with no rounding.

var num = parseFloat(15.7784514);  document.write(num.toFixed(1)+"<br />");  document.write(num.toFixed(2)+"<br />");  document.write(num.toFixed(3)+"<br />");  document.write(num.toFixed(10));  

Results in -

15.8  15.78  15.778  15.7784514000   

How do I display 15.77?

No comments:

Post a Comment