问:
kubernetes queued worker with autoscaling

I have a job queue in sqs/rabbitMQ that has messages arriving infrequently

Each time a message arrives in the queue I would like to spin up a new pod in my kubernetes cluster

All pods will have the exact same configuration, they just perform operations on different data depending on what information they pull out of the queue

When a pod spins up it will need to run for several hours and then can exit.

If a pod fails it will need to restart and ideally read the same message from the queue that it orignally read

There may be times when the message queue is totally empty and all pods have completed. But when a new message arrives in the queue it still needs to spawn a new pod

Can anyone tell me if there are any design patterns for this kind of thing? Or should I be writing a script to manage my pods programatically?

I'm open to any suggestions for any version of kubernetes including aws eks

I've read through some of the design patterns here but they don't seem to fit my use case because

a. Queue with Pod Per Work Item

```<code> 1. Doesn't seem to support jobs that don't complete after a pre-determined number of job completions
</code>```

b. Queue with Variable Pod Count

```<code> 2. Will not spawn new jobs after the first job completes. So it's not long running
</code>```

答:
The currents Job is, in my opinion, lacking for that sort of usage.
However, you can build a controller without too much trouble, if your messages (in the queue) have a reliable ID.

The idea would basically be :

```<code>#!/bin/bash
while true
tasks=$(get list of messages ID)
do
for task in tasks
do
   kubectl apply -f task-consumer-def.yaml -l task_id=$task
done
sleep 60
done
</code>```

In task-consumer-def.yaml, you'd use the Downward API (which allows you to expose Pod information to the containers inside it) to expose the task id on which this worker needs to operate.

It's probably a better idea to use a Job in task-consumer-def, which will take care of the restarting part for you.

This is the operator pattern. Basically, you ensure that each message has a worker assigned to it. I think you can let Kubernetes handle the garbage collection of completed works items. If the message has already a pod assigned, it won't be changed.

You could probably do it more efficiently, or add a maximum, but the concept stays mostly the same.

A variation on that would be to use Indexed Jobs with several work items per Job, but it would be a bit more complicated.

Body:
I have a job queue in sqs/rabbitMQ that has messages arriving infrequently

Each time a message arrives in the queue I would like to spin up a new pod in my kubernetes cluster

All pods will have the exact same configuration, they just perform operations on different data depending on what information they pull out of the queue

When a pod spins up it will need to run for several hours and then can exit.

If a pod fails it will need to restart and ideally read the same message from the queue that it orignally read

There may be times when the message queue is totally empty and all pods have completed. But when a new message arrives in the queue it still needs to spawn a new pod

Can anyone tell me if there are any design patterns for this kind of thing? Or should I be writing a script to manage my pods programatically?

I'm open to any suggestions for any version of kubernetes including aws eks

I've read through some of the design patterns here but they don't seem to fit my use case because

a. Queue with Pod Per Work Item

 1. Doesn't seem to support jobs that don't complete after a pre-determined number of job completions

b. Queue with Variable Pod Count

 2. Will not spawn new jobs after the first job completes. So it's not long running

Body:
The currents Job is, in my opinion, lacking for that sort of usage.
However, you can build a controller without too much trouble, if your messages (in the queue) have a reliable ID.

The idea would basically be :

#!/bin/bash
while true
tasks=$(get list of messages ID)
do
for task in tasks
do
   kubectl apply -f task-consumer-def.yaml -l task_id=$task
done
sleep 60
done

In task-consumer-def.yaml, you'd use the Downward API (which allows you to expose Pod information to the containers inside it) to expose the task id on which this worker needs to operate.

It's probably a better idea to use a Job in task-consumer-def, which will take care of the restarting part for you.

This is the operator pattern. Basically, you ensure that each message has a worker assigned to it. I think you can let Kubernetes handle the garbage collection of completed works items. If the message has already a pod assigned, it won't be changed.

You could probably do it more efficiently, or add a maximum, but the concept stays mostly the same.

A variation on that would be to use Indexed Jobs with several work items per Job, but it would be a bit more complicated.


来源: stackexchange

问:
Flutter WillPopScope doesn't respond
I am trying to get back button of phone to go to specific page using WillPopScope but it does not work (won't respond) at all.

Code

```<code>@override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context)!.settings.arguments as ArticleArgument;

    return WillPopScope(
      onWillPop: () async {
        Navigator.pushReplacementNamed(
          context,
          '/category',
          arguments: CategoryArgument(
            args.catSlug,
            args.catName,
          ),
        );
        return true;
      },
      child: Scaffold(...)
     );
}
</code>```

Any idea?

答:
Try this:</p>
```<code>  onWillPop: () async {
        await Navigator.pushReplacementNamed(
          context,
          '/category',
          arguments: CategoryArgument(
            args.catSlug,
            args.catName,
          ),
        );
        return true;
      }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Flutter WillPopScope doesn't respond

Body:
I am trying to get back button of phone to go to specific page using WillPopScope but it does not work (won't respond) at all.

Code

@override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context)!.settings.arguments as ArticleArgument;

    return WillPopScope(
      onWillPop: () async {
        Navigator.pushReplacementNamed(
          context,
          '/category',
          arguments: CategoryArgument(
            args.catSlug,
            args.catName,
          ),
        );
        return true;
      },
      child: Scaffold(...)
     );
}

Any idea?

Body:
Try this:

  onWillPop: () async {
        await Navigator.pushReplacementNamed(
          context,
          '/category',
          arguments: CategoryArgument(
            args.catSlug,
            args.catName,
          ),
        );
        return true;
      }


问:
XUnit Assertion for checking equality of objects
I am using XUnit framework to test my C# code.

Is there any assert method available in this framework which does the object comparison? My intention is to check for equality of each of the object's public and private member variables.

I tried those alternatives but seldom it works:

```<code>1) bool IsEqual = (Obj1 == Obj2)
2) Assert.Same(Obj1, Obj2) which I couldnt understand what happens internally
</code>```

答:
Here is another implementation of the IEqualityComparer interface with a really GenericComparer

And for asserting that 2 lists of same type are equal, regardless of the list container, you can add this extension:

```<code>public static bool IsEqualTo<T>(this IEnumerable<T> list, IEnumerable<T> expected) where T : class
{
    if (!list.HasSameLengthThan<T>(expected))
        return false;

    Assert.Equal(expected, list, new GenericComparer<T>());
    return true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using XUnit framework to test my C# code.

Is there any assert method available in this framework which does the object comparison? My intention is to check for equality of each of the object's public and private member variables.

I tried those alternatives but seldom it works:

1) bool IsEqual = (Obj1 == Obj2)
2) Assert.Same(Obj1, Obj2) which I couldnt understand what happens internally

Body:
Here is another implementation of the IEqualityComparer interface with a really GenericComparer

And for asserting that 2 lists of same type are equal, regardless of the list container, you can add this extension:

public static bool IsEqualTo<T>(this IEnumerable<T> list, IEnumerable<T> expected) where T : class
{
    if (!list.HasSameLengthThan<T>(expected))
        return false;

    Assert.Equal(expected, list, new GenericComparer<T>());
    return true;
}


问:
when i implement third party library in android studio ,android studio show error in Task Failed with an exception in build

1: Task failed with an exception.

What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.

Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
Could not find com.irozon.sneaker:sneaker:2.0.0.
Searched in the following locations:
- https://dl.google.com/dl/android/maven2/com/irozon/sneaker/sneaker/2.0.0/sneaker-2.0.0.pom
- https://repo.maven.apache.org/maven2/com/irozon/sneaker/sneaker/2.0.0/sneaker-2.0.0.pom
Required by:
project :app
Could not find com.kaopiz:kprogresshud:1.2.0.
Searched in the following locations:
- https://dl.google.com/dl/android/maven2/com/kaopiz/kprogresshud/1.2.0/kprogresshud-1.2.0.pom
- https://repo.maven.apache.org/maven2/com/kaopiz/kprogresshud/1.2.0/kprogresshud-1.2.0.pom
Required by:
project :app

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

答:
It's not blame of Android Studio, it's just Gradle can't find your declared dependency in your maven repositories.

That library stores in jitpack repository you not declared, just declare it in repositories block in your build.gradle in app module.

```<code>maven { url 'https://jitpack.io' }
</code>```

or if you use Gradle kotlin DSL

maven(url = "https://jitpack.io")
```

Body:
It's not blame of Android Studio, it's just Gradle can't find your declared dependency in your maven repositories.

That library stores in jitpack repository you not declared, just declare it in repositories block in your build.gradle in app module.

maven { url 'https://jitpack.io' }

or if you use Gradle kotlin DSL

maven(url = "https://jitpack.io")


问:
Mocking Entity Framework Context
I'm using the entity framework to access my database and I want to mock the database context inside my unit tests so that I can test my middle tier classes free of their dependency on real data. I know that I'm not the first to ask about this (Mocking an Entity Framework Model), but after some googling I have an instinct that it might be possible to instantiate the context based on the model's metadata alone.

Has anyone been able to do this?

答: A well known way of doing this is to use the Repository pattern. This acts as a layer over your concrete data access implementation and provides a place to inject test doubles.</p>

ContentLicense: CC BY-SA 2.5

Title: Mocking Entity Framework Context

OwnerDisplayName: Andrew Peters


问:
size of C structure
```<code>struct st1{
    int a:1; int b:3; int c:6; int d:3;
}s1;

struct st2{
    char a:3;
}s2;

