问:
Removing n columns from all the files from directory in Unix
I have around 2000+ files which has random number of columns in each file.
I wanted to remove last 4 columns from each of the file.

I tried to use below command, but it is not an inline command. Delimiter of the file is #

awk -F"#" '{NF-=4;OFS="#";print}' test > testing.csv

I wanted to save the file with the same name.(e.g. filename test with test only)

How to remove last 4 columns and save the file with same name?
Can someone please help?

答:
Using any POSIX awk:</p>

```<code>tmp=$(mktemp) || exit 1
for file in *; do
    awk '{sub(/(#[^#]*){4}$/,"")}1' "$file" > "$tmp" &&
    mv -- "$tmp" "$file"
done
</code>```

Body:
Using any POSIX awk:

tmp=$(mktemp) || exit 1
for file in *; do
    awk '{sub(/(#[^#]*){4}$/,"")}1' "$file" > "$tmp" &&
    mv -- "$tmp" "$file"
done


来源: stackexchange

问:
select date and time from 2 columns mysql with date_format
I have a table formatted as follows:

```<code>|   ID   |   Name  |     date       |   time     |
|   1    |    A    |   2020-05-04   |  19:00:00  |
|   2    |    B    |   2020-05-04   |  19:10:00  |
|   3    |    C    |   2020-05-04   |  19:20:00  |
</code>```

I want to select the result between 2020-05-04 - 19:00:00 and 2020-05-04 - 19:20:00, so I'm expecting the result to be B

And if I use date_format:

```<code>SELECT *
  from table
 where (date > DATE_FORMAT('2020-05-04 19:00:00','%Y-%m-%d %T'))
   AND (date < DATE_FORMAT('2020-05-04 19:20:00','%Y-%m-%d %T'))
</code>```

it ends up being wrong because it only uses the date.

How can I search in 2 columns at the same time?

ContentLicense: CC BY-SA 4.0

Body:
I have a table formatted as follows:

|   ID   |   Name  |     date       |   time     |
|   1    |    A    |   2020-05-04   |  19:00:00  |
|   2    |    B    |   2020-05-04   |  19:10:00  |
|   3    |    C    |   2020-05-04   |  19:20:00  |

I want to select the result between 2020-05-04 - 19:00:00 and 2020-05-04 - 19:20:00, so I'm expecting the result to be B

And if I use date_format:

SELECT *
  from table
 where (date > DATE_FORMAT('2020-05-04 19:00:00','%Y-%m-%d %T'))
   AND (date < DATE_FORMAT('2020-05-04 19:20:00','%Y-%m-%d %T'))

it ends up being wrong because it only uses the date.

How can I search in 2 columns at the same time?

Body: SELECT * from table where (date > DATE_FORMAT('2020-05-04','%Y-%m-%d')) AND (date < DATE_FORMAT('2020-05-04','%Y-%m-%d')) AND (time > DATE_FORMAT('19:00:00',  '%T')) AND (time < DATE_FORMAT('19:20:00',  '%T'))


问:
Sometimes getting nil while converting UTC date string to timestamp
Sometimes I am getting nil while converting date string to timestamp.

Here is my code:

```<code>class func createTimeStampFromDateString(dateString : String) -> Double? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let convertedDate = dateFormatter.date(from: dateString)
    let timeIntervalsince1970 = convertedDate?.timeIntervalSince1970
    return timeIntervalsince1970
}
</code>```

Could you please let me know what is wrong in this code.

Thanks in advance!

答:
Based on your comments, the bug is not because of this function (it is working as expected). The bug (the crash) you're experiencing is because you're force unwrapping a date value that is nil, and that is because the string used to create that date isn't in the valid format. And this is the nature of working with dates and strings from sources outside of your app—the strings aren't guaranteed to be in the right format. And this is why your function, as it should be, returns an optional value.

By the way, you could simplify your method and take advantage of the ISO8601DateFormatter:

```<code>func timestamp(from string: String) -> Double? {
    let df = ISO8601DateFormatter()
    df.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    return df.date(from: string)?.timeIntervalSince1970
}
</code>```

And to use it properly, use it conditionally without force unwrapping:

```<code>if let interval = timestamp(from: "2020-06-02T13:38:31.814Z") {
    print(interval)
}
</code>```

To correct your bug:

Don't force unwrap when working with date/string conversions. If the string is ever not in the correct format, consider discarding the result, providing a default value, displaying something like "unknown"—anything but forcing the app to crash.

Determine why the string isn't in the right format and see if that's correctable.

Body:
Sometimes I am getting nil while converting date string to timestamp.

Here is my code:

class func createTimeStampFromDateString(dateString : String) -> Double? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let convertedDate = dateFormatter.date(from: dateString)
    let timeIntervalsince1970 = convertedDate?.timeIntervalSince1970
    return timeIntervalsince1970
}

Could you please let me know what is wrong in this code.

Thanks in advance!

Body:
Based on your comments, the bug is not because of this function (it is working as expected). The bug (the crash) you're experiencing is because you're force unwrapping a date value that is nil, and that is because the string used to create that date isn't in the valid format. And this is the nature of working with dates and strings from sources outside of your app—the strings aren't guaranteed to be in the right format. And this is why your function, as it should be, returns an optional value.

By the way, you could simplify your method and take advantage of the ISO8601DateFormatter:

func timestamp(from string: String) -> Double? {
    let df = ISO8601DateFormatter()
    df.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    return df.date(from: string)?.timeIntervalSince1970
}

And to use it properly, use it conditionally without force unwrapping:

if let interval = timestamp(from: "2020-06-02T13:38:31.814Z") {
    print(interval)
}

To correct your bug:

Don't force unwrap when working with date/string conversions. If the string is ever not in the correct format, consider discarding the result, providing a default value, displaying something like "unknown"—anything but forcing the app to crash.

Determine why the string isn't in the right format and see if that's correctable.


问:
Flutter Web Rich Text Editor
I am looking for a text editor similar to the one in the image.

I have seen an add-on that performs exactly what I want but is associated with the mobile keyboard.

In flutter web no keyboard opens, but you type directly.

That is why I would like to know if there is any solution to get what I am looking for, I am waiting for an answer, thank you very much for your attention.

Here you have the plugin link:
https://pub.dev/packages/zefyr

答:
This will build for flutter web you need to make sure you are on master branch of zephyr and flutter

To change branch type in your console

```<code>flutter channel master

flutter channel upgrade
</code>```

Hope this helps friends.

Patrick.

Title: Flutter Web Rich Text Editor

Body:
This will build for flutter web you need to make sure you are on master branch of zephyr and flutter

To change branch type in your console

flutter channel master

flutter channel upgrade

Hope this helps friends.

Patrick.


问:
"Couldn't find <object> without an ID"
I'm having problems implementing a kind of comments form, where comments (called "microposts") belong_to both users and posts, users have_many comments, and posts (called "propositions") have_many comments.

My code for the comments form is:

```<code><%= form_for @micropost do |f| %>
  <div class="field">
      <%= f.text_area :content %>
  </div>

  <div class="actions">
    <%= f.submit "Submit" %>
  </div>
<% end %>
</code>```

The MicropostsController has this in the create action:

```<code>  def create

      @proposition = Proposition.find(params[:proposition_id])

  @micropost = current_user.microposts.build(params[:micropost])
  @micropost.proposition = @proposition
  if @micropost.save
      flash[:success] = "Contribution submitted"
      redirect_to root_path
  else
          @feed_items = []
      render 'pages/home'
  end
  end
</code>```

The form for creating a new micropost is on the same page as a proposition, yet the proposition id doesn't seem to get passed at any point.

This is the error I get on submitting the micropost form:

ActiveRecord::RecordNotFound in
  MicropostsController#create

Couldn't find Proposition without an
  ID

Parameters are:

{"commit"=>"Submit",
  "micropost"=>{"proposition_id"=>"",
  "content"=>"First comment"},
  "authenticity_token"=>"TD6kZaHv3CPWM7xLzibEbaLJHI0Uw43H+pq88HLZFjc=",
  "utf8"=>"âœ“"}

I'm completely new to rails and very new to coding anything at all, so I'd be grateful for any help you can give me!

Thanks in advance.

答:
As you can see, the proposition_id parameter is empty, so your controller can't find the proposition unless you give it a valid id.

You need to make sure your new form sends the proposition_id attribute. One way to do this is:

Set the proposition in the new action in the controller: @micropost.proposition = ...

In the form, add a hidden field for the id: f.hidden_field :proposition_id

In the create action, find the appropriate Proposition with params[:micropost][:proposition_id]

