Tuesday, March 29, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


com.azure.core.util.serializer.JacksonAdapter - Didn't set coercion defaults as it wasn't found on the classpath

Posted: 29 Mar 2022 01:52 AM PDT

While running the below code, I'm getting error:

String clientId = "*******";      String clientSecret  = "*********";      String tenant  = "********";      ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()              .clientId(clientId)              .clientSecret(clientSecret)              .tenantId(tenant)              .build();        TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(Arrays.asList("https://graph.microsoft.com/Mail.Send"), clientSecretCredential);        GraphServiceClient graphClient =        GraphServiceClient          .builder()          .authenticationProvider(tokenCredentialAuthProvider)          .buildClient();  

Error :

14:07:44.942 [main] DEBUG com.azure.core.util.serializer.JacksonAdapter - Failed to retrieve MethodHandles used to set coercion configurations. Setting coercion configurations will be skipped.java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.cfg.MutableCoercionConfigat java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)at java.base/java.lang.Class.forName0(Native Method)at java.base/java.lang.Class.forName(Class.java:377)at com.azure.core.util.serializer.JacksonAdapter.<clinit>(JacksonAdapter.java:77)at com.azure.identity.implementation.IdentityClient.<clinit>(IdentityClient.java:94)at com.azure.identity.implementation.IdentityClientBuilder.build(IdentityClientBuilder.java:113)at com.azure.identity.ClientSecretCredential.<init>(ClientSecretCredential.java:50)at com.azure.identity.ClientSecretCredentialBuilder.build(ClientSecretCredentialBuilder.java:62)at com.optum.subropoint.subro.fp.utils.MsGraph.main(MsGraph.java:28)14:07:45.850 [main] DEBUG com.azure.core.util.serializer.JacksonAdapter - Didn't set coercion defaults as it wasn't found on the classpath.14:07:46.209 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework

I'm using ms graph api to send an email

How to perform feature selection while relying on predefined train-test sets?

Posted: 29 Mar 2022 01:52 AM PDT

I am using the following code to perform an exhaustive feature selection.

from mlxtend.feature_selection import ExhaustiveFeatureSelector as EFS    efs1 = EFS(xg_cl,              min_features=1,             max_features=X.shape[1],             scoring='accuracy',             print_progress=True,             n_jobs=-1,             cv=5)    efs1 = efs1.fit(X_train, y_train)  

Instead of scoring the model performance with cross validation, while iterating over the features, I am targeting to score the model performance based on special X_train, X_test, y_train, y_test I define.

Why child thread loop can end? How should explain it by Happen-Before?

Posted: 29 Mar 2022 01:52 AM PDT

I am studying "Happen-Before". I know some rule for it. But follow code, I don't understand it.

code1

public class Demo {        private static boolean flag = true;      private static int a = 1;        public static void main(String[] args) throws InterruptedException {          new Thread() {              @Override              public void run() {                  while (flag) {                      a = 3;                  }              }          }.start();            Thread.sleep(1000);          flag = false;      }  }  

For code1, child thread can not stop. I know code1 is not suit Happen-Before rule.

code2

public class Demo {        private static boolean flag = true;        private static Integer b = 1;        public static void main(String[] args) throws InterruptedException {          new Thread() {              @Override              public void run() {                  while (flag) {                       b = 3;                  }              }          }.start();            Thread.sleep(1000);          flag = false;      }  }  

For code2, I think it is not suit for Happen-Before rule, But code2 can end.I am confused.

Asynchronous execution in php

Posted: 29 Mar 2022 01:52 AM PDT

Is it possible to request an external API in php with PG in progress? What we want to achieve is not to proceed with the php process after receiving the response from the external API, but to proceed at the same time.

Is curl_multi able to only proceed with multiple external APIs at the same time, or is it impossible to achieve the above?

Why does this Powershell script for printing out Unix time every second fail?

Posted: 29 Mar 2022 01:52 AM PDT

I wrote a very simple script to write out Unix time every second. Here it is:

while (1) {      $t = Get-Date -UFormat %s      if ($t -ne $(Get-Date -UFormat %s)) {          Write-Host $(Get-Date -UFormat %s)          $t = Get-Date -UFormat %s      }  }  

This sort of works, at least for a bit. After a few prints, it starts lagging behind. Here is an example of what the output of this script is:

1648540841  1648540842  1648540843  1648540845  1648540849  1648540854  1648540855  1648540856  1648540858  1648540860  1648540862  1648540864  1648540865  1648540867  

As you can see, some of the lines are separated by as much as 5 seconds. What causes this behaviour? Is the Get-Date command particularly slow? Even with optimizing the body of the if-statement to have one less call of Get-Date, as such:

if ($t -ne $(Get-Date -UFormat %s)) {      $t = Get-Date -UFormat %s      Write-Host $t  }  

I still get similar results.

re.split() not producing expected results

Posted: 29 Mar 2022 01:52 AM PDT

I am attempting to parse a polynomial using Python, and part of this includes splitting it on a ' + ' or ' - ' (the spaces must be present). My current code is:

polynomial = 'x^2 + 3xy - 42'  terms = re.split(r'(\s\+\s)|(\s-\s)', polynomial)  

I would expect this to produce ['x^2', '3xy', '42']. However, the actual result is ['x^2', ' + ', None, '3xy', None, ' - ', '42']. How would I rewrite the pattern to produce the expected output?

ECS Fargate Task in EventBridge fails with ResourceInitializationError

Posted: 29 Mar 2022 01:52 AM PDT

I have created an ECS Fargate Task, which I can manually run. It updates a Dynomodb and I get logs.

Now I want this to run on a schedule. I have setup a scheduled ECS task through EventBridge. However, this does not run.

My looking at the EventBridge logs I can see that the container has been stopped for the following stopped reason:

ResourceInitializationError: unable to pull secrets or registry auth: execution resource   retrieval failed: unable to retrieve ecr registry auth: service call has been retried 3  time(s): RequestError: send request failed caused by: Post https://api.ecr....  

I thought this might be a problem with permissions. The role assigned to this task has the following permissions:

{      "Version": "2012-10-17",      "Statement": [          {              "Sid": "VisualEditor0",              "Effect": "Allow",              "Action": "ecs:RunTask",              "Resource": "*",              "Condition": {                  "ArnLike": {                      "ecs:cluster": "arn:aws:ecs:*:XXXXXXXXXXX:cluster/YYYYYYYYY"                  }              }          },          {              "Sid": "VisualEditor1",              "Effect": "Allow",              "Action": "iam:PassRole",              "Resource": "*",              "Condition": {                  "StringLike": {                      "iam:PassedToService": "ecs-tasks.amazonaws.com"                  }              }          },          {              "Sid": "VisualEditor2",              "Effect": "Allow",              "Action": [                  "secretsmanager:GetSecretValue",                  "ssm:GetParameters"              ],              "Resource": [                  "arn:aws:ssm:*:XXXXXXXXXXX:parameter/*",                  "arn:aws:secretsmanager:*:XXXXXXXXXXX:secret:*"              ]          }      ]  }  

Is there a permission that I am missing here? Could the problem be something else?

Reactjs client does not get cookie from Express server

Posted: 29 Mar 2022 01:52 AM PDT

My set up as below:

  • Reactjs client in http://localhost:3000
  • Express server in http://localhost:5000

Client:

import { useState } from "react";  import axios from "axios";    import "./App.css";    const API = axios.create({ baseURL: "http://localhost:5000" });    function App() {    const [auth, setAuth] = useState(false);    const login = () => API.post("/login").then((res) => setAuth(true));    const ping = () =>      API.post("/ping", { withCredentials: true }).then((res) =>        console.log(res)      );    return (      <div className="wrapper">        <button className="log-btn btn" onClick={login}>          Login        </button>        {auth && (          <button className="ping-btn btn" onClick={ping}>            Ping          </button>        )}      </div>    );  }    export default App;  

Server:

import express from "express";  import cors from "cors";  import cookieParser from "cookie-parser";  import jwt from "jsonwebtoken";    // Express  const app = express();    // Middlewares  app.use(express.json({ limit: "60mb" }));  app.use(cors());  app.use(cookieParser());    // Routes  app.post("/login", (req, res) => {    const token = jwt.sign({ name: "TOKEN" }, "SECRET_KEY", {      expiresIn: "24h",    });    res.cookie("token", token, {      httpOnly: true,      secure: false,    });    res.status(202).send("LOGGED IN");  });    app.post("/ping", (req, res) => {    console.log(req.cookies);    res.status("202").send("YOU GOT IT");  });    // Run  app.listen(5000, () => {    console.log("Server is running on http://localhost:5000");  });  

My scenario is

  1. Client click Login button to make a post request to api /login
  2. Server receive the request, make a jwt and put in httpOnly cookie then response to client
  3. Client click Ping button to make a post request (contains above cookie) to api /ping
  4. Server receive and verify jwt inside cookie from request

I can see the cookie sent back from server at step 2 (using Chrome Dev Tools):

token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiVE9LRU4iLCJpYXQiOjE2NDg1NDM0MTgsImV4cCI6MTY0ODYyOTgxOH0._PiVonFtdyCo3O-1Xwupd2zxlE-J8DWa9OONVeP4e_s; Path=/; HttpOnly  

But I don't see it in the request at step 3 then in step 4 I get [Object: null prototype] {} when try to print req.cookies

How I can fix this problem ?

Thank you!

Unable to start mysql docker client on Mac M1

Posted: 29 Mar 2022 01:51 AM PDT

I have a docker-compose configuration as follows:

mysql:      image: mysql/mysql-server:8.0.23      ports:        - ${DOCKER_HOST_MYSQL_PORT:-3306}:3306      command: --default-authentication-plugin=mysql_native_password      environment:        MYSQL_ROOT_PASSWORD: secret        MYSQL_DATABASE: ${DB_DATABASE}      volumes:        - ./storage/docker/mysql:/var/lib/mysql      networks:  

then I ran the following: docker-compose up mysql

I'm getting the following error:

[+] Running 5/5   ⠿ mysql Pulled                                                                                                                                   14.1s     ⠿ 517a40cb4717 Pull complete                                                                                                                    5.9s     ⠿ 4a26b26e2152 Pull complete                                                                                                                   10.0s     ⠿ 14794e2450ed Pull complete                                                                                                                   10.0s     ⠿ 754b01a0f0ff Pull complete                                                                                                                   10.0s  [+] Running 1/1   ⠿ Container client-app-mysql-1  Recreated                                                                                                         0.4s  Attaching to client-app-mysql-1  client-app-mysql-1  | [Entrypoint] MySQL Docker Image 8.0.23-1.1.19  client-app-mysql-1  | [Entrypoint] Starting MySQL 8.0.23-1.1.19  client-app-mysql-1  | 2022-03-29T08:41:12.591047Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.23) starting as process 26  client-app-mysql-1  | 2022-03-29T08:41:12.597713Z 0 [Warning] [MY-010159] [Server] Setting lower_case_table_names=2 because file system for /var/lib/mysql/ is case insensitive  client-app-mysql-1  | 2022-03-29T08:41:12.611927Z 1 [System] [MY-011012] [Server] Starting upgrade of data directory.  client-app-mysql-1  | 2022-03-29T08:41:12.612425Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.  client-app-mysql-1  | 2022-03-29T08:41:13.343343Z 1 [ERROR] [MY-012224] [InnoDB] Tablespace flags are invalid in datafile: ./ibdata1, Space ID:0, Flags: 21. Please refer to http://dev.mysql.com/doc/refman/8.0/en/innodb-troubleshooting-datadict.html for how to resolve the issue.  client-app-mysql-1  | 2022-03-29T08:41:13.344157Z 1 [ERROR] [MY-012237] [InnoDB] Corrupted page [page id: space=0, page number=0] of datafile './ibdata1' could not be found in the doublewrite buffer.  client-app-mysql-1  | 2022-03-29T08:41:13.344888Z 1 [ERROR] [MY-012930] [InnoDB] Plugin initialization aborted with error Data structure corruption.  client-app-mysql-1  | 2022-03-29T08:41:13.833188Z 1 [ERROR] [MY-011013] [Server] Failed to initialize DD Storage Engine.  client-app-mysql-1  | 2022-03-29T08:41:13.835836Z 0 [ERROR] [MY-010020] [Server] Data Dictionary initialization failed.  client-app-mysql-1  | 2022-03-29T08:41:13.837260Z 0 [ERROR] [MY-010119] [Server] Aborting  client-app-mysql-1  | 2022-03-29T08:41:13.838870Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.23)  MySQL Community Server - GPL.  client-app-mysql-1 exited with code 1  