int main(){
    printf("%d : %d",sizeof(s1),sizeof(s2));
    getchar();
}
</code>```

I am getting the output as 2 : 1

will you please tell me, how this program works and whats the use of : operator (a:1) here.

Thank you

答:
There's at least two things worth noting here:

Every object must be addressable, which means it will at least occupy the size of one char.

The implementation is free to add padding for alignment or other issues as it sees fit. Iow, a struct containing two ints is not guaranteed to be equal in size to sizeof(int)*2.

Title: size of C structure

Body:
struct st1{
    int a:1; int b:3; int c:6; int d:3;
}s1;

struct st2{
    char a:3;
}s2;

int main(){
    printf("%d : %d",sizeof(s1),sizeof(s2));
    getchar();
}

I am getting the output as 2 : 1

will you please tell me, how this program works and whats the use of : operator (a:1) here.

Thank you


问:
Android Error when communicating with the Firebase Installations server API
I am getting an Error Message on App Startup Stating Logs like

```<code>W/Firebase-Installations: Error when communicating with the Firebase Installations server API. HTTP response: [400 Bad Request: {
  "error": {
    "code": 400,
    "message": "API key not valid. Please pass a valid API key.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developers console",
            "url": "https://console.developers.google.com"
          }
        ]
      }
    ]
  }
}
]
2020-04-27 12:42:34.621 22226-23596/in.co.androidapp.g7 E/Firebase-Installations: Firebase Installations can not communicate with Firebase server APIs due to invalid configuration. Please update your Firebase initialization process and set valid Firebase options (API key, Project ID, Application ID) when initializing Firebase.
</code>```

I got an email about a week earlier that I should update my google_services.json File, which I have done 4-5 times. No Improvements. It had been working fine for around a year. Its been only 2-3 days since I am facing this issue in the app.

Subsequently, Firebase Cloud Messaging and other firebase services are not working. I am not doing programmatic initialization (that is, using a FirebaseOptions object to provide these values), just the default initialization using FirebaseApp.initializeApp(this);

I have tried https://github.com/firebase/firebase-android-sdk/blob/master/firebase-installations/API_KEY_RESTRICTIONS.md

Thanks in Advance.

答:
This is mainly happened by your outdated google-services.json file. because sometime you may enable some extra services in firebase has changed the entire structure of that file. so go to your firebase console -> project settings -> download google-services.json and replace it

then rebuild your app. Now you check your firebase has error

Body:
I am getting an Error Message on App Startup Stating Logs like

W/Firebase-Installations: Error when communicating with the Firebase Installations server API. HTTP response: [400 Bad Request: {
  "error": {
    "code": 400,
    "message": "API key not valid. Please pass a valid API key.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developers console",
            "url": "https://console.developers.google.com"
          }
        ]
      }
    ]
  }
}
]
2020-04-27 12:42:34.621 22226-23596/in.co.androidapp.g7 E/Firebase-Installations: Firebase Installations can not communicate with Firebase server APIs due to invalid configuration. Please update your Firebase initialization process and set valid Firebase options (API key, Project ID, Application ID) when initializing Firebase.

I got an email about a week earlier that I should update my google_services.json File, which I have done 4-5 times. No Improvements. It had been working fine for around a year. Its been only 2-3 days since I am facing this issue in the app.

Subsequently, Firebase Cloud Messaging and other firebase services are not working. I am not doing programmatic initialization (that is, using a FirebaseOptions object to provide these values), just the default initialization using FirebaseApp.initializeApp(this);

I have tried https://github.com/firebase/firebase-android-sdk/blob/master/firebase-installations/API_KEY_RESTRICTIONS.md

Thanks in Advance.


问:
Node bcrypt's compare always returns false
I am stumped trying to get my passwords to successfully compare with bcrypt using node.  Maybe I missed something, but on account creation, I do the following within the signup method (with some code abbreviated):

```<code>bcrypt.genSalt(10, function(err, salt) {
               if(err) {

               }
               bcrypt.hash(user.Password, salt, function(err, hash) {
                           console.log('hashing and saving');
                           db.query(db insert code, function (error, rows, fields) {
                                    if(error) {
                                    console.log(error);
                                    res.setHeader('500', { 'Content-Type': 'x-application/json'});
                                    res.send({UserId: 0, ErrorMessage: 'Something terrible happened.'});
                                    } else {
                                    console.log('User created : ' + rows.insertId);
                                    res.setHeader('200', { 'Content-Type': 'x-application/json'});
                                    res.send({UserId: rows.insertId});
                                    }
                                    });
                           });
               });

return next();
</code>```

This all works fine.  My db has the encrypted password.  But when a user signs in, I cannot get a successful result from bcrypt.compare:

```<code>db.query(get account code, function(error, rows, fields) {
         if(rows.length == 1) {
           bcrypt.compare(request.params.password, rows[0].Password, function(err,res) {
              if(err) { console.log(err.toString()); }
              if(res == true)
              {
                        response.setHeader('200', { 'Content-Type': 'x-application/json' });
                        response.send({result: true});
              } else {
                        response.setHeader('401', { 'Content-Type': 'x-application/json' });
                        console.log('invalid password');
                        response.send({result:false});
                     }
              });
         }
        });

return next();
</code>```

And I always end up with invalid password.  Do I need to take the cleartext password and re-encrypt it before comparing to what I pull out of the database?

答: That was due to password length 45, increase it and that solves the issue.</p>

Body:
I am stumped trying to get my passwords to successfully compare with bcrypt using node.  Maybe I missed something, but on account creation, I do the following within the signup method (with some code abbreviated):

bcrypt.genSalt(10, function(err, salt) {
               if(err) {

               }
               bcrypt.hash(user.Password, salt, function(err, hash) {
                           console.log('hashing and saving');
                           db.query(db insert code, function (error, rows, fields) {
                                    if(error) {
                                    console.log(error);
                                    res.setHeader('500', { 'Content-Type': 'x-application/json'});
                                    res.send({UserId: 0, ErrorMessage: 'Something terrible happened.'});
                                    } else {
                                    console.log('User created : ' + rows.insertId);
                                    res.setHeader('200', { 'Content-Type': 'x-application/json'});
                                    res.send({UserId: rows.insertId});
                                    }
                                    });
                           });
               });

return next();

This all works fine.  My db has the encrypted password.  But when a user signs in, I cannot get a successful result from bcrypt.compare:

db.query(get account code, function(error, rows, fields) {
         if(rows.length == 1) {
           bcrypt.compare(request.params.password, rows[0].Password, function(err,res) {
              if(err) { console.log(err.toString()); }
              if(res == true)
              {
                        response.setHeader('200', { 'Content-Type': 'x-application/json' });
                        response.send({result: true});
              } else {
                        response.setHeader('401', { 'Content-Type': 'x-application/json' });
                        console.log('invalid password');
                        response.send({result:false});
                     }
              });
         }
        });

return next();

And I always end up with invalid password.  Do I need to take the cleartext password and re-encrypt it before comparing to what I pull out of the database?


问:
Why useEffect is not listening to changes?
I am having a react-quiz application whose code is:

Quiz.js file:

```<code>const Quiz = (props) => {
  const [options,setOptions]=useState();
  const [questions,setQuestions]=useState(props.questions);
  const [currentQuestion,setCurrentQuestion]=useState(0);
   useEffect(()=>{
     console.log(questions);
     var optionss=[];
     optionss.push(questions[currentQuestion].correct_answer);
     questions[currentQuestion].incorrect_answers.forEach((ans)=>optionss.push(ans));
     optionss.sort(()=>Math.random()-0.5);
     setOptions(optionss);
   },[options])

  return (
  <div className='quiz'>
    <span className="subtitle">Welcome ,{props.name}</span>
    <div className="questionInfo">
       <span>{questions[currentQuestion].category}</span>
       <span>Score : {props.score}</span>
    </div>
    <Question
      questions={questions}
      setQuestions={setQuestions}
      currentQuestion={currentQuestion}
      setCurrentQuestion={setCurrentQuestion}
      options={options}
      correctOption={questions[currentQuestion].correct_answer}
      score={props.score}
      setScore={props.setScore}
    />
  </div>
  );
};

