来源: stackexchange

问:
i18n find in associated models with rails 3
I need to build a multi-language site, where the client will add records in many languages.
I wanna know if Rails has something to do a website like this. Imagine these scenario: I have a Post and Category. The user language sessions is set to en-US. When the user do a search for category 'car' the system will retrieve the Category model and all Posts TRANSLATED in that language.

Can I accomplish this with Rails 3?

Thanks in advance

答: You can do this by yourself by adding a translation table for the posts and categories tables and join them with the original tables. Alternatively, have a look at Globalize2: https://github.com/joshmh/globalize2 which does all the backend work for you.</p>

ContentLicense: CC BY-SA 3.0


问:
Regex for file name containing string anywhere Java
Apologies if this is not worded well..

Basically I have this line in a servlet -

FileInputStream flinp = new FileInputStream("C:\\xampp\\img\\"+empid+".jpg");

where empid is a string.

So currently I am getting files with the empid as the name, but I need to get files that have the empid ANYWHERE in the name.. so for example if my empid is 2500, I need to get the file if its called anything like -

2500_Amy

Amy_2500

Amy2500

2500Amy

etc..
Can anyone help with this? Is it regex I need to use and if so what do I write? Thanks

I tried this but bringing me an error -

FileInputStream flinp = new FileInputStream("C:\\xampp\\img\\"+.*?empid.*+".jpg");

EDIT -

BTW, in my jsp I have a loop with this line in it so that multiple empid's are passed to the "ReadImage" servlet and multiple images are read.. not sure if this makes my question any different but just to add it anyway -

<img src='<%=request.getContextPath()%>/ReadImages?id<%=thisemp.getEmpGid()%>'

答:
Try to find required file using Files.walk(...):

```<code>var nameRegEx = ".*" + epid + ".*.jpd";
Optional<Path> path = Files.walk(Paths.get("C:\\xampp\\img\\"))
            .filter(Files::isRegularFile)
            .filter(p -> p.toFile().getName().matches(nameRegEx))
            .findFirst();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Try to find required file using Files.walk(...):

var nameRegEx = ".*" + epid + ".*.jpd";
Optional<Path> path = Files.walk(Paths.get("C:\\xampp\\img\\"))
            .filter(Files::isRegularFile)
            .filter(p -> p.toFile().getName().matches(nameRegEx))
            .findFirst();


问:
How to Analyze the Running Time of a Python For-Loop?
Consider the following line-by-line analysis of a classical for-loop:

```<code>1 for (int i = 0; i < N; i++) {    | 1 + N + (N - 1)
2                                  |
3     //do something               | c
4                                  |
5 }                                |
</code>```

In this example, the initialization of the for-loop takes one primitive operation, the loop condition is checked N times and the variable i is incremented N - 1 times while the body of the loop takes c primite operations, for some constant c. This means that line 1 is executed 1 + N + (N - 1) times, while the body of the loop is executed N times. However, in Python this analysis wouldn't work because for-loops in Python are implemented by using iterators. Consider the following simple example:

```<code>1 for i in range(len(N)):          | ?
2     //do something               | c
</code>```

If I would like to analyze the running time of this code snippet line-by-line as I already did above, how would I do that? Should I assume that line 1 is executed N times like in a classical for-loop or does it make more sense to say that in Python line 1 is executed one time and only the body of the loop is executed N times?

答:
Seems like you trying to calculate asymptotics, but you dont understand how it works :(

You cant say, that the classical for-loop (e.g. c++) executes T(C * (1 + N + (N - 1)), because all depends from 1000 and 1 other things, e.g. compiler...

If u want to calculate asymptotics (in our days) — better use O-notation, which says that both codes execute with O(C * N) operations.

Body:
Consider the following line-by-line analysis of a classical for-loop:

1 for (int i = 0; i < N; i++) {    | 1 + N + (N - 1)
2                                  |
3     //do something               | c
4                                  |
5 }                                |

In this example, the initialization of the for-loop takes one primitive operation, the loop condition is checked N times and the variable i is incremented N - 1 times while the body of the loop takes c primite operations, for some constant c. This means that line 1 is executed 1 + N + (N - 1) times, while the body of the loop is executed N times. However, in Python this analysis wouldn't work because for-loops in Python are implemented by using iterators. Consider the following simple example:

1 for i in range(len(N)):          | ?
2     //do something               | c

If I would like to analyze the running time of this code snippet line-by-line as I already did above, how would I do that? Should I assume that line 1 is executed N times like in a classical for-loop or does it make more sense to say that in Python line 1 is executed one time and only the body of the loop is executed N times?


问:
Terraform lambda source_code_hash update with same code
I have an AWS Lambda deployed successfully with Terraform:

```<code>resource "aws_lambda_function" "lambda" {
  filename                       = "dist/subscriber-lambda.zip"
  function_name                  = "test_get-code"
  role                           = <my_role>
  handler                        = "main.handler"
  timeout                        = 14
  reserved_concurrent_executions = 50
  memory_size                    = 128
  runtime                        = "python3.6"
  tags                           = <my map of tags>
  source_code_hash               = "${base64sha256(file("../modules/lambda/lambda-code/main.py"))}"
  kms_key_arn                    = <my_kms_arn>
  vpc_config {
    subnet_ids         = <my_list_of_private_subnets>
    security_group_ids = <my_list_of_security_groups>
  }
  environment {
    variables = {
      environment = "dev"
    }
  }
}
</code>```

Now, when I run terraform plan command it says my lambda resource needs to be updated because the source_code_hash has changed, but I didn't update lambda Python codebase (which is versioned in a folder of the same repo):

```<code>  ~ module.app.module.lambda.aws_lambda_function.lambda
  last_modified:                     "2018-10-05T07:10:35.323+0000" => <computed>
  source_code_hash:                  "jd6U44lfe4124vR0VtyGiz45HFzDHCH7+yTBjvr400s=" => "JJIv/AQoPvpGIg01Ze/YRsteErqR0S6JsqKDNShz1w78"
</code>```

I suppose it is because it compresses my Python sources each time and the source changes. How can I avoid that if there are no changes in the Python code? Is my hypothesis coherent if I didn't change the Python codebase (I mean, why then the hash changes)?

答:
This works for me and also doesn't trigger an update on the Lambda function when the code hasn't changed</p>

```<code>data "archive_file" "lambda_zip" {
  type        = "zip"
  source_dir  = "../dist/go"
  output_path = "../dist/lambda_package.zip"
}

resource "aws_lambda_function" "aggregator_func" {
  description      = "MyFunction"
  function_name    = "my-func-${local.env}"
  filename         = data.archive_file.lambda_zip.output_path
  runtime          = "go1.x"
  handler          = "main"
  source_code_hash = data.archive_file.lambda_zip.output_base64sha256
  role             = aws_iam_role.function_role.arn

  timeout = 120
  publish = true

  tags = {
    environment = local.env
  }
}
</code>```

Body:
I have an AWS Lambda deployed successfully with Terraform:

resource "aws_lambda_function" "lambda" {
  filename                       = "dist/subscriber-lambda.zip"
  function_name                  = "test_get-code"
  role                           = <my_role>
  handler                        = "main.handler"
  timeout                        = 14
  reserved_concurrent_executions = 50
  memory_size                    = 128
  runtime                        = "python3.6"
  tags                           = <my map of tags>
  source_code_hash               = "${base64sha256(file("../modules/lambda/lambda-code/main.py"))}"
  kms_key_arn                    = <my_kms_arn>
  vpc_config {
    subnet_ids         = <my_list_of_private_subnets>
    security_group_ids = <my_list_of_security_groups>
  }
  environment {
    variables = {
      environment = "dev"
    }
  }
}

Now, when I run terraform plan command it says my lambda resource needs to be updated because the source_code_hash has changed, but I didn't update lambda Python codebase (which is versioned in a folder of the same repo):

  ~ module.app.module.lambda.aws_lambda_function.lambda
  last_modified:                     "2018-10-05T07:10:35.323+0000" => <computed>
  source_code_hash:                  "jd6U44lfe4124vR0VtyGiz45HFzDHCH7+yTBjvr400s=" => "JJIv/AQoPvpGIg01Ze/YRsteErqR0S6JsqKDNShz1w78"

I suppose it is because it compresses my Python sources each time and the source changes. How can I avoid that if there are no changes in the Python code? Is my hypothesis coherent if I didn't change the Python codebase (I mean, why then the hash changes)?

Body:
This works for me and also doesn't trigger an update on the Lambda function when the code hasn't changed

data "archive_file" "lambda_zip" {
  type        = "zip"
  source_dir  = "../dist/go"
  output_path = "../dist/lambda_package.zip"
}

resource "aws_lambda_function" "aggregator_func" {
  description      = "MyFunction"
  function_name    = "my-func-${local.env}"
  filename         = data.archive_file.lambda_zip.output_path
  runtime          = "go1.x"
  handler          = "main"
  source_code_hash = data.archive_file.lambda_zip.output_base64sha256
  role             = aws_iam_role.function_role.arn

  timeout = 120
  publish = true

  tags = {
    environment = local.env
  }
}


答:
You cannot use a regex directly to an FileInputStream, However, you can read all the files and then filter out the required once like below. If reading all can be done in your case,

```<code>File folder = new File( "/user/folder/" ); // Base folder where you have all the files
List<File> collectedFiles = Arrays.stream( folder.listFiles() )
                                  .filter( file -> file.getName().contains( "1525" ) ) // Check if filename as your employee number
                                  .collect( Collectors.toList() ); // Get all the filtered files as a list
</code>```

Another approach is to use the FileNameFilter

```<code>FilenameFilter filter = ( dir, name ) -> name.contains( "1525" );
File folder = new File( "/user/folder/" ); // Base folder where you have all the files
List<File> collectedFiles = Arrays.stream( folder.listFiles(filter) )
                                  .collect( Collectors.toList() );