Website downloads instead of opens with user-agent Googlebot

Posted: 29 Mar 2022 01:51 AM PDT

On our website we have issues getting our homepage indexed. Google keeps giving errors on this certain url (our homepage), other (simpler) text pages are being indexed fine.

While testing, I've found that if I set my User-Agent to 'Googlebot' and visit my homepage, the page downloads as a file called 'download' rather than opening it. With any other user agent the website works fine.

If I inspect the headers of the request when the website downloads (as Googlebot), the content-type in the header looks strange to me:

content-type: <https://mywebsite.com/wp-json/>; rel="https://api.w.org/", <https://mywebsite.com/wp-json/wp/v2/pages/5089>; rel="alternate"; type="application/json", <https://mywebsite.com/>; rel=shortlink

Showing all column names where value is null

Posted: 29 Mar 2022 01:52 AM PDT

is there anyway i can show all column names where values are null? For example i have table like this:

id name surname
1 Jack NULL
2 NULL Grain
3 NULL NULL

And i want my result to look like that:

id nullFields
1 name
2 surname
3 name, surname

Perfect solution would be some sql which takes all the columns and check them (if there wouldnt be need to manually input column name) but if there is no such possibility "normal solution" will do fine.

Failed to convert object to string[]

Posted: 29 Mar 2022 01:51 AM PDT

There is a method accepting object. I want it to convert it to string[], so I can display it in the console.

// subscriptions = params string[] subscriptions  var subParams = new Dictionary<string, string[]>  {      { "subs", subscriptions }  };    Test(subParams);    public void Test(object subParams)  {      var subscriptions = ((IEnumerable)subParams)                          .Cast<object>()                          .Select(x => x.ToString())                          .ToArray(); // this doesn't work. It converts it to [0] = "[subs, System.String[]]"      Console.WriteLine($"subscribed to {string.Join(", ", subscriptions))}");  }  

Array Push Adds Data Only Once

Posted: 29 Mar 2022 01:52 AM PDT

I can't add more than one data to array. I couldn't solve this problem running on basic javascript events.

