Sunday, April 10, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to find filename in file content with bash script?

Posted: 10 Apr 2022 07:05 AM PDT

I wrote this command in my shell but it's not doing what I wanted and I can't figure out what I did wrong. I want to get files from current directories which include their names in their content.

find -type f -exec grep -il {} +  

I understand find -type f gives me standard files from the directory and -exec executes following grep command with pattern - which is filename - on given file ('+'). Am I right? Because it seems like I don't understand something since it's not finding my file specially created for this purpose.

Display ip address of devices which are connected to android hotspot in a app

Posted: 10 Apr 2022 07:05 AM PDT

I need to display ip address of devices which are connected to android hotspot in a app.

Executing shell and running "/proc/net/arp" or "ip neighbor" are prohibited in Android 9 and later versions.

Please help me.

JedisCluster configurations and how it maintains the pool of connections

Posted: 10 Apr 2022 07:05 AM PDT

I have recently started using JedisCluster for my application. There is little to no documentation and examples for the same. I tested a use case and the results are not what I expected

public class test {  private static JedisCluster setConnection(HashSet<HostAndPort> IP) {      JedisCluster jediscluster = new JedisCluster(IP, 30000, 3,              new GenericObjectPoolConfig() {{                  setMaxTotal(500);                  setMinIdle(1);                  setMaxIdle(500);                  setBlockWhenExhausted(true);                  setMaxWaitMillis(30000);              }});      return jediscluster;  }    public static int getIdleconn(Map<String, JedisPool> nodes){      int i = 0;      for (String k : nodes.keySet()) {          i+=nodes.get(k).getNumIdle();      }      return i;  }    public static void main(String[] args) {        HashSet IP = new HashSet<HostAndPort>() {          {              add(new HostAndPort("bidapi-g-usw1b-rpm-learning-models-c1.srv.media.net", 24100));              add(new HostAndPort("bidapi-g-usw1b-rpm-learning-models-c3.srv.media.net", 24100));          }};        JedisCluster cluster = setConnection(IP);        System.out.println(getIdleconn(cluster.getClusterNodes()));              cluster.set("Dummy", "0");              cluster.set("Dummy1", "0");              cluster.set("Dummy3", "0");      System.out.println(getIdleconn(cluster.getClusterNodes()));        try {          Thread.sleep(60000);      } catch (InterruptedException e) {          e.printStackTrace();      }        System.out.println(getIdleconn(cluster.getClusterNodes()));  }  

}

The output for this snippet is:

0  3  3  