(You'll also want to make sure to use attr_accessible in your Micropost model, and make sure proposition_id is NOT in that list. Otherwise, you'll be open to nasty security holes. See http://www.kalzumeus.com/2010/09/22/security-lessons-learned-from-the-diaspora-launch/ and Which fields should be protected from mass assignment?)

EDIT (due to comment):

Your new action should be like this:

```<code>def new
  @micropost = Micropost.new
  @micropost.proposition_id = params[:proposition_id]
</code>```

This is slightly different from what is said above, and is due to the fact you're sending the proposition id in the request to new. There's no need to look up the actual proposition record, since we're only interested in the id field (which we already have).

ContentLicense: CC BY-SA 3.0

Title: "Couldn't find <object> without an ID"

Body:
I'm having problems implementing a kind of comments form, where comments (called "microposts") belong_to both users and posts, users have_many comments, and posts (called "propositions") have_many comments.

My code for the comments form is:

<%= form_for @micropost do |f| %>

      <%= f.text_area :content %>

    <%= f.submit "Submit" %>

<% end %>

The MicropostsController has this in the create action:

  def create

      @proposition = Proposition.find(params[:proposition_id])

  @micropost = current_user.microposts.build(params[:micropost])
  @micropost.proposition = @proposition
  if @micropost.save
      flash[:success] = "Contribution submitted"
      redirect_to root_path
  else
          @feed_items = []
      render 'pages/home'
  end
  end

The form for creating a new micropost is on the same page as a proposition, yet the proposition id doesn't seem to get passed at any point.

This is the error I get on submitting the micropost form:

ActiveRecord::RecordNotFound in
  MicropostsController#create

Couldn't find Proposition without an
  ID

Parameters are:

{"commit"=>"Submit",
  "micropost"=>{"proposition_id"=>"",
  "content"=>"First comment"},
  "authenticity_token"=>"TD6kZaHv3CPWM7xLzibEbaLJHI0Uw43H+pq88HLZFjc=",
  "utf8"=>"âœ“"}

I'm completely new to rails and very new to coding anything at all, so I'd be grateful for any help you can give me!

Thanks in advance.

Body:
As you can see, the proposition_id parameter is empty, so your controller can't find the proposition unless you give it a valid id.

You need to make sure your new form sends the proposition_id attribute. One way to do this is:

Set the proposition in the new action in the controller: @micropost.proposition = ...

In the form, add a hidden field for the id: f.hidden_field :proposition_id

In the create action, find the appropriate Proposition with params[:micropost][:proposition_id]

(You'll also want to make sure to use attr_accessible in your Micropost model, and make sure proposition_id is NOT in that list. Otherwise, you'll be open to nasty security holes. See http://www.kalzumeus.com/2010/09/22/security-lessons-learned-from-the-diaspora-launch/ and Which fields should be protected from mass assignment?)

EDIT (due to comment):

Your new action should be like this:

def new
  @micropost = Micropost.new
  @micropost.proposition_id = params[:proposition_id]

This is slightly different from what is said above, and is due to the fact you're sending the proposition id in the request to new. There's no need to look up the actual proposition record, since we're only interested in the id field (which we already have).


问:
Get the path of first file in each directory or sub-directory
I have a directory structure as following: The Root directory contains some sub-directories in which many.txt files are placed or some  sub-directories again  that contains different files with the same extension.

```<code>├───Root
│   ├───SubDir1
        └───file1.txt
│   ├───SubDir2
│   ├───SubDir3
│       └───SubSubDir1
            └───file1.txt
            └───file2.txt
│   └───SubDir4
│       └───SubSubDir1
        └───SubSubDir2
            └───file1.txt
</code>```

I want to save all the first file-paths in each directoriy in a QStringList. E.g.:

```<code>/Root/SubDir1/file1.txt
/Root/SubDir3/SubSubDir1/file1.txt
/Root/SubDir4/SubSubDir2/file1.txt
</code>```

The following code gives me all the file-paths in a directory or sub-directories but not the path of the first file in each.

```<code>QDir rootFolder("/root");
QStringList list;
QDirIterator dirIter(rootFolder.absolutePath(), QDir::AllEntries | QDir::NoSymLinks |
QDir::NoDotAndDotDot, QDirIterator::Subdirectories);

while(dirIter.hasNext())
{
    dirIter.next();
    if(QFileInfo(dirIter.filePath()).isFile())
    {
        if(QFileInfo(dirIter.filePath()).suffix() == "txt")
        {
            qDebug()<<"File Path: " <<dirIter.filePath();

            list.append(dirIter.next());
            qDebug()<<"List: " <<list;
        }
    }
}
</code>```

答:
dirIter.next() returns already the next value !
The problem is, you skip the first item after your while loop.

EDIT: If you only want the first filename you can do this:

```<code>QDir rootFolder("/Users/chris/Downloads");
rootFolder.setSorting(QDir::Name);
QStringList list;
QDirIterator dirIter(rootFolder.absolutePath(), QStringList() << "*.txt", QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);

QStringList directoryList;

while(dirIter.hasNext())
{
    QString filename = dirIter.next();
    QFileInfo info(filename);

    if(directoryList.contains(info.absolutePath()))
    {
        continue;
    }

    qDebug()<<"File Path: " << info.absoluteFilePath();
    list.append(filename);
    directoryList.append(info.absolutePath());
}

qDebug()<< "List: " << list;
</code>```

Body:
I have a directory structure as following: The Root directory contains some sub-directories in which many.txt files are placed or some  sub-directories again  that contains different files with the same extension.

├───Root
│   ├───SubDir1
        └───file1.txt
│   ├───SubDir2
│   ├───SubDir3
│       └───SubSubDir1
            └───file1.txt
            └───file2.txt
│   └───SubDir4
│       └───SubSubDir1
        └───SubSubDir2
            └───file1.txt

I want to save all the first file-paths in each directoriy in a QStringList. E.g.:

/Root/SubDir1/file1.txt
/Root/SubDir3/SubSubDir1/file1.txt
/Root/SubDir4/SubSubDir2/file1.txt

The following code gives me all the file-paths in a directory or sub-directories but not the path of the first file in each.

QDir rootFolder("/root");
QStringList list;
QDirIterator dirIter(rootFolder.absolutePath(), QDir::AllEntries | QDir::NoSymLinks |
QDir::NoDotAndDotDot, QDirIterator::Subdirectories);

while(dirIter.hasNext())
{
    dirIter.next();
    if(QFileInfo(dirIter.filePath()).isFile())
    {
        if(QFileInfo(dirIter.filePath()).suffix() == "txt")
        {
            qDebug()<<"File Path: " <<dirIter.filePath();

            list.append(dirIter.next());
            qDebug()<<"List: " <<list;
        }
    }
}

Body:
dirIter.next() returns already the next value !
The problem is, you skip the first item after your while loop.

EDIT: If you only want the first filename you can do this:

QDir rootFolder("/Users/chris/Downloads");
rootFolder.setSorting(QDir::Name);
QStringList list;
QDirIterator dirIter(rootFolder.absolutePath(), QStringList() << "*.txt", QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);

QStringList directoryList;

while(dirIter.hasNext())
{
    QString filename = dirIter.next();
    QFileInfo info(filename);

    if(directoryList.contains(info.absolutePath()))
    {
        continue;
    }

    qDebug()<<"File Path: " << info.absoluteFilePath();
    list.append(filename);
    directoryList.append(info.absolutePath());
}

qDebug()<< "List: " << list;


问:
Shared variables in TypeScripts just like in JS
In JS I am able to connect scripts inside HTML. Assume I have two scripts first.js and second.js, so I can make this:

```<code><script src=".../first.js"></script>
<script src=".../second.js"></script>
</code>```

and then I am able to use any variable of first.js in second.js
How to reach such a result via TypeScript keeping those scripts as separated files?

答:
You need to declare this in your TypeScript file so that the compiler knows it exists.

declare var x: string; // The variable name should be the same as in your JS files.

Body:
In JS I am able to connect scripts inside HTML. Assume I have two scripts first.js and second.js, so I can make this:

and then I am able to use any variable of first.js in second.js
How to reach such a result via TypeScript keeping those scripts as separated files?


问:
best approch among EXE and MSI
I have an application that needs to be delivered as a package.

What are the best among EXE and MSI Installers, and why?

Is there any open source tool to decompile the EXE or MSI?

答:
You can just tell Visual Studio to make your application into an MSI/EXE.  If that works and does what you want, just do that.  It much effort on your part creating an installer.

MSI means you are using Microsoft's Installer.  Microsoft has legitimate reasons for recommending (i.e., not giving your application Certification) MSI.  However, a good MSI is tough to produce, so I don't recommend it unless you need your application to be certified.

If you don't require certification, I recommend Inno Setup, along with a front-end like ISTool.  It's easy to use and gives you simple interfaces to perform most common installer tasks.  In a pinch, it supports scripting to allow you to do anything it doesn't support.

Title: best approch among EXE and MSI


问:
Spring use different property files depending on request params
Background:

I am working on a java Spring REST microservice that needs to work with multiple identical back-end systems and multiple identical databases depending on the request parameters.

Basically I have 3 "brands". For each brand there is a set of downstream services and a database. I have no control over those.

My spring service will receive brand as a part of request and will need to call the right downstream services and use the correct database.

Previously I would deal with this by having a separate instance of the spring service for each of the brands. There would be a single property file for each brand and spring would use it to wire up beans. I would have separate URL's for each brand and there was no problem.

Some of my beans need to know about "brand" during creation as they are wrappers around connections downstream services. I.e. once the bean is created there won't be a way to switch it to be a "different brand".

Problem:

I would like to change this so that a single instance of my service can handle requests for any brand.

Requirements:
I was thinking about the following solution:

Have a general property file for non-branded stuff. Spring would wire any non-branded beans and keep them as singleton beans.

Have a property file with brand specific urls etc for each of the brands
Spring would create set of singleton beans for each of the brand using appropriate property file.

Next when the request comes in spring would read the request params and use bean specific for that brand.

Performance is important to me so I would like to reuse the beans as much as possible.

I would like to make this thing as transparent as possible so that people creating new beans don't have to worry about doing anything outside standard configuration/context class.

Does anyone know what would be the best solution to achieve this?

答:
I think you can solve the problem injecting the service in every request with the right set of configurations and beans; possibly already existing in your Application Context.

Given:

```<code>$ curl http://localhost:8080/greetings/rodo && echo
Hi from brand1, rodo
$ curl -H "x-brand-name: brand1" http://localhost:8080/greetings/rodo
Hi from brand1, rodo
$ curl -H "x-brand-name: brand2" http://localhost:8080/greetings/rodo && echo
Hi from brand2, rodo
</code>```

The following code would work:

-- application.yml --

```<code>brand1:
  greetingPrefix: Hi from brand1,

brand2:
  greetingPrefix: Hi from brand2,
</code>```

-- DemoApplication.java --

```<code>@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Configuration
    class ServiceConfig {
        @Bean
        public GreetingService greetingServiceBrand1(Brand1Config config) {
            return new GreetingService(config);
        }

        @Bean
        public GreetingService greetingServiceBrand2(Brand2Config config) {
            return new GreetingService(config);
        }
    }

    @Configuration
    class WebConfig implements WebMvcConfigurer {
        @Autowired
        private ApplicationContext applicationContext;

        @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
            resolvers.add(greetingServiceResolver());
        }

        private GreetingServiceResolver greetingServiceResolver() {
            GreetingService greetingServiceBrand1 = applicationContext.getBean("greetingServiceBrand1", GreetingService.class);
            GreetingService greetingServiceBrand2 = applicationContext.getBean("greetingServiceBrand2", GreetingService.class);
            return new GreetingServiceResolver(greetingServiceBrand1, greetingServiceBrand2);
        }
    }
}

@RestController
@RequestMapping("/greetings")
class GreetingController {
    @GetMapping("/{name}")
    public String get(GreetingService greetingService, @PathVariable String name) {
        return greetingService.sayHi(name);
    }
}

class GreetingServiceResolver implements HandlerMethodArgumentResolver {
    private final GreetingService greetingServiceBrand1;
    private final GreetingService greetingServiceBrand2;

    public GreetingServiceResolver(GreetingService greetingServiceBrand1, GreetingService greetingServiceBrand2) {
        this.greetingServiceBrand1 = greetingServiceBrand1;
        this.greetingServiceBrand2 = greetingServiceBrand2;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(GreetingService.class);
    }

    @Override
    public Object resolveArgument(
            MethodParameter methodParameter,
            ModelAndViewContainer modelAndViewContainer,
            NativeWebRequest nativeWebRequest,
            WebDataBinderFactory webDataBinderFactory
    ) throws Exception {
        String brand = nativeWebRequest.getHeader("x-brand-name");
        return resolveGreetingService(brand);
    }

    private GreetingService resolveGreetingService(String brand) {
        if ("brand2".equals(brand)) {
            return greetingServiceBrand2;
        }
        return greetingServiceBrand1; // default
    }
}

class GreetingService {
    private BaseConfig config;

    public GreetingService(BaseConfig config) {
        this.config = config;
    }

    public String sayHi(String name) {
        return config.getGreetingPrefix() + " " + name;
    }
}

abstract class BaseConfig {
    private String greetingPrefix;

    public String getGreetingPrefix() {
        return greetingPrefix;
    }

    public void setGreetingPrefix(String greetingPrefix) {
        this.greetingPrefix = greetingPrefix;
    }
}

@Configuration
@ConfigurationProperties("brand1")
class Brand1Config extends BaseConfig {
}

@Configuration
@ConfigurationProperties("brand2")
class Brand2Config extends BaseConfig {
}
</code>```

As you can see, it's fundamental to pass the service to each controller method, write a resolver and inject the right set of dependencies depending on a parameter passed to the request, in this case via header.

Body:
I think you can solve the problem injecting the service in every request with the right set of configurations and beans; possibly already existing in your Application Context.

Given:

$ curl http://localhost:8080/greetings/rodo && echo
Hi from brand1, rodo
$ curl -H "x-brand-name: brand1" http://localhost:8080/greetings/rodo
Hi from brand1, rodo
$ curl -H "x-brand-name: brand2" http://localhost:8080/greetings/rodo && echo
Hi from brand2, rodo

The following code would work:

-- application.yml --

brand1:
  greetingPrefix: Hi from brand1,

brand2:
  greetingPrefix: Hi from brand2,

-- DemoApplication.java --

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Configuration
    class ServiceConfig {
        @Bean
        public GreetingService greetingServiceBrand1(Brand1Config config) {
            return new GreetingService(config);
        }

        @Bean
        public GreetingService greetingServiceBrand2(Brand2Config config) {
            return new GreetingService(config);
        }
    }

    @Configuration
    class WebConfig implements WebMvcConfigurer {
        @Autowired
        private ApplicationContext applicationContext;

        @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
            resolvers.add(greetingServiceResolver());
        }

        private GreetingServiceResolver greetingServiceResolver() {
            GreetingService greetingServiceBrand1 = applicationContext.getBean("greetingServiceBrand1", GreetingService.class);
            GreetingService greetingServiceBrand2 = applicationContext.getBean("greetingServiceBrand2", GreetingService.class);
            return new GreetingServiceResolver(greetingServiceBrand1, greetingServiceBrand2);
        }
    }
}