export default Quiz;
</code>```

Question.js file:

```<code>const Question = ({
      questions,
      setQuestions,
      currentQuestion,
      setCurrentQuestion,
      options,
      correctOption,
      score,
      setScore
}) => {
  useEffect(()=>{

  },[]);
  console.log(options);
<h1>Question : {currentQuestion+1}</h1>
      <div className="singleQuestion">
        <h2>{questions[currentQuestion].question}</h2>
        <div className="options">
            {options.map((option)=>{
                return(
                    <button
                     disabled={selected}
                     key={option}
                     onClick={()=>{}}
                     className={`singleOption ${selected && handleSelect(option)}`}
                     >{option}</button>
                )
            })}
        </div>
      </div>
</code>```

App.js file:

```<code>import { BrowserRouter,Routes,Route} from 'react-router-dom';
import './App.css';
import Quiz from './components/quiz/quiz';
import axios from "axios"
import {useState} from 'react'
import Home from './components/home/home';
import Header  from './components/header.js';
import Result from './components/result/result';
import Footer from './components/footer';
import { useEffect } from 'react';
function App() {
    const [name,setName]=useState("");
    const [score,setScore]=useState(0);
    const [questions,setQuestions]=useState();
    useEffect(()=>{
      console.log("Questions have changed");
    },[questions]);
    const fetchQuestions=async(category,difficulty)=>{
       const {data}=await axios(`https://opentdb.com/api.php?amount=10&category=${category}&difficulty=${difficulty}&type=multiple`);
       setQuestions(data.results);
    }

  return (
    <BrowserRouter>
     <div className="App" style={{backgroundImage: "url(./ques1.png)"}}>
      <Header/>
       <Routes>
        <Route path="/home" exact element={<Home name={name} setName={setName} fetchQuestions={fetchQuestions}/>}></Route>
        <Route path="/quiz" exact element={<Quiz name={name} questions={questions} score={score} setScore={setScore} />}></Route>
       </Routes>
      <Footer></Footer>
     </div>
    </BrowserRouter>
  );
}

export default App;

</code>```

Even though my Quiz component is able to get the questions from the App component,however when I send the question,options to the Question component as props from the Quiz component,I get undefined on logging in the Question component.

答: UseEffect in Quiz.js file has no dependencies: [], it will only run once, for first component rendering. Pass there the value that you want to watch for: [options]

Body:
I am having a react-quiz application whose code is:

Quiz.js file:

const Quiz = (props) => {
  const [options,setOptions]=useState();
  const [questions,setQuestions]=useState(props.questions);
  const [currentQuestion,setCurrentQuestion]=useState(0);
   useEffect(()=>{
     console.log(questions);
     var optionss=[];
     optionss.push(questions[currentQuestion].correct_answer);
     questions[currentQuestion].incorrect_answers.forEach((ans)=>optionss.push(ans));
     optionss.sort(()=>Math.random()-0.5);
     setOptions(optionss);
   },[options])

  return (

    Welcome ,{props.name}

       {questions[currentQuestion].category}
       Score : {props.score}

    <Question
      questions={questions}
      setQuestions={setQuestions}
      currentQuestion={currentQuestion}
      setCurrentQuestion={setCurrentQuestion}
      options={options}
      correctOption={questions[currentQuestion].correct_answer}
      score={props.score}
      setScore={props.setScore}
    />

  );
};

export default Quiz;

Question.js file:

const Question = ({
      questions,
      setQuestions,
      currentQuestion,
      setCurrentQuestion,
      options,
      correctOption,
      score,
      setScore
}) => {
  useEffect(()=>{

  },[]);
  console.log(options);

Question : {currentQuestion+1}

{questions[currentQuestion].question}

            {options.map((option)=>{
                return(
                    <button
                     disabled={selected}
                     key={option}
                     onClick={()=>{}}
                     className={`singleOption ${selected && handleSelect(option)}`}
                     >{option}</button>
                )
            })}

App.js file:

import { BrowserRouter,Routes,Route} from 'react-router-dom';
import './App.css';
import Quiz from './components/quiz/quiz';
import axios from "axios"
import {useState} from 'react'
import Home from './components/home/home';
import Header  from './components/header.js';
import Result from './components/result/result';
import Footer from './components/footer';
import { useEffect } from 'react';
function App() {
    const [name,setName]=useState("");
    const [score,setScore]=useState(0);
    const [questions,setQuestions]=useState();
    useEffect(()=>{
      console.log("Questions have changed");
    },[questions]);
    const fetchQuestions=async(category,difficulty)=>{
       const {data}=await axios(`https://opentdb.com/api.php?amount=10&category=${category}&difficulty=${difficulty}&type=multiple`);
       setQuestions(data.results);
    }

  return (
    <BrowserRouter>

       <Routes>
        <Route path="/home" exact element={<Home name={name} setName={setName} fetchQuestions={fetchQuestions}/>}></Route>
        <Route path="/quiz" exact element={<Quiz name={name} questions={questions} score={score} setScore={setScore} />}></Route>
       </Routes>

    </BrowserRouter>
  );
}

export default App;

Even though my Quiz component is able to get the questions from the App component,however when I send the question,options to the Question component as props from the Quiz component,I get undefined on logging in the Question component.


问:
Docker tries to mkdir the folder that I mount
Why is Docker trying to create the folder that I'm mounting? If I cd to C:\Users\szx\Projects

```<code>docker run --rm -it -v "${PWD}:/src" ubuntu /bin/bash
</code>```

This command exits with the following error:

```<code>C:\Program Files\Docker Toolbox\docker.exe: Error response from daemon: error while creating mount source path '/c/Users/szx/Projects': mkdir /c/Users/szx/Projects: file exists.
</code>```

I'm using Docker Toolbox on Windows 10 Home.

答: I solved this by restarting docker and rebuilding the images.</p>

Body:
Why is Docker trying to create the folder that I'm mounting? If I cd to C:\Users\szx\Projects

docker run --rm -it -v "${PWD}:/src" ubuntu /bin/bash

This command exits with the following error:

C:\Program Files\Docker Toolbox\docker.exe: Error response from daemon: error while creating mount source path '/c/Users/szx/Projects': mkdir /c/Users/szx/Projects: file exists.

I'm using Docker Toolbox on Windows 10 Home.


问:
Prometheus and Node Exporter architecture
I have been 3 days reading about this, even configuring a set of containers to test them, but I have doubts.

I understand that the architecture of Prometheus + Node exporter is based on:

Node exporter knows how to extract metrics. Those are exposed in HTTP, eg. :9201/metrics

Prometheus queries every X seconds those HTTP endpoints (node-exporter HTTTP) and stores the metrics. It also provide another HTTP for graph/console visualization/querying.

Question 1:

Assume you want CPU metrics every 15s, HDD metrics every 5m, Network every 1m, process every 30s.

Since it is prometheus who decides the scraping interval, how can be configured to just scrape those values?

Question 2:

Assume you want 1 prometheus instance and 3 node exporters, different public servers. I don't see anything regarding the node exporter and its security. The HTTP endpoint is public.

How can I securely query the metrics from my 3 servers?

Question 3:

I don't know if I am missing something. But, for example, comparing this to Telegraf, the latter sends the metrics to a database. Therefore, Telegraf acts as "node-exporter". I only need to secure the database connection (only exposed port).