</code>```

Title: Regex for file name containing string anywhere Java

Body:
Apologies if this is not worded well..

Basically I have this line in a servlet -

FileInputStream flinp = new FileInputStream("C:\\xampp\\img\\"+empid+".jpg");

where empid is a string.

So currently I am getting files with the empid as the name, but I need to get files that have the empid ANYWHERE in the name.. so for example if my empid is 2500, I need to get the file if its called anything like -

2500_Amy

Amy_2500

Amy2500

2500Amy

etc..
Can anyone help with this? Is it regex I need to use and if so what do I write? Thanks

I tried this but bringing me an error -

FileInputStream flinp = new FileInputStream("C:\\xampp\\img\\"+.*?empid.*+".jpg");

EDIT -

BTW, in my jsp I have a loop with this line in it so that multiple empid's are passed to the "ReadImage" servlet and multiple images are read.. not sure if this makes my question any different but just to add it anyway -

<img src='<%=request.getContextPath()%>/ReadImages?id<%=thisemp.getEmpGid()%>'

Body:
You cannot use a regex directly to an FileInputStream, However, you can read all the files and then filter out the required once like below. If reading all can be done in your case,

File folder = new File( "/user/folder/" ); // Base folder where you have all the files
List<File> collectedFiles = Arrays.stream( folder.listFiles() )
                                  .filter( file -> file.getName().contains( "1525" ) ) // Check if filename as your employee number
                                  .collect( Collectors.toList() ); // Get all the filtered files as a list

Another approach is to use the FileNameFilter

FilenameFilter filter = ( dir, name ) -> name.contains( "1525" );
File folder = new File( "/user/folder/" ); // Base folder where you have all the files
List<File> collectedFiles = Arrays.stream( folder.listFiles(filter) )
                                  .collect( Collectors.toList() );


问:
Vim Editor .vimrc error during customizaiton
I has suffered while customizing my vim editor.

Specifically, I add function which store cursor location.

Below is my .vimrc file.

```<code>au BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ exe "norm g`\"" |
\ endif
</code>```

And Error content is below :

```<code>au: command not found
-bash: /home/ubuntu/.vimrc: line 24: syntax error near unexpected token `('
-bash: /home/ubuntu/.vimrc: line 24: `\ if line("'\"") > 0 && line("'\"") <= line("$") |'
</code>```

Could you give me the solution ?
Take care of your health during COVID-19.
Thanks !

I found solution that change file authority.

```<code>chmod +777 ~/.viminfo
</code>```

.vimsrc file compiled still suffering error.

But function that restore cursor position is working.

Reference : https://askubuntu.com/questions/202075/how-do-i-get-vim-to-remember-the-line-i-was-on-when-i-reopen-a-file

答:
You don't need to source .vimrc from the command line, this will be done automatically by vim. Just make sure it's in the right place ($HOME/.vimrc)

Then when you open vim, it will source automatically.

You can view how to debug, where you will see if your file has been sourced in this answer How to see which plugins are making Vim slow?

Body:
I has suffered while customizing my vim editor.

Specifically, I add function which store cursor location.

Below is my .vimrc file.

au BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ exe "norm g`\"" |
\ endif

And Error content is below :

au: command not found
-bash: /home/ubuntu/.vimrc: line 24: syntax error near unexpected token `('
-bash: /home/ubuntu/.vimrc: line 24: `\ if line("'\"") > 0 && line("'\"") <= line("$") |'

Could you give me the solution ?
Take care of your health during COVID-19.
Thanks !

I found solution that change file authority.

chmod +777 ~/.viminfo

.vimsrc file compiled still suffering error.

But function that restore cursor position is working.

Reference : https://askubuntu.com/questions/202075/how-do-i-get-vim-to-remember-the-line-i-was-on-when-i-reopen-a-file


问:
Wrapping each word and each letter within each word jQuery
Imagine you have string of text. Every letter in that string should get a random font from an array.

To do this, i wrapped all letters within a span and randomized that font-family.

Problem with this approach is word-wrap. Now, when a sentence breaks, i have a letter-wrap where individual letter break to next line.

To fix this i want to also wrap each word in a span and apply word-wrap on that span.

So every individual word should have span. Every individual letter within that word should also get a span.

I could really use some help, below example outputs all letters * words. How to fix this?

```<code>var elem = $('.curiosa-type');

    elem.each(function( i ) {

        var currentElem = $(this);
        var words = currentElem.text().split(" ");
        var fonts = ['&#39Times&#39', '&#39Arial&#39'];
        currentElem.empty();

        $.each(words, function (i, el) {

            currentElem.append('<span class="word">' + el + '</span>');

            var characters = currentElem.text().split("");

            console.log(characters);

                $.each(characters, function (i, el) {

                    var rand = fonts[Math.floor(Math.random() * fonts.length)];

                    currentElem.append("<span style='font-family:" + rand + "'>" + el + "</span");
                    // check 4 white space
                    if(el.indexOf(' ') >= 0){
                        //console.log(el);
                        currentElem.append('<span class="spacer"></span>');

                    }

                });

        });

    });
</code>```

答:
I made some changes on your code, you was emptying currentElem and then reading it's text(was returning empty, of course). I'm building the word container(div) before appending it into the DOM and then append it all to the DOM when it's done.

```<code>var elem = $('.curiosa-type');
elem.each(function( i ) {
    var currentElem = $(this);
    var words = currentElem.text().split(" ");
    var fonts = ['&#39Times&#39', '&#39Arial&#39'];
    currentElem.empty();
    $.each(words, function (i, el) {
        console.log(words);
        // currentElem.append('<span class="word">' + el + '</span>'); //doesnt need it
        var characters = el.split('');
        var $div = $('<div>'); // create jQuery Element on fly so we can append to it even when it isn't in the DOM yet
        console.log(characters);
        $.each(characters, function (i, el) {
            var rand = fonts[Math.floor(Math.random() * fonts.length)];
            $div.append("<span style='font-family:" + rand + "'>" + el + "</span");
            // check 4 white space
            if(el.indexOf(' ') >= 0){
                $div.append('<span class="spacer"></span>');
            }
        });
        currentElem.append($div); // append our jQuery Element o the current ".curiosa-type" element
    });
});
</code>```

Output:

Body:
Imagine you have string of text. Every letter in that string should get a random font from an array.

To do this, i wrapped all letters within a span and randomized that font-family.

Problem with this approach is word-wrap. Now, when a sentence breaks, i have a letter-wrap where individual letter break to next line.

To fix this i want to also wrap each word in a span and apply word-wrap on that span.

So every individual word should have span. Every individual letter within that word should also get a span.

I could really use some help, below example outputs all letters * words. How to fix this?

var elem = $('.curiosa-type');

    elem.each(function( i ) {

        var currentElem = $(this);
        var words = currentElem.text().split(" ");
        var fonts = ['&#39Times&#39', '&#39Arial&#39'];
        currentElem.empty();

        $.each(words, function (i, el) {

            currentElem.append('' + el + '');

            var characters = currentElem.text().split("");

            console.log(characters);

                $.each(characters, function (i, el) {

                    var rand = fonts[Math.floor(Math.random() * fonts.length)];

                    currentElem.append("" + el + "= 0){
                        //console.log(el);
                        currentElem.append('');

                    }

                });

        });

    });

Body:
I made some changes on your code, you was emptying currentElem and then reading it's text(was returning empty, of course). I'm building the word container(div) before appending it into the DOM and then append it all to the DOM when it's done.

var elem = $('.curiosa-type');
elem.each(function( i ) {
    var currentElem = $(this);
    var words = currentElem.text().split(" ");
    var fonts = ['&#39Times&#39', '&#39Arial&#39'];
    currentElem.empty();
    $.each(words, function (i, el) {
        console.log(words);
        // currentElem.append('<span class="word">' + el + '</span>'); //doesnt need it
        var characters = el.split('');
        var $div = $('<div>'); // create jQuery Element on fly so we can append to it even when it isn't in the DOM yet
        console.log(characters);
        $.each(characters, function (i, el) {
            var rand = fonts[Math.floor(Math.random() * fonts.length)];
            $div.append("<span style='font-family:" + rand + "'>" + el + "</span");
            // check 4 white space
            if(el.indexOf(' ') >= 0){
                $div.append('<span class="spacer"></span>');
            }
        });
        currentElem.append($div); // append our jQuery Element o the current ".curiosa-type" element
    });
});

Output:


问:
gdb: logging something instead of breaking?
Is it possible to have gdb log something to the terminal instead of breaking on it?  For example I would like to set a 'breakpoint' on some method and have gdb print self as well as the parameters each time the method is invoked. Basically I want to insert print statements into arbitrary places without actually recompiling.

thanks for any suggestions

This is what i have so far after these helpful comments:

```<code>define logFoo
b fooMethod
commands
po self
end
end
</code>```

GDB doesn't seem to like the nested end statements though. any thoughts?

答:
Use a breakpoint as usual, and set a macro to log and continue:</p>

```<code> define c
 print "foo"
 cont
 c
 end
</code>```

Body:
Is it possible to have gdb log something to the terminal instead of breaking on it?  For example I would like to set a 'breakpoint' on some method and have gdb print self as well as the parameters each time the method is invoked. Basically I want to insert print statements into arbitrary places without actually recompiling.

thanks for any suggestions

This is what i have so far after these helpful comments:

define logFoo
b fooMethod
commands
po self
end
end

GDB doesn't seem to like the nested end statements though. any thoughts?

Body:
Use a breakpoint as usual, and set a macro to log and continue:

 define c
 print "foo"
 cont
 c
 end


问:
Generator.next is not a function
Can someone please tell me why i get the error : generator.next is not a function
i'am using webdriverIO framework and try to count the number of visible elements which correspond to some classes.</p>

```<code>const generator = function* (){
            yield  $$('.class1')
            yield  $$('.class2')
            yield  $$('.class3')
            yield  $$('.class4')
            return "Done"
            }
            var N=0;
            const  getElementObject=null;
            do {
                getElementObject = generator.next()
                for (let i =0;i< getElementObject.value.length; i++)
                     {
                         if (getElementObject.value.isVisible()==true)
                                      N++
                     }
              }while (getElementObject.value=="Done");
</code>```

答:
thank you guys for the solutions it worked so.</p>

```<code>const generator = function* (){
        yield  $$('.class1')
        yield  $$('.class2')
        yield  $$('.class3')
        yield  $$('.class4')
        }
        let N=0;
        for (let collection of generator())
            for (let element of collection)
                     if (element.isDisplayed()==true)
                                  N++
          console.log(`theResultIs ${chalk.green(N)}`)
</code>```

Title: Generator.next is not a function

Body:
Can someone please tell me why i get the error : generator.next is not a function
i'am using webdriverIO framework and try to count the number of visible elements which correspond to some classes.

const generator = function* (){
            yield  $$('.class1')
            yield  $$('.class2')
            yield  $$('.class3')
            yield  $$('.class4')
            return "Done"
            }
            var N=0;
            const  getElementObject=null;
            do {
                getElementObject = generator.next()
                for (let i =0;i< getElementObject.value.length; i++)
                     {
                         if (getElementObject.value.isVisible()==true)
                                      N++
                     }
              }while (getElementObject.value=="Done");

Body:
thank you guys for the solutions it worked so.

const generator = function* (){
        yield  $$('.class1')
        yield  $$('.class2')
        yield  $$('.class3')
        yield  $$('.class4')
        }
        let N=0;
        for (let collection of generator())
            for (let element of collection)
                     if (element.isDisplayed()==true)
                                  N++
          console.log(`theResultIs ${chalk.green(N)}`)


问:
Pandas Multiindex selection criteria alongwith column selection criteria
I need to query a Pandas Dataframe based on multiple criteria on the Index and the Column. Please have a look at my data below. 'Country' and 'Surname' are two separate indices, while 'Name', 'Score', 'Type' are columns.