@RestController
@RequestMapping("/greetings")
class GreetingController {
    @GetMapping("/{name}")
    public String get(GreetingService greetingService, @PathVariable String name) {
        return greetingService.sayHi(name);
    }
}

class GreetingServiceResolver implements HandlerMethodArgumentResolver {
    private final GreetingService greetingServiceBrand1;
    private final GreetingService greetingServiceBrand2;

    public GreetingServiceResolver(GreetingService greetingServiceBrand1, GreetingService greetingServiceBrand2) {
        this.greetingServiceBrand1 = greetingServiceBrand1;
        this.greetingServiceBrand2 = greetingServiceBrand2;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(GreetingService.class);
    }

    @Override
    public Object resolveArgument(
            MethodParameter methodParameter,
            ModelAndViewContainer modelAndViewContainer,
            NativeWebRequest nativeWebRequest,
            WebDataBinderFactory webDataBinderFactory
    ) throws Exception {
        String brand = nativeWebRequest.getHeader("x-brand-name");
        return resolveGreetingService(brand);
    }

    private GreetingService resolveGreetingService(String brand) {
        if ("brand2".equals(brand)) {
            return greetingServiceBrand2;
        }
        return greetingServiceBrand1; // default
    }
}

class GreetingService {
    private BaseConfig config;

    public GreetingService(BaseConfig config) {
        this.config = config;
    }

    public String sayHi(String name) {
        return config.getGreetingPrefix() + " " + name;
    }
}

abstract class BaseConfig {
    private String greetingPrefix;

    public String getGreetingPrefix() {
        return greetingPrefix;
    }

    public void setGreetingPrefix(String greetingPrefix) {
        this.greetingPrefix = greetingPrefix;
    }
}

@Configuration
@ConfigurationProperties("brand1")
class Brand1Config extends BaseConfig {
}

@Configuration
@ConfigurationProperties("brand2")
class Brand2Config extends BaseConfig {
}

As you can see, it's fundamental to pass the service to each controller method, write a resolver and inject the right set of dependencies depending on a parameter passed to the request, in this case via header.


问:
How can I have Github on my own server?
Is there anything out there like Github that is for your own local server?  I am curious if there is like a PHP script or even a desktop client that mimics Github's functionality, I love Github but it would be nice to host on my own server.

Apologies if this isn't considered "programming" enough but generally only programmers use GIT and Github

Update

First of all thanks for all the great suggestions, it is great to see there are options out there.  From what is posted here and from my googling I can say it looks like the best looking/most alike to Github solutions are coded in Ruby, which is great for some but I am a PHP kind of guy (for now).

Most of the PHP GIT viewers either are  outdated and abandoned projects or they just look like crap ( I realize I could fix them up to be more like Github) but I ran across something in PHP that looks promising so far.  It is called Glip it is on Github here https://github.com/patrikf/glip and to me it is the most attractive and easy to use solution I have found for PHP so far.  For the advanced Git user, it may not be enough but for me, I just wanted to be able to view a git repo and that provides that functionality.

Now my search still continues for the perfect solution, will I ever find it?  I hope so but, for now, this is we got.  I am considering writing my own, one that is attractive like Github and has other features like an Issue tracker for bug and feature requests.  All the ones I have seen so far are not so good

答: Also you can install Trac. It's more than a Git server, it has other feature like tickets management and project management. Also it has the possiblity to extend it through plugins.</p>

Title: How can I have Github on my own server?


问:
Will having two NSTimers in one class cause them to be less accurate?
I have one NSTimer which is my main game loop, it calls 60 times a second. I have another timer which is a countdown, which gets called 0.001 times a second. Is it normal that timer is not accurate? or should i call the countdown timer fewer times per second?</p>

答: NSTimers are not accurate.  The time interval you specify is simply a goal.  The NSTimer will try to hit that goal but the more stuff you have running on that thread the slower the cycle time will be.  Your 0.001 timer is probably going way too fast to be useful and will suffer from accuracy problems.  If you need real time accuracy you will have to track what time the timer is actually firing with an NSDate and compensate accordingly.</p>


问:
how arguments are passed to __init__ in classes
Hello I am trying to understand __init__ in class in Python.I understood how classes work but i could not understand 1 thing
here is code:

```<code>class Computer:

    def __init__(self, name, cpu, ram, hdd, ssd):
        self.name = name
        self.cpu = cpu
        self.ram = ram
        self.hdd = hdd
        self.ssd = ssd
    def config(self):
        print("Configuration of computer is: ", self.name, self.cpu, self.ram, self.hdd, self.ssd )

computer1 = Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB")
computer1.config()
</code>```

why and how arguments Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB") are passed to __init__(self, name, cpu, ram, hdd, ssd) automatically?why we are writing this arguments in class parentheses and not separately like this:

```<code> computer1.__init__("HP ", "i7 ", "16gb ", "1TB ", "256GB")
</code>```

how the code can understand  that arguments written in Computer's parentheses have to be passed to __init__ ?

答: because The __init__ method is roughly what represents a constructor in Python. When you call Computer("HP ","i7 ","16gb ","1TB ","256GB") Python creates an object for you, and passes it as the first parameter to the __init__ method. Any additional parameters(more than the five you declared) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.

Body:
Hello I am trying to understand __init__ in class in Python.I understood how classes work but i could not understand 1 thing
here is code:

class Computer:

    def __init__(self, name, cpu, ram, hdd, ssd):
        self.name = name
        self.cpu = cpu
        self.ram = ram
        self.hdd = hdd
        self.ssd = ssd
    def config(self):
        print("Configuration of computer is: ", self.name, self.cpu, self.ram, self.hdd, self.ssd )

computer1 = Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB")
computer1.config()

why and how arguments Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB") are passed to __init__(self, name, cpu, ram, hdd, ssd) automatically?why we are writing this arguments in class parentheses and not separately like this:

 computer1.__init__("HP ", "i7 ", "16gb ", "1TB ", "256GB")

how the code can understand  that arguments written in Computer's parentheses have to be passed to __init__ ?


问:
Azure Data Studio: Save As CSV with header
I saw the article on how to save the result of the query as csv.  Is it possible to save it with header?

Reference:
Azure Data Studio: Save As CSV

答:
Yes, it always saves the data with headers. You can click on the first icon (see the picture below) on the right side or by right-clicking over the results table to save all the result.

You also have the possibility to select one or multiple rows (Ctrl+Click) from the result table and then do a right-click. It will prompt you a menu with save as CSV, only the selected data will be saved along with headers.


问:
Azure ACR task not able to pull the docker image from Azure container registry
I am following this article.
I have an Azure container registry as shown below image and I have defined the task as below.

```<code>az acr task create \
--name krushnaTask \
--registry krushna \
--cmd python-hello \
--schedule "1 10 * * *" \
--context /dev/null
</code>```

When the Azure is running the task it is giving below error :

```<code>2020/06/02 11:02:03 Alias support enabled for version >= 1.1.0, please see https://aka.ms/acr/tasks/task-aliases for more information.
2020/06/02 11:02:03 Creating Docker network: acb_default_network, driver: 'bridge'
2020/06/02 11:02:03 Successfully set up Docker network: acb_default_network
2020/06/02 11:02:03 Setting up Docker configuration...
2020/06/02 11:02:04 Successfully set up Docker configuration
2020/06/02 11:02:04 Logging in to registry: krushna.azurecr.io
2020/06/02 11:02:05 Successfully logged into krushna.azurecr.io
2020/06/02 11:02:05 Executing step ID: acb_step_0. Timeout(sec): 3600, Working directory: '', Network: 'acb_default_network'
2020/06/02 11:02:05 Launching container with name: acb_step_0
Unable to find image 'python-hello:latest' locally
docker: Error response from daemon: pull access denied for python-hello, repository does not   exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
2020/06/02 11:02:05 Container failed during run: acb_step_0. No retries remaining.
failed to run step ID: acb_step_0: exit status 125
</code>```