Can node-exporter be configured to send a set of metrics every X time to the prometheus server?
(so I don't have to expose a public port in every public server, just the prometheus server)
I understand "pushgateway" is for that? How to change the node-exporter behavior?

Do you recommend me any other architecture that could suite my needs? (1 master, many slaves to query metrics)

答:
Please take a look to Fluent Bit - https://docs.fluentbit.io (Ex. INPUT node_exporter)

Create monitoring containers for your needs using different scrape and flushing interval.


问:
Running npm start from ExecStart in systemctl service file
I have the following service file:

```<code>[Unit]
Description=MyApp
After=syslog.target network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
WorkingDirectory=/opt/nodejs-sites/MyApp
ExecStart=/usr/bin/npm start
Environment=NODE_ENV=development
User=root
Group=root
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=MyApp

[Install]
WantedBy=multi-user.target
</code>```

Here is the error from /var/log/syslog

```<code>Oct 14 13:00:55 devu18 systemd[1]: Started myapp.
Oct 14 13:00:55 devu18 systemd[3203]: myapp.service: Changing to the requested working directory failed: No such file or directory
Oct 14 13:00:55 devu18 systemd[3203]: myapp.service: Failed at step CHDIR spawning /usr/bin/npm: No such file or directory
Oct 14 13:00:55 devu18 systemd[1]: myapp.service: Main process exited, code=exited, status=200/CHDIR
Oct 14 13:00:55 devu18 systemd[1]: myapp.service: Failed with result 'exit-code'.
</code>```

I for the life of me can't figure out why it's complaining of cannot find the file.  npm start from the same working directory works just fine, no problems.  Am I missing some permissions or +x or something somewhere?

答:
```<code>/bin/npm --prefix $PATH start
</code>```

This worked for me

Body:
I have the following service file:

[Unit]
Description=MyApp
After=syslog.target network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
WorkingDirectory=/opt/nodejs-sites/MyApp
ExecStart=/usr/bin/npm start
Environment=NODE_ENV=development
User=root
Group=root
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=MyApp

[Install]
WantedBy=multi-user.target

Here is the error from /var/log/syslog

Oct 14 13:00:55 devu18 systemd[1]: Started myapp.
Oct 14 13:00:55 devu18 systemd[3203]: myapp.service: Changing to the requested working directory failed: No such file or directory
Oct 14 13:00:55 devu18 systemd[3203]: myapp.service: Failed at step CHDIR spawning /usr/bin/npm: No such file or directory
Oct 14 13:00:55 devu18 systemd[1]: myapp.service: Main process exited, code=exited, status=200/CHDIR
Oct 14 13:00:55 devu18 systemd[1]: myapp.service: Failed with result 'exit-code'.

I for the life of me can't figure out why it's complaining of cannot find the file.  npm start from the same working directory works just fine, no problems.  Am I missing some permissions or +x or something somewhere?

Body:
/bin/npm --prefix $PATH start

This worked for me


问:
Is Using a Trigger for Monitoring purpose is correct approach
I am working on a requirement , say for example there is a Bank account , and in case if there is a credit or debt of 5000 Rupees on it , i need to send a SMS .

I am planning to use Database Triggers for this , please tell me if this is correct approach or not ??
If this correct approach , please tell me how to call a Servlet from a Trigger to do this operation ??

Thank you very much .

答:
It may or may not be the correct approach, depending on whom you talk to. You could get this to work if you wanted to, no doubt.

I personally wouldn't recommend it though because this is clearly business logic that is being pushed onto the DB. Why would you want to distribute business logic into different technologies? The right place IMHO is to have this within the same code that handles all other business logic.


问:
Why the print('\n', 'abc') in Python 3 is giving new line and an empty space?
I was just expecting a new line character and written below code.

```<code>>>> print('\n', 'abc')

 abc
>>>
</code>```

But it gave single space also in front of the string abc, may I know why it added that space?

I am using Python 3.9 in Windows 10

答:
The default separator (sep) argument to the print function is a whitespace. Change it for a empty string to remove that single space indentation:

print('\n', 'abc', sep='')
```

Body:
I was just expecting a new line character and written below code.

>>> print('\n', 'abc')

 abc
>>>

But it gave single space also in front of the string abc, may I know why it added that space?

I am using Python 3.9 in Windows 10


问:
send a radio button value to the database
I have created form to apply values then insert to the table.
I need help to send a radio button value to the database

nodejs
/ejs file

```<code> <label class="container" >5
    <input type="radio" name="_rate" id="_rate" value="5" required >
    <span class="checkmark"></span>
  </label>
  <label class="container">3
    <input type="radio" name="_rate" id="_rate" value="3">
    <span class="checkmark"></span>
  </label>
  <label class="container">1
    <input type="radio" name="_rate" id="_rate" value="1">
    <span class="checkmark"></span>
  </label>
</code>```

app.js

```<code>var _rate= req.body._rate;

  var sql = `INSERT INTO [Test2] (rate) VALUES ('${_rate}')`;
</code>```

the value always in table shows null !!

答:
What type of data is expected in your database field?
In any case, please use prepared statements to avoid type errors like :
INSERT INTO [Test2] (rate) VALUES (?)

Body:
I have created form to apply values then insert to the table.
I need help to send a radio button value to the database

nodejs
/ejs file

 5
    <input type="radio" name="_rate" id="_rate" value="5" required >

  3
    <input type="radio" name="_rate" id="_rate" value="3">

  1
    <input type="radio" name="_rate" id="_rate" value="1">

app.js

var _rate= req.body._rate;

  var sql = `INSERT INTO [Test2] (rate) VALUES ('${_rate}')`;

the value always in table shows null !!


问:
Moving from MobX Provider to React context, typescript issue
Trying to move from mobx's provider to React context.
I have checked this article which suits pretty much exactly what I want
https://shevchenkonik.com/blog/react-typescript-mobx

My use case includes a single registry object, which contains stores and services, which by using React context needs to be passed down the components.

I have it working 99%, however typescript is giving me a hard time.
Below is a link to a sample. I have everything in 2 files to make it easier

https://codesandbox.io/s/minimal-observer-forked-sd88n

Although the UI is rendered, TS complains regarding the wrapped component not passing the props on line 53 (which are passed by the HOC).

Any help will be much appreciated
Thanks

答:
This approach does not really work very well with TS, that's why the author "cleverly" omits types from the actual example where he tries to use it:

```<code>@withStore
@observer
class UserNameComponent extends Component< ??? > {
    render() {
        // props are completely untyped here
        const { store } = this.props;
        return (
            <div>{store.userStore.name}<div>
        )
    }
}
</code>```

What you can do is mark properties as optional and then use null assertion operator ! to make TS skip null checking:

```<code>@withStore
@observer
class UserNameComponent extends Component<{ store?: Store }> {
    get store() {
       return this.props.store!
    }

    render() {
        return (
            <div>{this.store.userStore.name}<div>
        )
    }
}
</code>```

Obviously it's not super type safe, because if you forget to wrap your component with decorator it will throw. That's why functional components are much better and easier to use in that case.

Body:
This approach does not really work very well with TS, that's why the author "cleverly" omits types from the actual example where he tries to use it:

@withStore
@observer
class UserNameComponent extends Component< ??? > {
    render() {
        // props are completely untyped here
        const { store } = this.props;
        return (
            <div>{store.userStore.name}<div>
        )
    }
}

What you can do is mark properties as optional and then use null assertion operator ! to make TS skip null checking:

@withStore
@observer
class UserNameComponent extends Component<{ store?: Store }> {
    get store() {
       return this.props.store!
    }

    render() {
        return (
            <div>{this.store.userStore.name}<div>
        )
    }
}

Obviously it's not super type safe, because if you forget to wrap your component with decorator it will throw. That's why functional components are much better and easier to use in that case.


问:
SSRS expression - Line break after 3rd hyphen
I have a field that produces dates in 01-03-2022 - 07-03-2022 and want to put a line break after the 3rd hyphen so it displays like

```<code>01-03-2022 -
07-03-2022
</code>```

Does anyone know how this can be achieved?

答:
Try this...

=REPLACE(Fields!MyDatesField.Value, " - ", vbcrlf)

All we are doing is looking for the "space hyphen space" pattern and replaceing with the carriage return and line feed characters (equivalent to Chr(13) + Chr(10) as far as I remember)

Body:
I have a field that produces dates in 01-03-2022 - 07-03-2022 and want to put a line break after the 3rd hyphen so it displays like

01-03-2022 -
07-03-2022

Does anyone know how this can be achieved?


问:
Javascript change event on input element fires on only losing focus
I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.

```<code><input type="text" id="name" onchange="checkLength(this.value)" />
</code>```

----onchange does not fire on changing contents of name, but only fires when name goes out of focus.

Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.

I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?

答:
```<code>(function () {
    var oldVal;

    $('#name').on('change textInput input', function () {
        var val = this.value;
        if (val !== oldVal) {
            oldVal = val;
            checkLength(val);
        }
    });
}());
</code>```

This will catch change, keystrokes, paste, textInput, input (when available). And not fire more than necessary.

http://jsfiddle.net/katspaugh/xqeDj/

References:

textInput — a W3C DOM Level 3 event type. http://www.w3.org/TR/DOM-Level-3-Events/#events-textevents

A user agent must dispatch this event when one or more characters have
  been entered. These characters may originate from a variety of
  sources, e.g., characters resulting from a key being pressed or
  released on a keyboard device, from the processing of an input method
  editor, or resulting from a voice command. Where a “paste” operation
  generates a simple sequence of characters, i.e., a text passage
  without any structure or style information, this event type should be
  generated as well.

input — an HTML5 event type.

Fired at controls when the user changes the value

Firefox, Chrome, IE9 and other modern browsers support it.

This event occurs immediately after modification, unlike the onchange event, which occurs when the element loses focus.

Body:
I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.

<input type="text" id="name" onchange="checkLength(this.value)" />

----onchange does not fire on changing contents of name, but only fires when name goes out of focus.

Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.

I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?

Body:
(function () {
    var oldVal;

    $('#name').on('change textInput input', function () {
        var val = this.value;
        if (val !== oldVal) {
            oldVal = val;
            checkLength(val);
        }
    });
}());

This will catch change, keystrokes, paste, textInput, input (when available). And not fire more than necessary.

http://jsfiddle.net/katspaugh/xqeDj/

References:

textInput — a W3C DOM Level 3 event type. http://www.w3.org/TR/DOM-Level-3-Events/#events-textevents

A user agent must dispatch this event when one or more characters have
  been entered. These characters may originate from a variety of
  sources, e.g., characters resulting from a key being pressed or
  released on a keyboard device, from the processing of an input method
  editor, or resulting from a voice command. Where a “paste” operation
  generates a simple sequence of characters, i.e., a text passage
  without any structure or style information, this event type should be
  generated as well.

input — an HTML5 event type.

Fired at controls when the user changes the value

Firefox, Chrome, IE9 and other modern browsers support it.

This event occurs immediately after modification, unlike the onchange event, which occurs when the element loses focus.


问:
Angular Material Design Datepicker leads to Error: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value
When I use the Material Design date picker in my Angular code, to set a date, which I then send to my REST server with a MySQL database and a TIMESTAMP column, I get the error message: "Error: ER_TRUNCATED_WRONG_VALUE: Incorrect date time value:"

The reason for this is, that the date picker exports the date in the following date format ("2022-02-23T23:00:00.000Z"), while MySQL expects a date format like this: "2022-02-17 12:55:31".

How can I configure the date picker to export the date in the correct MySQL format? I know that there are ways to configure the MySQL server to accept this special format, but I'd prefer to do it on the client side.

答:
See Moment.js, you can manipulate dates easily.</p>
```<code>const formatedDate = moment(yourDate).format('YYYY-MM-DD HH:mm:ss')
</code>```

Body:
See Moment.js, you can manipulate dates easily.

const formatedDate = moment(yourDate).format('YYYY-MM-DD HH:mm:ss')


问:
Calculating the difference of two values within a group and given period (R)
may the answer is somewhere elese, but I don't find it.
My problem is, that I want to calculate the difference of a value within a group but only in a given Timespan.(With other words: I want to calculate the value difference of a country within e.g. 5 days)

```<code>Country <- c("Germany", "Germany", "Germany", "Germany", "USA", "USA", "USA", "USA", "Canada", "Canada", "Canada", "Canada")
Date = c("2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-01",  "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04")
Value <- c(5,6,7,9,1,3,4,5,0,5,10,15)
df <- data.frame(Country, Date, Value)
</code>```

So again, I would like add a new column where the differnce of the Value for all countries between a given timespan is. My Dataframe should at the end look like the following example, where are the differences of the Value within each group between the "04-01-2021" and the "02-01-2021" is given.

So at the at the dataframe should somehow look like the following:

```<code>df$ValueDif <- c(3,3,3,3, 2,2,2,2,10,10,10,10)
</code>```

view(df)

Thanks for your help!

答:
You can do as follows:

```<code>df$Date <- as.Date(df$Date, format = "%Y-%m-%d")

df1 <- df %>%
  group_by(Country) %>%
  mutate(diffValue = Value[Date == as.Date("2021-01-04")] - Value[Date == as.Date("2021-01-02")])
</code>```

It will give you output like this:

```<code>df1
# A tibble: 12 x 4
# Groups:   Country [3]
   Country Date       Value diffValue
   <chr>   <date>     <dbl>     <dbl>
 1 Germany 2021-01-01     5         3
 2 Germany 2021-01-02     6         3
 3 Germany 2021-01-03     7         3
 4 Germany 2021-01-04     9         3
 5 USA     2021-01-01     1         2
 6 USA     2021-01-02     3         2
 7 USA     2021-01-03     4         2
 8 USA     2021-01-04     5         2
 9 Canada  2021-01-01     0        10
10 Canada  2021-01-02     5        10
11 Canada  2021-01-03    10        10
12 Canada  2021-01-04    15        10
</code>```

P.S: I've hardcoded the dates in the code, to comply with your question.

EDIT
In order to get the nearest date corresponding to what you are looking for, you can use the birk library. There's a function called which.closest. It will give you the nearest value.

The code looks like below:

```<code>df1 <- df %>%
  group_by(Country) %>%
  mutate(diffValue = Value[Date == as.Date("2021-01-04")] -
           Value[Date == as.Date(Date[which.closest(df$Date, as.Date("2020-12-31"))])])
</code>```

And output:

```<code># A tibble: 12 x 4
# Groups:   Country [3]
   Country Date       Value diffValue
   <chr>   <date>     <dbl>     <dbl>
 1 Germany 2021-01-01     5         4
 2 Germany 2021-01-02     6         4
 3 Germany 2021-01-03     7         4
 4 Germany 2021-01-04     9         4
 5 USA     2021-01-01     1         4
 6 USA     2021-01-02     3         4
 7 USA     2021-01-03     4         4
 8 USA     2021-01-04     5         4
 9 Canada  2021-01-01     0        15
10 Canada  2021-01-02     5        15
11 Canada  2021-01-03    10        15
12 Canada  2021-01-04    15        15
</code>```

In the above example, I have checked the nearest date in the second part and not the first. You can use the same syntax there as well.

Body:
may the answer is somewhere elese, but I don't find it.
My problem is, that I want to calculate the difference of a value within a group but only in a given Timespan.(With other words: I want to calculate the value difference of a country within e.g. 5 days)

Country <- c("Germany", "Germany", "Germany", "Germany", "USA", "USA", "USA", "USA", "Canada", "Canada", "Canada", "Canada")
Date = c("2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-01",  "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04")
Value <- c(5,6,7,9,1,3,4,5,0,5,10,15)
df <- data.frame(Country, Date, Value)

So again, I would like add a new column where the differnce of the Value for all countries between a given timespan is. My Dataframe should at the end look like the following example, where are the differences of the Value within each group between the "04-01-2021" and the "02-01-2021" is given.

So at the at the dataframe should somehow look like the following:

df$ValueDif <- c(3,3,3,3, 2,2,2,2,10,10,10,10)

view(df)

Thanks for your help!

Body:
You can do as follows:

df$Date <- as.Date(df$Date, format = "%Y-%m-%d")

df1 <- df %>%
  group_by(Country) %>%
  mutate(diffValue = Value[Date == as.Date("2021-01-04")] - Value[Date == as.Date("2021-01-02")])

It will give you output like this:

df1
# A tibble: 12 x 4
# Groups:   Country [3]
   Country Date       Value diffValue
   <chr>   <date>     <dbl>     <dbl>
 1 Germany 2021-01-01     5         3
 2 Germany 2021-01-02     6         3
 3 Germany 2021-01-03     7         3
 4 Germany 2021-01-04     9         3
 5 USA     2021-01-01     1         2
 6 USA     2021-01-02     3         2
 7 USA     2021-01-03     4         2
 8 USA     2021-01-04     5         2
 9 Canada  2021-01-01     0        10
10 Canada  2021-01-02     5        10
11 Canada  2021-01-03    10        10
12 Canada  2021-01-04    15        10

P.S: I've hardcoded the dates in the code, to comply with your question.

EDIT
In order to get the nearest date corresponding to what you are looking for, you can use the birk library. There's a function called which.closest. It will give you the nearest value.

The code looks like below:

df1 <- df %>%
  group_by(Country) %>%
  mutate(diffValue = Value[Date == as.Date("2021-01-04")] -
           Value[Date == as.Date(Date[which.closest(df$Date, as.Date("2020-12-31"))])])

And output:

# A tibble: 12 x 4
# Groups:   Country [3]
   Country Date       Value diffValue
   <chr>   <date>     <dbl>     <dbl>
 1 Germany 2021-01-01     5         4
 2 Germany 2021-01-02     6         4
 3 Germany 2021-01-03     7         4
 4 Germany 2021-01-04     9         4
 5 USA     2021-01-01     1         4
 6 USA     2021-01-02     3         4
 7 USA     2021-01-03     4         4
 8 USA     2021-01-04     5         4
 9 Canada  2021-01-01     0        15
10 Canada  2021-01-02     5        15
11 Canada  2021-01-03    10        15
12 Canada  2021-01-04    15        15

In the above example, I have checked the nearest date in the second part and not the first. You can use the same syntax there as well.


问:
I am trying to use :g in Vim doesn't work "Command :g[lobal] is not yet implemented" i get in the status line
I wanted to try vim for a bit, and get used to it... i got stuck with trying to replicate Ctrl+D functionality of VScode... so I've tried couple Google solutions.

This is What I've tried when I got that error:
:g/oldword/norm newword

I see lots of people do search patterns like this, but it's annoying I get this message, without being able to find solution on google :D

I know I can solve this issue with /word then cgn newword and then just repeat with . operator, BUT, I want to be able to use the global command for searching patterns and stuff, for other purposes too, and it stresses me out that I can't make it work!

Here is the error I am getting.

Any help is extremely appreciated / welcome! Thanks.

Edit: Forgot to mention: We are talking about Vim for VScode, not the gvim installation stuff. Will try to install that too, and update the question.

Edit2: Okay so apparently, after instalilng gvim (from official site) and ran it through vim command in cmd prompt, the official vim can run the :g commands.

Like (for example) if you want to search for  and replace it with <router-link> you can do so by: :g//norm ciw<router-link>

Which means:

:g//norm  run a global (file) search for pattern

ciw - change in word

<router-link> the replacement pattern for
Note: The same should be done for  after that :D

The problem still exists tho.

While the native vim exe (outside of vscode) works and can run these stuffs, I still need to fix the vscode one (the extension that is). It is defo nice to have syntax highlighting and correction.

答:
If you want support for the global command in VSCode, install Neovim and the VSCode extension for it:

for those who expected this to work but it doesn't, it's possibly because you need to have installed neovim (firstly) and then vscode-neovim extension (secondly) https://marketplace.visualstudio.com/items?itemName=asvetliakov.vscode-neovim

Source: https://github.com/VSCodeVim/Vim/issues/2346


问:
What does beforefieldinit flag do?
What does beforefieldinit flag do?
When I look into the IL of my class I see this flag but I don't know what this flag is actually doing?</p>

答:
Quote from “CA1810: Initialize reference type static fields inline (code analysis) - .NET | Microsoft Docs” with emphasis mine and TL;DR at the bottom:

When a type declares an explicit static constructor, the just-in-time (JIT) compiler adds a check to each static method and instance constructor of the type to make sure that the static constructor was previously called. Static initialization is triggered when any static member is accessed or when an instance of the type is created. However, static initialization is not triggered if you declare a variable of the type but do not use it, which can be important if the initialization changes global state.

When all static data is initialized inline and an explicit static constructor is not declared, Microsoft intermediate language (MSIL) compilers add the beforefieldinit flag and an implicit static constructor, which initializes the static data, to the MSIL type definition.

When the JIT compiler encounters the beforefieldinit flag, most of the time the static constructor checks are not added. Static initialization is guaranteed to occur at some time before any static fields are accessed but not before a static method or instance constructor is invoked. Note that static initialization can occur at any time after a variable of the type is declared.

Static constructor checks can decrease performance. Often a static constructor is used only to initialize static fields, in which case you must only make sure that static initialization occurs before the first access of a static field. The beforefieldinit behavior is appropriate for these and most other types. It is only inappropriate when static initialization affects global state and one of the following is true:

The effect on global state is expensive and is not required if the type is not used.

The global state effects can be accessed without accessing any static fields of the type.

TL;DR: beforefieldinit flag helps avoid static constructor checks, which helps in performance (since the checks can affect performance). It does this by telling the JIT to run static constructors before the actual static field usage.

OwnerDisplayName: Praveen

Title: What does beforefieldinit flag do?


问:
Is there a simpler way to get an attribute's frontend value?
I have an array of attribute codes which I need to get the values of:

```<code>$attributes = array(
    'Category'           => 'type',
    'Manufacturer'       => 'brand',
    'Title'              => 'meta_title',
    'Description'        => 'description',
    'Product Link'       => 'url_path',
    'Price'              => 'price',
    'Product-image link' => 'image',
    'SKU'                => 'sku',
    'Stock'              => 'qty',
    'Condition'          => 'condition',
    'Shipping cost'      => 'delivery_cost');
</code>```

After iterating through a product collection I get the frontend values of the attributes like so:

```<code>$attributeId = Mage::getResourceModel('eav/entity_attribute')
    ->getIdByCode('catalog_product', $attribute_code);
$attribute = Mage::getModel('catalog/resource_eav_attribute')
    ->load($attributeId);
$value = $attribute->getFrontend()->getValue($product);
</code>```

Simply using $product->getDate($attribute) won't work with dropdowns and multi-selects, it just returns their id and not their frontend value.

While the code above works, it seems to be a long way around getting the value, but more importantly it runs quite slow. Is there a faster/more sensible way to get the frontend values for product attributes?

Edit

I now have the following (after dealing with special cases like image and qty) which is a bit easier on the eyes and does seem to run quicker (although I don't know why):

```<code>$inputType = $product->getResource()
                     ->getAttribute($attribute_code)
                     ->getFrontend()
                     ->getInputType();

switch ($inputType) {
case 'multiselect':
case 'select':
case 'dropdown':
    $value = $product->getAttributeText($attribute_code);
    if (is_array($value)) {
        $value = implode(', ', $value);
    }
    break;
default:
    $value = $product->getData($attribute_code);
    break;
}

$attributesRow[] = $value;
</code>```

If anyone can improve this (make it simpler/more efficient), please post an answer.

答:
It depends on how you have set up the attribute (is it accessible from the context you are trying to reach it?), but the simplest way is usually like this (for meta_title, for example):</p>

```<code>$product->getMetaTitle()
</code>```

Body:
I have an array of attribute codes which I need to get the values of:

$attributes = array(
    'Category'           => 'type',
    'Manufacturer'       => 'brand',
    'Title'              => 'meta_title',
    'Description'        => 'description',
    'Product Link'       => 'url_path',
    'Price'              => 'price',
    'Product-image link' => 'image',
    'SKU'                => 'sku',
    'Stock'              => 'qty',
    'Condition'          => 'condition',
    'Shipping cost'      => 'delivery_cost');

After iterating through a product collection I get the frontend values of the attributes like so:

$attributeId = Mage::getResourceModel('eav/entity_attribute')
    ->getIdByCode('catalog_product', $attribute_code);
$attribute = Mage::getModel('catalog/resource_eav_attribute')
    ->load($attributeId);
$value = $attribute->getFrontend()->getValue($product);

Simply using $product->getDate($attribute) won't work with dropdowns and multi-selects, it just returns their id and not their frontend value.

While the code above works, it seems to be a long way around getting the value, but more importantly it runs quite slow. Is there a faster/more sensible way to get the frontend values for product attributes?

Edit

I now have the following (after dealing with special cases like image and qty) which is a bit easier on the eyes and does seem to run quicker (although I don't know why):

$inputType = $product->getResource()
                     ->getAttribute($attribute_code)
                     ->getFrontend()
                     ->getInputType();

switch ($inputType) {
case 'multiselect':
case 'select':
case 'dropdown':
    $value = $product->getAttributeText($attribute_code);
    if (is_array($value)) {
        $value = implode(', ', $value);
    }
    break;
default:
    $value = $product->getData($attribute_code);
    break;
}

$attributesRow[] = $value;

If anyone can improve this (make it simpler/more efficient), please post an answer.

Body:
It depends on how you have set up the attribute (is it accessible from the context you are trying to reach it?), but the simplest way is usually like this (for meta_title, for example):

$product->getMetaTitle()


问:
Kubernetes service select pods based on start time
I have a K8s service defined as:

```<code>apiVersion: v1
kind: Service
metadata:
  labels:
    name: myapp
  name: myapp
  namespace: myapps

spec:
  ports:
    - name: ui
      port: 8081
      protocol: TCP
      targetPort: 8081
  selector:
    my-app: myapp
    my-deployment-type: jobmanager
  type: ClusterIP
</code>```

This service serves as backend for an ingress.

Now during blue green deployment there are two apps running i.e two sets of pods that match the selctors specified above:
my-app: myapp
my-deployment-type: jobmanager

And I observe that it selects both pods i.e both app versions at random till the older app pods gets killed.

Is there a way to ensure that the service will just choose the new app pods? i.e Have a selector to also depend on the "Start Time" of the pods apart from the selector?

答:
Is there a way to ensure that the service will just choose the new app pods? i.e Have a selector to also depend on the "Start Time" of the pods apart from the selector?

There is no such feature in Kubernetes to filter a pod start time in service selector block.

The official k8s documentation says ¨Labels selectors for service objects are defined in json or yaml files using maps, and only equality-based requirement selectors are supported ¨.

So, in your case the best option is to:

create a new k8s deployment with new labels for green deployment (the new application version)

create a new ClusterIP service for the green deployment

then switch your Ingress to this green deployment by changing the backend service name.

If something goes wrong, you can quickly switch back to your blue deployment (previous application version).

Body:
I have a K8s service defined as:

apiVersion: v1
kind: Service
metadata:
  labels:
    name: myapp
  name: myapp
  namespace: myapps

spec:
  ports:
    - name: ui
      port: 8081
      protocol: TCP
      targetPort: 8081
  selector:
    my-app: myapp
    my-deployment-type: jobmanager
  type: ClusterIP

This service serves as backend for an ingress.

Now during blue green deployment there are two apps running i.e two sets of pods that match the selctors specified above:
my-app: myapp
my-deployment-type: jobmanager

And I observe that it selects both pods i.e both app versions at random till the older app pods gets killed.

Is there a way to ensure that the service will just choose the new app pods? i.e Have a selector to also depend on the "Start Time" of the pods apart from the selector?


问:
Sign-Up Form Working But Errors Not Showing
I made a sign-up form for my website using php on my webpage, and connecting it to mySQL. The database seems to work and the data for signed up users does appear in it. However, on the front-end no messages of "Registration successful" or any errors are being displayed such as "Email already registered" But the queries seem to work as it only registers accounts following the conditions. I would appreciate any help in getting the messages to work.

Attached is the code in question:

Sign-up form:

```<code><?php

require_once "config.php";
require_once "session.php";

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

    $fullname = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);
    $password_hash = password_hash($password, PASSWORD_BCRYPT);

    if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
        $error = '';
        //Bind parameters (s=string, i=int, b=blob, etc), in our case the username is a string so we use "s"
        $query->bind_param('s', $email);
        $query->execute();
        //Store the result so we can check if account exists in database
        $query->store_result();
           if ($query->num_rows > 0) {
               $error .= '<p class="error">The email address is already registered!</p>';
           } else {
               //Validate password
               if (strlen($password) < 6) {
                   $error .= '<p class="error">Password must have atleast 6 characters</p>';
               }
               //Validate confirm password
               if (empty($confirm_password)) {
                   $error .= '<p class="error">Please enter confirm password.</p>';
               } else {
                   if (empty($error) && ($password != $confirm_password)) {
                       $error .= '<p class="error">Passwords did not match</p>';
                   }
               }
               if (empty($error)) {
                   $insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?,?,?);");
                   $insertQuery->bind_param("sss", $fullname, $email, $password_hash);
                   $result = $insertQuery->execute();
                   if ($result) {
                       $error .= '<p class="success">Your registration was successful</p>';
                   } else {
                       $error .= '<p class="error">Something went wrong!</p>';
                   }
                  $insertQuery->close();
               }
           }
    }
    $query->close();

    //Close DB connection
    mysqli_close($db);
}