```<code>y = pd.DataFrame({'Name':['Nikhil', 'Ankit', 'Keval', 'Darpan', 'Rajesh', 'John', 'Lynda'],
                  'Score':[89,92,96,82,95,98,97],
                  'Type':['Fat','Slim','Fat','Slim','Fat','Slim','Slim'],
                  'Country':['India','USA','Denmark','Australia','Italy','China','Israel'],
                  'Surname':['Sharma','Sharma','Patel','Shah','Sharma','Sharma','Sharma']}
                ).set_index('Country').set_index('Surname', append=True)
</code>```

I want to select data which meets following criteria:

Country should neither be India nor be USA

Surname should be Sharma

Score should be equal to or above 90

Type should be Slim

答:
For select in columns or in MultiIndex levels is possible use query with chained masks by and or &:

```<code>q='Country not in ["India","USA"] and Surname == "Sharma" and Score >= 90 and Type == "Slim"'
</code>```

Or:

```<code>q = 'Country not in ["India","USA"] & Surname == "Sharma" & Score >= 90 & Type == "Slim"'
</code>```

```<code>print (y.query(q))
                  Name  Score  Type
Country Surname
China   Sharma    John     98  Slim
Israel  Sharma   Lynda     97  Slim
</code>```

Alternative with boolean indexing, but chaining masks is strictly &:

```<code>m1 = ~y.index.get_level_values('Country').isin(["India","USA"])
m2 = y.index.get_level_values('Surname') == 'Sharma'
m3 = y['Score'].ge(90)
m4 = y['Type'].eq('Slim')
print (y[m1 & m2 & m3 & m4])
                  Name  Score  Type
Country Surname
China   Sharma    John     98  Slim
Israel  Sharma   Lynda     97  Slim
</code>```

Body:
I need to query a Pandas Dataframe based on multiple criteria on the Index and the Column. Please have a look at my data below. 'Country' and 'Surname' are two separate indices, while 'Name', 'Score', 'Type' are columns.

y = pd.DataFrame({'Name':['Nikhil', 'Ankit', 'Keval', 'Darpan', 'Rajesh', 'John', 'Lynda'],
                  'Score':[89,92,96,82,95,98,97],
                  'Type':['Fat','Slim','Fat','Slim','Fat','Slim','Slim'],
                  'Country':['India','USA','Denmark','Australia','Italy','China','Israel'],
                  'Surname':['Sharma','Sharma','Patel','Shah','Sharma','Sharma','Sharma']}
                ).set_index('Country').set_index('Surname', append=True)

I want to select data which meets following criteria:

Country should neither be India nor be USA

Surname should be Sharma

Score should be equal to or above 90

Type should be Slim

Body:
For select in columns or in MultiIndex levels is possible use query with chained masks by and or &:

q='Country not in ["India","USA"] and Surname == "Sharma" and Score >= 90 and Type == "Slim"'

Or:

q = 'Country not in ["India","USA"] & Surname == "Sharma" & Score >= 90 & Type == "Slim"'

print (y.query(q))
                  Name  Score  Type
Country Surname
China   Sharma    John     98  Slim
Israel  Sharma   Lynda     97  Slim

Alternative with boolean indexing, but chaining masks is strictly &:

m1 = ~y.index.get_level_values('Country').isin(["India","USA"])
m2 = y.index.get_level_values('Surname') == 'Sharma'
m3 = y['Score'].ge(90)
m4 = y['Type'].eq('Slim')
print (y[m1 & m2 & m3 & m4])
                  Name  Score  Type
Country Surname
China   Sharma    John     98  Slim
Israel  Sharma   Lynda     97  Slim


问:
How to get Runtime Library and Build Type from the obj file?
I work on Windows 10. I use cmake with Visual Studio 15 2017 generator. Do you know any tool which allow to check Runtime Library and Build Type based on the obj file ?</p>

答: Take a look at Dependency Walker, it might work.</p>


问:
How can I make a conditional reduce call for an array of objects in React?
This is the numbers array which is defined in a React Redux reducer file:

```<code>const initialState = {
    numbers: [
        { name: 'max', num: 3, inCart: false },
        { name: 'jack', num: 2, inCart: true },
        { name: 'jack', num: 2, inCart: true }
    ]
};
</code>```

In a component, I want to sum all the numeric values in all the objects in the numbers array only if  inCart === true.

This is how I'm doing it:

```<code>useEffect(() => {
    const total = props.numbers.reduce((prev, current) => {
        if (current.inCart) return prev + current.num;
    }, 0);
    console.log(total);
}, []);
</code>```

And this is the console log I get:

```<code>NaN
</code>```

So it's not working, what am I doing wrong?

答:
You could filter out the unnecessary items, and then reduce over the items inCart and accumulatively add up num property from each object.

```<code>const initialState = {
    numbers: [
        { name: 'max', num: 3, inCart: false },
        { name: 'jack', num: 2, inCart: true },
        { name: 'jack', num: 2, inCart: true }
    ]
};

initialState.numbers
  .filter(({ inCart }) => inCart)
  .reduce((acc, { num }) => acc += num, 0);
</code>```

Body:
This is the numbers array which is defined in a React Redux reducer file:

const initialState = {
    numbers: [
        { name: 'max', num: 3, inCart: false },
        { name: 'jack', num: 2, inCart: true },
        { name: 'jack', num: 2, inCart: true }
    ]
};

In a component, I want to sum all the numeric values in all the objects in the numbers array only if  inCart === true.

This is how I'm doing it:

useEffect(() => {
    const total = props.numbers.reduce((prev, current) => {
        if (current.inCart) return prev + current.num;
    }, 0);
    console.log(total);
}, []);

And this is the console log I get:

NaN

So it's not working, what am I doing wrong?

Body:
You could filter out the unnecessary items, and then reduce over the items inCart and accumulatively add up num property from each object.

const initialState = {
    numbers: [
        { name: 'max', num: 3, inCart: false },
        { name: 'jack', num: 2, inCart: true },
        { name: 'jack', num: 2, inCart: true }
    ]
};

initialState.numbers
  .filter(({ inCart }) => inCart)
  .reduce((acc, { num }) => acc += num, 0);


问:
Javascript load background-image asynchrously
Is it possible to load a background-image asynchronously?

I've seen many jQuery plugins to load normal image in an asynchronous way, but I can't find if it's possible to preload / asynchronously load a background-image.

EDIT

I clarify my problem. I've been working on this test site http://mentalfaps.com/
The background image is loaded randomly from a set of images refreshed each hour by a chron job (which takes random images on a flickr catalog).

The host is free and slow at the moment, so the background image takes some time to load.

The positioning of the first overlay (the one with the PNG transparent mentalfaps logo) and width are regulated by a function created in the jQuery(document).ready construct.

If you try to refresh the page many times, the width of the right overlay div is 0 (and so you see a "hole" in the layout)

Here is the method to set my positions:

```<code>function setPositions(){
    var oH = $('#overlay-header');
    var overlayHeaderOffset = oH.offset();
    var overlayRightWidth = $(window).width() - (overlayHeaderOffset.left + oH.width());
    if (overlayRightWidth >= 0) {
        $('#overlay-right').width(overlayRightWidth);
    } else {
        $('#overlay-right').width(0);
    }
    var lW =  $('#loader-wrapper');
    lW.offset({
        left: (overlayHeaderOffset.left + oH.width() - lW.width())
    });
}
</code>```

The problem is that the $(window).width() is lower then the effective window width! so the check fails and the script goes for $('#overlay-right').width(0);

any ideas?

答: As it is already mentioned, the background image is loaded asynchronously. If you need to load the background image from JQuery code you may also set the addClass() method to set a CSS class or attr("style=\"background-image:url('myimage.png')\"")</p>

Body:
Is it possible to load a background-image asynchronously?

I've seen many jQuery plugins to load normal image in an asynchronous way, but I can't find if it's possible to preload / asynchronously load a background-image.

EDIT

I clarify my problem. I've been working on this test site http://mentalfaps.com/
The background image is loaded randomly from a set of images refreshed each hour by a chron job (which takes random images on a flickr catalog).

The host is free and slow at the moment, so the background image takes some time to load.

The positioning of the first overlay (the one with the PNG transparent mentalfaps logo) and width are regulated by a function created in the jQuery(document).ready construct.

If you try to refresh the page many times, the width of the right overlay div is 0 (and so you see a "hole" in the layout)

Here is the method to set my positions:

function setPositions(){
    var oH = $('#overlay-header');
    var overlayHeaderOffset = oH.offset();
    var overlayRightWidth = $(window).width() - (overlayHeaderOffset.left + oH.width());
    if (overlayRightWidth >= 0) {
        $('#overlay-right').width(overlayRightWidth);
    } else {
        $('#overlay-right').width(0);
    }
    var lW =  $('#loader-wrapper');
    lW.offset({
        left: (overlayHeaderOffset.left + oH.width() - lW.width())
    });
}

The problem is that the $(window).width() is lower then the effective window width! so the check fails and the script goes for $('#overlay-right').width(0);

any ideas?


问:
Search solr keywords "OR", "AND" AND "will report errors [Hybris integrate solr]
**Search solr keywords "OR", "AND" AND "will report errors.
My local environment was good, but STG and DEV failed,So what's the solution.

It is feasible to translate the search conditions by adding "\" before the search conditions.
Are there any other solutions? Thanks.

Below is the error log:**

```<code> ERROR [hCSHTTP10] [SolrSearchRequestResponsePopulator] Exception while executing SOLR search
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |  de.hybris.platform.solrfacetsearch.search.FacetSearchException: Error from server at http://10.246.88.191:8983/solr: org.apache.solr.search.SyntaxError: Cannot parse '(skus_string_mv:(OR^40.0 OR *OR*^20.0)) OR (code_string:(OR^40.0 OR *OR*^20.0)) OR (styleNumber_string:(OR^40.0 OR *OR*^20.0)) OR (collectionName_text_en_mv:(or^160.0 OR *or*^80.0)) OR (collectionName_text_zh_mv:(or^160.0 OR *or*^80.0)) OR (keywords_text_en:(or^240.0 OR *or*^120.0)) OR (keywords_text_zh:(or^240.0 OR *or*^120.0)) OR (name_text_en:(or^220.0 OR *or*^110.0)) OR (name_text_zh:(or^220.0 OR *or*^110.0)) OR (categoryName_text_en_mv:(or^200.0)) OR (categoryName_text_zh_mv:(or^200.0)) OR (category_string_mv:(or^160.0 OR *or*^80.0)) OR (colorFamilyName_text_en:(or^140.0 OR *or*^70.0)) OR (colorFamilyName_text_zh:(or^140.0 OR *or*^70.0)) OR (swatchColorDisplayName_text_en:(or^140.0 OR *or*^70.0)) OR (swatchColorDisplayName_text_zh:(or^140.0 OR *or*^70.0)) OR (legacySkuCode_string:(OR^40.0 OR *OR*^20.0))': Encountered " <OR> "OR "" at line 1, column 17.
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 | Was expecting one of:
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     <NOT> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     "+" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     "-" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     <BAREOPER> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     "(" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     "*" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     <QUOTED> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     <TERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <PREFIXTERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <WILDTERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <REGEXPTERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     "[" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     "{" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <LPARAMS> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     "filter(" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <NUMBER> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <TERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     "*" ...
</code>```