$(".add-cart").on("click", function () {          let products = []          let name, price            name = "product 1"          price = "200"            products.push({              name: name,              price: price          })          // i will click so many times and result is only one length array          // products          // [{name: 'product 1', price: 200}]      });  

How can i put button inside textformfield?

Posted: 29 Mar 2022 01:53 AM PDT

I'm trying to create a textformfield that have button inside it. Please check the screenshot

enter image description here

Here is what i do

TextField(                          decoration: InputDecoration(                            prefixIcon: Icon(Icons.search),                            hintText: "Search",                            border: OutlineInputBorder(                              borderRadius: BorderRadius.circular(2.w),                              borderSide: BorderSide(                                width: 0,                                style: BorderStyle.none,                              ),                            ),                            suffixIcon: ElevatedButton(                              child: Text("Search"),                              onPressed: () {},                            ),                          ),                        ),  

Here is result from my script

enter image description here

The button is overlapping the textformfield, how can i fix it ?

git push returns 403 unable to access

Posted: 29 Mar 2022 01:52 AM PDT

I have a project inside my wsl ubuntu, the repo is from git/AWS CodeCommit (not sure since I do not have access, but the remote url is prefixed with git-codecommit),

I set the remote url to https://aws-iam-username:aws-iam-hash-pword@git-codecommit.eu-central-1.amazonaws.com/v1/repos/proj/

when I run, git remote -v:

origin  https://aws-iam-username:aws-iam-hash-pword@git-codecommit.eu-central-1.amazonaws.com/v1/repos/proj (fetch)  origin  https://aws-iam-username:aws-iam-hash-pword@git-codecommit.eu-central-1.amazonaws.com/v1/repos/proj (push)  

when I run, git config -l --global:

user.name=mygitusername  user.email=mygitemail  

Now, when I run git push origin HEAD:branch, it returns:

fatal: unable to access 'https://git-codecommit.eu-central-1.amazonaws.com/v1/repos/proj/': The requested URL returned error: 403  

Why is this happening? and what's the fix?

how to do grouping with one or more index in pandas

Posted: 29 Mar 2022 01:51 AM PDT

Id    Freq     ID2   PSC  a1     0        xy    33  a1     0        yz    35  a1     1        xz    60  a2     0        pq    70  a2     1        qr     75  a2     0        rs     80  

output should be

Id    Freq     ID2   PSC  a1     0        xy    33                  yz    35  a1     1        xz    60  a2     0        pq     70                  rs     80  a2     1        qr     75  

after that check a1 and freq=o psc shlould be unique

Django JWT graphql auth can not detect the logged in user

Posted: 29 Mar 2022 01:52 AM PDT

I have implemented jwt with graphql in django using django-graphql-jwt. I have graphql django userType as :

    class UserType(DjangoObjectType):      class Meta:          model = User          fields = ('id', 'username', 'email','first_name','last_name', 'is_active')  

and have use the tokenAuth for logging the user in. The mutation schema is:

  class Mutation(graphene.ObjectType):            token_auth = graphql_jwt.ObtainJSONWebToken.Field()      refresh_token = graphql_jwt.Refresh.Field()      verify_token = graphql_jwt.Verify.Field()    schema = graphene.Schema(query=Query, mutation=Mutation)  

and I call it by this query and get the response successfully:

mutation loginUser(        $email: String!,        $password: String!) {        tokenAuth(          email: $email,          password: $password) {          token          refreshToken          payload        }      }    

The verifyToken query also works successfully when I call it and put the returned token in my query variables:

  mutation VerifyToken($token: String!) {    verifyToken(token: $token) {      payload    }  }  

But When I want to get the logged in user in a query, Django does not detect it. The query class is implemented as:

  class Query(graphene.ObjectType):      #other stuff      profile = graphene.Field(UserType)        #other resolvers            def resolve_profile(root, info, **kwargs):                    user = info.context.user          #This line always prints "AnonymousUser"          print(user)            jwt_payload_handler = jwt_settings.JWT_PAYLOAD_HANDLER          jwt_encode_handler = jwt_settings.JWT_ENCODE_HANDLER          payload = jwt_payload_handler(user)          token = jwt_encode_handler(payload)          #This line does not print anything (print is not called). probably because the process had an exception in above lines          print("Token is ", token)            try:              return user          except User.DoesNotExist:              return None    

The query is as:

query profile{    profile{    email    username      }      }      

And I put "Authorization": "JWT [the token]" inside the request headers. But I get "'AnonymousUser' object has no attribute 'email'" error in query response.

As far as I understand, I can log in successfully and get a valid token, but when I want user to be authorized with the token, Django can not detect the user in the context.

Merge two dataframes with conditions in pyspark

Posted: 29 Mar 2022 01:52 AM PDT

Df1:  +-------------------+  |               Date|  +-------------------+  |2020-07-01 00:00:00|  |2020-07-02 00:00:00|  |2020-07-03 00:00:00|  |2020-07-04 00:00:00|  |2020-07-05 00:00:00|  |2020-07-06 00:00:00|  |2020-07-07 00:00:00|  |2020-07-08 00:00:00|  |2020-07-09 00:00:00|  |2020-07-10 00:00:00|  +-------------------+  
Df2:  +-------------------+----------+--------+--------+  |               Date|        ID|     Val|   f_val|  +-------------------+----------+--------+--------+  |2022-03-19 00:00:00|        34|     0.0|     0.0|  |2022-03-19 00:00:00|       108|     0.0|     0.0|  |2022-03-19 00:00:00|       155| 3070.61| 3070.61|  |2022-03-19 00:00:00|       193|22920.73|22920.73|  |2022-03-19 00:00:00|       211|   446.0|   446.0|  |2022-03-19 00:00:00|       321| 9314.16| 9314.16|  |2022-03-19 00:00:00|       362|  391.01|  391.01|  |2022-03-19 00:00:00|       368|    1.81|    1.81|  |2022-03-19 00:00:00|       375|    5.08|    5.08|  |2022-03-19 00:00:00|       530| 2444.76| 2444.76|  +-------------------+----------+--------+--------+  

Both the DataFrames have Date starting at 2022-03-19 and ending at 2020-07-01. Df1 contains a series of unique values from end to start date. However, Df2 is rather very large dataset with same dates over multiple rows till 2020-07-01. Date of Df2 has only 186 distinct values, and Date of Df1 has 626. With PySpark in Databricks, what I am trying to achieve here is, merge Date columns of Df1 and Df2 including all the missing dates in Df2, but Df2 should fill the newly acquired rows with the previous row values.

Here is a sample of data when filtered over ID:

+-------------------+----------+--------+--------+  |               Date|        ID|     Val|   f_val|  +-------------------+----------+--------+--------+  |2022-03-11 00:00:00|   Ax3838J|    -8.0|81111.73|  |2022-03-07 00:00:00|   Ax3838J|   17.94|81129.67|  |2022-02-27 00:00:00|   Ax3838J|    20.0|81149.67|  |2021-01-25 00:00:00|   Ax3838J|    40.0|81189.67|  |2021-10-22 00:00:00|   Ax3838J|   89.06|81278.73|  |2021-10-18 00:00:00|   Ax3838J|   10.89|81289.62|  |2021-10-15 00:00:00|   Ax3838J|    60.0|81349.62|  |2021-09-22 00:00:00|   Ax3838J|  -250.0|81099.62|  +-------------------+----------+--------+--------+  

And final expectation is:

+-------------------+----------+--------+--------+  |               Date|        ID|     Val|   f_val|  +-------------------+----------+--------+--------+  |2022-03-11 00:00:00|   Ax3838J|    -8.0|81111.73|  |2022-03-10 00:00:00|   Ax3838J|    -8.0|81111.73|  |2022-03-09 00:00:00|   Ax3838J|    -8.0|81111.73|  |2022-03-08 00:00:00|   Ax3838J|    -8.0|81111.73|  |2022-03-07 00:00:00|   Ax3838J|   17.94|81129.67|  |2022-03-06 00:00:00|   Ax3838J|   17.94|81129.67|  |2022-03-05 00:00:00|   Ax3838J|   17.94|81129.67|  |2022-03-04 00:00:00|   Ax3838J|   17.94|81129.67|  |2022-03-03 00:00:00|   Ax3838J|   17.94|81129.67|  |2022-03-02 00:00:00|   Ax3838J|   17.94|81129.67|         .                   .         .       .         .                   .         .       .  +-------------------+----------+--------+--------+  

Expect if condition with ssh password

Posted: 29 Mar 2022 01:52 AM PDT

I am currently trying to create a script with error handling.

Basically the script tests the ssh connection with this command : ssh -o BatchMode=yes $machine uname -a

There is 3 potential situation that i want to handle :

  1. SSH works just fine without password
  2. SSH is blocked because the machine isn't in the known_hosts file in .ssh
  3. SSH is blocked because the machine isn't in the known_hosts file in .ssh AND it requires a password to continue (which means the id_rsa.pub isn't in the authorized_keys file in .ssh

I have on main script that is calling an expect script here is what the main script looks like :

ssh -o BatchMode=yes ${machine} uname -a &> temp-file.txt 2>&1  # Here we test the ssh connection just once and we store the output of the command in a temp file    if [ $? -eq 255 ]  # If the ssh didn't work    then       if grep -q "Host key verification failed." temp-file.txt     # If the error message is "Host key verification failed."       then        expect script-expect-knownhosts.exp ${machine} 2>&1 >/dev/null  

And here is the script-expect-knownhosts.exp file in which i tried to make a condition :

#!/usr/bin/expect -f    set machine [lindex $argv 0]  # Here we state that the first argument used with the command will be the $machine variable    set prompt "#|%|>|\$ $"    set timeout 60    spawn ssh $machine  # We do a ssh on the machine    set prompt "#|%|>|\$ $"    expect {         "Are you sure you want to continue connecting (yes/no)? "  {send "yes\r";exp_continue}        # If he asks for a yes/no answer, then answer yes to add the machine to the known_hosts file        -exact "Password: " {send -- "^C";exp_continue}       # If he asks for a password, then send a CTRL + C        -re $prompt {send "exit\r";exp_continue}       # If the prompt shows up (if after the yes/no question, we don't need to put a password in) then type exit    }  

So here is what happens when i execute the expect script with a machine in case number 2 (works just fine):

spawn ssh machine  Are you sure you want to continue connecting (yes/no)? yes  machine:~ # exit  deconnection  Connection to machine closed.  

And here is what happens when i execute the expect script with a machine in case number 3 :

spawn ssh machine  Are you sure you want to continue connecting (yes/no)? yes  Password:   

And it stays stuck on Password until i manually do a CTRL + C

Python Pandas: Join two tables keeping no duplicates but also not changing the first table

Posted: 29 Mar 2022 01:52 AM PDT

I need to:

  • Join table1 and table2
  • Eliminate duplicates
  • Keep the originals from table1
  • A dictionary to say which was the id in the old table and which is the new id

Example: The output would be something like this

PS: Thing is, table1 originates from an already in production database, and the id I have here is used in many other tables so I CAN'T change what's already on it, only add the new data that's not already on it. But I will also need to say what's the new id of the data.

table1

id     name      birthdate       1    Goku        1997-12-15   2    Freeza      2000-10-03  3    Vegeta      2003-08-19  

table2

id     name      birthdate  1     Krillin     1983-02-28  2     Roshi       1960-06-07  3     Goku        1997-12-15  4     Freeza      1998-10-10  

So what I need to generate from this are the following

resulting_table1

id    name       birthdate       1     Goku        1997-12-15   2     Freeza      2000-10-03  3     Vegeta      2003-08-19  4     Krillin     1983-02-28  5     Roshi       1960-06-07  6     Freeza      1998-10-10  

but I also need a table that says which code a person was on the old table, and which is the new code, which would also, something like that:

from_to_table

id   origin    new_id  1    table_1     1  2    table_1     2  3    table_1     3  1    table_2     4  2    table_2     2  3    table_2     1  4    table_2     6  

I have tried many methods and the only one I got to work now was doing the insertion row by row and doing the checking on the two fields each time, but that just takes way too much time making it not viable.

So far the best way I found consists basically in: Joining the two tables -> Grouping the data and generating new id column -> join the grouped table with the joined two tables to create the from_to_table problem is, that approach will change the ids I must not change, and I don't know how to keep those.

I need the value of drilldown data with events click

Posted: 29 Mar 2022 01:52 AM PDT

https://semantia.com.au/articles/highcharts-drill-down-stacked-columns/

I am trying to get the value of the column where my cursor is, as I need that value off the graph to get data but it is not working correctly, it is mixing the series with the drilldown data.

Can someone explain to me what is going on... why when I use the "useState" to get the value, something is wrong!

OpenCL local memory exists on Mali/Adreno GPU

Posted: 29 Mar 2022 01:52 AM PDT

  1. Does OpenCL local memory really exist on Mali/Adreno GPU or they only exist in some special mobile phones?
  2. If they exist, in which case should we use local memory, such as GEMM/Conv or other cl kernel?

Jest Coverage fails when using jest.config resetMocks: 'true'

Posted: 29 Mar 2022 01:52 AM PDT

I am using jest config in my package.json:

"jest": {      "coverageThreshold": {        "global": {          "branches": 80,          "functions": 80,          "lines": 80,          "statements": 80        },        "resetMocks": true,        "restoreMocks": true      },      "collectCoverageFrom": [        "src/**/*.{js,ts,tsx}",        "!src/index.js",        "!src/setupTests.js",        "!src/serviceWorker.js",        "!src/setupApollo.js",        "!src/test/**/*",        "!src/mockData/**/*",        "!src"      ],      "coverageReporters": [        "cobertura",        "json",        "json-summary",        "lcov"      ]    },  

All of my coverage parameters pass except I get the following messages at the end:

Jest: Coverage data for resetMocks was not found. Jest: Coverage data for restoreMocks was not found.

How can exclude those two jest methods from coverage?

How to pass a video return from JavaScript to python backend in Django view for OpenCV

Posted: 29 Mar 2022 01:52 AM PDT

I want to do certain tasks and the processes are as follows: 1. Access the camera of the user to get the video-frames from them. 2. Process the video frames from the backend code for facial recognition and some more tasks. 3. Return the processed frame back to the user.

Initially, I had used cv2.VideoCapture(0) and it was simply triggering the camera of the system which was hosting the server, i.e. my personal laptop. So, I used JavaScript to trigger the camera of the user's system. The HTML and JS code is as follows:

<div id="container">      <video autoplay="true" id="videoElement">            </video>  </div>  
<script>      var video = document.querySelector("#videoElement");    if (navigator.mediaDevices.getUserMedia) {    navigator.mediaDevices.getUserMedia({ video: true })      .then(function (stream) {        video.srcObject = stream;      })      .catch(function (err0r) {        console.log("Something went wrong!");      });  }  </script>  

Now I want to get the video feed from the user and link it to the backend to process the video frames.

My views.py :

class VideoCamera():      def __init__(self):          self.video = cv.VideoCapture(0)          success, frame = self.video.read()          ...  

How to bring a data from the web.config to the view controller?

Posted: 29 Mar 2022 01:51 AM PDT

How do I bring data from the web.config to the view controller (xxx.controller.js)?

Why is String.prototype.substr() deprecated?

Posted: 29 Mar 2022 01:52 AM PDT

It is mentioned on the ECMAScript standard here that :

... These features are not considered part of the core ECMAScript language. Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code. ECMAScript implementations are discouraged from implementing these features unless the implementation is part of a web browser or is required to run the same legacy ECMAScript code that web browsers encounter.

There is also a red warning on MDN : String.prototype.substr() MDN doc

Does anyone know why (ECMAScript standard say that) programmers should not use or assume the existence of String.prototype.substr ?

how to find and replace any thing between <a href=""></a> in vs code

Posted: 29 Mar 2022 01:51 AM PDT

I want to find and delete in vs code.

for example

href ="/file/image1"  

and the second instance is

href ="/file/image2"  

I want to delete the href in between anything.

adminer only displays one database

Posted: 29 Mar 2022 01:52 AM PDT

I download Adminer 4.2.5 from https://www.adminer.org/#download which is just one php file around 414 kB in size. I placed this in /localhost/ and was able to log in to database without any issues. But the only problem is that, I have about 24 databases, and adminer only shows tables and contents from 1 database.

This database also happens to be the first one indexed as it starts with letters ab.. so I am guessing it is only grabbing it, but this is not the database I want to fetch. Is there any solution for this?

How to move files with firebase storage?

Posted: 29 Mar 2022 01:51 AM PDT

Is there a way to move files with firebase.storage()?

Example: user1/public/image.jpg to user1/private/image.jpg

How to bring view in front of everything?

Posted: 29 Mar 2022 01:52 AM PDT

I have activity and a lot of widgets on it, some of them have animations and because of the animations some of the widgets are moving (translating) one over another. For example the text view is moving over some buttons . . .

Now the thing is I want the buttons to be always on the front. And when the textview is moving I want to move behind the buttons.

I can not achieve this I tried everything I know, and "bringToFront()" definitelly doesn't work.

note I do not want to control the z-order by the order of placing element to layout cause I simply can't :), the layout is complex and I can not place all the buttons at the begging of the layout

No comments:

Post a Comment