?>
</code>```

config.php:

```<code><?php
define('DBSERVER', 'localhost'); //Database server
define('DBUSERNAME', 'root'); //Database username
define('DBPASSWORD',''); //Database password
define('DBNAME', 'users'); //Database name

/* connect to MySQL databse */
$db = mysqli_connect(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);

//check db connection
if($db === false){
    die("Error: connection error.".mysqli_connect_error());
}
?>
</code>```

session.php:

```<code><?php
//Start the session
session_start();

//if the user is already logged in then redirect user to welcome page
if (isset($_SESSION["userid"]) && $_SESSION["userid"] === true) {
    header("location: loggedinuserhome.html");
    exit;
}
?>
</code>```

I am making this form following tutorials so lack deep knowledge of the subject so would love if someone could guide me through it and explicitly point out the error. Thank You!

答:
You have stored your messages in $error but you haven't displayed them. Display them according to the condition using echo.

echo $error;

Body:
I made a sign-up form for my website using php on my webpage, and connecting it to mySQL. The database seems to work and the data for signed up users does appear in it. However, on the front-end no messages of "Registration successful" or any errors are being displayed such as "Email already registered" But the queries seem to work as it only registers accounts following the conditions. I would appreciate any help in getting the messages to work.

Attached is the code in question:

Sign-up form:

<?php

require_once "config.php";
require_once "session.php";

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

    $fullname = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);
    $password_hash = password_hash($password, PASSWORD_BCRYPT);

    if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
        $error = '';
        //Bind parameters (s=string, i=int, b=blob, etc), in our case the username is a string so we use "s"
        $query->bind_param('s', $email);
        $query->execute();
        //Store the result so we can check if account exists in database
        $query->store_result();
           if ($query->num_rows > 0) {
               $error .= '
The email address is already registered!
';
           } else {
               //Validate password
               if (strlen($password) < 6) {
                   $error .= '
Password must have atleast 6 characters
';
               }
               //Validate confirm password
               if (empty($confirm_password)) {
                   $error .= '
Please enter confirm password.
';
               } else {
                   if (empty($error) && ($password != $confirm_password)) {
                       $error .= '
Passwords did not match
';
                   }
               }
               if (empty($error)) {
                   $insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?,?,?);");
                   $insertQuery->bind_param("sss", $fullname, $email, $password_hash);
                   $result = $insertQuery->execute();
                   if ($result) {
                       $error .= '
Your registration was successful
';
                   } else {
                       $error .= '
Something went wrong!
';
                   }
                  $insertQuery->close();
               }
           }
    }
    $query->close();

    //Close DB connection
    mysqli_close($db);
}

?>

config.php:

<?php
define('DBSERVER', 'localhost'); //Database server
define('DBUSERNAME', 'root'); //Database username
define('DBPASSWORD',''); //Database password
define('DBNAME', 'users'); //Database name

/* connect to MySQL databse */
$db = mysqli_connect(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);

//check db connection
if($db === false){
    die("Error: connection error.".mysqli_connect_error());
}
?>

session.php:

<?php
//Start the session
session_start();

//if the user is already logged in then redirect user to welcome page
if (isset($_SESSION["userid"]) && $_SESSION["userid"] === true) {
    header("location: loggedinuserhome.html");
    exit;
}
?>

I am making this form following tutorials so lack deep knowledge of the subject so would love if someone could guide me through it and explicitly point out the error. Thank You!


问:
Replace/Rearrange/Swap words in string based on first number in SQL
I have a table containing a column "Description"

This column has multiple rows like this:

```<code>Heartxxx 03-0 ww wwwq
Heart Child 75-0 qweq
Legxxxxxxww 08-0 qaew
</code>```

What I need is the "word" chars consisting of 4 chars starting from the first number to be in the beginning of the string. So expected results:

```<code>03-0 Heartxxx ww wwwq
75-0 Heart Child qweq
08-0 Legxxxxxxww qaew
</code>```

Is this possible and how?

Thanks.

答:
If you are using MS SQL I bobbed this snippet together using substring, patindex & concat.

No physical tables were created.

```<code> create table #str_twist(str_orig nvarchar(255), Str_twist nvarchar(255))

