Monday, November 1, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Populating a matrix with only a single input

Posted: 01 Nov 2021 08:53 AM PDT

I have a code snippet that creates a matrix by populating the upper elements one by one and populate the lower elements afterwards

n = 4  m = np.ones([n,n])  for i in range(0,n):      for j in range(0,n):           if i<j:               x = input()               m[i,j] = float(x)                m[j,i] = 1/float(x)   

and in here the second code I can populate the matrix at once, but I need to populate the elements row-wise from top left to bottom right

n = int(input())  entries = list(map(int, input().split()))  matrix = np.array(entries).reshape(n, n)  

My question is, how can I populate the upper triangle of the matrix like the first snippet, but only by entering a list once like the second one?

Ex.

n=3

Input= 2 3 4 (list)

Output=  [[1.         2.         3.        ]   [0.5        1.         4.        ]   [0.33333333 0.25       1.        ]]  

Looking to create a function that can tell if a user has a certain music streaming app installed?

Posted: 01 Nov 2021 08:53 AM PDT

So, this is a tricky one. I'm working on figuring out if there's a way to make a universal link for musicians that has the ability to try to launch a streaming app like spotify. If it fails, instead of redirecting to the app store, it tries to launch on itunes. If that fails, then it redirects to our website.

I was looking into things like iOS universal linking, but I don't think that's able to do what I'm looking for because we don't own spotify. Any ideas?

Pytesseract keeps on getting syntax or path error

Posted: 01 Nov 2021 08:53 AM PDT

I'm trying to run a python code on my Raspberry Pi, in which I get from some tutorial. I followed everything there; installed the necessary packages or library in order for me to run the script.

The first one:

sudo apt-get install tesseract-ocr  

And I get these following messages.

  • Reading package lists... Done

    Building dependency tree

    Reading state information... Done tesseract-ocr is already the newest version (4.0.0-2).

    The following package was automatically installed and is no longer required: python-colorzero

    Use 'sudo apt autoremove' to remove it.

    0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.

    Screen shot 1

The second one is this:

pip3 install pytesseract  

I changed pip to pip3, since I read somewhere that pip is already obsolete. And so, I get these messages:

And lastly, in order for me to run the script. I install this.

pip3 install pillow  

Same as the above one, I also used pip3 in installing pillow. So, I get these messages:

After installing all the necessary requirements, I tried to run this simple script from the tutorial.

import pytesseract  from PIL import Image  import cv2    img = cv2.imread('platen5.jpeg',cv2.IMREAD_COLOR) #Open the image from which charectors has to be recognized  #img = cv2.resize(img, (620,480) ) #resize the image if required    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #convert to grey to reduce detials  gray = cv2.bilateralFilter(gray, 11, 17, 17) #Blur to reduce noise    original = pytesseract.image_to_string(gray, config='')  #test = (pytesseract.image_to_data(gray, lang=None, config='', nice=0) ) #get confidence level if required  #print(pytesseract.image_to_boxes(gray))    print (original)  

Unfortunately, I still get this syntax error thing though. The only thing I changed from the original script is the 'platen5.jpeg', since it is the saved image of a plate number I have on my file.

Here's the error:

Traceback (most recent call last):

File "tut.py", line 1, in

import pytesseract  

File "/home/pi/pytesseract/init.py", line 2, in

from .pytesseract import ALTONotSupported  

File "/home/pi/pytesseract/pytesseract.py", line 88

f"{tesseract_cmd} is not installed or it's not in your PATH."  

SyntaxError: invalid syntax

 [Screenshot 4][5]  

I am sorry, I'm kinda new to python, and raspberry pi, so I am very dependent on the tutorials on the internet, so I have no idea in which part I did wrong. Or am I missing something? Or everything from the tutorial are already obsolete so, it doesn't work?

Thanks.

Add custom shape on bezier path in SwiftUI

Posted: 01 Nov 2021 08:53 AM PDT

I generated custom Shape from my svg file using custom this online tool

My shape is basically a curved Path line:

enter image description here

I want to add a simple Circle or Rectangle on top of the path at certain points like 30%, 60% etc.

Circle()    .fill(Color.blue)    .frame(width: 20, height: 20)  

What is the correct way to write this function?

Posted: 01 Nov 2021 08:53 AM PDT