What can be done so the ACR task can access the docker image?

答:
When creating ACR Tasks, you should provide a git-access-token if your registry has RBAC enabled

```<code>--git-access-token
The access token used to access the source control provider.
</code>```

https://learn.microsoft.com/en-us/cli/azure/acr/task?view=azure-cli-latest#az-acr-task-create

you can create the access token from this DOC

https://learn.microsoft.com/en-us/azure/container-registry/container-registry-tutorial-quick-task#configure-registry-authentication

Body:
I am following this article.
I have an Azure container registry as shown below image and I have defined the task as below.

az acr task create \
--name krushnaTask \
--registry krushna \
--cmd python-hello \
--schedule "1 10 * * *" \
--context /dev/null

When the Azure is running the task it is giving below error :

2020/06/02 11:02:03 Alias support enabled for version >= 1.1.0, please see https://aka.ms/acr/tasks/task-aliases for more information.
2020/06/02 11:02:03 Creating Docker network: acb_default_network, driver: 'bridge'
2020/06/02 11:02:03 Successfully set up Docker network: acb_default_network
2020/06/02 11:02:03 Setting up Docker configuration...
2020/06/02 11:02:04 Successfully set up Docker configuration
2020/06/02 11:02:04 Logging in to registry: krushna.azurecr.io
2020/06/02 11:02:05 Successfully logged into krushna.azurecr.io
2020/06/02 11:02:05 Executing step ID: acb_step_0. Timeout(sec): 3600, Working directory: '', Network: 'acb_default_network'
2020/06/02 11:02:05 Launching container with name: acb_step_0
Unable to find image 'python-hello:latest' locally
docker: Error response from daemon: pull access denied for python-hello, repository does not   exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
2020/06/02 11:02:05 Container failed during run: acb_step_0. No retries remaining.
failed to run step ID: acb_step_0: exit status 125

What can be done so the ACR task can access the docker image?

Body:
When creating ACR Tasks, you should provide a git-access-token if your registry has RBAC enabled

--git-access-token
The access token used to access the source control provider.

https://learn.microsoft.com/en-us/cli/azure/acr/task?view=azure-cli-latest#az-acr-task-create

you can create the access token from this DOC

https://learn.microsoft.com/en-us/azure/container-registry/container-registry-tutorial-quick-task#configure-registry-authentication


问:
Current font used in a Text object in SwiftUI
Is there a way to get/obtain the current font used in a Text object in SwiftUI?  ex. Text("abc").font() does not work.

答:
The current font is accessible from the environment:

struct ChildView: View {
    @Environment(\.font) var font

    var body: some View {
        Text("Italic version of the hierarchy's font")
            .font((font ?? .body).italic())
    }
}
```

See https://developer.apple.com/documentation/swiftui/environmentvalues for the full list of available keys, they can come in handy.

Body:
The current font is accessible from the environment:

struct ChildView: View {
    @Environment(\.font) var font

    var body: some View {
        Text("Italic version of the hierarchy's font")
            .font((font ?? .body).italic())
    }
}

See https://developer.apple.com/documentation/swiftui/environmentvalues for the full list of available keys, they can come in handy.


问:
Code running despite no input being given (python)
When the user enters nothing, it is supposed to loop back and ask the question again. It performs correctly with every other type of input.

Here is the code:

```<code>string = ""

def str_analysis(string):

    while True:
        if string.isdigit():
            if int(string) > 99:
                print(str(string)+ " is a pretty big number!")
                break
            else:
                print(str(string)+ " is a smaller number than expected")
                break
        elif string.isalpha():
            print(string + " is an alphabetical character")
            break
        elif string == "":
            print("")
        else:
            print(string + " is a surprise! It's neither all alpha nor all digit characters!")
            break

print(str_analysis(input("Enter word or integer: ")))
</code>```

答:
This because when string is empty you are just printing an empty ""

```<code>elif string == "":
    print("")
    # break it here or take input again
    # break or string = input()
</code>```

Body:
When the user enters nothing, it is supposed to loop back and ask the question again. It performs correctly with every other type of input.

Here is the code:

string = ""

def str_analysis(string):

    while True:
        if string.isdigit():
            if int(string) > 99:
                print(str(string)+ " is a pretty big number!")
                break
            else:
                print(str(string)+ " is a smaller number than expected")
                break
        elif string.isalpha():
            print(string + " is an alphabetical character")
            break
        elif string == "":
            print("")
        else:
            print(string + " is a surprise! It's neither all alpha nor all digit characters!")
            break

print(str_analysis(input("Enter word or integer: ")))

Body:
This because when string is empty you are just printing an empty ""

elif string == "":
    print("")
    # break it here or take input again
    # break or string = input()


问:
Angular Toggle only the element click on
I have a method that toggles a div area.

At the moment I have 3 areas

app.component.ts

```<code>show = false;

toggle() {
    this.show = !this.show;
}
</code>```

app.component.html

```<code><div>
    <div *ngIf="show">
      <div>One</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="show">
      <div>Two</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="show">
      <div>Three</div>
    </div>
    <button type="button" toggle()"></button>
</div>
</code>```

At the moment is will show and hide the 3 sections.

How can I chan it so that it just toggles the div with the *ngIf="show" that I of the button I clicked?

答:
If you do not wish to have three different booleans in the controller, you could look into Angular TemplateRef to create different templates for each sections.

Template

<ng-template #templateOne>
  One
</ng-template>

<ng-template #templateTwo>
  Two
</ng-template>

<ng-template #templateThree>
  Three
</ng-template>

<ng-container *ngTemplateOutlet="template"></ng-container>

<button type="button" (mouseup)="showRef(templateOne)">Show Template 1</button>
<button type="button" (mouseup)="showRef(templateTwo)">Show Template 2</button>
<button type="button" (mouseup)="showRef(templateThree)">Show Template 3</button>
<button type="button" (mouseup)="showRef(null)">Hide all</button>
```

<p>Now you could set the <code>template</code> variable in the controller to the <code><ng-template></code> block that needs to be displayed.</p>

<pre class="lang-js prettyprint-override"><code>import { Component, TemplateRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  template: TemplateRef<any>;

  showRef(template: TemplateRef<any>) {
    this.template = template;
  }
}
</code>```

Working example: Stackblitz

Body:
I have a method that toggles a div area.

At the moment I have 3 areas

app.component.ts

show = false;

toggle() {
    this.show = !this.show;
}

app.component.html

One

    <button type="button" toggle()"></button>

Two

    <button type="button" toggle()"></button>

Three

    <button type="button" toggle()"></button>

At the moment is will show and hide the 3 sections.

How can I chan it so that it just toggles the div with the *ngIf="show" that I of the button I clicked?

Body:
If you do not wish to have three different booleans in the controller, you could look into Angular TemplateRef to create different templates for each sections.

Template

<ng-template #templateOne>
  One
</ng-template>

<ng-template #templateTwo>
  Two
</ng-template>

<ng-template #templateThree>
  Three
</ng-template>

<ng-container *ngTemplateOutlet="template"></ng-container>
<br /><br />

<button type="button" (mouseup)="showRef(templateOne)">Show Template 1</button>
<button type="button" (mouseup)="showRef(templateTwo)">Show Template 2</button>
<button type="button" (mouseup)="showRef(templateThree)">Show Template 3</button>
<button type="button" (mouseup)="showRef(null)">Hide all</button>

Now you could set the template variable in the controller to the <ng-template> block that needs to be displayed.

import { Component, TemplateRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  template: TemplateRef<any>;

  showRef(template: TemplateRef<any>) {
    this.template = template;
  }
}

Working example: Stackblitz


问:
Output whole row from list if duplicate has been found
I have a part of code that outputs duplicates from list. However it is giving only duplicates in particular column. How to output whole row if duplicate has been found?

Here is current code for finding duplicates:

```<code>var duplicatesPOSTADR = results.AsEnumerable()
    .Select(dr => dr.POSTADR.Trim())
    .GroupBy(x => x)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key)
    .ToList();
</code>```

Then I have another part that is sending an email message if duplicates has been found:

```<code>if (duplicatesPOSTADR?.Any() != false)
{
  string combindedString = string.Join(", ", duplicatesPOSTADR.Where(s => !string.IsNullOrEmpty(s)));
  string EmailBody = "There was an error and following duplicates has been found in POSTADR column: " + combindedString;
  CreateMailItem(EmailBody);
}
</code>```

So lets say I have data:

```<code>NRO   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      P4        OL         J8        U9
483   KIA    E89     S78     J7        K7      O9      P6        O5         J4        U6
</code>```

Now as an output I get:

```<code>P4
</code>```

However I would like to get:

```<code>423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      P4        OL         J8        U9
</code>```

Any hints how this can be achieved?

答:
By applying the .Select(dr => dr.POSTADR.Trim()) statement in your code, the end result will only contain the POSTADR string values.

Just do the grouping without this projection.

This results in an IEnumerable of your full class instances that have doubles in POSTADR.

```<code>var duplicatesPOSTADR =
    results.AsEnumerable()
        .GroupBy(x => x.POSTADR.Trim())
        .Where(g => g.Count() > 1)
        .SelectMany(g => g)
        ;
</code>```

Body:
I have a part of code that outputs duplicates from list. However it is giving only duplicates in particular column. How to output whole row if duplicate has been found?

Here is current code for finding duplicates:

var duplicatesPOSTADR = results.AsEnumerable()
    .Select(dr => dr.POSTADR.Trim())
    .GroupBy(x => x)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key)
    .ToList();

Then I have another part that is sending an email message if duplicates has been found:

if (duplicatesPOSTADR?.Any() != false)
{
  string combindedString = string.Join(", ", duplicatesPOSTADR.Where(s => !string.IsNullOrEmpty(s)));
  string EmailBody = "There was an error and following duplicates has been found in POSTADR column: " + combindedString;
  CreateMailItem(EmailBody);
}

So lets say I have data:

NRO   SNAME  NAMEA   NAMEB   IADDRESS  POSTA   POSTN   POSTADR   COMPANYN   COUNTRY   BID
423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      P4        OL         J8        U9
483   KIA    E89     S78     J7        K7      O9      P6        O5         J4        U6

Now as an output I get:

P4

However I would like to get:

423   Fiat   Punto   500     J5        K4      O3      P4        O2         JT        S1
463   BMW    E64     SE0     JR        KE      OT      P4        OL         J8        U9

Any hints how this can be achieved?

Body:
By applying the .Select(dr => dr.POSTADR.Trim()) statement in your code, the end result will only contain the POSTADR string values.

Just do the grouping without this projection.

This results in an IEnumerable of your full class instances that have doubles in POSTADR.

var duplicatesPOSTADR =
    results.AsEnumerable()
        .GroupBy(x => x.POSTADR.Trim())
        .Where(g => g.Count() > 1)
        .SelectMany(g => g)
        ;


问:
How do I scale an SVG based on my website's window size
I'm trying to use a settings icon svg file which will scale depending on then window width. I've tried to do this by creating a function in JavaScript that changes the element's width and height based on the window size but this doesn't work. (Btw i'm testing it with a width of 360 pixels but the svg's size is about 300 pixels).

The HTML:

```<code><img id="settings-icon" class="icon" src="images/icons/settings-icon.svg" onclick="settingsPage();" alt="Settings" />
</code>```

The JavaScript:

```<code>var settings_icon = scaleIcon(dcument.getElementById("settings-icon"));
scaleIcon(settings_icon);