答:
use this \\AND

and in my opinion those are stop words you don't need to search for them, if you want to use them as logic operator then just do it: q=java AND Python

Body:
**Search solr keywords "OR", "AND" AND "will report errors.
My local environment was good, but STG and DEV failed,So what's the solution.

It is feasible to translate the search conditions by adding "\" before the search conditions.
Are there any other solutions? Thanks.

Below is the error log:**

 ERROR [hCSHTTP10] [SolrSearchRequestResponsePopulator] Exception while executing SOLR search
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |  de.hybris.platform.solrfacetsearch.search.FacetSearchException: Error from server at http://10.246.88.191:8983/solr: org.apache.solr.search.SyntaxError: Cannot parse '(skus_string_mv:(OR^40.0 OR *OR*^20.0)) OR (code_string:(OR^40.0 OR *OR*^20.0)) OR (styleNumber_string:(OR^40.0 OR *OR*^20.0)) OR (collectionName_text_en_mv:(or^160.0 OR *or*^80.0)) OR (collectionName_text_zh_mv:(or^160.0 OR *or*^80.0)) OR (keywords_text_en:(or^240.0 OR *or*^120.0)) OR (keywords_text_zh:(or^240.0 OR *or*^120.0)) OR (name_text_en:(or^220.0 OR *or*^110.0)) OR (name_text_zh:(or^220.0 OR *or*^110.0)) OR (categoryName_text_en_mv:(or^200.0)) OR (categoryName_text_zh_mv:(or^200.0)) OR (category_string_mv:(or^160.0 OR *or*^80.0)) OR (colorFamilyName_text_en:(or^140.0 OR *or*^70.0)) OR (colorFamilyName_text_zh:(or^140.0 OR *or*^70.0)) OR (swatchColorDisplayName_text_en:(or^140.0 OR *or*^70.0)) OR (swatchColorDisplayName_text_zh:(or^140.0 OR *or*^70.0)) OR (legacySkuCode_string:(OR^40.0 OR *OR*^20.0))': Encountered " <OR> "OR "" at line 1, column 17.
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 | Was expecting one of:
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     <NOT> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     "+" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     "-" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     <BAREOPER> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     "(" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     "*" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     <QUOTED> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.453 |     <TERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <PREFIXTERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <WILDTERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <REGEXPTERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     "[" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     "{" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <LPARAMS> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     "filter(" ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <NUMBER> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     <TERM> ...
INFO   | jvm 1    | main    | 2020/05/25 03:58:19.454 |     "*" ...


问:
Using an Algorithm library operation in a vector array C++
Is it possible to use an Algorithm library operation in a vector array? If so, how am I supposed to do it and what operations could I use here(ex. remove_if)? Currently, I'm running a for loop to calculate my score checking if I hit a certain object and deleting it afterwards if it was hit. It all works great, but I somehow need to use an Algorithm library here. (I'm still quite new in C++) Here's what I have so far:

```<code>std::vector<Coin*>coins;
coins.push_back(new Coin(&window_object[0], 60.0f, 60.0f, 350.0f, 425.0f, "res/coin.png"));
coins.push_back(new Coin(&window_object[0], 60.0f, 60.0f, 450.0f, 425.0f, "res/coin.png"));
</code>```

...

```<code>for (size_t i = 0; i < coins.size(); i++) {
    if (coins[i]->CheckCollect(player)) {
        Coin* temp = coins[i];
        coins.erase(coins.begin()+i);
        delete temp;
        score++;
    }
}
</code>```

EDIT: code miss-type

答:
It's not hard to replace your for loop with a standard library algorithm. You're iterating over a vector, doing some work, and possibly erasing some elements. That can be done with std::remove_if.

I moved the loop body into a lambda expression and then used that in an erase/remove_if:

```<code>auto my_predicate = [&](Coin *coin) {
    if (coin->CheckCollect(player)) {
        delete coin;
        score++;
        return true; // remove this element
    }
    return false; // don't remove
};

coins.erase(std::remove_if(coins.begin(), coins.end(), my_predicate), coins.end());
</code>```

I don't know if it's cleaner code but it might perform better. The for loop repeatedly calling erase can be expensive as elements are moved multiple times to fill in the holes. With std::remove_if each element is moved at most once and there's a single erase to fix the vector size.

Body:
Is it possible to use an Algorithm library operation in a vector array? If so, how am I supposed to do it and what operations could I use here(ex. remove_if)? Currently, I'm running a for loop to calculate my score checking if I hit a certain object and deleting it afterwards if it was hit. It all works great, but I somehow need to use an Algorithm library here. (I'm still quite new in C++) Here's what I have so far:

std::vector<Coin*>coins;
coins.push_back(new Coin(&window_object[0], 60.0f, 60.0f, 350.0f, 425.0f, "res/coin.png"));
coins.push_back(new Coin(&window_object[0], 60.0f, 60.0f, 450.0f, 425.0f, "res/coin.png"));

...

for (size_t i = 0; i < coins.size(); i++) {
    if (coins[i]->CheckCollect(player)) {
        Coin* temp = coins[i];
        coins.erase(coins.begin()+i);
        delete temp;
        score++;
    }
}

EDIT: code miss-type

Body:
It's not hard to replace your for loop with a standard library algorithm. You're iterating over a vector, doing some work, and possibly erasing some elements. That can be done with std::remove_if.

I moved the loop body into a lambda expression and then used that in an erase/remove_if:

auto my_predicate = [&](Coin *coin) {
    if (coin->CheckCollect(player)) {
        delete coin;
        score++;
        return true; // remove this element
    }
    return false; // don't remove
};

coins.erase(std::remove_if(coins.begin(), coins.end(), my_predicate), coins.end());

I don't know if it's cleaner code but it might perform better. The for loop repeatedly calling erase can be expensive as elements are moved multiple times to fill in the holes. With std::remove_if each element is moved at most once and there's a single erase to fix the vector size.


问:
How to identify self referencing loop?
I have a below model from the EF entity:

```<code>public partial class Commodity
{
    public Commodity()
    {
        this.CommodityVarieties = new HashSet<CommodityVariety>();
    }

    public int CommodityID { get; set; }
    public string CommodityName { get; set; }
    public string CommodityVarietyDisplayName { get; set; }
    public string BackColor { get; set; }
    public string ForeColor { get; set; }
    public bool IsDeleted { get; set; }
    public int SortOrder { get; set; }

    public virtual ICollection<CommodityVariety> CommodityVarieties { get; set; }

}

public partial class CommodityVariety
{
    public int VarietyID { get; set; }
    public int CommodityID { get; set; }
    public string VarietyName { get; set; }
    public bool IsDeleted { get; set; }

    public virtual Commodity Commodity { get; set; }
}
</code>```

I would like to get a list of commodities and convert that list to JSON string using Newtonsoft. Hence, I write

```<code>DbContext context = new DbContext();
var list = context.Commodities.ToList();
string json = JsonConvert.SerializeObject(list);
</code>```

I am getting below error:

Self referencing loop detected for property 'Commodity' with type
  'System.Data.Entity.DynamicProxies.Commodity_B55D25F995ED72E0B75FED715153713965D91EB5A3BF576322FE6DEAC130C0F5'.
  Path '[0].CommodityVariety[0]

I know it is because of the reference to Commodity in the CommodityVariety class.

To avoid I updated JSON Serializing Setting to have ReferenceLoopHandling to Ignore like below:

```<code>options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
</code>```

Above settings give me

Exception of type 'System.OutOfMemoryException' was thrown.

I have tried all the possible answers from the StackOverflow.

Finally, I did

```<code>public DbContext() : base("name=DbContextEntity")
{
    Configuration.LazyLoadingEnabled = false;
    Configuration.ProxyCreationEnabled = false;
}
</code>```

Now, I get the code running without any error and Commodity.CommodityVarieties is null.

I have so many foreign keys and it is really hard to map them all manually after setting ProxyCreationEnabled to false.

Is there any way to identify self-referencing before JSON serializing and make it null? Like below:

```<code>DbContext context = new DbContext();
var list = context.Commodities.ToList();

//filter only properties of `Commodity` property and find object of type `Commodity`
//var suspectObjects = list.Any(x => x.OfType<Commodity>()).ToList();
//suspectObjects.ForEach(item => { item = null; });

//I know the above segment will not work. I seek your help and I thought something like above explain more to you what I want actually.

string json = JsonConvert.SerializeObject(list);
</code>```

答:
Well.. basically, most often Database model is not suited for being serialized to JSON. That's why there's often a mapping layer that translated structures from DB into API structures.

Anyways..

Nullifying the "offending" reference is one way to solve the problem, but if your ORM (EF, NH, XPO, whatever) tracks changes, you now get a risky situation: what if someone/something commits the changes afterwards? You'll save a lots of NULLs to the DB and break your data.

The JSON serializer that you are using, most probably Newtonsoft (judging from JsonConvert class) most probably offers you a configuration switch that will decide what to do when a circular reference is found in the serialized object graph. Check the docs.

For example, if you are using Newtonsoft's, then try ReferenceLoopHandling

You can also use attributes or settings to make the serializer ignore certain properties. In the example you provided, excluding CommodityVariety.Commodity would break the reference loop and solve the problem as well. Parent class has a collection of children, children no longer care about the parent, everything's fine for JSON. However, after DEserializing, you may need to manually fix the child-to-parent back-references back.

You can also implement and add your own plugins for the serializer and completely define the serialization however you like, that a sure-fire solution, but quite an overkill for this problem here.

Title: How to identify self referencing loop?

Body:
I have a below model from the EF entity:

public partial class Commodity
{
    public Commodity()
    {
        this.CommodityVarieties = new HashSet<CommodityVariety>();
    }

    public int CommodityID { get; set; }
    public string CommodityName { get; set; }
    public string CommodityVarietyDisplayName { get; set; }
    public string BackColor { get; set; }
    public string ForeColor { get; set; }
    public bool IsDeleted { get; set; }
    public int SortOrder { get; set; }

    public virtual ICollection<CommodityVariety> CommodityVarieties { get; set; }

}

public partial class CommodityVariety
{
    public int VarietyID { get; set; }
    public int CommodityID { get; set; }
    public string VarietyName { get; set; }
    public bool IsDeleted { get; set; }

    public virtual Commodity Commodity { get; set; }
}

I would like to get a list of commodities and convert that list to JSON string using Newtonsoft. Hence, I write

DbContext context = new DbContext();
var list = context.Commodities.ToList();
string json = JsonConvert.SerializeObject(list);

I am getting below error:

Self referencing loop detected for property 'Commodity' with type
  'System.Data.Entity.DynamicProxies.Commodity_B55D25F995ED72E0B75FED715153713965D91EB5A3BF576322FE6DEAC130C0F5'.
  Path '[0].CommodityVariety[0]

I know it is because of the reference to Commodity in the CommodityVariety class.

To avoid I updated JSON Serializing Setting to have ReferenceLoopHandling to Ignore like below:

options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Above settings give me