I was making a program where first parameter is a list and second parameter is a list of dictionaries. I want to return a list of lists like this:

As an example, if this were a function call: make_lists(['Example'], [{'Example': 'Made-up', 'Extra Keys' : 'Possible'}]) the expected return value would be: [ ['Made-up'] ]

As an second example, if this were a function call: make_lists(['Hint', 'Num'], [{'Hint': 'Length 2 Not Required', 'Num' : 8675309}, {'Num': 1, 'Hint' : 'Use 1st param order'}]) the expected return value would be: [ ['Length 2 Not Required', 8675309], ['Use 1st param order', 1] ]

I have written a code for this but my code does not return a list of lists, it just returns a single list. Please can someone explain? Code

def make_lists(s,lod):    a = []    lol =[]    i = 0    for x in lod:        for y in x:          for k in s:            if(y==k):              lol.append(x.get(y))              i = i+1    return lol  

Expected Output: [ ['Length 2 Not Required', 8675309],['Use 1st param order', 1] ]

Output: ['Length 2 Not Required', 8675309, 1, 'Use 1st param order']

React Native slow / freeze whet i call ethers.Wallet.fromMnemonic() [Ethers js 5.5.1]

Posted: 01 Nov 2021 08:52 AM PDT

when I call ethers.Wallet.fromMnemonic('....') my application freeze for 5/10 seconds and go next (is slow but work). If run application on emulator, work fine, but on android or ios I have this problem. I tried to follow the docs on https://docs.ethers.io/v5/cookbook/react-native/ but i have the same problem

import "react-native-get-random-values"  import "@ethersproject/shims"  import { ethers } from "ethers";    const account = ethers.Wallet.fromMnemonic(mnemonic);  

How to assure that Process.Start will not throw Win32Exception "File not found"

Posted: 01 Nov 2021 08:52 AM PDT

I generate a ProcessStartInfo by referencing a filename-only executable, without giving the absolute path. I expect the operating system to resolve the concrete location by using the PATH environment variable.

However, on some installations, the PATH variable is not set correctly and upon starting the Process by calling Process.Start() it will throw a

System.ComponentModel.Win32Exception

The system cannot find the file specified

Are there programmatic options to precheck if the Process.Start will work beforehand?

I tried to use File.Exists(fileName), but this does only work for files located in the applications working directory.

In the command prompt you could use the following call to determine if it will work:

//example where a file is found  C:\>where calc.exe   C:\Windows\System32\calc.exe    //example where a file is not found  C:\>where foo.exe  INFO: Could not find files for the given pattern(s).  

Is there something alike in .net to determine beforehand if the file path can be resolved so that Process.Start() will not throw?

How to view PDF with JSF in IE?

Posted: 01 Nov 2021 08:52 AM PDT

Task

I have BASE64 encoded string and I need to view it in a new window of Internet Explorer browser.

Existing solution

I've already done that in Google Chrome with StreamedContent class and <p:media>, but IE doesn't support any inline streaming

Possible solution

I tried to stream that pdf on an endpoint like that:

 @GET  
 @Path("doc.pdf")   
@Produces("application/pdf")
  public Response getDoc(@PathParam("id") Long id) {
        Response response = Response.status(Response.Status.NOT_FOUND).build();
     if (id != null && id != 0 && docExist(id).equals("true")) {
        Doc doc = getDoc(id);
                response = Response.ok(new ByteArrayInputStream(Base64.getDecoder().decode(doc.getFileData())))
.build();
         }
         return response;  
}  

Then I try to view it on a jsf page by redirecting to it from a specific controller:

public void redirectToViewer(){
       RequestContext context = RequestContext.getCurrentInstance();      context.execute("window.open('" + PAGE_URL + "', '_blank')");
  }  

It binds on other page like that:

<p:commandButton value="View doc"
>
      <f:actionListener binding="#{docViewController.redirectToViewer()}"/>  </p:commandButton>    

And my page looks like this:

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml"
              xmlns:h="http://xmlns.jcp.org/jsf/html"
             xmlns:p="http://primefaces.org/ui"         xmlns:f="http://java.sun.com/jsf/core">
     <h:head>

</h:head>
     <h:body>
            <div id="main">
                   <p:media value="#{diyaDocViewController.DOC_URL}" player="pdf" width="100%" height="100%"/>
        </div>
     </h:body>
  </html>  