insert into #str_twist(str_orig) values ('Heartxxx 03-0 ww wwwq'), ('Heart Child 75-0 qweq'), ('Legxxxxxxww 08-0 qaew')

select * into #TBLFormat from(
SELECT SUBSTRING(str_orig,(SELECT PATINDEX('%[0-9][0-9]-[0-9]%',str_orig)),5) as a,
PAtindex('%[0-9][0-9]-[0-9]%',str_orig)  as b,
replace(str_orig, (SUBSTRING(str_orig,(SELECT PATINDEX('%[0-9][0-9]-[0-9]%',str_orig)),5)),'') as c
FROM #str_twist)a

select * , concat(A,c)as d from #TBLFormat
</code>```

Sorry it looks  awful  but after running I got this

regards

Body:
I have a table containing a column "Description"

This column has multiple rows like this:

Heartxxx 03-0 ww wwwq
Heart Child 75-0 qweq
Legxxxxxxww 08-0 qaew

What I need is the "word" chars consisting of 4 chars starting from the first number to be in the beginning of the string. So expected results:

03-0 Heartxxx ww wwwq
75-0 Heart Child qweq
08-0 Legxxxxxxww qaew

Is this possible and how?

Thanks.

Body:
If you are using MS SQL I bobbed this snippet together using substring, patindex & concat.

No physical tables were created.

 create table #str_twist(str_orig nvarchar(255), Str_twist nvarchar(255))

insert into #str_twist(str_orig) values ('Heartxxx 03-0 ww wwwq'), ('Heart Child 75-0 qweq'), ('Legxxxxxxww 08-0 qaew')

select * into #TBLFormat from(
SELECT SUBSTRING(str_orig,(SELECT PATINDEX('%[0-9][0-9]-[0-9]%',str_orig)),5) as a,
PAtindex('%[0-9][0-9]-[0-9]%',str_orig)  as b,
replace(str_orig, (SUBSTRING(str_orig,(SELECT PATINDEX('%[0-9][0-9]-[0-9]%',str_orig)),5)),'') as c
FROM #str_twist)a

select * , concat(A,c)as d from #TBLFormat

Sorry it looks  awful  but after running I got this

regards


问:
Javascript find matched sentence with predefined words
Hello guys I need help to figure out an expression. I got phrases like

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

expectedOutput = "This dummy datas will be used for any example of matched needs "```
</div>
</div>
</p>
<p>As you see above, target's three words matches with last sentence. The purpose is to find sentence includes most matched words.</p>
<p>I did like</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