Exception of type 'System.OutOfMemoryException' was thrown.

I have tried all the possible answers from the StackOverflow.

Finally, I did

public DbContext() : base("name=DbContextEntity")
{
    Configuration.LazyLoadingEnabled = false;
    Configuration.ProxyCreationEnabled = false;
}

Now, I get the code running without any error and Commodity.CommodityVarieties is null.

I have so many foreign keys and it is really hard to map them all manually after setting ProxyCreationEnabled to false.

Is there any way to identify self-referencing before JSON serializing and make it null? Like below:

DbContext context = new DbContext();
var list = context.Commodities.ToList();

//filter only properties of `Commodity` property and find object of type `Commodity`
//var suspectObjects = list.Any(x => x.OfType<Commodity>()).ToList();
//suspectObjects.ForEach(item => { item = null; });

//I know the above segment will not work. I seek your help and I thought something like above explain more to you what I want actually.

string json = JsonConvert.SerializeObject(list);


问:
add another label by pressing button java swing
I am a beginner programmer, i get issue in adding label while pressing button as the code given when i press the button b1 it should print label 1 or label 2 but it prints nothing, am unable to understand why it happens

```<code>  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*;
  public class passField extends JFrame implements ActionListener
  {
    private JPasswordField pass;
    private JButton b1;
    private JLabel l,l0;
    private JLabel l1;
    private JLabel l2;

    String password;
    Container c;
    passField()
    {
       password="pass3word";
       c=super.getContentPane();
       pass=new JPasswordField(20);
       b1=new JButton("OK");
       l=new JLabel("Enter Password: ");
       l1=new JLabel("PASSWORD MATCH");
       l2=new JLabel("INCORRECT PASSWORD");
       Font f=new Font("SERIF",Font.PLAIN,22);
       l0=new JLabel("PASSWORD CHECKER");
       l1.setFont(f);
       l2 .setFont(f);
       l0.setFont(f);
       l0.setForeground(Color.WHITE);
       l.setForeground(Color.WHITE);
       l1.setForeground(Color.WHITE);
       l2.setForeground(Color.WHITE);
       add(l0);
       add(l);
       add(pass);
       add(b1);
       b1.addActionListener(this);
       setVisible(true);
       setSize(400,400);
       setLayout(new FlowLayout());
       c.setBackground(Color.BLACK);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(password==pass.getText())
            add(l1);
        else
          add(l2);
    }
}
</code>```

答:
Advise to do the following changes:

1. add before the Label and just change Text accordingly

2. replace deprecated getText() on pass

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class passField extends JFrame implements ActionListener
{
private JPasswordField pass;
private JButton b1;
private JLabel l,l0;
private JLabel l1;
private JLabel l2;

String password;
Container c;
passField()
{
   password="pass3word";
   c=super.getContentPane();
   pass=new JPasswordField(20);
   b1=new JButton("OK");
   l=new JLabel("Enter Password: ");
   l1=new JLabel("PASSWORD MATCH");
   l1.setText("nothing");
   l2=new JLabel("INCORRECT PASSWORD");
   Font f=new Font("SERIF",Font.PLAIN,22);
   l0=new JLabel("PASSWORD CHECKER");
   add(l1);
   l1.setFont(f);
   l2 .setFont(f);
   l0.setFont(f);
   l0.setForeground(Color.WHITE);
   l.setForeground(Color.WHITE);
   l1.setForeground(Color.WHITE);
   l2.setForeground(Color.WHITE);
   add(l0);
   add(l);
   add(pass);
   add(b1);
   b1.addActionListener(this);
   setVisible(true);
   setSize(400,400);
   setLayout(new FlowLayout());
   c.setBackground(Color.BLACK);
}
public void actionPerformed(ActionEvent e)
{
    String outPass = new String(pass.getPassword());
    System.out.println(password+"\n"+outPass);
    if(password.equals(outPass))
        l1.setText("PASSWORD MATCH");
    else
        l1.setText("INCORRECT PASSWORD");

}
public static void main(String args[])
{
    new passField();
}
}
</code>```

Output:

Body:
I am a beginner programmer, i get issue in adding label while pressing button as the code given when i press the button b1 it should print label 1 or label 2 but it prints nothing, am unable to understand why it happens

  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*;
  public class passField extends JFrame implements ActionListener
  {
    private JPasswordField pass;
    private JButton b1;
    private JLabel l,l0;
    private JLabel l1;
    private JLabel l2;

    String password;
    Container c;
    passField()
    {
       password="pass3word";
       c=super.getContentPane();
       pass=new JPasswordField(20);
       b1=new JButton("OK");
       l=new JLabel("Enter Password: ");
       l1=new JLabel("PASSWORD MATCH");
       l2=new JLabel("INCORRECT PASSWORD");
       Font f=new Font("SERIF",Font.PLAIN,22);
       l0=new JLabel("PASSWORD CHECKER");
       l1.setFont(f);
       l2 .setFont(f);
       l0.setFont(f);
       l0.setForeground(Color.WHITE);
       l.setForeground(Color.WHITE);
       l1.setForeground(Color.WHITE);
       l2.setForeground(Color.WHITE);
       add(l0);
       add(l);
       add(pass);
       add(b1);
       b1.addActionListener(this);
       setVisible(true);
       setSize(400,400);
       setLayout(new FlowLayout());
       c.setBackground(Color.BLACK);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(password==pass.getText())
            add(l1);
        else
          add(l2);
    }
}

Body:
Advise to do the following changes:

1. add before the Label and just change Text accordingly

2. replace deprecated getText() on pass

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class passField extends JFrame implements ActionListener
{
private JPasswordField pass;
private JButton b1;
private JLabel l,l0;
private JLabel l1;
private JLabel l2;

String password;
Container c;
passField()
{
   password="pass3word";
   c=super.getContentPane();
   pass=new JPasswordField(20);
   b1=new JButton("OK");
   l=new JLabel("Enter Password: ");
   l1=new JLabel("PASSWORD MATCH");
   l1.setText("nothing");
   l2=new JLabel("INCORRECT PASSWORD");
   Font f=new Font("SERIF",Font.PLAIN,22);
   l0=new JLabel("PASSWORD CHECKER");
   add(l1);
   l1.setFont(f);
   l2 .setFont(f);
   l0.setFont(f);
   l0.setForeground(Color.WHITE);
   l.setForeground(Color.WHITE);
   l1.setForeground(Color.WHITE);
   l2.setForeground(Color.WHITE);
   add(l0);
   add(l);
   add(pass);
   add(b1);
   b1.addActionListener(this);
   setVisible(true);
   setSize(400,400);
   setLayout(new FlowLayout());
   c.setBackground(Color.BLACK);
}
public void actionPerformed(ActionEvent e)
{
    String outPass = new String(pass.getPassword());
    System.out.println(password+"\n"+outPass);
    if(password.equals(outPass))
        l1.setText("PASSWORD MATCH");
    else
        l1.setText("INCORRECT PASSWORD");

}
public static void main(String args[])
{
    new passField();
}
}

Output:


问:
Can't connect to MySQL server on 'db' ([Errno -2] Name does not resolve)
I am trying to connect mysql with docker using python. but this error is occurring. I am using python3. I am new in docker so I am unable to find any solution.

Dockerfile:

```<code>FROM python:3.8-alpine
MAINTAINER Fahim Ahmed Irfan

ENV PYTHONUNBUFFERED 1

COPY ./requirements.txt /requirements.txt
RUN apk add --update --no-cache jpeg-dev
RUN apk --update add --no-cache --virtual .tmp-build-deps \
      gcc build-base libffi-dev freetype-dev libpng-dev openblas-dev linux-headers mysql-dev zlib zlib-dev
RUN pip install -r /requirements.txt

RUN mkdir /app
WORKDIR ./app
COPY ./app /app

RUN adduser -D user
User user
EXPOSE 8000
</code>```

Docker-compose file:

```<code>version: '3'

services:
  app:
    restart: always
    build:
      context: .
    ports:
      - "8000:8000"
    volumes:
      - ./app:/app
    command: >
      sh -c "python check_db.py --service-name mysql --ip db --port 3306 &&
             python manage.py makemigrations &&
             python manage.py migrate &&
             python manage.py runserver 0.0.0.0:8000"
    environment:
      - DB_HOST=db
      - DB_NAME=app
      - DB_USER=root
      - DB_PASS=supersecretpassword
    depends_on:
      - db

  db:
    image: mysql:8.0
    environment:
      - MYSQL_HOST=localhost
      - MYSQL_PORT=3306
      - MYSQL_ROOT_HOST=%
      - MYSQL_DATABASE=app
      - MYSQL_USER=root
      - MYSQL_PASSWORD=supersecretpassword

    ports:
      - "3306:3306"
</code>```

check_db.py:

```<code>import socket
import time
import argparse
""" Check if port is open, avoid docker-compose race condition """

parser = argparse.ArgumentParser(description='Check if port is open, avoid\
                                 docker-compose race condition')
parser.add_argument('--service-name', required=True)
parser.add_argument('--ip', required=True)
parser.add_argument('--port', required=True)

args = parser.parse_args()

# Get arguments
service_name = str(args.service_name)
port = int(args.port)
ip = str(args.ip)

# Infinite loop
while True:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex((ip, port))
    if result == 0:
        print("{0} port is open! Bye!".format(service_name))
        break
    else:
        print("{0} port is not open! I'll check it soon!".format(service_name))
        time.sleep(3)
</code>```

settings.py:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': os.environ.get('DB_HOST'),
        'NAME': os.environ.get('DB_NAME'),
        'USER': os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_PASS'),
        'PORT': '3306',
    }
</code>```

requirements.txt:

```<code>Django==2.1.3,<2.2.0
djangorestframework==3.9.0,<3.10.0
pymysql
</code>```

The error is: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno -2] Name does not resolve)")

Dont know how to solve this. Please advice.

答:
Finally I got this working, I have made a few important changes that are required for your code.

```<code>WORKDIR app
</code>```

WORKDIR does the creation of the directory app and also moving into the directory app so you can remove the statement RUN mkdir /app
As you also move to that directory so change the COPY statement to

```<code>COPY . .
</code>```

first . is the place where the dockerfile exists and the second . is the app folder in the container. So it is always good to have dockerfile in the app folder.

```<code>    volumes:
      - ./app:/app
</code>```

the above code from the docker-compose is not required as you are copying the contents directly so mounting again is of no use.

```<code>      - MYSQL_ROOT_PASSWORD=supersecretpassword
</code>```

Also, add the above environment variable to the db service in the docker-compose

```<code>- MYSQL_HOST=localhost
</code>```

Please remove this environment variable as it is not required here.

```<code>image: mysql:5.7
</code>```

I would recommend using version 5.7 as it is one of the stable ones I extensively use without many issues from the database server.

Body:
I am trying to connect mysql with docker using python. but this error is occurring. I am using python3. I am new in docker so I am unable to find any solution.

Dockerfile:

FROM python:3.8-alpine
MAINTAINER Fahim Ahmed Irfan