function scaleIcon(icon) {
    var w = window.innerWidth;
    var h = window.innerHeight;
    if (w <= 360) {
        icon.width = "44";
        icon.height="44";
    }
    else if (w <= 400) {
        icon.width = "48";
        icon.height="48";
    }
    else if (w <= 440) {
        icon.width = "52";
        icon.height="52";
    }
}
</code>```

答: I think you spelt 'document' as 'dcument'. Also, try using icon.style.width and icon.style.height. Also, remember to add the units for your measurements. Example: icon.style.width = "44vw";

Body:
I'm trying to use a settings icon svg file which will scale depending on then window width. I've tried to do this by creating a function in JavaScript that changes the element's width and height based on the window size but this doesn't work. (Btw i'm testing it with a width of 360 pixels but the svg's size is about 300 pixels).

The HTML:

The JavaScript:

var settings_icon = scaleIcon(dcument.getElementById("settings-icon"));
scaleIcon(settings_icon);

function scaleIcon(icon) {
    var w = window.innerWidth;
    var h = window.innerHeight;
    if (w <= 360) {
        icon.width = "44";
        icon.height="44";
    }
    else if (w <= 400) {
        icon.width = "48";
        icon.height="48";
    }
    else if (w <= 440) {
        icon.width = "52";
        icon.height="52";
    }
}


问:
Does Firestore security rules return early?
I have 2 conditions for checking permission to the user. The first condition doesn't require any database query but the second one does.
For Example

```<code>allow read, write: if (docId == request.auth.uid);
allow read: if get(/databases/$(database)/documents/groups/$(docId)).data[request.auth.uid].membership == true
</code>```

My database is structured in a way that I need to give read and write access if docId belongs to that user. Otherwise, the user might be accessing something from a group which he's part of. In which case I'll make a DB query and check if the user really a member.

Suppose a user is accessing a document that belongs only to him, in which case the DB query is not required and the first condition should return true.

Will the rule still make a DB query?

答:
In general, if you have two conditions:

```<code>allow read: if X;
allow read: if Y;
</code>```

This is the same as a logical OR between X and Y in the order they were defined:

```<code>allow read: if X || Y;
</code>```

The security rules language will short circuit when X evaluates true, and skip the evaluation of Y.

So, if your first condition (docId == request.auth.uid) evaluates true, then there is no need to get the document in the second condition.

Body:
I have 2 conditions for checking permission to the user. The first condition doesn't require any database query but the second one does.
For Example

allow read, write: if (docId == request.auth.uid);
allow read: if get(/databases/$(database)/documents/groups/$(docId)).data[request.auth.uid].membership == true

My database is structured in a way that I need to give read and write access if docId belongs to that user. Otherwise, the user might be accessing something from a group which he's part of. In which case I'll make a DB query and check if the user really a member.

Suppose a user is accessing a document that belongs only to him, in which case the DB query is not required and the first condition should return true.

Will the rule still make a DB query?

Body:
In general, if you have two conditions:

allow read: if X;
allow read: if Y;

This is the same as a logical OR between X and Y in the order they were defined:

allow read: if X || Y;

The security rules language will short circuit when X evaluates true, and skip the evaluation of Y.

So, if your first condition (docId == request.auth.uid) evaluates true, then there is no need to get the document in the second condition.


问:
What does re.compile(r'[[]]') match?
With Python's re module, why do the following act differently:</p>

```<code>>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]
</code>```

答: The regular expression "[[]]" matches the substring "[]". The first [ in the expression begins a character class, and the first ] ends it. There is only one character ([) in the class, and then it has to be followed by the second ]. So the expression is "any of the characters in "[", followed by a "]".</p>

OwnerDisplayName: gray

ContentLicense: CC BY-SA 2.5

Title: What does re.compile(r'[[]]') match?

Body:
With Python's re module, why do the following act differently:

>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]

LastEditorDisplayName: dbr

OwnerDisplayName: Kieron


问:
kubernetes autoscale on queue_size versus number of pods running
Is there a way I can set up autoscaling with a complete customized algorithm?

1. I would like to autoscale my pods based on the ratio of (size of the azure storage queue) to (number of pods currently running) which means the average number of messages every pod needs to handle.

2. Can I create metrics and scale based on the metrics freely? Like

```<code>if 2 > metrics > 1:
     scale pods to 2
if 5 > metrics > 2:
     scale pods to 3
if 10 > metrics > 5:
     scale pods to 4
</code>```

if so, where can I set up the autoscale algorithm?

答:
You can use keda with the corresponding trigger for that:

https://keda.sh/docs/1.4/scalers/azure-storage-queue/

Here is an example from the docs for azure storage queue.

```<code> apiVersion: keda.k8s.io/v1alpha1
kind: TriggerAuthentication
metadata:
  name: azure-queue-auth
spec:
  podIdentity:
    provider: azure
---
apiVersion: keda.k8s.io/v1alpha1
kind: ScaledObject
metadata:
  name: azure-queue-scaledobject
  namespace: default
spec:
  scaleTargetRef:
    deploymentName: azurequeue-function
  triggers:
  - type: azure-queue
    metadata:
      # Required
      queueName: functionsqueue
      # Required: connection OR authenticationRef that defines connection
      connection: STORAGE_CONNECTIONSTRING_ENV_NAME # Default: AzureWebJobsStorage. Reference to a connection string in deployment
      # or authenticationRef as defined below
      #
      # Optional
      queueLength: "5" # default 5
    authenticationRef:
        name: azure-queue-auth #
</code>```

All kinds of other triggers are supported as well.

Body:
Is there a way I can set up autoscaling with a complete customized algorithm?

1. I would like to autoscale my pods based on the ratio of (size of the azure storage queue) to (number of pods currently running) which means the average number of messages every pod needs to handle.

2. Can I create metrics and scale based on the metrics freely? Like

if 2 > metrics > 1:
     scale pods to 2
if 5 > metrics > 2:
     scale pods to 3
if 10 > metrics > 5:
     scale pods to 4

if so, where can I set up the autoscale algorithm?

Body:
You can use keda with the corresponding trigger for that:

https://keda.sh/docs/1.4/scalers/azure-storage-queue/

Here is an example from the docs for azure storage queue.

 apiVersion: keda.k8s.io/v1alpha1
kind: TriggerAuthentication
metadata:
  name: azure-queue-auth
spec:
  podIdentity:
    provider: azure
---
apiVersion: keda.k8s.io/v1alpha1
kind: ScaledObject
metadata:
  name: azure-queue-scaledobject
  namespace: default
spec:
  scaleTargetRef:
    deploymentName: azurequeue-function
  triggers:
  - type: azure-queue
    metadata:
      # Required
      queueName: functionsqueue
      # Required: connection OR authenticationRef that defines connection
      connection: STORAGE_CONNECTIONSTRING_ENV_NAME # Default: AzureWebJobsStorage. Reference to a connection string in deployment
      # or authenticationRef as defined below
      #
      # Optional
      queueLength: "5" # default 5
    authenticationRef:
        name: azure-queue-auth #

All kinds of other triggers are supported as well.


问:
Remove Columns And Create Unique Row For Each Removed Column Pandas Dataframe
This is a really tricky issue I've run into which is slamming my memory management, here's the setup:

I have a dataframe with the following column setup:

```<code>Unique1 Unique2 Unique3 d_1 d_2 d_3..... d_2000
   A       B      C      1   4   0         100
</code>```

I want to remove the d_1...d_2000 columns and instead have a unique row for each entry:

```<code>Unique1 Unique2 Unique3 d_index d_value
   A       B       C      d_1     1
   A       B       C      d_2     4
   A       B       C      d_3     0
   .
   .
   .
   A       B       C      d_2000  100
</code>```

The following code gives me a 2 dim series which can be zipped back up into a dataframe, but because I need to work with a few working variables it quickly runs out of 32gb of ram on linux (works on windows env but is very slow):

```<code>def convert_timeseries_to_rows(row):
    d_idx = 1
    rows_to_return = []
    for day_count in row[6:]: ### d columns start from 6
        new = list(row[:6]) ### keep first 6 columns
        day_string = "d_"+str(d_idx)
        new.append(day_string)
        new.append(day_count)
        rows_to_return.append(new)
        d_idx = d_idx + 1
    return rows_to_return ### return all rows generated

2_dim_series = df.apply(convert_timeseries_to_rows, axis=1)

data = []
columns = ['unique1', "unique2"..., 'date_index', 'units']
for each in 2_dim_series :
    for row in each:
        data.append(dict(zip(columns,row)))
data = pd.DataFrame(data)
data.to_csv('save_to_disk.csv')
</code>```

Can any of the pros think of a better way to do this (in python)?

Thanks!

Example Input:

```<code>Unique1 Unique2 Unique3 d_1 d_2 d_3
   A       B      C      1   4   0
   D       E      F      5   9   12
</code>```

Example Output:

```<code>Unique1 Unique2 Unique3 d_index d_value
   A       B       C      d_1     1
   A       B       C      d_2     4
   A       B       C      d_3     0
   D       E       F      d_1     5
   D       E       F      d_2     9
   D       E       F      d_3     12

</code>```

答:
I recreated the dataframe like this:

```<code>import pandas as pd
n = 2000
df = pd.DataFrame(columns=['Unique' + str(i) for i in range(1,4)]
             + ['d_' + str(i) for i in range(n)],
            data= [['A','B','C']  + np.random.randint(0,100,n).astype(str).tolist()],
                  index = [0])
</code>```

Then identified the columns you're working with:

```<code>d_cols = df.columns[df.columns.str.contains('d_')]
u_cols = df.columns[df.columns.str.contains('Unique')]
</code>```

Then generated a second dataframe:

```<code>df2 = pd.DataFrame({'d_index':d_cols,
                    'd_value': df[d_cols].values.flatten()})