target = target.split(' ')

const expectedOutput = phrases.filter(sentence => {

  return target.every(word => {
    return sentence.indexOf(word) !== -1
  })
})
console.log(expectedOutput)</code>```

But it gives nothing

答:
Use .filter(), .some(), .includes() and .sort() methods as explained below.

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

target = target.split(' ');

const expectedOutput = phrases
//Find if any phrases contain at least one target word
.filter( phrase => target.some(word => phrase.includes(word)) )
//Now sort the phrases in descending order of how many words matched
.sort( (a,b) => target.filter(word => b.includes(word)).length - target.filter(word => a.includes(word)).length )
//The first phrase matched the most words or at least the first and second matched the most words, otherwise return ''
[0] || '';

console.log( expectedOutput );
//Output: "This dummy datas will be used for any example of matched needs "```

Body:
Hello guys I need help to figure out an expression. I got phrases like

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

expectedOutput = "This dummy datas will be used for any example of matched needs "

As you see above, target's three words matches with last sentence. The purpose is to find sentence includes most matched words.

I did like

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

target = target.split(' ')

const expectedOutput = phrases.filter(sentence => {

  return target.every(word => {
    return sentence.indexOf(word) !== -1
  })
})
console.log(expectedOutput)

But it gives nothing


问:
Application crash during Item click of recyclerView
My Application is crashed when I click on ItemView of RecyclerView, There is no error showing in code.
The data are load in toast but not pass to the other class or what don't know, but when I click any Item the appliaction is crash..

This is my Main RecyclerView Class

```<code>
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class Admin extends AppCompatActivity {
     Button addUser;
     RecyclerView mainUserRecyclerView;
     UserAdapter adapter;
     FirebaseDatabase database;
     ArrayList<UserInfo> userInfoArrayList  = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);

        mainUserRecyclerView = findViewById(R.id.mainUserRecyclerView);
        mainUserRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        addUser = findViewById(R.id.addUserBtn);

        database= FirebaseDatabase.getInstance();

       DatabaseReference reference = database.getReference().child("userInfo");
        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                for(DataSnapshot dataSnapshot : snapshot.getChildren()){
                    UserInfo userInfo = dataSnapshot.getValue(UserInfo.class);
                    userInfoArrayList.add(userInfo);
                }
                adapter.notifyDataSetChanged();
            }
            @Override
            public void onCancelled(@NonNull  DatabaseError error) {
                Toast.makeText(Admin.this,"Failed to get data",Toast.LENGTH_SHORT).show();
            }
        });
        adapter = new UserAdapter(Admin.this,userInfoArrayList);
        mainUserRecyclerView.setAdapter(adapter);
    }

      public void setAddUser(View view){
        Intent intent = new Intent(this,user_detail.class);
          startActivity(intent);
      }

}
</code>```

This is my Adapter Class

```<code>package com.example.rent;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.viewHolder> {
    Context  admin;
   ArrayList<UserInfo> userInfoArrayList;
    public UserAdapter(Admin admin, ArrayList<UserInfo> userInfoArrayList) {

        this.admin = admin;
        this.userInfoArrayList = userInfoArrayList;
    }
    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull  ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(admin).inflate(R.layout.user_list_item,parent,false);
        return new viewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull  UserAdapter.viewHolder holder, int position) {
        UserInfo userInfo = userInfoArrayList.get(position);
        holder.user_name.setText(userInfo.getShopName());
        holder.itemView.setOnClickListener(v -> {

           Intent intent = new Intent(admin,Display_User.class);
            //Toast.makeText(admin, ""+userInfo.getOneMonthRent(), Toast.LENGTH_SHORT).show();
            intent.putExtra("Name",userInfo.getShopName());
            intent.putExtra("Rent",userInfo.getOneMonthRent());
            intent.putExtra("Complex",userInfo.getComplexName());
            intent.putExtra("PaidRent",userInfo.getPaidAmount());
            intent.putExtra("DMonth",userInfo.getDefaultMonth());
            intent.putExtra("PendingRent",userInfo.getPendingAmount());
            admin.startActivity(intent);

        });
    }

    @Override
    public int getItemCount() {
        return userInfoArrayList.size();
    }

   public static class viewHolder extends RecyclerView.ViewHolder  {
        TextView user_name;
        public viewHolder(@NonNull  View itemView) {
            super(itemView);
            user_name = itemView.findViewById(R.id.tvUserName);

        }
   }
}
</code>```

And The display User class where I have to fetch the data

```<code>package com.example.rent;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class Display_User extends AppCompatActivity {

     TextView tvName,tvRent,tvComplex,tvPaidRent,tvDefaultMonth,tvPendingRent;
     String Sname, rent, complex, paidRent, defaultMonth, pendingRent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_user);

         Sname = getIntent().getStringExtra("Name");
         rent = getIntent().getStringExtra("Rent");
         complex = getIntent().getStringExtra("Complex");
         paidRent = getIntent().getStringExtra("PaidRent");
         defaultMonth = getIntent().getStringExtra("DMonth");
         pendingRent = getIntent().getStringExtra("Pending");

        tvName = findViewById(R.id.tvName);
        tvName.setText(Sname);

        tvRent = findViewById(R.id.tvRent);
        tvRent.setText(rent);

        tvComplex = findViewById(R.id.tvComplex);
        tvComplex.setText(complex);

        tvPaidRent = findViewById(R.id.tvPaidRent);
        tvPaidRent.setText(paidRent);

        tvDefaultMonth = findViewById(R.id.tvDefault);
        tvDefaultMonth.setText(defaultMonth);

        tvPendingRent = findViewById(R.id.tvPending);
        tvPendingRent.setText(pendingRent);

    }
}
</code>```

答: Have you declared the Activity on the manifest file? And the intent ?</p>

Body:
My Application is crashed when I click on ItemView of RecyclerView, There is no error showing in code.
The data are load in toast but not pass to the other class or what don't know, but when I click any Item the appliaction is crash..

This is my Main RecyclerView Class

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class Admin extends AppCompatActivity {
     Button addUser;
     RecyclerView mainUserRecyclerView;
     UserAdapter adapter;
     FirebaseDatabase database;
     ArrayList<UserInfo> userInfoArrayList  = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);

        mainUserRecyclerView = findViewById(R.id.mainUserRecyclerView);
        mainUserRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        addUser = findViewById(R.id.addUserBtn);

        database= FirebaseDatabase.getInstance();

       DatabaseReference reference = database.getReference().child("userInfo");
        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                for(DataSnapshot dataSnapshot : snapshot.getChildren()){
                    UserInfo userInfo = dataSnapshot.getValue(UserInfo.class);
                    userInfoArrayList.add(userInfo);
                }
                adapter.notifyDataSetChanged();
            }
            @Override
            public void onCancelled(@NonNull  DatabaseError error) {
                Toast.makeText(Admin.this,"Failed to get data",Toast.LENGTH_SHORT).show();
            }
        });
        adapter = new UserAdapter(Admin.this,userInfoArrayList);
        mainUserRecyclerView.setAdapter(adapter);
    }

      public void setAddUser(View view){
        Intent intent = new Intent(this,user_detail.class);
          startActivity(intent);
      }

}

This is my Adapter Class