ENV PYTHONUNBUFFERED 1

COPY ./requirements.txt /requirements.txt
RUN apk add --update --no-cache jpeg-dev
RUN apk --update add --no-cache --virtual .tmp-build-deps \
      gcc build-base libffi-dev freetype-dev libpng-dev openblas-dev linux-headers mysql-dev zlib zlib-dev
RUN pip install -r /requirements.txt

RUN mkdir /app
WORKDIR ./app
COPY ./app /app

RUN adduser -D user
User user
EXPOSE 8000

Docker-compose file:

version: '3'

services:
  app:
    restart: always
    build:
      context: .
    ports:
      - "8000:8000"
    volumes:
      - ./app:/app
    command: >
      sh -c "python check_db.py --service-name mysql --ip db --port 3306 &&
             python manage.py makemigrations &&
             python manage.py migrate &&
             python manage.py runserver 0.0.0.0:8000"
    environment:
      - DB_HOST=db
      - DB_NAME=app
      - DB_USER=root
      - DB_PASS=supersecretpassword
    depends_on:
      - db

  db:
    image: mysql:8.0
    environment:
      - MYSQL_HOST=localhost
      - MYSQL_PORT=3306
      - MYSQL_ROOT_HOST=%
      - MYSQL_DATABASE=app
      - MYSQL_USER=root
      - MYSQL_PASSWORD=supersecretpassword

    ports:
      - "3306:3306"

check_db.py:

import socket
import time
import argparse
""" Check if port is open, avoid docker-compose race condition """

parser = argparse.ArgumentParser(description='Check if port is open, avoid\
                                 docker-compose race condition')
parser.add_argument('--service-name', required=True)
parser.add_argument('--ip', required=True)
parser.add_argument('--port', required=True)

args = parser.parse_args()

# Get arguments
service_name = str(args.service_name)
port = int(args.port)
ip = str(args.ip)

# Infinite loop
while True:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex((ip, port))
    if result == 0:
        print("{0} port is open! Bye!".format(service_name))
        break
    else:
        print("{0} port is not open! I'll check it soon!".format(service_name))
        time.sleep(3)

settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': os.environ.get('DB_HOST'),
        'NAME': os.environ.get('DB_NAME'),
        'USER': os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_PASS'),
        'PORT': '3306',
    }

requirements.txt:

Django==2.1.3,<2.2.0
djangorestframework==3.9.0,<3.10.0
pymysql

The error is: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno -2] Name does not resolve)")

Dont know how to solve this. Please advice.

Body:
Finally I got this working, I have made a few important changes that are required for your code.

WORKDIR app

WORKDIR does the creation of the directory app and also moving into the directory app so you can remove the statement RUN mkdir /app
As you also move to that directory so change the COPY statement to

COPY . .

first . is the place where the dockerfile exists and the second . is the app folder in the container. So it is always good to have dockerfile in the app folder.

    volumes:
      - ./app:/app

the above code from the docker-compose is not required as you are copying the contents directly so mounting again is of no use.

      - MYSQL_ROOT_PASSWORD=supersecretpassword

Also, add the above environment variable to the db service in the docker-compose

- MYSQL_HOST=localhost

Please remove this environment variable as it is not required here.

image: mysql:5.7

I would recommend using version 5.7 as it is one of the stable ones I extensively use without many issues from the database server.


问:
IE not supporting VueJS - Symfony application
How to make work the VueJS - Symfony application in IE11?

I'm using Babel Encore.

Already checked available answers in Stack but not working for me. Also, tried import the @babel/polyfill directly to the JS which is not working either.

Here is the webpack.config.js configuration of my application

```<code>const {VueLoaderPlugin} = require('vue-loader');
let Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .enableSourceMaps(!Encore.isProduction())
    .addEntry('app', './assets/js/app.js')
    // .enableVueLoader()
    .addLoader({
        test: /\.vue$/,
        loader: 'vue-loader'
    })
    .enableBuildNotifications()
    // .configureBabel(() => {}, {
    //     useBuiltIns: 'entry',
    //     corejs: 3
    // })

    .addPlugin(new VueLoaderPlugin())
    .enableSassLoader()
    .enableVersioning(Encore.isProduction())
;

module.exports = Encore.getWebpackConfig();
</code>```

Note: The IE browser now showing an error in the console SCRIPT1010: Expected identifier and showing a blank page.

答:
Issue fixed by updating the configuration

```<code>const {VueLoaderPlugin} = require('vue-loader');
let Encore = require('@symfony/webpack-encore');

Encore
  .setOutputPath('public/build/')
  .setPublicPath('/build')
  .cleanupOutputBeforeBuild()
  .enableSourceMaps(!Encore.isProduction())
  .addEntry('app', './assets/js/app.js')
  .addLoader({
      test: /\.vue$/,
      loader: 'vue-loader'
  })
  .enableBuildNotifications()

  .addPlugin(new VueLoaderPlugin())
  .enableSassLoader()
  .enableVersioning(Encore.isProduction())
 .configureBabel(function(babelConfig) {
    // add additional presets
    // babelConfig.presets.push('@babel/preset-flow');

    // no plugins are added by default, but you can add some
    // babelConfig.plugins.push('styled-jsx/babel');
  }, {
    // node_modules is not processed through Babel by default
    // but you can whitelist specific modules to process
    // includeNodeModules: ['foundation-sites'],

    // or completely control the exclude rule (note that you
    // can't use both "includeNodeModules" and "exclude" at
    // the same time)
    exclude: /loadash/
  });
</code>```

module.exports = Encore.getWebpackConfig();

Body:
How to make work the VueJS - Symfony application in IE11?

I'm using Babel Encore.

Already checked available answers in Stack but not working for me. Also, tried import the @babel/polyfill directly to the JS which is not working either.

Here is the webpack.config.js configuration of my application

const {VueLoaderPlugin} = require('vue-loader');
let Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .enableSourceMaps(!Encore.isProduction())
    .addEntry('app', './assets/js/app.js')
    // .enableVueLoader()
    .addLoader({
        test: /\.vue$/,
        loader: 'vue-loader'
    })
    .enableBuildNotifications()
    // .configureBabel(() => {}, {
    //     useBuiltIns: 'entry',
    //     corejs: 3
    // })

    .addPlugin(new VueLoaderPlugin())
    .enableSassLoader()
    .enableVersioning(Encore.isProduction())
;

module.exports = Encore.getWebpackConfig();

Note: The IE browser now showing an error in the console SCRIPT1010: Expected identifier and showing a blank page.

Body:
Issue fixed by updating the configuration

const {VueLoaderPlugin} = require('vue-loader');
let Encore = require('@symfony/webpack-encore');

Encore
  .setOutputPath('public/build/')
  .setPublicPath('/build')
  .cleanupOutputBeforeBuild()
  .enableSourceMaps(!Encore.isProduction())
  .addEntry('app', './assets/js/app.js')
  .addLoader({
      test: /\.vue$/,
      loader: 'vue-loader'
  })
  .enableBuildNotifications()

  .addPlugin(new VueLoaderPlugin())
  .enableSassLoader()
  .enableVersioning(Encore.isProduction())
 .configureBabel(function(babelConfig) {
    // add additional presets
    // babelConfig.presets.push('@babel/preset-flow');

    // no plugins are added by default, but you can add some
    // babelConfig.plugins.push('styled-jsx/babel');
  }, {
    // node_modules is not processed through Babel by default
    // but you can whitelist specific modules to process
    // includeNodeModules: ['foundation-sites'],

    // or completely control the exclude rule (note that you
    // can't use both "includeNodeModules" and "exclude" at
    // the same time)
    exclude: /loadash/
  });

module.exports = Encore.getWebpackConfig();


问:
How do i make a function in my .bash_profile accept input from stdin using pipe |
say i have a function of this nature in my .bash_profile

```<code>sayword(){
   echo $1
}
</code>```

now the command will be run like sayword hello
now i want the function to be able to  take input from other command using  unix pipe. something  like cat words.txt | sayword and it outputs each of the word in words.txt. How do i do that ?. I read a question here that talks about redirecting to dev/null but that doesn't seem to work .

答:
You can write it this way