for col in u_cols:
    df2[col] = df[col][0]
</code>```

Body:
This is a really tricky issue I've run into which is slamming my memory management, here's the setup:

I have a dataframe with the following column setup:

Unique1 Unique2 Unique3 d_1 d_2 d_3..... d_2000
   A       B      C      1   4   0         100

I want to remove the d_1...d_2000 columns and instead have a unique row for each entry:

Unique1 Unique2 Unique3 d_index d_value
   A       B       C      d_1     1
   A       B       C      d_2     4
   A       B       C      d_3     0
   .
   .
   .
   A       B       C      d_2000  100

The following code gives me a 2 dim series which can be zipped back up into a dataframe, but because I need to work with a few working variables it quickly runs out of 32gb of ram on linux (works on windows env but is very slow):

def convert_timeseries_to_rows(row):
    d_idx = 1
    rows_to_return = []
    for day_count in row[6:]: ### d columns start from 6
        new = list(row[:6]) ### keep first 6 columns
        day_string = "d_"+str(d_idx)
        new.append(day_string)
        new.append(day_count)
        rows_to_return.append(new)
        d_idx = d_idx + 1
    return rows_to_return ### return all rows generated

2_dim_series = df.apply(convert_timeseries_to_rows, axis=1)

data = []
columns = ['unique1', "unique2"..., 'date_index', 'units']
for each in 2_dim_series :
    for row in each:
        data.append(dict(zip(columns,row)))
data = pd.DataFrame(data)
data.to_csv('save_to_disk.csv')

Can any of the pros think of a better way to do this (in python)?

Thanks!

Example Input:

Unique1 Unique2 Unique3 d_1 d_2 d_3
   A       B      C      1   4   0
   D       E      F      5   9   12

Example Output:

Unique1 Unique2 Unique3 d_index d_value
   A       B       C      d_1     1
   A       B       C      d_2     4
   A       B       C      d_3     0
   D       E       F      d_1     5
   D       E       F      d_2     9
   D       E       F      d_3     12

Body:
I recreated the dataframe like this:

import pandas as pd
n = 2000
df = pd.DataFrame(columns=['Unique' + str(i) for i in range(1,4)]
             + ['d_' + str(i) for i in range(n)],
            data= [['A','B','C']  + np.random.randint(0,100,n).astype(str).tolist()],
                  index = [0])

Then identified the columns you're working with:

d_cols = df.columns[df.columns.str.contains('d_')]
u_cols = df.columns[df.columns.str.contains('Unique')]

Then generated a second dataframe:

df2 = pd.DataFrame({'d_index':d_cols,
                    'd_value': df[d_cols].values.flatten()})
for col in u_cols:
    df2[col] = df[col][0]


问:
MySQL PHP, SELECT WHERE condition is an array
I am trying to SELECT products from db WHERE condition is an array. My method is working when array is declared but not when elements of array are generate after submitting form.

```<code>    $selected_categories = array();        //create empty array

    if(isset($_POST['submit'])){          //if form is submitted

        $name = $_POST['category'];

        foreach ($name as $category){
            $selected_categories[] = $category;          //add all checked checkboxes values into the array, every single $category element is text i.e. programming science
        }

        $get_products = "SELECT P.*, C.category_name, GROUP_CONCAT(category_name SEPARATOR ', ') AS cat FROM products P NATURAL JOIN categories C NATURAL JOIN product_to_categories WHERE category_name IN ('$selected_categories') GROUP BY product_name ORDER BY 1 DESC LIMIT $start_from,$per_page";
    }
</code>```

the problem (i think) is in array, because when I am using one element from the array:

```<code>... WHERE category_name IN ('$selected_categories[1]')...
</code>```

is working correctly it is also working when using:

```<code>... WHERE category_name IN ('programming', 'science')...
</code>```

答:
WHERE category_name IN ('$selected_categories') is wrong - the parameter will be treated as ONE string literal, not as a list of separate literals.

Use WHERE FIND_IN_SET(category_name, '$selected_categories').

Separate values in $selected_categories must be separated by comma strictly (if some another separator is used then replace it).

Body:
I am trying to SELECT products from db WHERE condition is an array. My method is working when array is declared but not when elements of array are generate after submitting form.

    $selected_categories = array();        //create empty array

    if(isset($_POST['submit'])){          //if form is submitted

        $name = $_POST['category'];

        foreach ($name as $category){
            $selected_categories[] = $category;          //add all checked checkboxes values into the array, every single $category element is text i.e. programming science
        }

        $get_products = "SELECT P.*, C.category_name, GROUP_CONCAT(category_name SEPARATOR ', ') AS cat FROM products P NATURAL JOIN categories C NATURAL JOIN product_to_categories WHERE category_name IN ('$selected_categories') GROUP BY product_name ORDER BY 1 DESC LIMIT $start_from,$per_page";
    }

the problem (i think) is in array, because when I am using one element from the array:

... WHERE category_name IN ('$selected_categories[1]')...

is working correctly it is also working when using:

... WHERE category_name IN ('programming', 'science')...


问:
change state in Grandparent Component with button
Hello i'm new on react and have to do a Tutorial where i have to change the state of the Child Component with a button onClick function.
currently i'm use a button in my Parent component to do it and it works but now i have to use call this button in other child components and not directly in the Parent to restart my Tutorial.

but i dont know how i can do it.
ill happy about every suggestion.

```<code>class Child extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      run: this.props.run,
      stepIndex: this.props.stepIndex
    }
  }

 componentWillReceiveProps (props) {
    this.setState({ run: props.run, stepIndex: props.stepIndex })
  }

callback = (tour) => {
    const { action, index, type } = tour

    // if you delete  action === 'skip', the Tutorial will not start on other pages after skipped once.
    if (action === 'close' || action === 'skip' || type === 'tour:end') {
      this.setState({ run: false })
    } else if ([EVENTS.STEP_AFTER, EVENTS.TARGET_NOT_FOUND].includes(type)) {
      this.setState({ stepIndex: index + (action === ACTIONS.PREV ? -1 : 1) })
    }
  }

 render () {
    let { run, stepIndex, steps } = this.state

    if (this.props.location.pathname === '/') {
      steps = []
      run = false
    } else if (this.props.location.pathname === '/matches/' || this.props.location.pathname.length === '/matches') {
      steps = matchSiteSteps
    } else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.endsWith('/edit/')) {
      steps = matchEditorSteps
    } else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.includes('sequence')) {
      steps = matchSequenceSteps
    } else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.match('\\d+')) {
      steps = matchSteps
    }

    return (
      <>
        <Joyride
          callback={this.callback}
          run={run}
          stepIndex={stepIndex}
          steps={steps}
          continuous
          disableOverlayClose
          spotlightClicks
          showSkipButton
          locale={{
            back: <span>Zurück</span>,
            last: (<span>Beenden</span>),
            next: (<span>Weiter</span>)
          }}
        />
      </>
    )
  }
}

class Parent extends Component {
  constructor (props) {
    super(props)
    this.handler = this.handler.bind(this)
    this.state = {
      run: true,
      stepIndex: 0,
    }
  }

  handler () {
    this.setState({ run: true, stepIndex: 0 })
  }
render () {
    return (
    //some other stuff
        <RestartButton handler={this.handler} />
        <Tutorial run={this.state.run} stepIndex={this.state.stepIndex} />
    //some other stuff
    )
  }
}

class RestartButton extends React.Component {
  render () {
    return (
      <button className='restartButton' onClick={() => this.props.handler()}>click</button>
    )
  }
}
</code>```

答:
You shouldn't store props in the child component state if state.run and state.stepIndex are always going to be the same as props.run and props.stepIndex. Instead you should just use those props directly when you need to use them in the render method. stepIndex={this.props.stepIndex} will pass exactly the same values to the Joyride component as setting the child component's state.stepIndex equal to props.stepIndex and then passing stepIndex={this.state.stepIndex}.

If you want to change the value of the parent component's state from a child component, you can pass the handler method (bound to the parent component) through as many layers of components as you want, or to as many different children as you want.

```<code>class Tutorial extends React.Component {
    constructor(props) {
      super(props)
    }

    render() {
        return (
          <>
            <RestartButton handler={this.props.handler}/>
            <Joyride
              callback={this.callback}
              run={this.props.run}
              stepIndex = {this.props.stepIndex}
              steps={steps}
              continuous
              disableOverlayClose
              spotlightClicks
              showSkipButton
              locale={{
                back: < span > Zurück < /span>,
                last: ( < span > Beenden < /span>),
                next: ( < span > Weiter < /span>)
              }}
            />
          </>
        )
    }
}

class Parent extends Component {
  constructor(props) {
    super(props)
    this.handler = this.handler.bind(this)
    this.state = {
      run: true,
      stepIndex: 0,
    }
  }

  handler() {
    this.setState({run: true, stepIndex: 0})
  }

  render() {
    return (
      <Tutorial
        run={this.state.run}
        stepIndex={this.state.stepIndex}
      />
    )
  }
}