I should mention that receiving of the Doc, class Doc, PAGE_URL, DOC_URL, method binding and the page works properly.

Problem

The mentioned endpoint /doc.pdf is accessed only by authorisation and I don't know if it even possible to authorise in a JSF tag. Also, I'm restricted to write any files to memory, to read it then.

Passed single parameter in mysqli_fetch_array() still getting parameter warning [duplicate]

Posted: 01 Nov 2021 08:54 AM PDT

I am new to PHP and MySQL and I just can't figure this one out. I passed a single parameter in mysqli_fetch_array() , but for some reason getting this error

PHP Warning:  mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /.../admin/index.php on line 159  

below is my index file

    <?php  $books_query=mysqli_query($con,"select * from books");  while($books_rows=mysqli_fetch_array($books_query)){  ?><tr>  <td><?php echo $books_rows['BookID'] ; ?></td>  <td><?php echo $books_rows['Title'] ; ?></td>  <td><?php echo $books_rows['Author'] ; ?></td>  <td><?php echo $books_rows['PublisherName'] ; ?></td>  <td><?php echo $books_rows['CertificateType'] ; ?></td>  <td><?php echo $books_rows['CopyrightYear'] ; ?></td>  <td><?php echo $books_rows['ExpiryOn'] ; ?></td>  

How can I Insert a list of arrays in SQL with WHERE condition?

Posted: 01 Nov 2021 08:53 AM PDT

I am trying to insert some arrays(users) into my SQL table where user_login does not already exist.

INSERT INTO wp_post_count(user_login, post_count, comment_count, premium)   SELECT        FieldName1, FieldName2, FieldName3, FieldName4  FROM    (      Values          ( "a",0,0,0),          ( "a",0,0,0 ),          ( "a",0,0,0 ),          ( "a",0,0,0)    ) AS TempTableName ( FieldName1, FieldName2, FieldName3, FieldName4 )    WHERE NOT EXISTS(       SELECT 1        FROM wp_post_count        WHERE user_login = a    )  

When I run this statement I get the following error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Values          ( "a",0,0,0),          ( "a",0,0,0 ),          ( "a",0,0,0 ),  ' at line 6  

I am not sure what the syntax error is that could be causing this. Is there something I am missing or a better way to do this?

LLVM load array index

Posted: 01 Nov 2021 08:52 AM PDT

It is very shameful that when searching array subscription for llvm, I cannot find any concrete results and most of answers on stackoverflow are actually a hint for experts than a solution.

What I am after is how to load my_array[my_index]. My llvm version is 10.0.0.

I am after a solution working on both global and local array and any variable index.

llvm::Value * address_of_array = ...  llvm::Value * index = ... // a variable index  llvm::LoadInst * loader = ??????  

what should I place instead of the question marks?

Does json.loads() always return a list of dict objects?

Posted: 01 Nov 2021 08:52 AM PDT

Trying to build a wrapper for APIs. Thanks for anything.

Comparing two sets not giving correct results [closed]

Posted: 01 Nov 2021 08:52 AM PDT

OK when Im trying to compare two sets to each other using this method:

temp3 = set(df_filehistory) - set(sftp_ntt)  print(set(df_filehistory).difference(set(sftp_ntt)))  

I do not get the expected result. I intentionally put a blank text file on the ftp to make sure this works, but it doesnt show the text file. I expect to see 'myFile.txt' (the file i put on the ftp) in the difference between these two sets.

What I am trying to do is to compare our audit log in SQL Server of incoming files to the list of files on the clients FTP site. I do not want to loop over each list as thats obviously the worst.

Here is the list in SQL Server:

enter image description here

Here is when I check for the file

enter image description here

here is the file im looking for to test for the differences:

enter image description here

Here is code (all functions and other bits work as intended, in case anyone wants to question that stuff):

import os  import pandas as pd  from zipfile import ZipFile  from dotenv import load_dotenv, find_dotenv  from mymodules import MyLogging, FTP, SendEmail, ODBC  import MyFunctions as fn  import shutil    con = ODBC.CallODBC('NTT')  df_filehistory = ODBC.ReadSQL('NTT', 'SELECT FROM WHERE ')  sftp_ntt = FTP.SFTP('ftp.something.com', 'UID', 'PW').listdir('/Outgoing')     temp3 = set(df_filehistory) - set(sftp_ntt)  print(set(df_filehistory).difference(set(sftp_ntt)))  

Select columns in dataset where at least 90 percent of the values are bigger than zero

Posted: 01 Nov 2021 08:53 AM PDT

I want to select the columns in a dataset where at least 90 percent of the values are bigger than zero. Would appreciate it if someone could show me a code that does this.

Creating 1 step transition matrix, find probability that someone moves to a particular city

Posted: 01 Nov 2021 08:53 AM PDT

I'm looking for a way to find the transition matrix (in R) with probabilities where someone moves. This is how my df looks:

    City_year1         City_year2     <fct>               <fct>     1 Alphen aan den Rijn NA        2 Tynaarlo            NA        3 Eindhoven           NA        4 Emmen               Emmen     5 Emmen               Emmen     6 Schagen             Schagen   7 Bergen              NA        8 Schagen             Schagen   9 Schagen             Schagen  10 Amsterdam           Rotterdam          # .... with 200.000 more rows  

How do I easily create a transition matrix with the probabilities that some one moves from Amsterdam in year 1 to Rotterdam in year 2, based on the data available in this df. Extra info: The number of unique values in year 1 is not necessarily equal to the #unique values in year 2. I have tried to use Markov functions, but without success.

I hope someone can help me!

How to Display data from list in datatable flutter [closed]

Posted: 01 Nov 2021 08:53 AM PDT

I store data in a list and want to display it as a table , How do I display it

How to add my own customization into laravel Model __call method?

Posted: 01 Nov 2021 08:52 AM PDT

When i want to override __call for my Post model, it always return a string which is "hydrate", No matter what i write in __call it always return hydrate as string

class Post extends Model {        public function __call($method, $parameters)      {           parent::__call($method, $parameters);                      // $method always is 'hydrate'      }  }    
$post = Post::find(1);    $post->notExistsMethod(); // return 'hydrate' string  

Detect word and page of occurrence in Word Document

Posted: 01 Nov 2021 08:52 AM PDT

I am trying to detect specific words (with a regex pattern that I already have) in a Word Document. I do not only want to detect the word but also to know in which page it appears, I think of something like a list of tuples: [(WordA, 10), (WordB, 4) ....]

I am able to extract the text from the word document and detect all the words that match the regex pattern but I am not able to know if which page the word appears. Also, I want to detect all the occurrences regardless if they appear in the header, body or footnotes.

Here is my regex pattern:

pattern = re.compile(r'\bDOC[-–—]\d{9}(?!\d)')  

Extraction of text:

import docx2txt     result = docx2txt.process("Word_Document.docx")  

Thank you in advance,

How to handle different suffix in i18next for agglutinative languages (eg. Turkish, Japanese, etc.)

Posted: 01 Nov 2021 08:52 AM PDT

I am trying to add Turkish support in my product. Turkish is agglutinative language. Which means that it tends to express concepts in complex words consisting of many elements, rather than by inflection or by using isolated elements. Currently we have created keys for i18next like following: tr/resourceExample.json

{      "comment":"Yorum",      "comment_plural":"Yorumlar",      "select_label":"{{label}} seç"  }  

Whenever we want to add a sentence like "Select comments" we use

t("resourceExample:select_label",{label:t("resourceExample:comment_plural")})  

Now this works properly for languages like English or Spanish. But for Turkish, the suffix of comment changes if the word is used with verb.

For example, our currently key structure will give output for Turkish following:

Yorumlar seç

But the actual expected result for Turkish is:

Yorumları seç

The reason behind keeping this structure is that we didn't want to create new keys for select_label because Select something is used in many places where something can be replaced by many different words.

So, my question is that is there any functionality in i18next which can help in this situation?

Advance Kusto Queries for Workbook

Posted: 01 Nov 2021 08:53 AM PDT

I am working on writting some queries which will help users visualize some metrics in Appinsight workbook.

I have written some queries which has some parameters based on which it filters and grouping them by metrics name to get graphs for each of those metrics in same panel

Sample query:

customMetrics  | where name=='HeartbeatState'  | where cloud_RoleName=='{cloud_rolename}'  | project timestamp,cloud_RoleName,cloud_RoleInstance,valueCount  

Here if Column grouping setting is set to cloud_RoleInstance, then for every new pod, colour in line graph will change depicting different colour graph for two pods whenever pod restart happen.

Another sample query having multiple graph:

customMetrics  | where name in ('Heap Memory Usage - used', 'Heap Memory Usage - committed','Heap Memory Usage - max')  | where cloud_RoleName == "{cloud_rolename}"  | project timestamp,name,cloud_RoleName,cloud_RoleInstance,valueSum,valueCount  | summarize ['Value']=sum(valueSum)/sum(valueCount) by name,cloud_RoleInstance, bin(timestamp,5m)  

Here data is required for average of 5 minutes.

I want to write query which does double group by, grouping by cloud_RoleInstance as well as name of metrics. Is it possible ?

Thanks in Advance.

Azure Synapse - How to read data from Azure Cosmos DB container containing multiple types in same collection?

Posted: 01 Nov 2021 08:53 AM PDT

I have a container in Azure Cosmos DB that has multiple document types in the same container. So based on the type, the key pairs change. I'm trying to read the data from this container in Synapse using the following code:

cfg = {  "spark.cosmos.accountEndpoint": Endpoint,  "spark.cosmos.accountKey": accountKey,  "spark.cosmos.database": databaseName,  "spark.cosmos.container": containerName,  }    df = spark.read.format("cosmos.oltp").options(**cfg)\      .option("spark.cosmos.read.inferSchema.enabled","true").load()  

However, the schema that I'm getting through this dataframe is of the first row's type. How can I ensure that I read data for one particular type and the schema is inferred accordingly?

Using the MultiCell fpdf method

Posted: 01 Nov 2021 08:53 AM PDT

I am trying to generate a PDF with fpdf. How to use the MultiCell method to adjust the layout of my data in my table. Here is my PHP code:

I am trying to generate a PDF with fpdf. How to use the MultiCell method to adjust the layout of my data in my table. Here is my PHP code:

<?php  require('mysql_table.php');  class PDF extends PDF_MySQL_Table  {  protected $ProcessingTable=false;  protected $aCols=array();  protected $TableX;  protected $HeaderColor;  protected $RowColors;  protected $ColorIndex;  function Header()  {      // Print the table header if necessary      //if($this->ProcessingTable)       //   $this->TableHeader();      // Title      $this->SetFont('Arial','',14);      // Logo  $this->Image('logo.png',160,15,30);  // Saut de ligne  $this->Ln(10);  $this->y0 = $this->GetY();      // Ensure table header is printed      parent::Header();  }  function TableHeader()  {      $this->SetFont('Arial','B',12);      $this->SetX($this->TableX);      $fill=!empty($this->HeaderColor);      if($fill)          $this->SetFillColor($this->HeaderColor[0],$this->HeaderColor[1],$this->HeaderColor[2]);      foreach($this->aCols as $col)          $this->Cell($col['w'],6,$col['c'],1,0,'C',$fill);      $this->Ln();  }     function Row($data)  {      $this->SetX($this->TableX);      $ci=$this->ColorIndex;      $fill=!empty($this->RowColors[$ci]);      if($fill)          $this->SetFillColor($this->RowColors[$ci][0],$this->RowColors[$ci][1],$this->RowColors[$ci][2]);      foreach($this->aCols as $col)          $this->Cell($col['w'],5,$data[$col['f']],1,0,$col['a'],$fill);      $this->Ln();      $this->ColorIndex=1-$ci;  }     function CalcWidths($width, $align)  {      // Compute the widths of the columns      $TableWidth=0;      foreach($this->aCols as $i=>$col)      {          $w=$col['w'];          if($w==-1)              $w=$width/count($this->aCols);          elseif(substr($w,-1)=='%')              $w=$w/100*$width;          $this->aCols[$i]['w']=$w;          $TableWidth+=$w;      }      // Compute the abscissa of the table      if($align=='C')          $this->TableX=max(($this->w-$TableWidth)/2,0);      elseif($align=='R')          $this->TableX=max($this->w-$this->rMargin-$TableWidth,0);      else          $this->TableX=$this->lMargin;  }     function AddCol($field=-1, $width=-1, $caption='', $align='L')  {      // Add a column to the table      if($field==-1)          $field=count($this->aCols);      $this->aCols[]=array('f'=>$field,'c'=>$caption,'w'=>$width,'a'=>$align);  }     function Table($link, $query, $prop=array())  {      // Execute query      $res=mysqli_query($link,$query) or die('Error: '.mysqli_error($link)."<br>Query: $query");      // Add all columns if none was specified      if(count($this->aCols)==0)      {          $nb=mysqli_num_fields($res);          for($i=0;$i<$nb;$i++)              $this->AddCol();      }      // Retrieve column names when not specified      foreach($this->aCols as $i=>$col)      {          if($col['c']=='')          {              if(is_string($col['f']))                  $this->aCols[$i]['c']=ucfirst($col['f']);              else                  $this->aCols[$i]['c']=ucfirst(mysqli_fetch_field_direct($res,$col['f'])->name);          }      }      // Handle properties      if(!isset($prop['width']))          $prop['width']=0;      if($prop['width']==0)          $prop['width']=$this->w-$this->lMargin-$this->rMargin;      if(!isset($prop['align']))          $prop['align']='C';      if(!isset($prop['padding']))          $prop['padding']=$this->cMargin;      $cMargin=$this->cMargin;      $this->cMargin=$prop['padding'];      if(!isset($prop['HeaderColor']))          $prop['HeaderColor']=array();      $this->HeaderColor=$prop['HeaderColor'];      if(!isset($prop['color1']))          $prop['color1']=array();      if(!isset($prop['color2']))          $prop['color2']=array();      $this->RowColors=array($prop['color1'],$prop['color2']);      // Compute column widths      $this->CalcWidths($prop['width'],$prop['align']);      // Print header      $this->TableHeader();      // Print rows      $this->SetFont('Arial','',11);      $this->ColorIndex=0;      $this->ProcessingTable=true;      while($row=mysqli_fetch_array($res))          $this->Row($row);      $this->ProcessingTable=false;      $this->cMargin=$cMargin;      $this->aCols=array();  }  }     // Connect to database  $link = mysqli_connect('localhost','test','test_','test');     $pdf = new PDF();  $pdf->AddPage();  // First table: output all columns  $pdf->Table($link,'SELECT date,details,sender,content,amount,check_status FROM int_transfer WHERE user_id = 142 UNION SELECT date,details,sender,content,amount,check_status FROM tran_acct WHERE user_id = 142 UNION SELECT date,details,sender,content,amount,check_status FROM int_transfer_admin WHERE user_id = 142 ORDER BY date DESC');  $pdf->AddPage();  // Second table: specify 3 columns  $pdf->AddCol('date',25,'','C');  $pdf->AddCol('details',20,'Type');  $pdf->AddCol('sender',30,'Beneficiary','R');   $pdf->AddCol('content',60,'Details ','C');  $pdf->AddCol('amount',20,'Amount');  $pdf->AddCol('check_status',30,'Status','C');     $prop = array('HeaderColor'=>array(255,150,100),              'color1'=>array(210,245,255),              'color2'=>array(255,255,210),              'padding'=>2);  $pdf->Table($link,'SELECT date,details,sender,content,amount,check_status FROM int_transfer WHERE user_id = 142 UNION SELECT date,details,sender,content,amount,check_status FROM tran_acct WHERE user_id = 142 UNION SELECT date,details,sender,content,amount,check_status FROM int_transfer_admin WHERE user_id = 142 ORDER BY date DESC',$prop);  $pdf->Output();     ?>    

What I get as PDF result enter image description here

How I can get such a result, the arrangement of the data in the table is well done. enter image description here

generating one chatRoomId with two userIds

Posted: 01 Nov 2021 08:53 AM PDT

    Future<Stream<QuerySnapshot>> getChatMessages() async {      return chatRoomsRef          .doc(getChatRoomIdByUserId(widget.chatter1.id, widget.chatter2.id))          .collection("messages")          .orderBy("TimeStamp", descending: true)          .snapshots();    }       getChatRoomIdByUserId(String a, String b) {      if (a.substring(0, 1).codeUnitAt(0) > b.substring(0, 1).codeUnitAt(0)) {        return "$b\-$a";      } else {        return "$a\-$b";      }    }  

the problem is I want to create a string named chatRoomId that does not matter if you enter the chat from user id b or user id a ... it should read and write to the same chatRoomId.

but when I tried it creates two chatRoomIds ...

106660068626993723901-110397997856010677626 110397997856010677626-106660068626993723901

How to send custom JSON headers with requests in drf_spectacular (django)?

Posted: 01 Nov 2021 08:53 AM PDT

Can I create an custom description of JSON headers in drf_spectacular without using serializers class in @extend_schema decorator?

How can I get R to follow symbolic links in Windows 10?

Posted: 01 Nov 2021 08:53 AM PDT

I have multiple RStudio projects, each in its own working directory. All of the projects draw data from the same series of CSV files.

I would like to place the CSV files in a separate "data" directory, then put a Windows shortcut inside each project directory pointing to the data directory. The directory structure would thus be:

/data  /project-1  /project-1/data = Windows shortcut pointing to /data  /project-2  /project-2/data = Windows shortcut pointing to /data  etc.  

However, when I attempt to access the "data" directory via the shortcut from e.g. project-1, R generates the following error:

> write.csv(df, "data/df.csv")  Error in file(file, ifelse(append, "a", "w")) :     cannot open the connection  In addition: Warning message:  In file(file, ifelse(append, "a", "w")) :    cannot open file 'data/df.csv': No such file or directory  

What am I doing wrong?

DatePicker From and To

Posted: 01 Nov 2021 08:53 AM PDT

In a form, I have two DatePicker fields which are From and To. In this case user should not be able to choose a value for To less than what he/she choose for the From field.

I just wanted to know is there any SAPUI5 native way to do this comparison and validate the DatePicker fields? In the image blow, you can see that the From has a greater value than the To, which is wrong! In this case, I need to show the validation error around the fields.

enter image description here

What is the workflow for writing Sass or similar?

Posted: 01 Nov 2021 08:52 AM PDT

I am a developer and I am trying to understand one thing... how does the Sass processor fit into the day to day design/development workflow?

Without it it was something simple like saving the CSS file and refresh the page.

But if you use, let's say, something like SASS, how does it change?

If I got it right:

  1. You write your sass files on your favourite text editor
  2. Process it in some way
  3. Check the results on your localhost (or wherever you have the development version)

Is this how the workflow is with Sass or another CSS pre-processor? And if it is, isn't this time consuming?

Spring Boot without the web server

Posted: 01 Nov 2021 08:53 AM PDT

I have a simple Spring Boot application that gets messages from a JMS queue and saves some data to a log file, but does not need a web server. Is there any way of starting Spring Boot without the web server?

Why CSS selectors on links are tricky with underline with hover?

Posted: 01 Nov 2021 08:53 AM PDT

Here are two examples based on this HTML.

<a href="#">      <div class="foo">          hello          <span class="bar">world</span>      </div>  </a>  

In the first one, I make the link not underline on hover, then make a sub-portion of the link underline, and that works fine:

a {      text-decoration:none;  }  a:hover {      text-decoration: none;  }  a:hover .bar {      text-decoration: underline;  }  

http://jsfiddle.net/3qPyX/1/

In the second, I now reverse the selectors so that the second word should be un-underlined. However, now something strange happens. The entire link remains underlined even though the selectors seem like they should remove underline from the second word. <-- (this is the question. why does this happen?)

a {      text-decoration:none;  }  a:hover {      text-decoration: underline;  }  a:hover .bar {      text-decoration: none;  }  

http://jsfiddle.net/EAmwt/

Can someone explain what's going wrong in the second example? Inspecting with Chrome shows the span.bar has a computed style of text-decoration:none.

Update: a few answers explaining how to get around the problem, which is great except that's not really my question. What I want to know is why is this behavior different than, say, bold? For instance, if I try the 2nd example with bold, I get the expected results: http://jsfiddle.net/3qPyX/4/

How to test whether a service is running from the command line

Posted: 01 Nov 2021 08:52 AM PDT

I would like to be able to query whether or not a service is running from a windows batch file. I know I can use:

sc query "ServiceName"

but, this dumps out some text. What I really want is for it to set the errorlevel environment variable so that I can take action on that.

Do you know a simple way I can do this?

UPDATE
Thanks for the answers so far. I'm worried the solutions that parse the text may not work on non English operating systems. Does anybody know a way around this, or am I going to have to bite the bullet and write a console program to get this right.

No comments:

Post a Comment