function sayword() {
  if [ $# -eq 0 ]
  then
    while read input; do
      echo $input
    done
  else
    echo $1
  fi
}
```

<p>and then you can call it like this </p>

```date | sayword
```

Body:
say i have a function of this nature in my .bash_profile

sayword(){
   echo $1
}

now the command will be run like sayword hello
now i want the function to be able to  take input from other command using  unix pipe. something  like cat words.txt | sayword and it outputs each of the word in words.txt. How do i do that ?. I read a question here that talks about redirecting to dev/null but that doesn't seem to work .

Body:
You can write it this way

function sayword() {
  if [ $# -eq 0 ]
  then
    while read input; do
      echo $input
    done
  else
    echo $1
  fi
}

and then you can call it like this

date | sayword


问:
Splunk query filter out based on other event in same index
I have a index named Events

It contains a bunch of different events, all events have a property called EventName.
Now I want to do a query where I return everything that matches the following:

IF AccountId exists in event with EventName AccountCreated AND there is at least 1 event with EventName FavoriteCreated with the same AccountId -> return all events where EventName == AccountCreated

Example events:

AccountCreated

```<code>{
   "AccountId": 1234,
   "EventName": "AccountCreated",
   "SomeOtherProperty": "Some value",
   "Brand": "My Brand",
   "DeviceType": "Mobile",
   "EventTime": "2020-06-01T12:13:14Z"
}
</code>```

FavoriteCreated

```<code>{
   "AccountId": 1234,
   "EventName": "FavoritesCreated,
   "Brand": "My Brand",
   "DeviceType": "Mobile",
   "EventTime": "2020-06-01T12:13:14Z"
}
</code>```

Given the following two events, I would like to create 1 query that returns the AccountCreated event.

I've tried the following but it does not work, surely I must be missing something simple?

```<code>index=events EventName=AccountCreated
  [search index=events EventName=FavoriteCreated | dedup AccountId | fields AccountId]
| table AccountId, SomeOtherProperty
</code>```

Im expecting ~6000 hits here but Im only getting 2298 events. What am I missing?

UPDATE
Based on the answer given by @warren below, the following query works. The only problem is that it's using a JOIN which limits us to 50K results from the subsearch. When running this query I get 5900 results in total = Correct.

```<code>index=events EventName=AccountCreated AccountId=*
| stats count by AccountId, EventName
| fields - count
| join AccountId
    [ | search index=events EventName=FavoriteCreated AccountId=*
    | stats count by AccountId ]
| fields - count
| table AccountId, EventName
</code>```

I then tried to use his updated example like this but the problem seems to be that it returns FavoriteCreated events instead of AccountCreated.
When running this query I get 25 494 hits = Incorrect.

```<code>index=events AccountId=* (EventName=AccountCreated OR EventName=FavoriteCreated)
| stats values(EventName) as EventName by AccountId
| eval EventName=mvindex(EventName,-1)
| search EventName="FavoriteCreated"
| table AccountId, EventName
</code>```

Update 2 - WORKING
@warren is awesome, here is a full working query that only returns data from the AccountCreated events IF 1 or more FavoriteCreated event exists.

```<code>index=events AccountId=* (EventName=AccountCreated OR EventName=FavoriteCreated)
| stats
    values(Brand) as Brand,
    values(DeviceType) as DeviceType,
    values(Email) as Email,
    values(EventName) as EventName
    values(EventTime) as EventTime,
    values(Locale) as Locale,
    values(ClientIp) as ClientIp
  by AccountId
| where mvcount(EventName)>1
| eval EventName=mvindex(EventName,0)
| eval EventTime=mvindex(EventTime,0)
| eval ClientIp=mvindex(ClientIp,0)
| eval DeviceType=mvindex(DeviceType,0)
</code>```

答:
You found, perhaps, one factor of your issues - that subsearches are capped at 50,000 (when doing a join) events (or 60 seconds run time (or 10,000 results when you use a "normal" subsearch)).

Start by dumping dedup in favor of stats:

```<code>index=events EventName=AccountCreated AccountId=*
| stats count by AccountId, SomeOtherProperty [, more, fields, as, desired]
| fields - count
| search
    [ | search index=events EventName=FavoriteCreated AccountId=*
    | stats count by AccountId
    | fields - count]
<rest of search>
</code>```

If that doesn't get you where you want to be (ie, you still have too many results in your subsearch), you can try join:

```<code>index=events EventName=AccountCreated AccountId=*
| stats count by AccountId, SomeOtherProperty [, more, fields, as, desired]
| fields - count
| join AccountId
    [ | search index=events EventName=FavoriteCreated AccountId=*
    | stats count by AccountId ]
| fields - count
<rest of search>
</code>```

There are yet more ways of doing what you're looking for - but these two should get you a long ways toward your goal

Here's a join-less approach which'll show only "FavoriteCreated" events:

```<code>index=events AccountId=* (EventName=AccountCreated OR EventName=FavoriteCreated)
| stats values(EventName) as EventName values(SomeOtherProperty) as SomeOtherProperty by AccountId
| eval EventName=mvindex(EventName,-1)
| search EventName="FavoriteCreated"
</code>```

And here's one that shows "FavoriteCreated" only if there was also an "AccountCreated" event in the same timeframe:

```<code>index=events AccountId=* (EventName=AccountCreated OR EventName=FavoriteCreated)
| stats values(EventName) as EventName values(SomeOtherProperty) as SomeOtherProperty by AccountId
| where mvcount(EventName)>1
</code>```

And if you want to 'pretend' the values() didn't happen (ie, throw-out the "favoriteCreated" entry), add this:

```<code>| eval EventName=mvindex(EventName,0)
</code>```

Body:
I have a index named Events

It contains a bunch of different events, all events have a property called EventName.
Now I want to do a query where I return everything that matches the following:

IF AccountId exists in event with EventName AccountCreated AND there is at least 1 event with EventName FavoriteCreated with the same AccountId -> return all events where EventName == AccountCreated

Example events:

AccountCreated

{
   "AccountId": 1234,
   "EventName": "AccountCreated",
   "SomeOtherProperty": "Some value",
   "Brand": "My Brand",
   "DeviceType": "Mobile",
   "EventTime": "2020-06-01T12:13:14Z"
}

FavoriteCreated

{
   "AccountId": 1234,
   "EventName": "FavoritesCreated,
   "Brand": "My Brand",
   "DeviceType": "Mobile",
   "EventTime": "2020-06-01T12:13:14Z"
}

Given the following two events, I would like to create 1 query that returns the AccountCreated event.

I've tried the following but it does not work, surely I must be missing something simple?

index=events EventName=AccountCreated
  [search index=events EventName=FavoriteCreated | dedup AccountId | fields AccountId]
| table AccountId, SomeOtherProperty

Im expecting ~6000 hits here but Im only getting 2298 events. What am I missing?

UPDATE
Based on the answer given by @warren below, the following query works. The only problem is that it's using a JOIN which limits us to 50K results from the subsearch. When running this query I get 5900 results in total = Correct.

index=events EventName=AccountCreated AccountId=*
| stats count by AccountId, EventName
| fields - count
| join AccountId
    [ | search index=events EventName=FavoriteCreated AccountId=*
    | stats count by AccountId ]
| fields - count
| table AccountId, EventName

I then tried to use his updated example like this but the problem seems to be that it returns FavoriteCreated events instead of AccountCreated.
When running this query I get 25 494 hits = Incorrect.

index=events AccountId=* (EventName=AccountCreated OR EventName=FavoriteCreated)
| stats values(EventName) as EventName by AccountId
| eval EventName=mvindex(EventName,-1)
| search EventName="FavoriteCreated"
| table AccountId, EventName

Update 2 - WORKING
@warren is awesome, here is a full working query that only returns data from the AccountCreated events IF 1 or more FavoriteCreated event exists.

index=events AccountId=* (EventName=AccountCreated OR EventName=FavoriteCreated)
| stats
    values(Brand) as Brand,
    values(DeviceType) as DeviceType,
    values(Email) as Email,
    values(EventName) as EventName
    values(EventTime) as EventTime,
    values(Locale) as Locale,
    values(ClientIp) as ClientIp
  by AccountId
| where mvcount(EventName)>1
| eval EventName=mvindex(EventName,0)
| eval EventTime=mvindex(EventTime,0)
| eval ClientIp=mvindex(ClientIp,0)
| eval DeviceType=mvindex(DeviceType,0)

Body:
You found, perhaps, one factor of your issues - that subsearches are capped at 50,000 (when doing a join) events (or 60 seconds run time (or 10,000 results when you use a "normal" subsearch)).

Start by dumping dedup in favor of stats:

index=events EventName=AccountCreated AccountId=*
| stats count by AccountId, SomeOtherProperty [, more, fields, as, desired]
| fields - count
| search
    [ | search index=events EventName=FavoriteCreated AccountId=*
    | stats count by AccountId
    | fields - count]
<rest of search>

If that doesn't get you where you want to be (ie, you still have too many results in your subsearch), you can try join:

index=events EventName=AccountCreated AccountId=*
| stats count by AccountId, SomeOtherProperty [, more, fields, as, desired]
| fields - count
| join AccountId
    [ | search index=events EventName=FavoriteCreated AccountId=*
    | stats count by AccountId ]
| fields - count
<rest of search>

There are yet more ways of doing what you're looking for - but these two should get you a long ways toward your goal

Here's a join-less approach which'll show only "FavoriteCreated" events:

index=events AccountId=* (EventName=AccountCreated OR EventName=FavoriteCreated)
| stats values(EventName) as EventName values(SomeOtherProperty) as SomeOtherProperty by AccountId
| eval EventName=mvindex(EventName,-1)
| search EventName="FavoriteCreated"

And here's one that shows "FavoriteCreated" only if there was also an "AccountCreated" event in the same timeframe:

index=events AccountId=* (EventName=AccountCreated OR EventName=FavoriteCreated)
| stats values(EventName) as EventName values(SomeOtherProperty) as SomeOtherProperty by AccountId
| where mvcount(EventName)>1

And if you want to 'pretend' the values() didn't happen (ie, throw-out the "favoriteCreated" entry), add this:

| eval EventName=mvindex(EventName,0)


问:
What's the meaning of some sort of custom binary file?
In Head First C book, there is a "there are no dumb questions" section.

Are bitfields really just used to save space?

No, They're important if you need to read low-level binary information

Such as?

If you're reading or writing some sort of custom binary file.

What is that mean?

答:
You'll have to ask the author of that book what they were thinking. Generally, bit-fields do not save space in any way, but they may very likely lead to increased memory use. If you have a bit-field such as

```<code>struct foo { unsigned int a: 31; bool b: 1; }
</code>```

then the compiler is free to allocate 32 bits for the int part and 32 more bits for the bool part. And that is exactly what happens on gcc. The bit-field resulted in twice the memory use.

This has to do with various details regarding internal chunks of memory inside the bit-field mentioned in the C standard as "storage units". It's an abstract and poorly-specified concept. Where such a storage unit ends, what it can contain, how it reacts to different types isn't specified. It is however specified that the compiler is free to throw in padding bytes in the middle of the bit-field.

Furthermore, bit-fields are not useful for low-level binary information, because they are incredibly poorly defined by the C standard, to the point where they are completely non-portable and nearly useless. Details here: https://stackoverflow.com/a/6044223/584518

Always use unsigned integer types, bitwise operators and bit masks instead of bit-fields.

Body:
You'll have to ask the author of that book what they were thinking. Generally, bit-fields do not save space in any way, but they may very likely lead to increased memory use. If you have a bit-field such as

struct foo { unsigned int a: 31; bool b: 1; }

then the compiler is free to allocate 32 bits for the int part and 32 more bits for the bool part. And that is exactly what happens on gcc. The bit-field resulted in twice the memory use.

This has to do with various details regarding internal chunks of memory inside the bit-field mentioned in the C standard as "storage units". It's an abstract and poorly-specified concept. Where such a storage unit ends, what it can contain, how it reacts to different types isn't specified. It is however specified that the compiler is free to throw in padding bytes in the middle of the bit-field.

Furthermore, bit-fields are not useful for low-level binary information, because they are incredibly poorly defined by the C standard, to the point where they are completely non-portable and nearly useless. Details here: https://stackoverflow.com/a/6044223/584518

Always use unsigned integer types, bitwise operators and bit masks instead of bit-fields.


问:
C# ComboBox show names and use id's as values?
I'm displaying data from a database in a ComboBox in C#.

So I have a database table with an id and the name of it.

Now I try to display the name in the ComboBox and use the id as value. I know the are some other questions about this but unfortunately it didn't solve it for me.

The code I used now is like this:

```<code>            lblId.Visible = false;
            txtId.Visible = false;

            cbType.Items.Clear();
            con.Open();
            cmd = "SELECT Type_id, Type FROM type";

            SqlDataAdapter da = new SqlDataAdapter(cmd, con);
            DataTable dt = new DataTable();
            da.Fill(dt);

            foreach (DataRow dr in dt.Rows)
            {
                cbType.Items.Add(dr["Type_id"].ToString());
            }

            con.Close();
</code>```

Here I only ask for the id but I found something like this:

```<code>            cbType.DataSource = dt;
            cbType.DisplayMember = "Type";
            cbType.ValueMember = "Type_id";
</code>```

This displays the name.

But now I need to insert it into the database. For this I use the following code:

```<code>            string klant = txtKlant.Text;
            string kenteken = txtKenteken.Text;
            string type = cbType.SelectedItem.ToString();
            DateTime startdatum = dtpStartdatum.Value;
            DateTime einddatum = dtpEinddatum.Value;

            int result = 0;

            con.Open();

            cmd = "INSERT INTO reserveringen (Klant, Kenteken, Type_id, Startdatum, Einddatum) values(@Klant, @Kenteken, @Type_id, @Startdatum, @Einddatum)";
            command = new SqlCommand(cmd, con);

            command.Parameters.Add(new SqlParameter("@Klant", klant));
            command.Parameters.Add(new SqlParameter("@Kenteken", kenteken));
            command.Parameters.Add(new SqlParameter("@Type_id", type));
            command.Parameters.Add(new SqlParameter("@Startdatum", startdatum));
            command.Parameters.Add(new SqlParameter("@Einddatum", einddatum));

            result = command.ExecuteNonQuery();

            if (result > 0)
            {
                MessageBox.Show("De reservering is toegevoegd.");

                txtKlant.Text = "";
                txtKenteken.Text = "";
                cbType.Items.Clear();
                dtpStartdatum.Value = DateTime.Now;
                dtpEinddatum.Value = DateTime.Now;

                con.Close();

                bekijkReserveringen();
            }
            else
            {
                MessageBox.Show("Er is iets misgegaan, de reservering is niet toegevoegd.");
                con.Close();
            }
</code>```

But when I try to add it to the database I get te following error on result = command.ExecuteNonQuery();:
Conversion failed when converting the nvarchar value 'System.Data.DataRowView' to data type int.

When I use type I talk about name of the id because it's called like this in the database.

If I insert it with the first block of code it works fine, but for the user I need to show the name.

So does someone know what the problem could be?

Thanks in advance!

答: Use cbType.SelectedValue instead of SelectedItem and you should correctly get the value.

Body:
I'm displaying data from a database in a ComboBox in C#.

So I have a database table with an id and the name of it.

Now I try to display the name in the ComboBox and use the id as value. I know the are some other questions about this but unfortunately it didn't solve it for me.

The code I used now is like this:

            lblId.Visible = false;
            txtId.Visible = false;

            cbType.Items.Clear();
            con.Open();
            cmd = "SELECT Type_id, Type FROM type";

            SqlDataAdapter da = new SqlDataAdapter(cmd, con);
            DataTable dt = new DataTable();
            da.Fill(dt);

            foreach (DataRow dr in dt.Rows)
            {
                cbType.Items.Add(dr["Type_id"].ToString());
            }

            con.Close();

Here I only ask for the id but I found something like this:

            cbType.DataSource = dt;
            cbType.DisplayMember = "Type";
            cbType.ValueMember = "Type_id";

This displays the name.

But now I need to insert it into the database. For this I use the following code:

            string klant = txtKlant.Text;
            string kenteken = txtKenteken.Text;
            string type = cbType.SelectedItem.ToString();
            DateTime startdatum = dtpStartdatum.Value;
            DateTime einddatum = dtpEinddatum.Value;

            int result = 0;

            con.Open();

            cmd = "INSERT INTO reserveringen (Klant, Kenteken, Type_id, Startdatum, Einddatum) values(@Klant, @Kenteken, @Type_id, @Startdatum, @Einddatum)";
            command = new SqlCommand(cmd, con);

            command.Parameters.Add(new SqlParameter("@Klant", klant));
            command.Parameters.Add(new SqlParameter("@Kenteken", kenteken));
            command.Parameters.Add(new SqlParameter("@Type_id", type));
            command.Parameters.Add(new SqlParameter("@Startdatum", startdatum));
            command.Parameters.Add(new SqlParameter("@Einddatum", einddatum));

            result = command.ExecuteNonQuery();

            if (result > 0)
            {
                MessageBox.Show("De reservering is toegevoegd.");

                txtKlant.Text = "";
                txtKenteken.Text = "";
                cbType.Items.Clear();
                dtpStartdatum.Value = DateTime.Now;
                dtpEinddatum.Value = DateTime.Now;

                con.Close();

                bekijkReserveringen();
            }
            else
            {
                MessageBox.Show("Er is iets misgegaan, de reservering is niet toegevoegd.");
                con.Close();
            }

But when I try to add it to the database I get te following error on result = command.ExecuteNonQuery();:
Conversion failed when converting the nvarchar value 'System.Data.DataRowView' to data type int.

When I use type I talk about name of the id because it's called like this in the database.

If I insert it with the first block of code it works fine, but for the user I need to show the name.

So does someone know what the problem could be?

Thanks in advance!


问:
PowerShell Extracting text from a string
I'm really terrible when it comes to Regex and have stuck for a little while now. How can I get Person A from the following string?

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br>
Affected: Lorem<br>
Duty Officer: Person A<br>
Affected: Ipsum
</code>```

Thanks in advance!

答:
here's yet another method. it presumes the data is ONE multiline string and that there is only the one block of target text involved in that string.

what it does ...

builds the multiline string to work on

sets the prefix to split on

sets the suffix to split on

splits on the prefix

grabs the last item in the resulting array

splits on the suffix

grabs the 1st item in that array

trims away any leading or trailing whitespace

assigns the value to a $Var

displays that value

the code ...

```<code># this presumes the data is ONE multiline string
#     and that there are no other blocks of data in the string
$InStuff = @'
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br>
Affected: Lorem<br>
Duty Officer: Person A<br>
Affected: Ipsum
'@

$Prefix = 'Duty Officer:'
$Suffix = '<br>'

$DutyOfficer = (($InStuff -split $Prefix)[-1] -split $Suffix)[0].Trim()

$DutyOfficer
</code>```

output = Person A

Body:
I'm really terrible when it comes to Regex and have stuck for a little while now. How can I get Person A from the following string?

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

Affected: Lorem

Duty Officer: Person A

Affected: Ipsum

Thanks in advance!

Body:
here's yet another method. it presumes the data is ONE multiline string and that there is only the one block of target text involved in that string.

what it does ...

builds the multiline string to work on

sets the prefix to split on

sets the suffix to split on

splits on the prefix

grabs the last item in the resulting array

splits on the suffix

grabs the 1st item in that array

trims away any leading or trailing whitespace

assigns the value to a $Var

displays that value

the code ...

# this presumes the data is ONE multiline string
#     and that there are no other blocks of data in the string
$InStuff = @'
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br>
Affected: Lorem<br>
Duty Officer: Person A<br>
Affected: Ipsum
'@

$Prefix = 'Duty Officer:'
$Suffix = '<br>'

$DutyOfficer = (($InStuff -split $Prefix)[-1] -split $Suffix)[0].Trim()

$DutyOfficer

output = Person A


问:
Problem with shinyapps.io and Microsoft R Client - "rsconnect package out of date"
I'm running RStudio 1.3 and Microsoft R Client 3.5.2 (to give me access to the revoScaleR package) on a Windows 10 PC. I'm now trying to set myself up to share Shiny apps using shinyapps.io so that I can - in future - send various "widgets" to clients remotely.

I've followed the instructions on the shinyapps.io website to install the rsconnect package in RStudio. The package installed ok. However I was then instructed to run the following code to authorise the account:

```<code>rsconnect::setAccountInfo(name='xxxxxxxxxxxxx',
                          token='xxxxxxxxxxxxxx',
                          secret='xxxxxxxxxxxxxxx')
</code>```

(obviously I've hidden the details of name/token/secret)

And I had an error message:

Error: HTTP 426 GET https://api.shinyapps.io/v1/users/current/ The
  rsconnect package is out of date.  Please update to the latest
  available on CRAN.

Is this happening because by using Microsoft R Client 3.5.2 (instead of R 4.0.0 for example), I'm not able to access the very latest version of the package? If so, is there any way around this problem?

Thank you.

答: I seem to have fixed this by downloading a tar.gz file from CRAN and installing it manually. This gives the latest version (0.8.16) instead of the version I previously had (0.8.13).

Body:
I'm running RStudio 1.3 and Microsoft R Client 3.5.2 (to give me access to the revoScaleR package) on a Windows 10 PC. I'm now trying to set myself up to share Shiny apps using shinyapps.io so that I can - in future - send various "widgets" to clients remotely.

I've followed the instructions on the shinyapps.io website to install the rsconnect package in RStudio. The package installed ok. However I was then instructed to run the following code to authorise the account:

rsconnect::setAccountInfo(name='xxxxxxxxxxxxx',
                          token='xxxxxxxxxxxxxx',
                          secret='xxxxxxxxxxxxxxx')

(obviously I've hidden the details of name/token/secret)

And I had an error message:

Error: HTTP 426 GET https://api.shinyapps.io/v1/users/current/ The
  rsconnect package is out of date.  Please update to the latest
  available on CRAN.

Is this happening because by using Microsoft R Client 3.5.2 (instead of R 4.0.0 for example), I'm not able to access the very latest version of the package? If so, is there any way around this problem?

Thank you.


问:
How can I modify an struct in another .c?
I'm trying to add some data to my struct in another .c, but I'm getting segfault.

This is an example of my main.c.
I used "REGISTER *reg" to use the struct from the other file.

```<code>#include "otherfile.c"

int main(){
   char mom[30];
   char baby[30];
   int age;

   REGISTER *reg;

   scanf("%s", mom);
   scanf("%s", baby);
   scanf("%d", &age);

   set_mothersName(reg,mom);
   set_childsName(reg,baby);
   set_age(reg,age);

return 0;
}
</code>```

In the other file, I try this:

```<code>typedef struct register{
   char mothersName[30];
   char childsName[30];
   int age;
}REGISTER;

void set_mothersName(REGISTER *reg, char* name){
   strcpy(reg->mothersName,name);
}
void set_childsName(REGISTER *reg, char*name){
   strcpy(reg->childsName,name);
}
void set_age(REGISTER* reg, int age){
   reg->age = age;
}
</code>```

I think I'm using pointers wrong, but I can't know where and why.

答:
As user unholy Sheep says "REGISTER *reg; is an uninitialized pointer - it doesn't point to a valid REGISTER object."

Instead of declaring REGISTER *reg;, just declare as

```<code>REGISTER reg;
</code>```

and now call the functions as for example:

```<code>set_mothersName(&reg,mom);
</code>```

Body:
I'm trying to add some data to my struct in another .c, but I'm getting segfault.

This is an example of my main.c.
I used "REGISTER *reg" to use the struct from the other file.

#include "otherfile.c"

int main(){
   char mom[30];
   char baby[30];
   int age;

   REGISTER *reg;

   scanf("%s", mom);
   scanf("%s", baby);
   scanf("%d", &age);

   set_mothersName(reg,mom);
   set_childsName(reg,baby);
   set_age(reg,age);

return 0;
}

In the other file, I try this:

typedef struct register{
   char mothersName[30];
   char childsName[30];
   int age;
}REGISTER;

void set_mothersName(REGISTER *reg, char* name){
   strcpy(reg->mothersName,name);
}
void set_childsName(REGISTER *reg, char*name){
   strcpy(reg->childsName,name);
}
void set_age(REGISTER* reg, int age){
   reg->age = age;
}

I think I'm using pointers wrong, but I can't know where and why.

Body:
As user unholy Sheep says "REGISTER *reg; is an uninitialized pointer - it doesn't point to a valid REGISTER object."

Instead of declaring REGISTER *reg;, just declare as

REGISTER reg;

and now call the functions as for example:

set_mothersName(&reg,mom);