class RestartButton extends React.Component {
  render() {
    return (
      <button
        className='restartButton'
        onClick={() => this.props.handler()}
      > click </button>
    )
  }
}
</code>```

(Also, componentWillReceiveProps is deprecated and you should use componentDidUpdate instead, if you do need to do something on component update).

Body:
Hello i'm new on react and have to do a Tutorial where i have to change the state of the Child Component with a button onClick function.
currently i'm use a button in my Parent component to do it and it works but now i have to use call this button in other child components and not directly in the Parent to restart my Tutorial.

but i dont know how i can do it.
ill happy about every suggestion.

class Child extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      run: this.props.run,
      stepIndex: this.props.stepIndex
    }
  }

 componentWillReceiveProps (props) {
    this.setState({ run: props.run, stepIndex: props.stepIndex })
  }

callback = (tour) => {
    const { action, index, type } = tour

    // if you delete  action === 'skip', the Tutorial will not start on other pages after skipped once.
    if (action === 'close' || action === 'skip' || type === 'tour:end') {
      this.setState({ run: false })
    } else if ([EVENTS.STEP_AFTER, EVENTS.TARGET_NOT_FOUND].includes(type)) {
      this.setState({ stepIndex: index + (action === ACTIONS.PREV ? -1 : 1) })
    }
  }

 render () {
    let { run, stepIndex, steps } = this.state

    if (this.props.location.pathname === '/') {
      steps = []
      run = false
    } else if (this.props.location.pathname === '/matches/' || this.props.location.pathname.length === '/matches') {
      steps = matchSiteSteps
    } else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.endsWith('/edit/')) {
      steps = matchEditorSteps
    } else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.includes('sequence')) {
      steps = matchSequenceSteps
    } else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.match('\\d+')) {
      steps = matchSteps
    }

    return (
      <>
        <Joyride
          callback={this.callback}
          run={run}
          stepIndex={stepIndex}
          steps={steps}
          continuous
          disableOverlayClose
          spotlightClicks
          showSkipButton
          locale={{
            back: Zurück,
            last: (Beenden),
            next: (Weiter)
          }}
        />
      </>
    )
  }
}

class Parent extends Component {
  constructor (props) {
    super(props)
    this.handler = this.handler.bind(this)
    this.state = {
      run: true,
      stepIndex: 0,
    }
  }

  handler () {
    this.setState({ run: true, stepIndex: 0 })
  }
render () {
    return (
    //some other stuff
        <RestartButton handler={this.handler} />
        <Tutorial run={this.state.run} stepIndex={this.state.stepIndex} />
    //some other stuff
    )
  }
}

class RestartButton extends React.Component {
  render () {
    return (
      <button className='restartButton' onClick={() => this.props.handler()}>click</button>
    )
  }
}

Body:
You shouldn't store props in the child component state if state.run and state.stepIndex are always going to be the same as props.run and props.stepIndex. Instead you should just use those props directly when you need to use them in the render method. stepIndex={this.props.stepIndex} will pass exactly the same values to the Joyride component as setting the child component's state.stepIndex equal to props.stepIndex and then passing stepIndex={this.state.stepIndex}.

If you want to change the value of the parent component's state from a child component, you can pass the handler method (bound to the parent component) through as many layers of components as you want, or to as many different children as you want.

class Tutorial extends React.Component {
    constructor(props) {
      super(props)
    }

    render() {
        return (
          <>
            <RestartButton handler={this.props.handler}/>
            <Joyride
              callback={this.callback}
              run={this.props.run}
              stepIndex = {this.props.stepIndex}
              steps={steps}
              continuous
              disableOverlayClose
              spotlightClicks
              showSkipButton
              locale={{
                back: < span > Zurück < /span>,
                last: ( < span > Beenden < /span>),
                next: ( < span > Weiter < /span>)
              }}
            />
          </>
        )
    }
}

class Parent extends Component {
  constructor(props) {
    super(props)
    this.handler = this.handler.bind(this)
    this.state = {
      run: true,
      stepIndex: 0,
    }
  }

  handler() {
    this.setState({run: true, stepIndex: 0})
  }

  render() {
    return (
      <Tutorial
        run={this.state.run}
        stepIndex={this.state.stepIndex}
      />
    )
  }
}

class RestartButton extends React.Component {
  render() {
    return (
      <button
        className='restartButton'
        onClick={() => this.props.handler()}
      > click </button>
    )
  }
}

(Also, componentWillReceiveProps is deprecated and you should use componentDidUpdate instead, if you do need to do something on component update).


问:
Creating a JSON object with name of the JSON file and its content in bash
I have a few .json files in my directory. If I do:

```<code>find . -name '*.json' -exec echo "{\"filename\": \"{}\", \"content\": `cat {}` }," \;
</code>```

I get:

```<code>{"filename": "./a.json", "content":  },
{"filename": "./b.json", "content":  },
</code>```

However, if I do:

```<code>find . -name '*.json' -exec echo "{\"filename\": \"{}\", \"content\": cat {} }," \;
</code>```

I get:

```<code>{"filename": "./a.json", "content": cat ./a.json },
{"filename": "./b.json", "content": cat ./b.json },
</code>```

so how do I make the a.json and b.json contents be cated correctly ?

BTW, if I do:

```<code>find . -name '*.json' -exec cat {} \;
</code>```

the json files are correctly printed in the console, so I know that the file contents are valid.

答:
With simple bash :</p>

```<code>$ cat a.json
{ "a":123 }
$ cat b.json
{ "b":234 }
$ cat "foo/bar/base/c c.json"
{ "c": 456 }
$ shopt -s globstar # enable recursion with '**'
$ for i in **/*.json; do
    cat<<EOF
    { "filename": "$i", "content": $(cat "$i") }
EOF
done | tee file.json
$ cat file.json
{ "filename": "a.json", "content": {"a":123} }
{ "filename": "b.json", "content": {"b":234} }
{ "filename": "foo/bar/base/c c.json", "content": { "c": 456 } }
</code>```

Body:
I have a few .json files in my directory. If I do:

find . -name '*.json' -exec echo "{\"filename\": \"{}\", \"content\": `cat {}` }," \;

I get:

{"filename": "./a.json", "content":  },
{"filename": "./b.json", "content":  },

However, if I do:

find . -name '*.json' -exec echo "{\"filename\": \"{}\", \"content\": cat {} }," \;

I get:

{"filename": "./a.json", "content": cat ./a.json },
{"filename": "./b.json", "content": cat ./b.json },

so how do I make the a.json and b.json contents be cated correctly ?

BTW, if I do:

find . -name '*.json' -exec cat {} \;

the json files are correctly printed in the console, so I know that the file contents are valid.

Body:
With simple bash :

$ cat a.json
{ "a":123 }
$ cat b.json
{ "b":234 }
$ cat "foo/bar/base/c c.json"
{ "c": 456 }
$ shopt -s globstar # enable recursion with '**'
$ for i in **/*.json; do
    cat<<EOF
    { "filename": "$i", "content": $(cat "$i") }
EOF
done | tee file.json
$ cat file.json
{ "filename": "a.json", "content": {"a":123} }
{ "filename": "b.json", "content": {"b":234} }
{ "filename": "foo/bar/base/c c.json", "content": { "c": 456 } }


问:
git still shows files as modified after adding to .gitignore
i'm adding this to .gitignore file

```<code>.idea/*
</code>```

but anyway the status is:

```<code>#       modified:   .gitignore
#       modified:   .idea/.generators
#       modified:   .idea/dovezu.iml
#       modified:   .idea/misc.xml
#       modified:   .idea/workspace.xml
</code>```