package com.example.rent;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.viewHolder> {
    Context  admin;
   ArrayList<UserInfo> userInfoArrayList;
    public UserAdapter(Admin admin, ArrayList<UserInfo> userInfoArrayList) {

        this.admin = admin;
        this.userInfoArrayList = userInfoArrayList;
    }
    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull  ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(admin).inflate(R.layout.user_list_item,parent,false);
        return new viewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull  UserAdapter.viewHolder holder, int position) {
        UserInfo userInfo = userInfoArrayList.get(position);
        holder.user_name.setText(userInfo.getShopName());
        holder.itemView.setOnClickListener(v -> {

           Intent intent = new Intent(admin,Display_User.class);
            //Toast.makeText(admin, ""+userInfo.getOneMonthRent(), Toast.LENGTH_SHORT).show();
            intent.putExtra("Name",userInfo.getShopName());
            intent.putExtra("Rent",userInfo.getOneMonthRent());
            intent.putExtra("Complex",userInfo.getComplexName());
            intent.putExtra("PaidRent",userInfo.getPaidAmount());
            intent.putExtra("DMonth",userInfo.getDefaultMonth());
            intent.putExtra("PendingRent",userInfo.getPendingAmount());
            admin.startActivity(intent);

        });
    }

    @Override
    public int getItemCount() {
        return userInfoArrayList.size();
    }

   public static class viewHolder extends RecyclerView.ViewHolder  {
        TextView user_name;
        public viewHolder(@NonNull  View itemView) {
            super(itemView);
            user_name = itemView.findViewById(R.id.tvUserName);

        }
   }
}

And The display User class where I have to fetch the data

package com.example.rent;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class Display_User extends AppCompatActivity {

     TextView tvName,tvRent,tvComplex,tvPaidRent,tvDefaultMonth,tvPendingRent;
     String Sname, rent, complex, paidRent, defaultMonth, pendingRent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_user);

         Sname = getIntent().getStringExtra("Name");
         rent = getIntent().getStringExtra("Rent");
         complex = getIntent().getStringExtra("Complex");
         paidRent = getIntent().getStringExtra("PaidRent");
         defaultMonth = getIntent().getStringExtra("DMonth");
         pendingRent = getIntent().getStringExtra("Pending");

        tvName = findViewById(R.id.tvName);
        tvName.setText(Sname);

        tvRent = findViewById(R.id.tvRent);
        tvRent.setText(rent);

        tvComplex = findViewById(R.id.tvComplex);
        tvComplex.setText(complex);

        tvPaidRent = findViewById(R.id.tvPaidRent);
        tvPaidRent.setText(paidRent);

        tvDefaultMonth = findViewById(R.id.tvDefault);
        tvDefaultMonth.setText(defaultMonth);

        tvPendingRent = findViewById(R.id.tvPending);
        tvPendingRent.setText(pendingRent);

    }
}


问:
I cound'nt find buildscript in build.gradle(Project)
This is build.gradle(Project) what i knew.

```<code>buildscript {

    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}
</code>```

But my Project's build.gradle(Project) is that.

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.1' apply false
    id 'com.android.library' version '7.1.1' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

I tried to link Firebase with Android, but build.gradle(Project) was different from the file I knew.

I tried to modify it by force, but it didn't sync...

How can I access the Top-Level Gradle file??

答: Try classpath 'com.android.tools.build:gradle:7.1.1' for Android Studio Bumblebee; Android Studio Arctic Fox still uses AGP up to 7.0.4. In every case, you cannot add version 7.0.0 to class-path, but then use version 7.1.1. These version numbers need to match. Most likely the Gradle wrapper also needs to be updated. Maybe think about version control once ...because one could basically sum up the question as "I've deleted a file, what now?"

Body:
This is build.gradle(Project) what i knew.

buildscript {

    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

But my Project's build.gradle(Project) is that.

// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.1' apply false
    id 'com.android.library' version '7.1.1' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I tried to link Firebase with Android, but build.gradle(Project) was different from the file I knew.

I tried to modify it by force, but it didn't sync...

How can I access the Top-Level Gradle file??


问:
CSS: How to shrink td containing ellipsis
I have done quite a bit or searching on this but could not find a solution for my specific case. I am a beginner to CSS and the solution is probably really simple, I just cannot find it. So I am trying to create a table that has some columns with long text. I am able to show ellipsis to cut off too long text, but I would like to have the column resize and the ellipsis be updated if I reduce the size of the window, that also reduces the size of the table itself. Now the cell width remains the same and a horizontal scroll bar is shown, which I want to prevent. I know using fixed width for the column is probably the problem, but it is the only way I am able to show the ellipsis in the first place, without fixed width no ellipsis is shown. Here is a very simplified piece of code and the css that easily shows the problem:

```<code><div class="tableFixHead">
  <table>
    <thead>
      <tr>
        <th>one</th>
        <th>two</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          first column
        </td>
        <td>
          <div class="overflowTableText">
            the entire text that is way too long to show all at once
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>
</code>```
```<code>.tableFixHead {
  overflow: scroll;
  height: 200px;
  max-width: 50%;
}

.overflowTableText {
  width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
</code>```

Any pointers are appreciated

答:
One way to do this is to use @media query. Do something like this

.tableFixHead {
    overflow: scroll;
    height: 200px;
    max-width: 50%;
}

.overflowTableText {
    max-width: 300px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* add as many break points you want */
@media screen (max-width: 768px) {
    .overflowTableText {
        max-width: 200px;
    }
}
@media screen (max-width: 576px) {
    .overflowTableText {
        max-width: 150px;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tableFixHead">
    <table>
        <thead>
            <tr>
                <th>one</th>
                <th>two</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>first column</td>
                <td>
                    <div class="overflowTableText">
                        the entire text that is way too long to show all at once
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
</div></code>```

Body:
I have done quite a bit or searching on this but could not find a solution for my specific case. I am a beginner to CSS and the solution is probably really simple, I just cannot find it. So I am trying to create a table that has some columns with long text. I am able to show ellipsis to cut off too long text, but I would like to have the column resize and the ellipsis be updated if I reduce the size of the window, that also reduces the size of the table itself. Now the cell width remains the same and a horizontal scroll bar is shown, which I want to prevent. I know using fixed width for the column is probably the problem, but it is the only way I am able to show the ellipsis in the first place, without fixed width no ellipsis is shown. Here is a very simplified piece of code and the css that easily shows the problem:

        one
        two

          first column

            the entire text that is way too long to show all at once

.tableFixHead {
  overflow: scroll;
  height: 200px;
  max-width: 50%;
}

.overflowTableText {
  width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

Any pointers are appreciated

Body:
One way to do this is to use @media query. Do something like this

.tableFixHead {
    overflow: scroll;
    height: 200px;
    max-width: 50%;
}

.overflowTableText {
    max-width: 300px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* add as many break points you want */
@media screen (max-width: 768px) {
    .overflowTableText {
        max-width: 200px;
    }
}
@media screen (max-width: 576px) {
    .overflowTableText {
        max-width: 150px;
    }
}

<div class="tableFixHead">
    <table>
        <thead>
            <tr>
                <th>one</th>
                <th>two</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>first column</td>
                <td>
                    <div class="overflowTableText">
                        the entire text that is way too long to show all at once
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
</div>


问:
XCOPY - How to exclude a certain file name?
This is my current xcopy command:

```<code>xcopy C:\SourceCodeOld\Release\"Source Code"\*.vb C:\SourceCodeNew\"Source Code"\ /S /Y /R
</code>```

In several subfolders, I have a file named "AssemblyInfo.vb". How can I exclude it from being copied?

答:
There is an /EXCLUDE option of xcopy, which allows to specify (the path to) a text file that contains partial file paths/names one per line (note also the fixed quotation):

xcopy /S /Y /R /I /EXCLUDE:exclude.txt "C:\SourceCodeOld\Release\Source Code\*.vb" "C:\SourceCodeNew\Source Code"
```
<p>with <code>exclude.txt</code> being in the current working directory and containing:</p>
<pre class="lang-cmd prettyprint-override"><code>AssemblyInfo.vb
</code>```

However, the implementation of the /EXCLUDE option is terrible, because actually all files are excluded whose absolute source paths contain any of the given strings at any position (in a case-insensitive manner). Moreover, you cannot even use wildcards in these strings. Furthermore, you cannot provide a quoted path to the exclusion text file to protect potential spaces or special characters. (Refer also to this related answer of mine.)

I strongly recommend to use the robocopy command, whose exclusion options are more mature:

robocopy "C:\SourceCodeOld\Release\Source Code" "C:\SourceCodeNew\Source Code" "*.vb" /S /XF "AssemblyInfo.vb"
```

This truly excludes only files whose names are AssemblyInfo.vb.

Body:
This is my current xcopy command:

xcopy C:\SourceCodeOld\Release\"Source Code"\*.vb C:\SourceCodeNew\"Source Code"\ /S /Y /R

In several subfolders, I have a file named "AssemblyInfo.vb". How can I exclude it from being copied?

Body:
There is an /EXCLUDE option of xcopy, which allows to specify (the path to) a text file that contains partial file paths/names one per line (note also the fixed quotation):

xcopy /S /Y /R /I /EXCLUDE:exclude.txt "C:\SourceCodeOld\Release\Source Code\*.vb" "C:\SourceCodeNew\Source Code"

with exclude.txt being in the current working directory and containing:

AssemblyInfo.vb

However, the implementation of the /EXCLUDE option is terrible, because actually all files are excluded whose absolute source paths contain any of the given strings at any position (in a case-insensitive manner). Moreover, you cannot even use wildcards in these strings. Furthermore, you cannot provide a quoted path to the exclusion text file to protect potential spaces or special characters. (Refer also to this related answer of mine.)

I strongly recommend to use the robocopy command, whose exclusion options are more mature:

robocopy "C:\SourceCodeOld\Release\Source Code" "C:\SourceCodeNew\Source Code" "*.vb" /S /XF "AssemblyInfo.vb"

This truly excludes only files whose names are AssemblyInfo.vb.