Questions=>

  1. I have set the timeout to 30000 JedisCluster(IP, 30000, 3,new GenericObjectPoolConfig() . I believe this is the connection timeout which means Idle connections are closed after 30 seconds. Although this doesn't seem to be happening. After sleeping for 60 seconds, the number of idle connections is still 3. What I am doing/understanding wrong here? I want the pool to close the connection if not used for more than 30 seconds.

  2. setMinIdle(1). Does this mean that regardless the connection timeout, the pool will always maintain one connection?

  3. I prefer availability more than throughput for my app. What should be the value for setMaxWaitMillis if conn timeout is 30 secs?

  4. Though rare, the app fails with redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException: No reachable node in cluster. This i think is connected to 1. How to prevent this?

Extend default MaterialUI components

Posted: 10 Apr 2022 07:05 AM PDT

I started with MUI5 and I want to add custom components to MUI defaults (like as MuiAlert, MuiBox, etc.).

I've a multi-tenant app with the most common components and need to pass a custom theme to my components. These custom components have the same logic, but I need to use a different theme for them. Of course, I can extend default MUI palette like this one:

declare module '@mui/material/styles/createPalette' {    interface Palette {      brand: string;    }      interface PaletteOptions {      brand: string;    }  }  

but I don't know how to override components property and if it's possible...

Thanks for the advice.

What is the correct input for the program print the word Good Job

Posted: 10 Apr 2022 07:04 AM PDT

#include <stdio.h>

#include <inttypes.h>

#include <stdlib.h>

static int64_t metallica[] = { 32538, 37741, 89540, 14627, 34272, 58765 };

const static int N = sizeof(metallica)/sizeof(*meta llica);

static void fail(){

puts("Nope!");

exit(EXIT_FAILURE); }

static void the_beatles(int64_t h, int64_t s, int64 _t i){

if ( h - i / 7 + 3 * s / 11 )

fail(); }

static void anthrax(int z, int64_t j){

int64_t p = j;

for(; z<N; ++z) {

if ((z % 2) == 0) continue;

p += metallica[z]; }

if (p != 69857)

fail(); }

static void eagles(int k, int64_t d){

if (k<N) {

if (k % 2)

eagles(++k, d);

else eagles(k + 1, d * metallica[k]);

} else if (d != 1269229500)

fail();

} int main(){

int64_t a, e, y;

printf("Please enter the right three numbers: ");

fflush(stdout);

if (scanf("%" SCNd64 " %" SCNd64 " %" SCNd64, &a,

&e, &y) != 3)

fail();

metallica[0] = a;

metallica[5] = e;

metallica[4] = y;

anthrax(0, 15916);

eagles(1, 9);

the_beatles(a, e, y);

puts("Exactly! Good job."); }

Missed Print Line

Posted: 10 Apr 2022 07:04 AM PDT

I am trying to print the code like this


Inserting 1
Inserting 2
Inserting 3
Top element is 3
Removing 3
Removing 2
Removing 1
The stack is empty


But when I run the program, I missed "Inserting 1". can Someone help me?

My code look like this

which profit is great?

Posted: 10 Apr 2022 07:04 AM PDT

Can you please explain which profit is high in below image

This profit

This Profit

Trying to target specific links for styling in CSS

Posted: 10 Apr 2022 07:04 AM PDT

Newbie front-end here:

I'm trying to target just the links in my nav bar as I have inserted other dummy links further down in my home page that I want to style on their own. I have tried adding an ID/class to the section that my header tags live in, and I have also tried targeting each individual with a class or ID attribute. This is lending itself to some functions being applied while others are not. This is purely a little practice site I am building alongside what I learn in my Udemy course, but I wanted real-time feedback. Here is the HTML I have right now:

Welcome to Peter's Penguins!
  <nav class="nav">      <a href="index.html" class="nav-links">Home</a>      <a href="about.html" class="nav-links">About Us</a>      <a href="team.html" class="nav-links">Meet The Team</a>      <a href="contact.html" class="nav-links">Contact Us</a>      <a href="penguins.html" class="nav-links">Our Penguins</a>    </nav>  </header>  

and my (external) CSS is:

    .nav {        font-family: sans-serif;        font-weight: bold;        text-decoration: none;      }        .nav-links {        text-decoration: none;        padding: 5px;        margin: 23px;      }  

Is there a way I can use the pseudo-class property for my LVHA portions? I.e.

    .nav-links a:link {        }          .nav-links a:visited {        }   

Or is this improper syntax?

haw to create many2one with xml rpc ODOO v14?

Posted: 10 Apr 2022 07:04 AM PDT

i want to create PRODUCT I want to show 'categ_id' How can it be accomplished 'categ_id' . fields many2one with XML RPC

Nest multiple routes in Next.js

Posted: 10 Apr 2022 07:03 AM PDT

I want to achieve something like this:


/categories/javascript/es6/functions

/categories/javascript/arrays/methods


How can I achieve it using latest Next.js, I mean what structure inside /pages folder should I have?

Is there a limit of repeated keywords on the app description?

Posted: 10 Apr 2022 07:03 AM PDT

I mean, imagine that I publish an app and on its description of Google Play it has like 15 keywords that are repeated on the description, I have not found anything related to repeating keywords on the google play description. Could google shadow ban my account considering that too many keywords are being repeated and being used only for seo position? Thanks in advance

div margin level why when we apply margin property to lower div it apply on the upper div

Posted: 10 Apr 2022 07:03 AM PDT

Here i have three divs i want the div three to have margin from the top but since then I am giving it the margin to the third div but what and expected to move from the top only bit the complete div is moving

*{      margin:0;    padding:0;  }    .divone{    background-color:red;  }  .divtwo{    margin:10px 4px;  }  .divthree{    display:flex;    justify-content:space-between;  }
<div class="divone">    <div class="divtwo">      <div class="divthree">        <div class="ndiv">          <h3>I am</h3>        </div>        <div class="ndiv">          <h3>Hello</h3>        </div>      </div>    </div>  </div>

Setup ssh tunnel for mysql to mysql server that is accessed through ssh tunnel itself

Posted: 10 Apr 2022 07:03 AM PDT

There is a MySQL server running inside a VM(1) that do not have any port forwarding to public IP and can only be accessed inside the VMWare network. I have an ssh connection to a sibling VM(2) though which I can connect to the VM(1) and can also setup an ssh tunnel to it. How can I connect to MySQL on my local machine? I tried setting up a tunnel on VM(2) like this

ssh -fNTM -S $(dirname "$0")/tmp/$ENV-mysql-socket -L "$mysql":"$mysql_server" "$login"@"$ip" "$ENV.server"  

But when I try to connect to it on my machine an error occurs: handshake: reading initial communication packet

How to define a matric of doubles in C correcltly? [duplicate]

Posted: 10 Apr 2022 07:04 AM PDT

Hi I have a Hilbert matrix of size 5X5 and wanted to do some operation like taking determinant with it. I've deifined it like:

double matrix[N][N] = {      { 1,   -1/2, -1/3, -1/4, -1/5},      {-1/2,  1/3, -1/4, -1/5, -1/6},      {-1/3, -1/4,  1/5, -1/6, -1/7},      {-1/4, -1/5, -1/6,  1/7, -1/8},      {-1/5, -1/6,  -1/7, -1/8, 1/9},    };  

And I've used a print satatement like this:

printf("The determinant is %3.4lf\n", Det);  

But when I take it determinant it gives me 0.0 instead of having -0.03.

I'm 100% sure that calculating determinant part is correct. but I do not know why I don't get float number when I eneter the elements of matrix as 1/2 and not as 0.5. How can I have 1/2, 1/3,.. and still get float number. Is that possible?

How to write C++ macro that places code without parsing?

Posted: 10 Apr 2022 07:04 AM PDT

I did this and it doesnt work as comma perceived a macro params separator

#define PRNT(a) char _s[1024]; \                  snprintf(_s, 1024, a); \                  cout << _s << endl;  int main()  {      int n = 10;      PRNT("print: %d", n)    

What I need is to pass code into macro somehow that it is placed as a whole. In this particular example - I need to write format string and variable number of parameters into snprintf, so it becomes

PRNT("print: %d", n) -> snprinf(_s, 1024, "print: %d", n);  PRNT("another: %d %s", n, s) -> snprinf(_s, 1024, "another: %d %s", n, s);  ...  

Javascript switch statement does not work

Posted: 10 Apr 2022 07:05 AM PDT

This code works perfectly. But if I uncomment the switch statement, it fails completely. The switch statement seems to be correct. Any help will be greatly appreciated.

function draw(n) {      let canvas = document.querySelector('#my-canvas');    let context = canvas.getContext('2d');    context.fillStyle = 'black'      let contourInterval = 1500    let contourWidth = 500    let fsize = 1000    let x0 = fsize / 2    let y0 = fsize / 2      for (j = 0, y = -y0; j < fsize; j++, y++) {      for (i = 0, x = -x0; i < fsize; i++, x++) {        /*              switch(n) {            case 0:              let fun = (x*x + y*y)              break;            case 1:              let fun = (x*x - y*y)                                     break;            case 2:              let fun = 1.0/(x*x + y*y)              break;            default:              let fun = (x*x + y*y)          }        */        let fun = (x * x + y * y)        if (Math.abs(fun % contourInterval) < contourWidth) {          context.fillRect(x + x0 / 2, y + y0 / 2, 1, 1)        }      }    }  }    draw(1)
<canvas id="my-canvas" width="500" height="500"></canvas>

How to pass a state from component to a parent - the App.js (click outside to close navbar)

Posted: 10 Apr 2022 07:06 AM PDT

I would like to pass a state from component Navbar.js to the App.js to do when I click outside the SideMenu() in closes the navbar. How to fix this error? I got an error: Unhandled Runtime Error ReferenceError: setIsSideMenuOpen is not defined in App.js

App.js

import "../styles/globals.css";  import Navbar from "../comps/Navbar";  import { useState, useEffect, useRef } from "react";    let useClickOutside = (handler) => {    let domNode = useRef();      useEffect(() => {      let maybeHandler = (event) => {        if (!domNode.current?.contains(event.target)) {          handler();        }      };        document.addEventListener("mousedown", maybeHandler);        return () => {        document.removeEventListener("mousedown", maybeHandler);      };    });      return domNode;  };    function MyApp({ Component, pageProps }) {    let domNode = useClickOutside(() => {      setIsSideMenuOpen(false);    });    return (      <div className="relative">        <Navbar />        <div ref={domNode}>          <Component {...pageProps} />        </div>      </div>    );  }    export default MyApp;  

../components/Navbar.js

import { useState, useEffect, useRef } from "react";  import { HiMenuAlt1, HiOutlineX } from "react-icons/hi";    export default function Navbar() {    const [isSideMenuOpen, setIsSideMenuOpen] = useState(false);    const showSideMenu = () => {      isSideMenuOpen ? setIsSideMenuOpen(false) : setIsSideMenuOpen(true);    };      return (      <div className="absolute z-40 w-full h-8  text-cyan-600 flex flex-row justify-between items-center text-2xl ">        <div className="brand-logo text-xl font-bold px-2 font-extrabold text-cyan-600">          Trener        </div>        <ul className="md:flex hidden menu-list text-xl font-bold ">          <li className="menu-list-item px-2">            <a href="/">Strona główna</a>          </li>          <li className="menu-list-item px-2">            <a href="#b">O mnie</a>          </li>          <li className="menu-list-item px-2">            <a href="#c">Plany treningowe</a>          </li>        </ul>          <button          onClick={() => {            showSideMenu();          }}          className="lg:hidden menu-button"        >          {isSideMenuOpen ? (            <HiOutlineX className="w-8 h-8 px-2 bg-red-600" />          ) : (            <HiMenuAlt1 className="w-8 h-8 px-2" />          )}        </button>        {isSideMenuOpen ? SideMenu() : ""}      </div>    );  }    function SideMenu() {    return (      <div className="fixed z-20  w-1/2 sm:w-1/4 lg:hidden bg-gray-300 top-8 right-0 p-3">        <ul className="menu-list flex flex-col text-lg font-bold">          <li className="menu-list-item py-2 hover:bg-white hover:text-blue-700">            <a href="/">Strona główna</a>          </li>          <li className="menu-list-item py-2 hover:bg-white hover:text-blue-700">            <a href="/about">O mnie</a>          </li>          <li className="menu-list-item py-2 hover:bg-white hover:text-blue-700">            <a href="#c">Plany treningowe</a>          </li>        </ul>      </div>    );  }    

Is there a way to display an excel sheet onto pygame?

Posted: 10 Apr 2022 07:04 AM PDT

Not quite sure how to phrase this, but I have a database of information in Excel that I want to display to the pygame UI once they click a button. Anyone know if it is even possible?

Edit: The data is something as follows: 1

Binary File Input/Output with Data*Stream Classes

Posted: 10 Apr 2022 07:03 AM PDT

I have the following test program that is writing out a Person record's field values using java.io.DataOutputStream and it writes them out just fine. Then, after a pause that I put in to check the data file, it is supposed to read in the same three records using java.io.DataInputStream, but it reads in the first record, the Person.id of the second record and throws the EOFException, but is not at the end of file. Here's the code:

public class BinaryFileAccessTest {        private static File dataFile = new File(System.getProperty("user.home") + File.separator + "dataFile.dat");            /**       * @param args the command line arguments       */      public static void main(String[] args) {          List<Person> people = new ArrayList<>();                    people.add(new Person("Dough", "John", new Date(70, 03, 17), 23500.00d));          people.add(new Person("Smith", "Sean", new Date(70, 05, 06), 53900.00d));          people.add(new Person("Carrick", "Rebecca", new Date(59, 06, 13), 20000.00d));                    System.out.println("From List<Person> people:");          for (Person p : people) {              System.out.println("\tCreated: " + p.toString());          }                    try (DataOutputStream out = new DataOutputStream(new FileOutputStream(dataFile))) {              System.out.println("Writing Person to file:");              for (Person p : people) {                  out.writeLong(p.getId());                  out.writeUTF(p.getLastName());                  out.writeUTF(p.getFirstName());                  out.write(p.getBirthDate().toString().getBytes());                  out.writeDouble(p.getSalary());                                    System.out.println("\tWrote: " + p.toString());              }          } catch (IOException ex) {              System.err.println("An error occurred writing to " + dataFile);              System.err.println(ex);              ex.printStackTrace(System.err);          }                    Scanner keyboard = new Scanner(System.in);          boolean exit = false;          while (!exit) {              String input = keyboard.nextLine();              if (input != null) {                  exit = true;              }          }                    try (DataInputStream in = new DataInputStream(new FileInputStream(dataFile))) {              people.clear();              System.out.println("Reading Person from file:");                            while (true) {                  Person p = new Person();                  p.setId(in.readLong());                  p.setLastName(in.readUTF());                  p.setFirstName(in.readUTF());                  p.setBirthDate(new Date(in.read()));                  p.setSalary(in.readDouble());                                    System.out.println("\tRead: " + p.toString());                  people.add(p);              }          } catch (IOException ex) {  //            if (!(ex instanceof EOFException)) {                  System.err.println("An error occurred writing to " + dataFile);                  System.err.println(ex);                  ex.printStackTrace(System.err);  //            } else {  //                System.out.println("End of file reached.");  //            }          }                    System.out.println("From List<Person> people:");          for (Person p : people) {              System.out.println("\tContains: " + p.toString());          }               }    }  

The output from this program is:

From List<Person> people:      Created: Dough, John [birth=Fri Apr 17 00:00:00 CST 1970; salary=23500.0      Created: Smith, Sean [birth=Sat Jun 06 00:00:00 CDT 1970; salary=53900.0      Created: Carrick, Rebecca [birth=Mon Jul 13 00:00:00 CDT 1959; salary=20000.0  Writing Person to file:      Wrote: Dough, John [birth=Fri Apr 17 00:00:00 CST 1970; salary=23500.0      Wrote: Smith, Sean [birth=Sat Jun 06 00:00:00 CDT 1970; salary=53900.0      Wrote: Carrick, Rebecca [birth=Mon Jul 13 00:00:00 CDT 1959; salary=20000.0    Reading Person from file:      Read: Dough, John [birth=Wed Dec 31 18:00:00 CST 1969; salary=1.3403241663660614E243  

In the second try...catch block, the first record (for John Dough) is read in and stored in the people list just fine. On the second iteration of the while loop, it reads in the ID value for Sean Smith, then when reading in the last name, it throws the EOFException, even though it is not at the end of the file. When I look at the contents of the file during the program execution pause, it has three blocks of data, which are clearly visible:

𐀀ꑢ?ꣁ???甔? 珐????? ꗌ?쵐?  

Of course, it looks different in the editor in which I look at it, but there are three clear blocks of data present. Yet, after reading the one field from the second block of data, it somehow hits the EOF.

Can anyone explain why this would be? It seems that if these classes are working correctly, when data is written out as I did, then read in by the inverse class, it would read in exactly as it was written out, so it should read in the same number of datapoints as were written.

I guess the better question is, where did I screw this up? ;)

Thank you for any help you can provide!

-SC

[EDIT] I also just noticed that John Dough's salary is not being read back in as the same value as written, neither is his birthDate. Why would this be?

Thx!

Does MongoDB support optional filters?

Posted: 10 Apr 2022 07:04 AM PDT

I have a case where I want to run a query that MUST match some field conditions but SHOULD match some others. If they don't match however the query should still return the conditions that MUST.

For example let's say in a collection I have 3 documents such as:

{ _id: 1, position: "Developer", name: "Greg", surname: "Smith" },  { _id: 2, position: "QA", name: "Andrew", surname: "Samson" },  { _id: 3, position: "Developer", name: "Adam", surname: "Mount" }  

If I run a query with a condition { position: "Developer" } that is a MUST and { name: "Greg" } that is a SHOULD I should just get the record:

{ _id: 1, position: "Developer", name: "Greg", surname: "Smith" }  

However, if I run the query again with { position: "Developer" } and { "name": "Daniel" }, I should get all records that match the MUST condition, therefore I don't want the position condition to fail the query if it doesn't match. So return records:

{ _id: 1, position: "Developer", name: "Greg", surname: "Smith" },  { _id: 3, position: "Developer", name: "Adam", surname: "Mount" }  

Furthermore, if I have a query with MUST conditon { position: "Developer" } and SHOULD conditions { name: "Greg", surname: "Garbrandt" } I should still get:

{ _id: 1, position: "Developer", name: "Greg", surname: "Smith" }  

Not sure if there is a way to write the query to work like this or if there is a functionality that could do this outright.

Add Two Column Values in DataFrame and name it with its Prefix Name

Posted: 10 Apr 2022 07:05 AM PDT

MyData looks like    ID, kgp11274425_M, kgp11274425_F, kgp5732633_M, kgp5732633_F, rs7077812_M, rs7077812_F  1       C                T            G             T              C            A  2       C                C            T             G              A            A  3       A                A            G             G              C            G  4       G                G            C             C              A            A    

Note: Like above I have 522 rows and 369 Columns ( of individual Mother & Father SNP values) which I need to combine

I'm working with GWAS data, these were the SNPs id of our cell containing One Mother Chromosome and Father Chromosome. I would like to combine individual SNP values of M & F into One and Name it with SNP ID (kgp11274425_M + kgp11274425_F = kgp11274425)

Desired Output:  ID, kgp11274425, kgp5732633, rs7077812  1      CT           GT           CA  2      CC           TG           AA  3      AA           GG           CG  4      GG           CC           AA    Can Anyone please help me with Python Code, all support & help needed   

How can I install "npx create-react-app" globally on my machine so It takes less time to create new apps

Posted: 10 Apr 2022 07:04 AM PDT

npx crate-react-app _name takes too much time to create new React-Apps on local, also If I copy from local React-App folder, it takes time to copy all the node_modules as there are large numbers of files in it.

My questions is...

Is there any way by which It can be avoided by simply installing npx crate-react-app _name in local & use them in new React-App globally on my machine

Full Outer Join failing to return all records from both tables

Posted: 10 Apr 2022 07:04 AM PDT

I have a pair of tables I need to join, I want to return any record that's in tableA, tableB or both. I think I need a FULL OUTER JOIN

This query return 1164 records

SELECT name FROM tableA   WHERE reportDay = '2022-Apr-05'  

And this one return 3339 records

SELECT name FROM tableB   WHERE reportDay = '2022-Apr-05'  

And this one returns 3369 records (so there must be 30 records in tableA that aren't in tableB)

select distinct name FROM tableA where reportDay = '2022-Apr-05'  union distinct  select distinct name FROM tableB where reportDay = '2022-Apr-05'  

I want to obtain a list of all matching records in either table. The query above returns 3369 records, so a FULL OUTER JOIN should also return 3369 rows (I think). My best effort so far is shown below. It returns 1164 rows and returns what looks to me to be a left join between tableA and tableB.

SELECT tableA.name.*, tableB.name.*   FROM tableA  FULL OUTER JOIN tableB   ON (tableA.name = tableB.name and tableB.reportDay = '2022-Apr-05')  WHERE tableA.reportDay = '2022-Apr-05'   

Help appreciated. (if this looks question looks familiar, it's a follow-on question to this one )

UPDATE - Some data to help....

DROP TABLE tableA;  DROP TABLE tableB;    CREATE TABLE tableA (    name         VARCHAR(10),    reportDay    DATE,     val1         INTEGER,    val2         INTEGER    );    CREATE TABLE tableB (    name         VARCHAR(10),    reportDay    DATE,     test1        INTEGER,    test2        INTEGER    );    INSERT INTO tableA values   ('A','2022-Apr-05',1,2),   ('B','2022-Apr-05',3,4),  ('C','2022-Apr-05',5,6),  ('Z','2022-Apr-06',5,6)    INSERT INTO tableB values   ('B','2022-Apr-05',11,22),   ('C','2022-Apr-05',33,44),  ('D','2022-Apr-05',55,66),  ('Q','2022-Apr-06',5,6)    SELECT tableA.*, tableB.*   FROM tableA  FULL OUTER JOIN tableB   ON (tableA.name = tableB.name and tableB.reportDay = '2022-Apr-05'  AND  tableA.reportDay = '2022-Apr-05' )  

Additional data....

INSERT INTO tableA values   ('A','2022-Apr-06',1,2),   ('B','2022-Apr-06',3,4),  ('C','2022-Apr-06',5,6)    INSERT INTO tableB values   ('B','2022-Apr-06',11,22),   ('C','2022-Apr-06',33,44),  ('D','2022-Apr-06',55,66)  

For this data, I'd hope to see 4 rows of data 'A' from tableA only, 'B' and 'C' from both tables, and 'D' from table B only. I'm also after the 5th April records only. The fix suggested by forpas works for the initial data, but after the 2nd set of records are added the solution no longer works (also pulls back data for other days)

Weird NoMethodError only in PRODUCTION when new User is created

Posted: 10 Apr 2022 07:02 AM PDT

HELP!

I recently added API functionality for User registration and login via API and devise-jwt. When I pushed this onto my heroku production environment now, it suddenly throws a new error when somebody tries to sign up.

NoMethodError (undefined method `jti' for #<User:0x00007f59d0453ab8>):  app/models/user.rb:33:in `add_jti'  

Signing up locally on my development environment works without any problems. Here are other key points:

  • logging in works fine for already created users
  • Already existing users also have the "jti" attribute and it can be called as a method
  • It is possible to create users via terminal commands on the production environement, here it basically does the same thing as in normal registration but for some reason has no problem calling this "jti" method.
  • The versions of the gems seems to be the same in both variables.
  • debugging in the method that causes the problem shows no problem in development environment

Here is the code for the User model, where the bug is caused...

class User < ApplicationRecord    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :validatable, :trackable      validates :email, uniqueness: true    validates :username, uniqueness: true, format: { without: /\s/ }      has_many :ratings, dependent: :destroy    has_many :reports, dependent: :destroy    has_many :posts, dependent: :destroy       acts_as_voter      before_create :add_jti    def add_jti      self.jti ||= SecureRandom.uuid    end    end  

There is also a model for "Api-User", which makes use of the jwt strategies any everything

class ApiUser < User    include Devise::JWT::RevocationStrategies::JTIMatcher    devise :jwt_authenticatable, jwt_revocation_strategy: self    validates :jti, presence: true    def generate_jwt      JWT.encode({ id: id,                  exp: 5.days.from_now.to_i },                 Rails.env.devise.jwt.secret_key)    end  end  

Thanks for any help!

What concepts and techniques I need to apply for cartoon image retrieval [closed]

Posted: 10 Apr 2022 07:04 AM PDT

I tried Gabor filter, HOG, Haar classifiers and also facial landmarks. But none of these techniques are giving correct results. Lots of misclassifications are there.

Which techniques can be used for feature extracting, feature matching, similarity measures and finally retrieval ?

npm error - verify that the package.json has a valid "main" entry

Posted: 10 Apr 2022 07:04 AM PDT

Im playing around with a simple trading bot using binance and cctx

when i run my script with node index.js

i get this long error:

internal/modules/cjs/loader.js:323        throw err;        ^    Error: Cannot find module '/home/ether/Documents/nodesendeth/node_modules/cctx/index.js'. Please verify that the package.json has a valid "main" entry      at tryPackage (internal/modules/cjs/loader.js:315:19)      at Function.Module._findPath (internal/modules/cjs/loader.js:703:18)      at Function.Module._resolveFilename (internal/modules/cjs/loader.js:967:27)      at Function.Module._load (internal/modules/cjs/loader.js:862:27)      at Module.require (internal/modules/cjs/loader.js:1040:19)      at require (internal/modules/cjs/helpers.js:72:18)      at Object.<anonymous> (/home/ether/Documents/nodesendeth/index.js:2:14)      at Module._compile (internal/modules/cjs/loader.js:1151:30)      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)      at Module.load (internal/modules/cjs/loader.js:1000:32) {    code: 'MODULE_NOT_FOUND',    path: '/home/ether/Documents/nodesendeth/node_modules/cctx/package.json',    requestPath: 'cctx'  }  

so it basically cant find the cctx module cctx was installed with npm i cctx and i also ran npm install afterwards just to make sure.

It also says verify that package.json file has a valid main entry, which it does:

{    "name": "nodesendeth",    "version": "1.0.0",    "description": "",    "main": "index.js",    "scripts": {      "test": "echo \"Error: no test specified\" && exit 1"    },    "author": "",    "license": "ISC",    "dependencies": {      "cctx": "^1.0.1",      "dotenv": "^8.2.0"    }  }  

I pasted the code to my script here https://paste.ubuntu.com/p/p4n6MH3vbn/

Also my await functions arent working- even though i use them in an async function

So Im not a 100% sure what exactly the error is, there is a main entry in the package.json file and the cctx module has been installed

How to get all the metrics of an instance with prometheus api?

Posted: 10 Apr 2022 07:03 AM PDT

I want to fetch the monitor host's metrics through the api of prometheus, and I need to initiate a request for each metric requested.

curl http://IP:9090/api/v1/query?query=node_cpu_seconds_total{instance="IP:9100"}    curl http://IP:9090/api/v1/query?query=node_memory_MemTotal_bytes{instance="IP:9100"}  

Is there a way to request all the performance data from the monitoring host at once?

How to unit test Next.js dynamic components?

Posted: 10 Apr 2022 07:04 AM PDT

The Next.js dynamic() HOC components aren't really straightforward to tests. I have 2 issues right now;

  • First jest is failing to compile dynamic imports properly (require.resolveWeak is not a function - seems to be added by next babel plugin)
  • Second I can't get good coverage of the modules logic; looks like it's simply not run when trying to render a dynamic component.

Unable to see all collections from a MongoDB remote server using mongolite

Posted: 10 Apr 2022 07:05 AM PDT

This may be a trivial problem. I'm able to connect to remote MongoDB server. Im using mongolite for connecting to the db. My DB is mobileapps. I also don't know what to specify in 'collection'. I know I can specify any collection.

library(mongolite)  con=mongo(collection = "test", url = "mongodb://user:password@ds035965.mongolab.com:35965/mobileapps")  

Though it is connecting, but doesn't show any data. Also I don't understand why does it show this for str(con): why is jeroen there.

Classes 'mongo', 'jeroen', 'environment' <environment: 0x0000000014a8ec00>  

It is connecting but I am unable to see all the collections. How do I see all the collections in the db.

Also how do some basic statistics about the collection without querying like column names, types. I could only use con$count() to count the rows in the db. Something similar to db.getCollectionNames() from cmd prompt.

Update 1

I understand that I have to specify a particular collection while connecting from mongolite. But how do I connect using Rmongodb is still an issue.

mongo.create(host = "ds035965.mongolab.com", name = "MobileApp1", username = "user", password = "password ", db = "mobileapps")  

This gives me an error:

Unable to connect to replset  Authentication failed.  

Update 2

When I connect to my local host using rmongodb I get this error.

Error in as.environment(pos) : invalid 'pos' argument  

Even though I'm able to see the db and the collection within, I still get this error. Any thoughts on what's happening?

Django form.save()

Posted: 10 Apr 2022 07:03 AM PDT

I have some problems with CRUD in Django. I can't add an object to the database.

File views.py

@login_required  def persons_add(request):      form = forms.PersonForm(request.POST)      if form.is_valid():          form.save()          return redirect('persons_list')      context = {          'form': form      }      return render(request, 'persons/persons_add.html', context)  

File form.html

<form role="form" method="POST" action="/persons/">      {% csrf_token %}      <table class="table table-bordered">          {% for field in form.visible_fields %}          <tr>              <th>                  {{ field.label }}              </th>              <td>                  {{ field }}              </td>          </tr>          {% endfor %}      </table>      <button type="submit" name="submit" class="btn btn-success">Add Person</button>  </form>  

File forms.py

from django import forms    from persons import models    class PersonForm (forms.ModelForm):      class Meta:          model = models.Person          fields = ['name', 'surname']  

File person_list.html

<tbody>      {% for person in persons_list %}      <tr>          <td>{{ person.name }}</td>          <td>{{ person.surname }}</td>          <td>              <a href="{{ person.id }}/edit"                 <p data-placement="top" data-toggle="tooltip" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil"></span></button></p>              </a>          </td>          <td>              <a href="{{ person.id }}/delete">                  <p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p>              </a>          </td>      </tr>      {% endfor %}  </tbody>  

File urls.py (application)

from django.conf.urls import patterns, include, url  from django.contrib import admin    from persons import views    urlpatterns = patterns('',      #url(r'^$', views.PersonsView.as_view(), name='persons'),      url(r'^$', views.persons_list, name='persons_list'),      url(r'^add/', views.persons_add, name="persons_add"),      url(r'^(?P<person_id>\d+)/edit/$', views.persons_edit, name="persons_edit"),      url(r'^(?P<person_id>\d+)/delete/$', views.persons_delete, name="persons_delete"),  )  

File urls.py (main project)

from django.conf.urls import patterns, include, url  from django.contrib import admin  from hr import views    urlpatterns = patterns('',      url(r'^persons/', include('persons.urls', namespace='persons')),      url(r'^admin/', include(admin.site.urls)),      url(r'^$', views.index, name='index'),      url(r'^logout/$', 'django.contrib.auth.views.logout', {'template_name': 'login.html'}),      url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),  )  

Where is the bug? Why is nothing working here? Why can't I send POST to database and add Person?

No comments:

Post a Comment