what am i doing wrong ?
i even added .idea/* to the global ~/.gitignore_global
but git status, anyway shows me:

```<code>#       modified:   .gitignore
#       modified:   .idea/.generators
#       modified:   .idea/dovezu.iml
#       modified:   .idea/misc.xml
#       modified:   .idea/workspace.xml
</code>```

答:
The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.

I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore (and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.

I first commited the actual changes I had made, then went about solving this - took me far too long.
I tried git rm -r --cached . but would always get path-spec ERRORS, with different variations of the path-spec as well as with the -f and -r flags.

git status would still show the filenames, so I tried using some of those verbatim with git rm -cached, but no luck.
Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe).
I have finally removed these entries for good using

```<code>git reset
</code>```

I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.

Body:
i'm adding this to .gitignore file

.idea/*

but anyway the status is:

#       modified:   .gitignore
#       modified:   .idea/.generators
#       modified:   .idea/dovezu.iml
#       modified:   .idea/misc.xml
#       modified:   .idea/workspace.xml

what am i doing wrong ?
i even added .idea/* to the global ~/.gitignore_global
but git status, anyway shows me:

#       modified:   .gitignore
#       modified:   .idea/.generators
#       modified:   .idea/dovezu.iml
#       modified:   .idea/misc.xml
#       modified:   .idea/workspace.xml

Body:
The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.

I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore (and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.

I first commited the actual changes I had made, then went about solving this - took me far too long.
I tried git rm -r --cached . but would always get path-spec ERRORS, with different variations of the path-spec as well as with the -f and -r flags.

git status would still show the filenames, so I tried using some of those verbatim with git rm -cached, but no luck.
Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe).
I have finally removed these entries for good using

git reset

I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.


问:
Nginx - Error during WebSocket handshake: Unexpected response code: 502
I am running a websocket server on my Digital Ocean droplet using pm2. Also, I am using websocket/ws websocket library.

It is listening on port 3030.

Using the command, netstat -l -p, I am able to see that it is indeed listening.

Below is the setup on my nginx sites-enabled configuration file. I am running static files in the / url, and running /socket url. And, /path/to/blah is modified for security reasons.

```<code> 31 server {
 30   . . . listen 80;
 29   . . . listen [::]:80;
 28
 27   . . . server_name xxxx.com www.xxxx.com;
 26   . . . return 302 https://$server_name$request_uri;
 25 }
 24
 23 server {
 22   . . . # SSL configuration
 21
 20   . . . listen 443 ssl http2 default_server;
 19   . . . listen [::]:443 ssl http2 default_server;
 18   . . . server_name xxxx.com www.xxxx.com;
 17
 16   . . . ssl_certificate /path/to/cert;
 15   . . . ssl_certificate_key /path/to/key;
 14
 13   . . . location / {
 12   . . . . . .proxy_pass http://127.0.0.1:5000;
 11   . . . }
 10
  9   . . . location /socket {
  8   . . . . . . proxy_set_header   X-Forwarded-For $remote_addr;
  7   . . . . . . proxy_set_header   Host $http_host;
  6   . . . . . . proxy_pass http://127.0.0.1:3030;
  5   . . . . . . proxy_http_version 1.1;
  4   . . . . . . proxy_set_header Upgrade $http_upgrade;
  3   . . . . . . proxy_set_header Connection 'upgrade';
  2   . . . . }
  1 }
</code>```

When connecting to the websocket using wss://www.xxxx.com/socket. I get this error:

Error during WebSocket handshake: Unexpected response code: 502

Looking at the log file for Nginx located at /var/log/nginx. This is the error I am seeing.

[error] 31009#31009: *19 upstream prematurely closed connection while
  reading response header from upstream, client: X.X.XX.XXX, server:
  xxxxx.com, request: "GET /socket HTTP/1.1", upstream:
  "http://127.0.0.1:3030/socket", host: "www.xxxxx.com"

When inspecting the header for this websocket. This is what I got.

The static asset is able to render fine, but not the websocket server.
This tells me that at least wss://www.xxxx.com is able to contact my Nginx server at /socket, but it seems that the response is not right.  When I looked into my pm2 log and error file, I see that it has outputted nothing. When I tested it with localhost, it worked fine. But, when deploying to server, it breaks.

答:
I have found the solution to my problem.

I discovered is that if a problem like this arises it is usually issues related to the upstream, which in my case is the application running on port 3030. It turns out that my websocket was not doing what I expected it to do.

If others run into the issue as well. I recommend taking a really simple websocket that you know for sure works, and see if it works on Nginx.

Body:
I am running a websocket server on my Digital Ocean droplet using pm2. Also, I am using websocket/ws websocket library.

It is listening on port 3030.

Using the command, netstat -l -p, I am able to see that it is indeed listening.

Below is the setup on my nginx sites-enabled configuration file. I am running static files in the / url, and running /socket url. And, /path/to/blah is modified for security reasons.

 31 server {
 30   . . . listen 80;
 29   . . . listen [::]:80;
 28
 27   . . . server_name xxxx.com www.xxxx.com;
 26   . . . return 302 https://$server_name$request_uri;
 25 }
 24
 23 server {
 22   . . . # SSL configuration
 21
 20   . . . listen 443 ssl http2 default_server;
 19   . . . listen [::]:443 ssl http2 default_server;
 18   . . . server_name xxxx.com www.xxxx.com;
 17
 16   . . . ssl_certificate /path/to/cert;
 15   . . . ssl_certificate_key /path/to/key;
 14
 13   . . . location / {
 12   . . . . . .proxy_pass http://127.0.0.1:5000;
 11   . . . }
 10
  9   . . . location /socket {
  8   . . . . . . proxy_set_header   X-Forwarded-For $remote_addr;
  7   . . . . . . proxy_set_header   Host $http_host;
  6   . . . . . . proxy_pass http://127.0.0.1:3030;
  5   . . . . . . proxy_http_version 1.1;
  4   . . . . . . proxy_set_header Upgrade $http_upgrade;
  3   . . . . . . proxy_set_header Connection 'upgrade';
  2   . . . . }
  1 }

When connecting to the websocket using wss://www.xxxx.com/socket. I get this error:

Error during WebSocket handshake: Unexpected response code: 502

Looking at the log file for Nginx located at /var/log/nginx. This is the error I am seeing.

[error] 31009#31009: *19 upstream prematurely closed connection while
  reading response header from upstream, client: X.X.XX.XXX, server:
  xxxxx.com, request: "GET /socket HTTP/1.1", upstream:
  "http://127.0.0.1:3030/socket", host: "www.xxxxx.com"

When inspecting the header for this websocket. This is what I got.

The static asset is able to render fine, but not the websocket server.
This tells me that at least wss://www.xxxx.com is able to contact my Nginx server at /socket, but it seems that the response is not right.  When I looked into my pm2 log and error file, I see that it has outputted nothing. When I tested it with localhost, it worked fine. But, when deploying to server, it breaks.


答:
There are a few things in your code that make no sense.

1:

print(str_analysis(input("Enter word or integer: ")))

You are trying to print the output of a function that has no return value

2:
It cant loop back and ask the question again, because the input is not taken inside of the function.

3:
If the string is empty you dont break the code but constantly print newlines.

Here is some code wich I think should do what you wanted:

```<code>def str_analasys():
    while True:
        string = input("Enter word or integer: ")
        if string == '':
            continue

        elif string.isdigit():
            if int(string) > 99:
                print(str(string)+ " is a pretty big number!")
            else:
                print(str(string)+ " is a smaller number than expected")
        elif string.isalpha():
            print(string + " is an alphabetical character")
        else:
            print(string + " is a surprise! It's neither all alpha nor all digit characters!")

        break
str_analasys()
</code>```

Title: Code running despite no input being given (python)

Body:
When the user enters nothing, it is supposed to loop back and ask the question again. It performs correctly with every other type of input.

Here is the code:

string = ""

def str_analysis(string):

    while True:
        if string.isdigit():
            if int(string) > 99:
                print(str(string)+ " is a pretty big number!")
                break
            else:
                print(str(string)+ " is a smaller number than expected")
                break
        elif string.isalpha():
            print(string + " is an alphabetical character")
            break
        elif string == "":
            print("")
        else:
            print(string + " is a surprise! It's neither all alpha nor all digit characters!")
            break

print(str_analysis(input("Enter word or integer: ")))

Body:
There are a few things in your code that make no sense.

1:

print(str_analysis(input("Enter word or integer: ")))

You are trying to print the output of a function that has no return value

2:
It cant loop back and ask the question again, because the input is not taken inside of the function.

3:
If the string is empty you dont break the code but constantly print newlines.

Here is some code wich I think should do what you wanted:

def str_analasys():
    while True:
        string = input("Enter word or integer: ")
        if string == '':
            continue

        elif string.isdigit():
            if int(string) > 99:
                print(str(string)+ " is a pretty big number!")
            else:
                print(str(string)+ " is a smaller number than expected")
        elif string.isalpha():
            print(string + " is an alphabetical character")
        else:
            print(string + " is a surprise! It's neither all alpha nor all digit characters!")

        break
str_analasys()


问:
How to check successive values in a CSV file by awk?
In a two-column CSV, I want to check the successive numbers (the values are integers):

```<code>1,1
4,1
5,1
6,1
7,1
10,1
11,1
4,2
5,2
6,2
10,2
5,3
5,7
5,8
5,9
</code>```

I tried

```<code>awk -F, '
{
    if($1==a+1) { n+=1 }
    else { n = 1 }
{a=$1}
} {print $1"," n}
' file.txt
</code>```

to produce

```<code>1,1,1
4,1,1
5,1,2
6,1,3
7,1,4
10,1,1
11,1,2
4,2,1
5,2,2
6,2,3
10,2,1
5,3,1
5,7,1
5,8,1
5,9,1
</code>```

where the third column counts the successive rows with respect to the first column.

Is my approach is correct (particularly performance-wise because it is a huge file)?

What is the best way to calculate the fourth column based on the second column (counting the successive values in the second column)?

This is the expected output including the fourth column.

```<code>1,1,1,1
4,1,1,1
5,1,2,1
6,1,3,1
7,1,4,1
10,1,1,1
11,1,2,1
4,2,1,1
5,2,2,1
6,2,3,1
10,2,1,1
5,3,1,1
5,7,1,1
5,8,1,2
5,9,1,3
</code>```

My idea is to sort the produced 3-column CSV (sort -t, -k1,1n -k2,2n) and do the same thing with the second column, but I am not sure.

EDIT: I made a mistake in the first dataset. When we count the first column, the second column is constant, and vice versa.

答:
Could you please try following, written and tested  on shown samples(basically re-designed OP's code in more awkish way :) , thanks to OP for letting know in comments).

```<code>awk '
BEGIN{
  FS=OFS=","
}
{
  count=$1-prev==1 && prev?++count:"1"
  print $0,count
  prev=$1
}
'  Input_file
</code>```

Explanation:

In this approach we haven't re-assigned current line and simply printing the value of current line along with count value, which should be less time taking.

Output will be as follows.

```<code>1,10,1
4,10,1
5,10,2
6,11,3
7,14,4
10,9,1
11,2,2
</code>```

NOTE: In case you want to sort output after awk's calculations then we could further use | sort to perform sorting on 3rd column IMHO.

Body:
In a two-column CSV, I want to check the successive numbers (the values are integers):

1,1
4,1
5,1
6,1
7,1
10,1
11,1
4,2
5,2
6,2
10,2
5,3
5,7
5,8
5,9

I tried

awk -F, '
{
    if($1==a+1) { n+=1 }
    else { n = 1 }
{a=$1}
} {print $1"," n}
' file.txt

to produce

1,1,1
4,1,1
5,1,2
6,1,3
7,1,4
10,1,1
11,1,2
4,2,1
5,2,2
6,2,3
10,2,1
5,3,1
5,7,1
5,8,1
5,9,1

where the third column counts the successive rows with respect to the first column.

Is my approach is correct (particularly performance-wise because it is a huge file)?

What is the best way to calculate the fourth column based on the second column (counting the successive values in the second column)?

This is the expected output including the fourth column.

1,1,1,1
4,1,1,1
5,1,2,1
6,1,3,1
7,1,4,1
10,1,1,1
11,1,2,1
4,2,1,1
5,2,2,1
6,2,3,1
10,2,1,1
5,3,1,1
5,7,1,1
5,8,1,2
5,9,1,3

My idea is to sort the produced 3-column CSV (sort -t, -k1,1n -k2,2n) and do the same thing with the second column, but I am not sure.

EDIT: I made a mistake in the first dataset. When we count the first column, the second column is constant, and vice versa.

Body:
Could you please try following, written and tested  on shown samples(basically re-designed OP's code in more awkish way :) , thanks to OP for letting know in comments).

awk '
BEGIN{
  FS=OFS=","
}
{
  count=$1-prev==1 && prev?++count:"1"
  print $0,count
  prev=$1
}
'  Input_file

Explanation:

In this approach we haven't re-assigned current line and simply printing the value of current line along with count value, which should be less time taking.

Output will be as follows.

1,10,1
4,10,1
5,10,2
6,11,3
7,14,4
10,9,1
11,2,2

NOTE: In case you want to sort output after awk's calculations then we could further use | sort to perform sorting on 3rd column IMHO.


问:
If statment in Azure Devops Yaml
I can't figure out how to make this if statment works:

```<code>- pwsh: |
    $affected = 'bleh'
    Write-Host "##vso[task.setvariable variable=affected;isOutput=true]$affected"
- ${{ if eq(variables.affected.Contains('bleh'), 'True') }}:
    [...]

</code>```

It says Unexpected symbol (, which is the ( in eq(

Thanks

答:
There are a couple of issues with your syntax.

Firstly you are using template syntax to read the variable that in your pipeline is not set before compile. The template syntax (the expressions wrapped with {{) are evaluated at compile time, before your variable is set (during runtime). For more info on variable syntax see here > https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables#understand-variable-syntax Instead of using an inline template, you could use a condition attribute for your second step. Condition syntax > https://learn.microsoft.com/en-us/azure/devops/pipelines/process/conditions

Secondly you are setting isOutput to true, this is used for passing variables between jobs. It sets the variable is a different place than if you dont have the isOutput option set. For more info on setting variables during runtime see here > https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables#set-variables-in-scripts

Thirdly to do a contains check the syntax is contains(string, sub-string), not string.contains(sub-string). See > https://learn.microsoft.com/en-us/azure/devops/pipelines/process/expressions#contains

If you want to conditionally run the second step based on the variable set by the first, try this:

- pwsh: |
  $affected = 'bleh'
  Write-Host "##vso[task.setvariable variable=affected]$affected"
- pwsh: echo "do something"
  condition: contains(variables.affected, 'bleh')
```

Title: If statment in Azure Devops Yaml

Body:
I can't figure out how to make this if statment works:

- pwsh: |
    $affected = 'bleh'
    Write-Host "##vso[task.setvariable variable=affected;isOutput=true]$affected"
- ${{ if eq(variables.affected.Contains('bleh'), 'True') }}:
    [...]

It says Unexpected symbol (, which is the ( in eq(

Thanks