问:
Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem
I've been struggling with this for some time.

I've installed Rails 3, gem, mysql on my Snow Leopard machine. All was going well until I created my first project and tried to run

```<code>rails server
</code>```

Upon running this I get:

```<code>jontybrook$ rails server
/Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle: dlopen(/Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmysqlclient.16.dylib (LoadError)
  Referenced from: /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle
  Reason: image not found - /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle
    from /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2.rb:7
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler.rb:112:in `require'
    from /Users/jontybrook/Dropbox/CODING/simple_cms/config/application.rb:7
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:28:in `require'
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:28
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:27:in `tap'
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:27
    from script/rails:6:in `require'
    from script/rails:6
jontybrook$
</code>```

As far as I can tell the problem is with the mysql2 gem. MySQL seems to be running fine and my Gemfile references mysql2, my database.yml file seems ok also.

The error mentions

```<code>Reason: image not found - /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle
</code>```

And yet

```<code>jontybrook$ cd /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2
jontybrook$ ls
client.rb   em.rb       error.rb      mysql2.bundle result.rb
</code>```

MySQL2.bundle is there!?

If I use the old mysql gem, WEBrick boots fine. But that's not ideal, is it?

I've tried everything google can give me! Any help much appreciated.

答:
This is how it worked for me:

I ran the below command

sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib ~/.rvm/gems/ruby-1.9.2-p180/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle

My environments:

$ rails -v
Rails 3.0.6

$ mysql --version

mysql  Ver 14.14 Distrib 5.5.11, for osx10.6 (i386) using readline 5.1

$ ruby -v

ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.7.0]

Hope this helps someone.

Body:
I've been struggling with this for some time.

I've installed Rails 3, gem, mysql on my Snow Leopard machine. All was going well until I created my first project and tried to run

rails server

Upon running this I get:

jontybrook$ rails server
/Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle: dlopen(/Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmysqlclient.16.dylib (LoadError)
  Referenced from: /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle
  Reason: image not found - /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle
    from /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2.rb:7
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler.rb:112:in `require'
    from /Users/jontybrook/Dropbox/CODING/simple_cms/config/application.rb:7
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:28:in `require'
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:28
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:27:in `tap'
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:27
    from script/rails:6:in `require'
    from script/rails:6
jontybrook$

As far as I can tell the problem is with the mysql2 gem. MySQL seems to be running fine and my Gemfile references mysql2, my database.yml file seems ok also.

The error mentions

Reason: image not found - /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle

And yet

jontybrook$ cd /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2
jontybrook$ ls
client.rb   em.rb       error.rb      mysql2.bundle result.rb

MySQL2.bundle is there!?

If I use the old mysql gem, WEBrick boots fine. But that's not ideal, is it?

I've tried everything google can give me! Any help much appreciated.


来源: stackexchange

问:
How to overlay density histogram with gamma distribution fit in R?
I am new to R and would like to add a fit to a gamma distribution to my histogram. I would like the gamma distribution fit to overlay my histogram.

I am able to calculate the gamma distribution with the dgamma function and also with the fitdist function. However, I am not able to overlay this gamma distribution as a fit onto my histogram.

This is the code I tried:

```<code>hist(mydata, breaks = 30, freq = FALSE, col = "grey")

lines(dgamma(mydata, shape = 1))
</code>```

The code I tried does not overlay the gamma distribution fit onto my histogram. I only get the histogram without the fit.

答:
See if the following example can help in overlaying

a fitted line in black

a PDF graph in red, dotted

on a histogram.

First, create a dataset.

```<code>set.seed(1234)    # Make the example reproducible
mydata <- rgamma(100, shape = 1, rate = 1)
</code>```

Now fit a gamma distribution to the data.

```<code>param <- MASS::fitdistr(mydata, "gamma")
</code>```

This vector is needed for the fitted line.

```<code>x <- seq(min(mydata), max(mydata), length.out = 100)
</code>```

And plot them all.

```<code>hist(mydata, breaks = 30, freq = FALSE, col = "grey", ylim = c(0, 1))
curve(dgamma(x, shape = param$estimate[1], rate = param$estimate[2]), add = TRUE)
lines(sort(mydata), dgamma(sort(mydata), shape = 1),
      col = "red", lty = "dotted")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to R and would like to add a fit to a gamma distribution to my histogram. I would like the gamma distribution fit to overlay my histogram.

I am able to calculate the gamma distribution with the dgamma function and also with the fitdist function. However, I am not able to overlay this gamma distribution as a fit onto my histogram.

This is the code I tried:

hist(mydata, breaks = 30, freq = FALSE, col = "grey")

lines(dgamma(mydata, shape = 1))

The code I tried does not overlay the gamma distribution fit onto my histogram. I only get the histogram without the fit.

Body:
See if the following example can help in overlaying

a fitted line in black

a PDF graph in red, dotted

on a histogram.

First, create a dataset.

set.seed(1234)    # Make the example reproducible
mydata <- rgamma(100, shape = 1, rate = 1)

Now fit a gamma distribution to the data.

param <- MASS::fitdistr(mydata, "gamma")

This vector is needed for the fitted line.

x <- seq(min(mydata), max(mydata), length.out = 100)

And plot them all.

hist(mydata, breaks = 30, freq = FALSE, col = "grey", ylim = c(0, 1))
curve(dgamma(x, shape = param$estimate[1], rate = param$estimate[2]), add = TRUE)
lines(sort(mydata), dgamma(sort(mydata), shape = 1),
      col = "red", lty = "dotted")


问:
Excel - Array Formula Extend
I am using this array formula which works fine

```<code>=IF(ROWS(K$62:K62)>COUNTIF(accounts_table[§],"<>J"),"",INDEX(accounts_table[Account Name],SMALL(IF(accounts_table[§]<>"J",ROW(accounts_table[§])-ROW(Ledger!$H$17)+1),ROWS($K$62:K62))))
</code>```

However, I need to extend this for multiple COUNTIF Criteria:

```<code>accounts_table[§],"<>J"
accounts_table[§],"<>T"
accounts_table[§],"<>P"
</code>```

I haven't been successful in doing this. I have tried this but doesn't work:

```<code>=IF(OR(ROWS(K$62:K62)>COUNTIF(accounts_table[§],"<>J"),ROWS(K$62:K62)>COUNTIF(accounts_table[§],"<>T")),"",INDEX(accounts_table[Account Name],SMALL(IF(OR(accounts_table[§]<>"J",accounts_table[§]<>"T"),ROW(accounts_table[§])-ROW(Ledger!$H$17)+1),ROWS($K$62:K62))))
</code>```

答:
You have to make two adjustments to the formula:

(1) I was talking total rubbish previously, it is correct that the easiest thing to do is to use Countifs. You could subtract the two separate counts of J and T from the total, but it's longer.

(2) You can't use AND or OR in array formulas - they only give you one result for the entire array instead of iterating over the cells like you want them to. Instead you have to use multiply (*) or add (+). Here you are trying to include cells which are both not equal to J and not equal to T, so again you need AND logic, therefore you want to multiply.

```<code>=IF(ROWS(K$62:K62)>COUNTIFS(accounts_table[§],"<>J",accounts_table[§],"<>T"),"",INDEX(accounts_table[Account Name],SMALL(IF((accounts_table[§]<>"J")*(accounts_table[§]<>"T"),ROW(accounts_table[§])-ROW(Ledger!$H$2)+1),ROWS(K$62:$K62))))
</code>```

Extending it to more variables is left as an exercise for the reader...unless you have a real lot of values to exclude in which case another approach might be needed.

Title: Excel - Array Formula Extend

Body:
I am using this array formula which works fine

=IF(ROWS(K$62:K62)>COUNTIF(accounts_table[§],"<>J"),"",INDEX(accounts_table[Account Name],SMALL(IF(accounts_table[§]<>"J",ROW(accounts_table[§])-ROW(Ledger!$H$17)+1),ROWS($K$62:K62))))

However, I need to extend this for multiple COUNTIF Criteria:

accounts_table[§],"<>J"
accounts_table[§],"<>T"
accounts_table[§],"<>P"

I haven't been successful in doing this. I have tried this but doesn't work:

=IF(OR(ROWS(K$62:K62)>COUNTIF(accounts_table[§],"<>J"),ROWS(K$62:K62)>COUNTIF(accounts_table[§],"<>T")),"",INDEX(accounts_table[Account Name],SMALL(IF(OR(accounts_table[§]<>"J",accounts_table[§]<>"T"),ROW(accounts_table[§])-ROW(Ledger!$H$17)+1),ROWS($K$62:K62))))

Body:
You have to make two adjustments to the formula:

(1) I was talking total rubbish previously, it is correct that the easiest thing to do is to use Countifs. You could subtract the two separate counts of J and T from the total, but it's longer.

(2) You can't use AND or OR in array formulas - they only give you one result for the entire array instead of iterating over the cells like you want them to. Instead you have to use multiply (*) or add (+). Here you are trying to include cells which are both not equal to J and not equal to T, so again you need AND logic, therefore you want to multiply.

=IF(ROWS(K$62:K62)>COUNTIFS(accounts_table[§],"<>J",accounts_table[§],"<>T"),"",INDEX(accounts_table[Account Name],SMALL(IF((accounts_table[§]<>"J")*(accounts_table[§]<>"T"),ROW(accounts_table[§])-ROW(Ledger!$H$2)+1),ROWS(K$62:$K62))))

Extending it to more variables is left as an exercise for the reader...unless you have a real lot of values to exclude in which case another approach might be needed.


问:
Creating a lambda function dynamically
Is there some way I could create a lambda function dynamically? For example,

```<code>f = lambda t : (1 + 32*t + 23*np.power(t,2) + 23*np.power(t,3) + 23*np.power(t,4))
</code>```

in the above lambda function f, I want to increment the value of t in 23*np.power(t,2) and want it to go until 467. So:

```<code>f = lambda t : (1 + 32*t + 23*np.power(t,2) + .. + 23*np.power(t,467))
</code>```

Is there a way I could do this automatically?

答: You might you something like f = lambda t : 1 + sum(23 * np.power(t, i) for i in range(1, 467)). You can't use for loops or something like that, but simple expressions, function calls etc. you can

Title: Creating a lambda function dynamically

Body:
Is there some way I could create a lambda function dynamically? For example,

f = lambda t : (1 + 32*t + 23*np.power(t,2) + 23*np.power(t,3) + 23*np.power(t,4))

in the above lambda function f, I want to increment the value of t in 23*np.power(t,2) and want it to go until 467. So:

f = lambda t : (1 + 32*t + 23*np.power(t,2) + .. + 23*np.power(t,467))

Is there a way I could do this automatically?


问:
How to fix problem with Roboto font load in Google Chrome?
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

```<code>GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND
</code>```

I tried to import directy in the CSS and in the HTML this:

```<code>@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}
</code>```

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>
        <style>
            @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
        </style>
        <!-- JQuery Mobile -->
        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>
        <!-- Project CSS -->
        <link rel="stylesheet" href="./css/style.css"></link>
        <!-- NativeDroid2 CSS -->
        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>
    </head>
    <body>
        <div data-role="main" class="ui-content">
            <form method="post">
                <div class="img-container">
                    <img src="img/logo_gemott.png" alt="No es pot carregar la imatge" height="110" width="350">
                </div>

                <div>
                    <h2>Registre</h2>
                    <hr>
                    <label for="mail"><b>Correu electrònic</b></label>
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    <label for="psw"><b>Contrasenya</b></label>
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>
                    <div class="center-text">
                        <p>Al registrar-te, acceptes els <a href=#>termes de privacitat</a></p>
                        <p>Ja estàs <a href="login.html">registrat?</a></p>
                    </div>
                </div>

                <a href="javascript:registry()" class="ui-btn ui-btn-raised clr-primary">Registrar-me</a>

                <div class="img-container" id="uab-logo">
                    <img src="img/UAB.jpg" alt="No es pot carrerar la imatge" height="150" witdh="150">
                </div>
            </form>
        </div>
        <!-- JQuery -->
        <script type="text/javascript" src="jquery/jquery-2.2.4.js"></script>
        <!-- Project Js -->
        <script type="text/javascript" src="js/app.js"></script>
        <!-- JQuery Mobile -->
        <script type="text/javascript" src="jquery/jquery.mobile-1.4.5.min.js"></script>
        <!-- NativeDroid2 Js -->
        <script type="text/javascript" src="bower_components/Waves/dist/waves.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/nd2settings.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/js/nativedroid2.js"></script>
    </body>
</html>
</code>```

答:
The standard way to import a Google Font, is placing a link tag in the head section of your HTML:

```<code><link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
</code>```

At least in the past, using @import was problematic when including larger files (font files are quite large) because browsers waited tor the file to download before continuing to render the page.

Your description gives the impression things have improved with Firefox, but not with Chrome.

So I suggest you include the link tag in your HTML file's head, remove the style tag and also remove the line starting with @import from your CSS.

As the OP reported an error message, I'm attaching a short example:

```<code><html>
    <head>
        <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
        <style>
            body {
                font-family:'Roboto'
            }
        </style>
    </head>

    <body>
        <h1>Test</h1>
    </body>
</html>
</code>```

Body:
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND

I tried to import directy in the CSS and in the HTML this:

@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

<!DOCTYPE html>

        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>

        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>

        <link rel="stylesheet" href="./css/style.css"></link>

        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>

            <form method="post">

Registre

                    Correu electrònic
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    Contrasenya
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>

Al registrar-te, acceptes els termes de privacitat

Ja estàs registrat?

                Registrar-me

            </form>

Body:
The standard way to import a Google Font, is placing a link tag in the head section of your HTML:

<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">

At least in the past, using @import was problematic when including larger files (font files are quite large) because browsers waited tor the file to download before continuing to render the page.

Your description gives the impression things have improved with Firefox, but not with Chrome.

So I suggest you include the link tag in your HTML file's head, remove the style tag and also remove the line starting with @import from your CSS.

As the OP reported an error message, I'm attaching a short example:

<html>
    <head>
        <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
        <style>
            body {
                font-family:'Roboto'
            }
        </style>
    </head>

    <body>
        <h1>Test</h1>
    </body>
</html>


问:
UIView Function Bug
I am trying to create a UIView function which when called will return a view with 2 buttons, a TextView in some stackViews. I am having trouble and at the moment all it is returning is an empty rectangle(it's not showing any of the info inside). What am I doing wrong?

```<code>func returnView(text1: String, text2: String) -> UIView {

let customView = UIView()
let firstButton = UIButton()
let secondButton = UIButton()
let textView = UITextView()

customView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 90)
customView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

firstButton.setTitle(text1, for: .normal)
firstButton.setTitleColor(UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0), for: .normal)
firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)

secondButton.setTitle("apple", for: .normal)
secondButton.setTitleColor(UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0), for: .normal)
secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)

textView.text = text2

let stack1 = UIStackView()
stack1.axis = .horizontal
stack1.alignment = .fill
stack1.distribution = .fillEqually

stack1.addArrangedSubview(firstButton)
stack1.addArrangedSubview(secondButton)

let stack2 = UIStackView()
stack2.axis = .horizontal
stack2.alignment = .fill
stack2.distribution = .fillEqually

stack2.addArrangedSubview(textView)

let fullStack = UIStackView()
fullStack.axis = .vertical
fullStack.alignment = .fill
fullStack.distribution = .fillEqually
fullStack.addArrangedSubview(stack1)
fullStack.addArrangedSubview(stack2)

customView.addSubview(fullStack)

stack1.translatesAutoresizingMaskIntoConstraints = false
stack2.translatesAutoresizingMaskIntoConstraints = false
fullStack.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([fullStack.topAnchor.constraint(equalTo: customView.topAnchor), fullStack.leftAnchor.constraint(equalTo: customView.leftAnchor), fullStack.rightAnchor.constraint(equalTo: customView.rightAnchor), fullStack.heightAnchor.constraint(equalTo: customView.heightAnchor), (fullStack.centerXAnchor.constraint(equalTo: customView.centerXAnchor))])

return customView
}
</code>```

EDIT I am calling it from this function:

```<code>func renderAttachment() {

    let view = returnView(text1: "test1", text2: "test2")

    // Render Image
    let renderer = UIGraphicsImageRenderer(size: view.frame.size)
    let image = renderer.image {
        view.layer.render(in: $0.cgContext)
    }

    // Create Attachment
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(origin: .zero, size: image.size)

    // Current Attributed String
    let atStr = NSMutableAttributedString(attributedString: textview.attributedText)

    // Insert Attachment
    let attachmentAtStr = NSAttributedString(attachment: attachment)
    if let selectedRange = textview.selectedTextRange {
        let cursorIndex = textview.offset(from: textview.beginningOfDocument, to: selectedRange.start)
        atStr.insert(attachmentAtStr, at: cursorIndex)
        atStr.addAttributes(self.textview.typingAttributes, range: NSRange(location: cursorIndex, length: 1))
    } else {
        atStr.append(attachmentAtStr)
    }
    textview.attributedText = atStr
    print(atStr)
}
</code>```

This is how it shows in my textView(just an empty box!)

答:
You are rendering a view that hasn't been added to a view hierarchy, so you need to trigger layout by calling view.layoutIfNeeded():

```<code>let view = returnView(text1: "test1", text2: "test2")
view.layoutIfNeeded()

// Render Image
let renderer = UIGraphicsImageRenderer(size: view.frame.size)
let image = renderer.image {
    view.layer.render(in: $0.cgContext)
}
</code>```

Title: UIView Function Bug

Body:
I am trying to create a UIView function which when called will return a view with 2 buttons, a TextView in some stackViews. I am having trouble and at the moment all it is returning is an empty rectangle(it's not showing any of the info inside). What am I doing wrong?

func returnView(text1: String, text2: String) -> UIView {

let customView = UIView()
let firstButton = UIButton()
let secondButton = UIButton()
let textView = UITextView()

customView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 90)
customView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

firstButton.setTitle(text1, for: .normal)
firstButton.setTitleColor(UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0), for: .normal)
firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)

secondButton.setTitle("apple", for: .normal)
secondButton.setTitleColor(UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0), for: .normal)
secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)

textView.text = text2

let stack1 = UIStackView()
stack1.axis = .horizontal
stack1.alignment = .fill
stack1.distribution = .fillEqually

stack1.addArrangedSubview(firstButton)
stack1.addArrangedSubview(secondButton)

let stack2 = UIStackView()
stack2.axis = .horizontal
stack2.alignment = .fill
stack2.distribution = .fillEqually

stack2.addArrangedSubview(textView)

let fullStack = UIStackView()
fullStack.axis = .vertical
fullStack.alignment = .fill
fullStack.distribution = .fillEqually
fullStack.addArrangedSubview(stack1)
fullStack.addArrangedSubview(stack2)

customView.addSubview(fullStack)

stack1.translatesAutoresizingMaskIntoConstraints = false
stack2.translatesAutoresizingMaskIntoConstraints = false
fullStack.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([fullStack.topAnchor.constraint(equalTo: customView.topAnchor), fullStack.leftAnchor.constraint(equalTo: customView.leftAnchor), fullStack.rightAnchor.constraint(equalTo: customView.rightAnchor), fullStack.heightAnchor.constraint(equalTo: customView.heightAnchor), (fullStack.centerXAnchor.constraint(equalTo: customView.centerXAnchor))])

return customView
}

EDIT I am calling it from this function:

func renderAttachment() {

    let view = returnView(text1: "test1", text2: "test2")

    // Render Image
    let renderer = UIGraphicsImageRenderer(size: view.frame.size)
    let image = renderer.image {
        view.layer.render(in: $0.cgContext)
    }

    // Create Attachment
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(origin: .zero, size: image.size)

    // Current Attributed String
    let atStr = NSMutableAttributedString(attributedString: textview.attributedText)

    // Insert Attachment
    let attachmentAtStr = NSAttributedString(attachment: attachment)
    if let selectedRange = textview.selectedTextRange {
        let cursorIndex = textview.offset(from: textview.beginningOfDocument, to: selectedRange.start)
        atStr.insert(attachmentAtStr, at: cursorIndex)
        atStr.addAttributes(self.textview.typingAttributes, range: NSRange(location: cursorIndex, length: 1))
    } else {
        atStr.append(attachmentAtStr)
    }
    textview.attributedText = atStr
    print(atStr)
}

This is how it shows in my textView(just an empty box!)

Body:
You are rendering a view that hasn't been added to a view hierarchy, so you need to trigger layout by calling view.layoutIfNeeded():

let view = returnView(text1: "test1", text2: "test2")
view.layoutIfNeeded()

// Render Image
let renderer = UIGraphicsImageRenderer(size: view.frame.size)
let image = renderer.image {
    view.layer.render(in: $0.cgContext)
}


问:
What is the most elegant way to cast a variable you just received as an argument?
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

```<code>public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}
</code>```

Or am I missing the point here? Is there a better way to handle this in general?

答:
Personally I like

```<code>Graphics2D g2 = g as Graphics2D;
if (g2 == null)
//do stuff
</code>```

But as said before, no reason to make it anymore complicated than it is :P

OwnerDisplayName: spligak

ContentLicense: CC BY-SA 2.5

Body:
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}

Or am I missing the point here? Is there a better way to handle this in general?

Body:
Personally I like

Graphics2D g2 = g as Graphics2D;
if (g2 == null)
//do stuff

But as said before, no reason to make it anymore complicated than it is :P

OwnerDisplayName: Meeh


问:
DB backend webapp testing in java [tool needed]
I want to create a test suit for my java web application. Its a JSP applications with JDBC connectivity . My requirements are as follows,

1 - I should be able to test my database logic (Queries etc) through my models.

2 - Its great if i could test my .jsp pages as well (if possible)

After doing some research I found that DBUnit is good for database backend system testing, but unfortunately i couldnt find any good resource as a starter

What are you all think about testing options I have and it would be great if you could post some links to resources/ examples as well

EDIT:

and I have come across with mock objects (like JMock..), wonder I could use it as a replacement for DBUnit ?

thanks in advance

cheers

sameera

答:
It's not clear from your question if you want to run Integration tests (Front end + back end) or Unit Tests against you Database layer.

If you need a tool that allows you to write Integration tests, you should definitively look at Selenium.
With Selenium you can generate functional tests by simply navigating your web site (JSP pages) and asserting that stuff on the page exists or it's equal to some values.

Selenium comes with a Firefox plugin that will basically generate the code for you. You can replay the test in the browser or export them as Java code and make them part of your test suite. Selenium is an invaluable tool.

The drawback of using a tool like Selenium is that your application need to be deployed somewhere before you can run your test suite. This may be a limitation if you plan to run automated tests generated using Selenium.

If you are only interested in testing your database access code (DAO, Data Access Layer) DBUnit is the perfect tool.
Generally, DBUnit is used to initialize the database tables before testing and, less often, to run assertions on the database content. DBUnit uses an XML based format to represent the data that will be inserted into the database.

The XML files containing the data to pre-populate the db are normally triggered by a build script (Ant, Maven, etc.) or directly in your unit test code.
I have used both approaches, it really depends on how your code is structured and how you access the database (Hibernate, Spring+Hibernate, JDBC...).

If your database is not too big, I'd recommend you populate it just before running your test suite. Alternatively, you can populate only the tables that you are interested in testing prior to every test.

Here is a link to Unitils, that is an additional library that can be used on top of DBUnit to simplify the database testing strategy. I think it can be used as a reference to get you started:
http://www.unitils.org/tutorial.html#Database_testing

Here is anoter link (quite old, 2004) showing the basic mechanics of DBUnit:

http://onjava.com/pub/a/onjava/2004/01/21/dbunit.html

ContentLicense: CC BY-SA 3.0


问:
Is there a way to only play audio from a video?
I want to play a downloaded talk show, but I only want to play audio. Whenever I do MediaPlayer.media().play("video.mp4"), it opens the video in a pop-up window. Is there a way to hide that window, or to disable video track if needed?

I've tried setting renderer to null, but it doesn't do anything

```<code>mediaPlayer.setRenderer(null);
</code>```

```<code>String url = "video.mp4";
mediaPlayer.media().play(url);
</code>```

I'd like to only play Audio from a video, but I always get a pop-up playing video track.

答:
You can do this with custom VLC switches passed as media player factory arguments:

```<code>MediaPlayerFactory factory = new MediaPlayerFactory("--novideo");
AudioMediaPlayerComponent mediaPlayer = new AudioMediaPlayerComponent(factory);
</code>```

You don't need to use AudioMediaPlayerComponent, it just happens to be the most convenient.

Body:
I want to play a downloaded talk show, but I only want to play audio. Whenever I do MediaPlayer.media().play("video.mp4"), it opens the video in a pop-up window. Is there a way to hide that window, or to disable video track if needed?

I've tried setting renderer to null, but it doesn't do anything

mediaPlayer.setRenderer(null);

String url = "video.mp4";
mediaPlayer.media().play(url);

I'd like to only play Audio from a video, but I always get a pop-up playing video track.

Body:
You can do this with custom VLC switches passed as media player factory arguments:

MediaPlayerFactory factory = new MediaPlayerFactory("--novideo");
AudioMediaPlayerComponent mediaPlayer = new AudioMediaPlayerComponent(factory);

You don't need to use AudioMediaPlayerComponent, it just happens to be the most convenient.


问:
just making the query in parent component and not rendering anything and sending all data as props
I want to make one query in my parent component and not render anything and pass that data onto some child component .
How can we achieve this in react and graphql ?

```<code>               {
                   ({loading,error,data}) =>{
                     if(loading) return <h4>Loading...</h4>
                       if(error) console.log(error)
                       console.log("graphql data is ",data);

                       return(
                       <div className="body">
                                  </div>

                               </div>

                       );
                 }
               }

              </Query>
</code>```

I want to make this query in my parent component and pass it as child components .
In case of simple apis ,I could simply call the api and store it in my redux and then get those data as props in child .
How can same be achieved without rendering anything ?

答:
You can create a component just to render its children. Here is an example how to do it in react.

Something like this.

```<code>class Query extends Component {
  state = {
    loading: true,
    error: {},
    data: {}
  }
  componentDidMount() {
    //do the apicall here
    this.setState({ loading: false, data: { header: "may the force be with you" } });
  }

  render() {
    const { state: props, props: { children } } = this;

    // return the data here
    // passing state as props here after renaming state to props
    return children(props);
  }
}
</code>```

Using react state instead of redux. You can make this connected component if you want to use redux. And the use the component like this.

```<code>    <Query>
      {
        ({ loading, error, data }) => {
          if (loading) return <>Loading.......</>
          if (Object.keys(error).length > 0) return <>Some Error Handler</>
          if (data) return (
            <>
              <img src={logo} className="App-logo" alt="logo" />
              <a
                className="App-link"
                href="https://reactjs.org"
                target="_blank"
                rel="noopener noreferrer"
              >
                {data.header}
              </a>
            </>
          )
        }
      }
    </Query>
</code>```

Body:
I want to make one query in my parent component and not render anything and pass that data onto some child component .
How can we achieve this in react and graphql ?

               {
                   ({loading,error,data}) =>{
                     if(loading) return
Loading...

                       if(error) console.log(error)
                       console.log("graphql data is ",data);

                       return(

                       );
                 }
               }

              </Query>

I want to make this query in my parent component and pass it as child components .
In case of simple apis ,I could simply call the api and store it in my redux and then get those data as props in child .
How can same be achieved without rendering anything ?

Body:
You can create a component just to render its children. Here is an example how to do it in react.

Something like this.

class Query extends Component {
  state = {
    loading: true,
    error: {},
    data: {}
  }
  componentDidMount() {
    //do the apicall here
    this.setState({ loading: false, data: { header: "may the force be with you" } });
  }

  render() {
    const { state: props, props: { children } } = this;

    // return the data here
    // passing state as props here after renaming state to props
    return children(props);
  }
}

Using react state instead of redux. You can make this connected component if you want to use redux. And the use the component like this.

    <Query>
      {
        ({ loading, error, data }) => {
          if (loading) return <>Loading.......</>
          if (Object.keys(error).length > 0) return <>Some Error Handler</>
          if (data) return (
            <>
              <img src={logo} className="App-logo" alt="logo" />
              <a
                className="App-link"
                href="https://reactjs.org"
                target="_blank"
                rel="noopener noreferrer"
              >
                {data.header}
              </a>
            </>
          )
        }
      }
    </Query>


问:
Help with unexpected LINQ query results
I have these 4 tables:

This query

```<code>    var query = db.Authors
                    .Where(x=> x.ItemAuthors
                        .Any(z=> z.Item.CategoryItems
                            .Any(b=> b.categoryID == 10)))
                    .Select(ci=> new
                {
                    authorText = string.Format("{0} ({1})", ci.text,
                                                       ci.ItemAuthors.Count()),
                    authorId = ci.authorID
                });
</code>```

Which populates an Authors drop down list which works as expected. The problem is when I try to count the number of items assigned to each author it counts every item the author has in the entire items table.

So for example if author one has 10 books total, but only 2 of these books show up in the above query, I still get a count for 10 books. When I bind that same query to a control I get back the correct data, it's just the count operation that won't work correctly.

To reiterate I bound it to a gridview and I only see one book per author, not all of the books the author wrote. So it appears my query should be correct.

Update: @Jon Skeet, I wasn't able to use the let operator as I'm conditionally building my query. I solved my problem by using the original query to get the count. Here's how I modified my original Count() syntax:

```<code>var query = authors2.Select(x => new
            {

                authorText = string.Format("{0} ({1})",x.text, x.ItemAuthors
                        .Where(qq=> qq.Item.CategoryItems
                            .Any(xt=> xt.categoryID == 10))
                            .Count()),
                authorId = x.authorID

            });
</code>```

答:
You're using i.Author.ItemAuthors.Count() which goes straight back to the full table. I suspect you may want something like:

```<code>var query = from ia in db.ItemAuthors
            let count = ia.CategoryItems.Count(t => t.categoryID == 10))
            where count > 0
            select new
            {
                authorText = string.Format("{0} ({1})", i.Author.text, count),
                authorId = i.Author.authorID
            };
</code>```

On the other hand, I would expect that to give one result per ItemAuthor which isn't really what you want. If you want a list of authors, I'd expect a query starting in the Authors table:

```<code>var query = from author in db.ItemAuthors
            let count = author.Items
                              .Count(ia => ia.Item.CategoryItems
                                                  .Any(ci => ci.CategoryID == 10))
            select new
            {
                authorText = string.Format("{0} ({1})", author.text, count),
                authorId = author.authorID
            };
</code>```

In other words, for each author, find out how many items have at least one category with ID 10... and then report that many items.

It's somewhat complex because of the various 1-many relationships (each book having potentially multiple authors and multiple categories).

Title: Help with unexpected LINQ query results

Body:
I have these 4 tables:

This query

    var query = db.Authors
                    .Where(x=> x.ItemAuthors
                        .Any(z=> z.Item.CategoryItems
                            .Any(b=> b.categoryID == 10)))
                    .Select(ci=> new
                {
                    authorText = string.Format("{0} ({1})", ci.text,
                                                       ci.ItemAuthors.Count()),
                    authorId = ci.authorID
                });

Which populates an Authors drop down list which works as expected. The problem is when I try to count the number of items assigned to each author it counts every item the author has in the entire items table.

So for example if author one has 10 books total, but only 2 of these books show up in the above query, I still get a count for 10 books. When I bind that same query to a control I get back the correct data, it's just the count operation that won't work correctly.

To reiterate I bound it to a gridview and I only see one book per author, not all of the books the author wrote. So it appears my query should be correct.

Update: @Jon Skeet, I wasn't able to use the let operator as I'm conditionally building my query. I solved my problem by using the original query to get the count. Here's how I modified my original Count() syntax:

var query = authors2.Select(x => new
            {

                authorText = string.Format("{0} ({1})",x.text, x.ItemAuthors
                        .Where(qq=> qq.Item.CategoryItems
                            .Any(xt=> xt.categoryID == 10))
                            .Count()),
                authorId = x.authorID

            });

Body:
You're using i.Author.ItemAuthors.Count() which goes straight back to the full table. I suspect you may want something like:

var query = from ia in db.ItemAuthors
            let count = ia.CategoryItems.Count(t => t.categoryID == 10))
            where count > 0
            select new
            {
                authorText = string.Format("{0} ({1})", i.Author.text, count),
                authorId = i.Author.authorID
            };

On the other hand, I would expect that to give one result per ItemAuthor which isn't really what you want. If you want a list of authors, I'd expect a query starting in the Authors table:

var query = from author in db.ItemAuthors
            let count = author.Items
                              .Count(ia => ia.Item.CategoryItems
                                                  .Any(ci => ci.CategoryID == 10))
            select new
            {
                authorText = string.Format("{0} ({1})", author.text, count),
                authorId = author.authorID
            };

In other words, for each author, find out how many items have at least one category with ID 10... and then report that many items.

It's somewhat complex because of the various 1-many relationships (each book having potentially multiple authors and multiple categories).


问:
How to fix date formatting using python3
I have data with the date format as follows:

    date_format = 190410
    year  = 19
    month = 04
    date  = 10
```

<p>I want to change the date format, to be like this:</p>

```date_format = 10-04-2019
```

How do I solve this problem?

答:
This is what you want(Notice that you have to change your format)

import datetime

date_format = '2019-04-10'

date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')

print(date_time_obj)
```

<p>Here is an other example</p>

<pre class="lang-py prettyprint-override"><code>import datetime

date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
</code>```

You can also do this

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

print(date)
```

There are many ways to achieve what you want.

Body:
I have data with the date format as follows:

    date_format = 190410
    year  = 19
    month = 04
    date  = 10

I want to change the date format, to be like this:

date_format = 10-04-2019

How do I solve this problem?

Body:
This is what you want(Notice that you have to change your format)

import datetime

date_format = '2019-04-10'

date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')

print(date_time_obj)

Here is an other example

import datetime

date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)

You can also do this

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

print(date)

There are many ways to achieve what you want.


问:
How to delete duplicate rows in MySQL table?
I am using the following query, which I saw from another stackoverflow question but I am getting error.

```<code>delete from mytable
 where myid not in (
    select max(myid)
      from mytable
group by myid2)
</code>```

Error:

#1093 - Table 'mytable' is specified twice, both as a target for 'DELETE' and as a separate source for data

Edit 2:

I also tried this query:

```<code>delete from mytable
 where myid in (
    SELECT
    myid, COUNT(*)
FROM
    mytable
GROUP BY
    myid2
HAVING
    COUNT(*) > 1)
</code>```

And got this error:

#1241 - Operand should contain 1 column(s)

答:
In MySQL, you need to use a JOIN for this purpose.  I assume you mean something like this:

```<code>delete t
   from mytable t left join
        (select max(myid) as myid
         from mytable
         group by myid2
        ) tt
        on t.myid = tt.myid
   where tt.myid is null;
</code>```

Where ? is whatever you really want to group by.  Your version will not delete anything because the group by and max() use the same column.

Body:
I am using the following query, which I saw from another stackoverflow question but I am getting error.

delete from mytable
 where myid not in (
    select max(myid)
      from mytable
group by myid2)

Error:

#1093 - Table 'mytable' is specified twice, both as a target for 'DELETE' and as a separate source for data

Edit 2:

I also tried this query:

delete from mytable
 where myid in (
    SELECT
    myid, COUNT(*)
FROM
    mytable
GROUP BY
    myid2
HAVING
    COUNT(*) > 1)

And got this error:

#1241 - Operand should contain 1 column(s)

Body:
In MySQL, you need to use a JOIN for this purpose.  I assume you mean something like this:

delete t
   from mytable t left join
        (select max(myid) as myid
         from mytable
         group by myid2
        ) tt
        on t.myid = tt.myid
   where tt.myid is null;

Where ? is whatever you really want to group by.  Your version will not delete anything because the group by and max() use the same column.


问:
How do I scale the height of a div the same way that a div with an image does?
I have 2 divs that are floated next to each other. In one of the divs I have an image that scales (both it´s height and width) when I decrease the size of the browser window. In the other div I have some other content, but this is only being scaled in width when I decrease the size of the browser window. I want both of the divs to have the same height at all times, even when they are being scaled. Is this possible?

If you want a live preview, please check out this link:
http://jjberg.com/cipher/index.html

I know part of the problem is that I´ve actually set a height of 500px to the cipherSide div. This is because so far I haven´t been able to make the height of this div closer to the height of the pinupSide div in any other way.

I tried to copy the declarations from the pinupSide and pinUpGirl to the cipherSide and verticalAlign divs, but to no avail. This only pushed the content in the cipherSide div all the way to the top.

 Dirty Diana

Dirty Diana wants to send dirty love messages to her husband, but she does not want Big Brother to know about it. Try out the tool I made for her!

      <textarea rows="10" placeholder="Insert the text you want to cipher or decipher here!" required></textarea>
      <button id="cipherIT">Cipher It!</button>
      <button id="deCipher">Decipher!</button>

```

<pre class="lang-css prettyprint-override"><code>.container {
  max-width: 992px;
  height: 100%;
  margin: 0 auto;
  background: blue;
}
.pinupSide {
  background: green;
  width: 50%;
  height: 100%;
  float: left;
}
.pinUpGirl {
  max-width: 100%;
  max-height: 100%;
  background: black;
}
.cipherSide {
  position: relative;
  background: red;
  width: 50%;
  height: 500px;
  float: left;
}
.verticalAlign {
  position: absolute;
  top: 25%;
  height: 50%;
  width: 100%;
  background: yellow;
}
</code>```

I want both of the divs to have the same height at all times, no matter how I´m scaling the width of the browser window.

答:
I second the use of grid like Auguste said. You could also use flex-box instead of floats and absolute positioning. Here is one possible implementation.

You'll probably have to play with object-fit on the image. Or just set the background of the pinup side to be the image and change the positioning through background properties. Either way it should work out.

You can also set hard heights and widths if you want to and just you the flex-box for positioning.

If you run the code snippet be sure to view it full screen because it uses view-port units for the height of the container.

* {
  box-sizing: border-box;
}

.container {
  padding: 2rem;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pinupSide,
.cipherSide {
  flex: 1 1;
  height: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.pinupSide {
  align-items: center;
  background: rgba(0,0,0,.6);
}

.pinUpGirl {
  width: 100%;
  object-fit: cover;
  object-position: 50% 50%;
}

.cipherSide {
  align-items: flex-start;
  background: rgba(231, 76, 60, 1)
}

.heading-group {
  background: rgba(241, 196, 15, 1);
}

textarea {
  width: 100%;
}

.button-group {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="pinupSide">
    <img class="pinUpGirl" src="https://images.unsplash.com/photo-1530650819615-f14c8a735dd8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1055&q=80" alt="Pin up girl">
  </div>

  <div class="cipherSide">
    <div class="heading-group">
      <h1> Dirty Diana </h1>
      <p>Dirty Diana wants to send dirty love messages to her husband, but she does not want Big Brother to know about it. Try out the tool I made for her!</p>
    </div>
    <textarea rows="10" placeholder="Insert the text you want to cipher or decipher here!" required></textarea>
    <div class="button-group">
      <button id="cipherIT">Cipher It!</button>
      <button id="deCipher">Decipher!</button>
    </div>
    <p id="newOne"></p>
  </div><!-- cipherSide -->

</div><!-- container --></code>```

Body:
I have 2 divs that are floated next to each other. In one of the divs I have an image that scales (both it´s height and width) when I decrease the size of the browser window. In the other div I have some other content, but this is only being scaled in width when I decrease the size of the browser window. I want both of the divs to have the same height at all times, even when they are being scaled. Is this possible?

If you want a live preview, please check out this link:
http://jjberg.com/cipher/index.html

I know part of the problem is that I´ve actually set a height of 500px to the cipherSide div. This is because so far I haven´t been able to make the height of this div closer to the height of the pinupSide div in any other way.

I tried to copy the declarations from the pinupSide and pinUpGirl to the cipherSide and verticalAlign divs, but to no avail. This only pushed the content in the cipherSide div all the way to the top.

 Dirty Diana

Dirty Diana wants to send dirty love messages to her husband, but she does not want Big Brother to know about it. Try out the tool I made for her!

      <textarea rows="10" placeholder="Insert the text you want to cipher or decipher here!" required></textarea>
      <button id="cipherIT">Cipher It!</button>
      <button id="deCipher">Decipher!</button>

.container {
  max-width: 992px;
  height: 100%;
  margin: 0 auto;
  background: blue;
}
.pinupSide {
  background: green;
  width: 50%;
  height: 100%;
  float: left;
}
.pinUpGirl {
  max-width: 100%;
  max-height: 100%;
  background: black;
}
.cipherSide {
  position: relative;
  background: red;
  width: 50%;
  height: 500px;
  float: left;
}
.verticalAlign {
  position: absolute;
  top: 25%;
  height: 50%;
  width: 100%;
  background: yellow;
}

I want both of the divs to have the same height at all times, no matter how I´m scaling the width of the browser window.

Body:
I second the use of grid like Auguste said. You could also use flex-box instead of floats and absolute positioning. Here is one possible implementation.

You'll probably have to play with object-fit on the image. Or just set the background of the pinup side to be the image and change the positioning through background properties. Either way it should work out.

You can also set hard heights and widths if you want to and just you the flex-box for positioning.

If you run the code snippet be sure to view it full screen because it uses view-port units for the height of the container.

* {
  box-sizing: border-box;
}

.container {
  padding: 2rem;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pinupSide,
.cipherSide {
  flex: 1 1;
  height: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.pinupSide {
  align-items: center;
  background: rgba(0,0,0,.6);
}

.pinUpGirl {
  width: 100%;
  object-fit: cover;
  object-position: 50% 50%;
}

.cipherSide {
  align-items: flex-start;
  background: rgba(231, 76, 60, 1)
}

.heading-group {
  background: rgba(241, 196, 15, 1);
}

textarea {
  width: 100%;
}

.button-group {
  width: 100%;
}

<div class="container">

  <div class="pinupSide">
    <img class="pinUpGirl" src="https://images.unsplash.com/photo-1530650819615-f14c8a735dd8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1055&q=80" alt="Pin up girl">
  </div>

  <div class="cipherSide">
    <div class="heading-group">
      <h1> Dirty Diana </h1>
      <p>Dirty Diana wants to send dirty love messages to her husband, but she does not want Big Brother to know about it. Try out the tool I made for her!</p>
    </div>
    <textarea rows="10" placeholder="Insert the text you want to cipher or decipher here!" required></textarea>
    <div class="button-group">
      <button id="cipherIT">Cipher It!</button>
      <button id="deCipher">Decipher!</button>
    </div>
    <p id="newOne"></p>
  </div><!-- cipherSide -->

</div><!-- container -->


问:
can't render the Data in *ngFor but it already show in console in angular 7
I'm trying to render the data that I get from API to show it in my html page. But, i can't render the data to my html page even though it already show when I'm using console.log()

I already try some of this answer from this topic but it still not solve my problem:

I am getting Data in Console Using Angular but I can't render it in html

Angular - How ngFor works?

this is my body.component.ts:

```<code>import { Component, OnInit } from '@angular/core';
import { TimelineService } from 'src/app/services/timeline.service';

@Component({
  selector: 'app-body-homepage',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component..scss']
})
export class BodyComponent implements OnInit {

  constructor(public timeline: TimelineService) {   }

  ngOnInit() {
    this.getTimeline();
  }

  getTimeline(){
    this.timeline.timeline().subscribe((data)=>{
      let timelines = [];
      let i;

      for (i=0; i < data.timelines.length; i++) {
        let id = data.timelines[i]._id;
        let date = data.timelines[i].date;
        let title = data.timelines[i].title;

        timelines.push({"id": id, "date": date, "title": title})
      }
      console.log("Cek Timelines : ", timelines);
    });
  }

  scrollToElement($element): void {
    console.log($element);
    $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
  }
}

</code>```

this is the response data in console:

```<code>[{
    "_id": "5ce8122d7e55260d3d9dd78a",
    "title": "Kumpul Perdana",
    "body": "Kumpul Perdana MPKMB 56",
    "date": "2019-08-29T17:00:00.000Z",
    "__v": 0
  },
  {
    "_id": "5ce812b27e55260d3d9dd78b",
    "title": "Pembagian Kelompok Besar",
    "body": "Pembagian Kelompok Besar",
    "date": "2019-09-15T17:00:00.000Z",
    "__v": 0
  }
]
</code>```

this is my html code:

```<code><div class="row">
  <div class="col-12 col-md-12 col-lg-12">
    <ul>
      <li *ngFor="let item of timelines">
        {{item.date}}. {{item.title}}
      </li>
    </ul>
  </div>
</div>
</code>```

but when I try to use the data normally without using API like this:

ts:

```<code>items = [{
    "_id": "5ce8122d7e55260d3d9dd78a",
    "title": "Kumpul Perdana",
    "body": "Kumpul Perdana MPKMB 56",
    "date": "2019-08-29T17:00:00.000Z",
    "__v": 0
  },
  {
    "_id": "5ce812b27e55260d3d9dd78b",
    "title": "Pembagian Kelompok Besar",
    "body": "Pembagian Kelompok Besar",
    "date": "2019-09-15T17:00:00.000Z",
    "__v": 0
  }
]
</code>```

html:

```<code><div class="row">
  <div class="col-12 col-md-12 col-lg-12">
    <ul>
      <li *ngFor="let item of items">
        {{item.date}}. {{item.title}}
      </li>
    </ul>
  </div>
</div>
</code>```

it works fine

can someone help me to solve this problem? i feel i miss something to solve it but i can't figure it which the problem is

答:
Declare the timelines at the top within the component,

```<code>timelines = [];
</code>```

and then,

```<code>this.timelines.push({"id": id, "date": date, "title": title})
</code>```

using let within the method will make your variable available only to that method.

Body:
I'm trying to render the data that I get from API to show it in my html page. But, i can't render the data to my html page even though it already show when I'm using console.log()

I already try some of this answer from this topic but it still not solve my problem:

I am getting Data in Console Using Angular but I can't render it in html

Angular - How ngFor works?

this is my body.component.ts:

import { Component, OnInit } from '@angular/core';
import { TimelineService } from 'src/app/services/timeline.service';

@Component({
  selector: 'app-body-homepage',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component..scss']
})
export class BodyComponent implements OnInit {

  constructor(public timeline: TimelineService) {   }

  ngOnInit() {
    this.getTimeline();
  }

  getTimeline(){
    this.timeline.timeline().subscribe((data)=>{
      let timelines = [];
      let i;

      for (i=0; i < data.timelines.length; i++) {
        let id = data.timelines[i]._id;
        let date = data.timelines[i].date;
        let title = data.timelines[i].title;

        timelines.push({"id": id, "date": date, "title": title})
      }
      console.log("Cek Timelines : ", timelines);
    });
  }

  scrollToElement($element): void {
    console.log($element);
    $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
  }
}

this is the response data in console:

[{
    "_id": "5ce8122d7e55260d3d9dd78a",
    "title": "Kumpul Perdana",
    "body": "Kumpul Perdana MPKMB 56",
    "date": "2019-08-29T17:00:00.000Z",
    "__v": 0
  },
  {
    "_id": "5ce812b27e55260d3d9dd78b",
    "title": "Pembagian Kelompok Besar",
    "body": "Pembagian Kelompok Besar",
    "date": "2019-09-15T17:00:00.000Z",
    "__v": 0
  }
]

this is my html code:

        {{item.date}}. {{item.title}}

but when I try to use the data normally without using API like this:

ts:

items = [{
    "_id": "5ce8122d7e55260d3d9dd78a",
    "title": "Kumpul Perdana",
    "body": "Kumpul Perdana MPKMB 56",
    "date": "2019-08-29T17:00:00.000Z",
    "__v": 0
  },
  {
    "_id": "5ce812b27e55260d3d9dd78b",
    "title": "Pembagian Kelompok Besar",
    "body": "Pembagian Kelompok Besar",
    "date": "2019-09-15T17:00:00.000Z",
    "__v": 0
  }
]

html:

        {{item.date}}. {{item.title}}

it works fine

can someone help me to solve this problem? i feel i miss something to solve it but i can't figure it which the problem is

Body:
Declare the timelines at the top within the component,

timelines = [];

and then,

this.timelines.push({"id": id, "date": date, "title": title})

using let within the method will make your variable available only to that method.


问:
Traversing an array to find the second largest element in linear time
Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.

Solution : Sort the array and take the second element but Sorting not allowed

Modification : By definition second largest element will be the one which is numerically smaller. Like if we have

Arr = {5,5,4,3,1}
Then second largest is 4

Addition
Lets say if i want to generalize the question to kth largest and complexity less than linear like nlogn, what can be the solution.

答:
```<code>// assuming that v is the array and length is its length
int m1 = max(v[0], v[1]), m2 = min(v[0], v[1]);

for (int i=2; i<length; i++) {
  if (likely(m2 >= v[i]))
    continue;
  if (unlikely(m1 < v[i]))
    m2 = m1, m1 = v[i];
  else
    m2 = v[i];
}
</code>```

The result you need is in m2 (likely and unlikely are macros defined as here for performance purposes, you can simply remove them if you don't need them).

Body:
// assuming that v is the array and length is its length
int m1 = max(v[0], v[1]), m2 = min(v[0], v[1]);

for (int i=2; i<length; i++) {
  if (likely(m2 >= v[i]))
    continue;
  if (unlikely(m1 < v[i]))
    m2 = m1, m1 = v[i];
  else
    m2 = v[i];
}

The result you need is in m2 (likely and unlikely are macros defined as here for performance purposes, you can simply remove them if you don't need them).


问:
RegEx for matching MongoDB strings
I'm using mongoose and have a large quantity of objects like this:

```<code>{
"_id" : ObjectId("5bfeb4aa0a49bf3d84d885b5"),
"category" : [
    "Cult",
    "Space Opera"
],
"actors" : [
    "David Prowse in the role of Darth Vader",
    "Mark Hamill as Luke Skywalker",
    "Carrie Fisher as Leia Organa",
    ...
],
"title" : "Star Wars",
"description" : ".....",
"rating" : 4.65,
"__v" : 0
</code>```

}

I need to find all the films that matches with my array of actors

for example: ["David Prowse", "Mark Hamill", "Carrie Fisher"]

Using this array one of films should be Star Wars but in the film object there aren't clean actor names so probably need to match with regex or something like that to match by substring (case insensitive).

My actual query return always empty array of documents   ----------

```<code>let arrayOfqueries = [];

    for (let i = 0; i < arrayOfActors.length; i++) {
        arrayOfqueries.push({$regex: ".*" + arrayOfActors[i] + ".*", $options: "i"});
    }

    Utils.searchFilms({
        "actors": {
            "$all": arrayOfqueries
        }
    }).then((docs) => {
        console.log(docs)
    }).catch((err) => {
        console.log(err);
    });
</code>```

答:
Your regular expression should be</p>

```<code>for (let i = 0; i < arrayOfActors.length; i++) {
  arrayOfqueries.push(new RegExpr("\b" + arrayOfActors[i] + "\b"))
}
</code>```

Title: RegEx for matching MongoDB strings

Body:
I'm using mongoose and have a large quantity of objects like this:

{
"_id" : ObjectId("5bfeb4aa0a49bf3d84d885b5"),
"category" : [
    "Cult",
    "Space Opera"
],
"actors" : [
    "David Prowse in the role of Darth Vader",
    "Mark Hamill as Luke Skywalker",
    "Carrie Fisher as Leia Organa",
    ...
],
"title" : "Star Wars",
"description" : ".....",
"rating" : 4.65,
"__v" : 0

}

I need to find all the films that matches with my array of actors

for example: ["David Prowse", "Mark Hamill", "Carrie Fisher"]

Using this array one of films should be Star Wars but in the film object there aren't clean actor names so probably need to match with regex or something like that to match by substring (case insensitive).

My actual query return always empty array of documents   ----------

let arrayOfqueries = [];

    for (let i = 0; i < arrayOfActors.length; i++) {
        arrayOfqueries.push({$regex: ".*" + arrayOfActors[i] + ".*", $options: "i"});
    }

    Utils.searchFilms({
        "actors": {
            "$all": arrayOfqueries
        }
    }).then((docs) => {
        console.log(docs)
    }).catch((err) => {
        console.log(err);
    });

Body:
Your regular expression should be

for (let i = 0; i < arrayOfActors.length; i++) {
  arrayOfqueries.push(new RegExpr("\b" + arrayOfActors[i] + "\b"))
}


问:
Signal/Method for every executed sql statement
According to this 12 years old issue, django does not support a signal for every executed sql statement: https://code.djangoproject.com/ticket/5415

I need this in a production environment where debug=False.

This means overwriting connection.queries does not work.

Is there a way to run some custom code after each sql statement (even if debug=False)?

答:
Maybe you could add a logger to your db backends:

```<code>import logging
logger = logging.getLogger('django.db.backends')
logger.setLevel(logging.DEBUG) #set the log level you want
logger.addHandler(logging.StreamHandler())
</code>```

This will track all database transactions.

I remember seeing this some years ago, but I think it should work, since the logging system is pretty much the same.

It is not a signal, but I think it would do what you want.

Body:
Maybe you could add a logger to your db backends:

import logging
logger = logging.getLogger('django.db.backends')
logger.setLevel(logging.DEBUG) #set the log level you want
logger.addHandler(logging.StreamHandler())

This will track all database transactions.

I remember seeing this some years ago, but I think it should work, since the logging system is pretty much the same.

It is not a signal, but I think it would do what you want.


问:
How to filter 2 comboboxes based on the selection in 1 combobox?
I have 3 tables:

1) House:

```<code>| ID_house | House_names | num_region |
---------------------------------------
|   int    |    names    |    int     |
</code>```

num_region - a foreign key, which equals to a primary key(Region.ID_region) in Region table.

2) Region:

```<code>| ID_region | Nameofregions | num_arearegion |
---------------------------------------------
|   int     |    names      |      int       |
</code>```

num_arearegion - a foreign key, equals to primary key(Areas_InRegion.ID_areas) in Areas_InRegion table.

3) Areas_InRegion:

```<code>| ID_areas | Area_names |
------------------------
|   int   |    names   |
</code>```

In the form I have 3 comboboxes:

1) cmbHouse - for showing names of houses from House table.

2) cmbRegion - for showing names of regions from Region table.

3) cmbArea - for showing names of areas in regions from Areas_InRegion table.

I populate comboboxes like this:

```<code>    //cmbHouse
    string cmbHouse_query = "SELECT * FROM House";
    OleDbDataAdapter dahouse = new OleDbDataAdapter(cmbHouse_query, connection);
    DataTable tablehouse = new DataTable();
    dahouse.Fill(tablehouse);
    cmbHouse.DataSource = tablehouse;
    cmbHouse.DisplayMember = "House_names";
    cmbHouse.ValueMember = "House.num_region";
    cmbHouse.SelectedIndex = -1;

    //cmbRegion
    string cmbRegion_query = "SELECT * FROM Region";
    OleDbDataAdapter daregion = new OleDbDataAdapter(cmbRegion_query, connection);
    DataTable tableregion = new DataTable();
    daregion.Fill(tableregion);
    cmbRegion.DataSource = tableregion;
    cmbRegion.DisplayMember = "Nameofregions";
    cmbRegion.ValueMember = "Region.ID_region";
    cmbRegion.SelectedIndex = -1;

    //cmbArea
    string cmbArea_query = "SELECT * FROM Areas_InRegion";
    OleDbDataAdapter daArea = new OleDbDataAdapter(cmbArea_query, connection);
    DataTable tablearea = new DataTable();
    daArea.Fill(tablearea);
    cmbArea.DataSource = tablearea;
    cmbArea.DisplayMember = "Names_OfAreas";
    cmbArea.ValueMember = "Areas_InRegion.ID_areas";
    cmbArea.SelectedIndex = -1;
</code>```

Combobox cmbRegion has valuemember as the primary key.

I can filter cmbHouse combobox by the primary key as valuemeber in cmbRegion combo, but I can't filter cmbArea combobox.

```<code>    private void cmbHouse_SelectionChangeCommitted(object sender, EventArgs e)
    {
        if (cmbHouse.SelectedIndex > -1)
        {
            //DataRow selectedDataRow = ((DataRowView)cmbHouse.SelectedItem).Row;
            int num_region = Convert.ToInt32(cmbHouse.SelectedValue);

            OleDbCommand com = new OleDbCommand();
            com.CommandText = "SELECT * FROM Region WHERE Region.ID_region=" + num_region.ToString() + "";
            //com.Parameters.AddWithValue("House.num_region", typeof(int));
            OleDbDataAdapter danum_region = new OleDbDataAdapter(com.CommandText, connection);
            DataTable tablenum_region = new DataTable();
            danum_region.Fill(tablenum_region);
            cmbRegion.DataSource = tablenum_region;
            cmbRegion.DisplayMember = "Nameofregions";
            cmbRegion.ValueMember = "Region.num_arearegion";
            //cmbRegion.SelectedIndex = -1;
            if(cmbRegion.SelectedIndex > -1)
            {
                int num_area = Convert.ToInt32(cmbRegion.SelectedValue);

                OleDbCommand com2 = new OleDbCommand();

                com2.CommandText = "SELECT * FROM Areas_InRegion WHERE Areas_InRegion.ID_areas=" + num_area.ToString(); // + num_area.ToString() + " ; WHERE Region.num_arearegion=@Areas_InRegion.ID_area
                                                                                //com2.Parameters.AddWithValue("@Areas_InRegion.ID_area", num_area);
                OleDbDataAdapter danum_area = new OleDbDataAdapter(com2.CommandText, connection);
                DataTable tablenum_area = new DataTable();
                //tablenum_area.DefaultView.RowFilter = "Areas_InRegion.ID_areas=" + num_area.ToString();
                danum_area.Fill(tablenum_area);

                cmbArea.DataSource = tablenum_area;
                cmbArea.DisplayMember = "Names_OfAreas";
                cmbArea.ValueMember = "Areas_InRegion.ID_areas";
                //cmbArea.SelectedIndex = -1;
            }
        }
    }
</code>```

For this, it is necessary that there was another valuemeber as a foreign key [Region.num_areas].

Is it possible to have multiple valuemembers in every single combobox?

When I click on any of the comboboxes, other comboboxes should be filtered.

Please help me.

Thank you.

答:
An house is located in a region (1-1 relationship), a Region can have one or more Areas (1-n relationship), an Area belongs to one and only one Region with these relationships you have your database schema wrong. You need something like this (because obviously an house could be located in only one Area)

```<code>1) House:
| ID_house | House_names | ID_region | ID_areas |
--------------------------------------------------
|   int    |    names    |    int     | int      |

2) Region:
| ID_region | Nameofregions |
-----------------------------
|   int     |    names      |

3) Areas:
| ID_areas | Area_names | ID_region |
-------------------------------------
|   int   |    names    | int       |
</code>```

Now when you get the id for the house you have also the id for the region and the area.

```<code>private void cmbHouse_SelectionChangeCommitted(object sender, EventArgs e)
{
    if (cmbHouse.SelectedIndex > -1)
    {
        // Each item in a combobox binded to a datatable is a DataRowView
        // If we get this object we can access all the columns from that row
        DataRowView rv = cmbHouse.SelectedItem as DataRowView;

        // Extract the fk for the region and the area
        int id_region = Convert.ToInt32(rv["ID_region"]);
        int id_area = Convert.ToInt32(rv["ID_area"]);

        // at startup you have already filled the combo with the regions,
        // so there is no need to look again in the database for the region
        // Just set the current selected value to the region
        cmbRegion.SelectedValue = num_region;

        // the same happens for the Areas combo. It is already filled with the
        // areas, but here we should really have only the areas that belongs to
        // the selected region not all the area to avoid problems
        // (so remove the initial filling and do it only when the user choose an House)
        // Query for all areas belonging to the selected region
        string areaSql = @"SELECT * FROM Areas
                           WHERE ID_Region=@reg";
        OleDbCommand com2 = new OleDbCommand(areaSql, connection);
        com2.Parameters.AddWithValue("@reg", num_region);
        OleDbDataAdapter danum_area = new OleDbDataAdapter(com2);
        DataTable tablenum_area = new DataTable();
        danum_area.Fill(tablenum_area);

        // Always put the Datasource after the setting for DisplayMember and ValueMember
        // to avoid performance drops and problems if there is a SelectedIndexChanged event
        cmbArea.DisplayMember = "Names_OfAreas";
        cmbArea.ValueMember = "ID_areas";
        cmbArea.DataSource = tablenum_area;

        // last step is setting the SelectedValue on the cmbArea to the house's area
        cmbArea.SelectedValue = id_area;
    }
}
</code>```

Body:
I have 3 tables:

1) House:

| ID_house | House_names | num_region |
---------------------------------------
|   int    |    names    |    int     |

num_region - a foreign key, which equals to a primary key(Region.ID_region) in Region table.

2) Region:

| ID_region | Nameofregions | num_arearegion |
---------------------------------------------
|   int     |    names      |      int       |

num_arearegion - a foreign key, equals to primary key(Areas_InRegion.ID_areas) in Areas_InRegion table.

3) Areas_InRegion:

| ID_areas | Area_names |
------------------------
|   int   |    names   |

In the form I have 3 comboboxes:

1) cmbHouse - for showing names of houses from House table.

2) cmbRegion - for showing names of regions from Region table.

3) cmbArea - for showing names of areas in regions from Areas_InRegion table.

I populate comboboxes like this:

    //cmbHouse
    string cmbHouse_query = "SELECT * FROM House";
    OleDbDataAdapter dahouse = new OleDbDataAdapter(cmbHouse_query, connection);
    DataTable tablehouse = new DataTable();
    dahouse.Fill(tablehouse);
    cmbHouse.DataSource = tablehouse;
    cmbHouse.DisplayMember = "House_names";
    cmbHouse.ValueMember = "House.num_region";
    cmbHouse.SelectedIndex = -1;

    //cmbRegion
    string cmbRegion_query = "SELECT * FROM Region";
    OleDbDataAdapter daregion = new OleDbDataAdapter(cmbRegion_query, connection);
    DataTable tableregion = new DataTable();
    daregion.Fill(tableregion);
    cmbRegion.DataSource = tableregion;
    cmbRegion.DisplayMember = "Nameofregions";
    cmbRegion.ValueMember = "Region.ID_region";
    cmbRegion.SelectedIndex = -1;

    //cmbArea
    string cmbArea_query = "SELECT * FROM Areas_InRegion";
    OleDbDataAdapter daArea = new OleDbDataAdapter(cmbArea_query, connection);
    DataTable tablearea = new DataTable();
    daArea.Fill(tablearea);
    cmbArea.DataSource = tablearea;
    cmbArea.DisplayMember = "Names_OfAreas";
    cmbArea.ValueMember = "Areas_InRegion.ID_areas";
    cmbArea.SelectedIndex = -1;

Combobox cmbRegion has valuemember as the primary key.

I can filter cmbHouse combobox by the primary key as valuemeber in cmbRegion combo, but I can't filter cmbArea combobox.

    private void cmbHouse_SelectionChangeCommitted(object sender, EventArgs e)
    {
        if (cmbHouse.SelectedIndex > -1)
        {
            //DataRow selectedDataRow = ((DataRowView)cmbHouse.SelectedItem).Row;
            int num_region = Convert.ToInt32(cmbHouse.SelectedValue);

            OleDbCommand com = new OleDbCommand();
            com.CommandText = "SELECT * FROM Region WHERE Region.ID_region=" + num_region.ToString() + "";
            //com.Parameters.AddWithValue("House.num_region", typeof(int));
            OleDbDataAdapter danum_region = new OleDbDataAdapter(com.CommandText, connection);
            DataTable tablenum_region = new DataTable();
            danum_region.Fill(tablenum_region);
            cmbRegion.DataSource = tablenum_region;
            cmbRegion.DisplayMember = "Nameofregions";
            cmbRegion.ValueMember = "Region.num_arearegion";
            //cmbRegion.SelectedIndex = -1;
            if(cmbRegion.SelectedIndex > -1)
            {
                int num_area = Convert.ToInt32(cmbRegion.SelectedValue);

                OleDbCommand com2 = new OleDbCommand();

                com2.CommandText = "SELECT * FROM Areas_InRegion WHERE Areas_InRegion.ID_areas=" + num_area.ToString(); // + num_area.ToString() + " ; WHERE Region.num_arearegion=@Areas_InRegion.ID_area
                                                                                //com2.Parameters.AddWithValue("@Areas_InRegion.ID_area", num_area);
                OleDbDataAdapter danum_area = new OleDbDataAdapter(com2.CommandText, connection);
                DataTable tablenum_area = new DataTable();
                //tablenum_area.DefaultView.RowFilter = "Areas_InRegion.ID_areas=" + num_area.ToString();
                danum_area.Fill(tablenum_area);

                cmbArea.DataSource = tablenum_area;
                cmbArea.DisplayMember = "Names_OfAreas";
                cmbArea.ValueMember = "Areas_InRegion.ID_areas";
                //cmbArea.SelectedIndex = -1;
            }
        }
    }

For this, it is necessary that there was another valuemeber as a foreign key [Region.num_areas].

Is it possible to have multiple valuemembers in every single combobox?

When I click on any of the comboboxes, other comboboxes should be filtered.

Please help me.

Thank you.

Body:
An house is located in a region (1-1 relationship), a Region can have one or more Areas (1-n relationship), an Area belongs to one and only one Region with these relationships you have your database schema wrong. You need something like this (because obviously an house could be located in only one Area)

1) House:
| ID_house | House_names | ID_region | ID_areas |
--------------------------------------------------
|   int    |    names    |    int     | int      |

2) Region:
| ID_region | Nameofregions |
-----------------------------
|   int     |    names      |

3) Areas:
| ID_areas | Area_names | ID_region |
-------------------------------------
|   int   |    names    | int       |

Now when you get the id for the house you have also the id for the region and the area.

private void cmbHouse_SelectionChangeCommitted(object sender, EventArgs e)
{
    if (cmbHouse.SelectedIndex > -1)
    {
        // Each item in a combobox binded to a datatable is a DataRowView
        // If we get this object we can access all the columns from that row
        DataRowView rv = cmbHouse.SelectedItem as DataRowView;

        // Extract the fk for the region and the area
        int id_region = Convert.ToInt32(rv["ID_region"]);
        int id_area = Convert.ToInt32(rv["ID_area"]);

        // at startup you have already filled the combo with the regions,
        // so there is no need to look again in the database for the region
        // Just set the current selected value to the region
        cmbRegion.SelectedValue = num_region;

        // the same happens for the Areas combo. It is already filled with the
        // areas, but here we should really have only the areas that belongs to
        // the selected region not all the area to avoid problems
        // (so remove the initial filling and do it only when the user choose an House)
        // Query for all areas belonging to the selected region
        string areaSql = @"SELECT * FROM Areas
                           WHERE ID_Region=@reg";
        OleDbCommand com2 = new OleDbCommand(areaSql, connection);
        com2.Parameters.AddWithValue("@reg", num_region);
        OleDbDataAdapter danum_area = new OleDbDataAdapter(com2);
        DataTable tablenum_area = new DataTable();
        danum_area.Fill(tablenum_area);

        // Always put the Datasource after the setting for DisplayMember and ValueMember
        // to avoid performance drops and problems if there is a SelectedIndexChanged event
        cmbArea.DisplayMember = "Names_OfAreas";
        cmbArea.ValueMember = "ID_areas";
        cmbArea.DataSource = tablenum_area;

        // last step is setting the SelectedValue on the cmbArea to the house's area
        cmbArea.SelectedValue = id_area;
    }
}


问:
R MLR package: Stop makeClassifTask from dropping empty factor levels for testing set
I have a binary classification problem involving categorical predictor variables Var1 & Var2:

```<code>> head(traindata)

#  ID   Var1 Var2 response
# 1 101   -2   0      0
# 2 201    0  -1      1
# 3 301    0  -2      0
# 4 401   -1   0      0
# 6 501    0  -1      1
</code>```

The training set includes all -2,-1,0 as levels of Var1 but the testing set does not include -1 as an input in Var1.

I did ensure that Var1 contains all the levels in the testing set:

```<code>testdata$Var1 <- factor(testdata$Var1, levels = levels(traindata$Var1)
</code>```

So the blank factor level does exist even though test data does not include -1 in its records.

But when I try to create a task for the test set using:

```<code>testtask <- makeClassifTask(data = testdata, target = "response", positive = "1")
</code>```

I get a warning stating the empty factor levels were dropped for columns: Var1

I tried setting the fixup.data = "no" parameter as well. It gives the following error:

```<code>testtask <- makeClassifTask(data = testdata, target = "response", positive = "1", fixup.data = "no")

# Error in (function (cn, x)  :
#   Column 'Var1' contains empty factor levels.
</code>```

PS: I'm not resampling the testing data on my own, it's an external data set for which I do not know the response variable.

Also, I did recode dummy values for the response variable in the test set before creating the task.

答:
give the below parameters. You need to use check.data along with fixup.data. Hope this helps :)

Syntax:

```<code>testtask = makeClassifTask(data = testdata, target = "response", positive = "1",fixup.data = "no",check.data = FALSE)
</code>```

Body:
I have a binary classification problem involving categorical predictor variables Var1 & Var2:

> head(traindata)

#  ID   Var1 Var2 response
# 1 101   -2   0      0
# 2 201    0  -1      1
# 3 301    0  -2      0
# 4 401   -1   0      0
# 6 501    0  -1      1

The training set includes all -2,-1,0 as levels of Var1 but the testing set does not include -1 as an input in Var1.

I did ensure that Var1 contains all the levels in the testing set:

testdata$Var1 <- factor(testdata$Var1, levels = levels(traindata$Var1)

So the blank factor level does exist even though test data does not include -1 in its records.

But when I try to create a task for the test set using:

testtask <- makeClassifTask(data = testdata, target = "response", positive = "1")

I get a warning stating the empty factor levels were dropped for columns: Var1

I tried setting the fixup.data = "no" parameter as well. It gives the following error:

testtask <- makeClassifTask(data = testdata, target = "response", positive = "1", fixup.data = "no")

# Error in (function (cn, x)  :
#   Column 'Var1' contains empty factor levels.

PS: I'm not resampling the testing data on my own, it's an external data set for which I do not know the response variable.

Also, I did recode dummy values for the response variable in the test set before creating the task.

Body:
give the below parameters. You need to use check.data along with fixup.data. Hope this helps :)

Syntax:

testtask = makeClassifTask(data = testdata, target = "response", positive = "1",fixup.data = "no",check.data = FALSE)


问:
Any utility which can print out map quickly
I am wondering any utility to print out map quickly for debugging purpose.</p>

答:
You can just print the toString() of a Map to get a 1-line version of the map, divided up in to key/value entries. If that isn't readable enough, you could do your own looping to print or use Guava to do this:

```<code>System.out.println(Joiner.on('\n').withKeyValueSeparator(" -> ").join(map));
</code>```

That'll give you output of the form

```key1 -> value1
key2 -> value2
...```

Body:
You can just print the toString() of a Map to get a 1-line version of the map, divided up in to key/value entries. If that isn't readable enough, you could do your own looping to print or use Guava to do this:

System.out.println(Joiner.on('\n').withKeyValueSeparator(" -> ").join(map));

That'll give you output of the form

key1 -> value1
key2 -> value2
...


问:
Should I use configure await in all methods or only in the first method?
I have a library with async methods and I have read that for libraries, it is recommended to use ConfigureAwait(false).

For example, if I have something like:

```<code>public async Task myMethod01()
{
    await myMethod02();
}

private async Task myMethod02()
{
    await myMethod03();
}

private async Task myMethod03()
{
    await anotherMetodAsync().ConfigureAwait(false);
}
</code>```

The library user can only use method01, the other 2 methods are private because they are auxliar methods for the main method method01().

But I don't know if it is needed to use ConfigureAwait only in the first method of the chain call or I should to use in all of them.

答:
tl;dr

Yes, it is needed in order to ensure that all of your asynchronous continuations within your library code are executed on a thread pool thread (depending on the SynchronizationContext/TaskScheduler in use).

Would you like to know more?

Task.ConfigureAwait(Boolean)

true attempts to marshal the remainder of the async method back to the original context captured

false schedules the remainder of the async method on a thread pool thread

Consider the following WPF example:
WPF uses the DispatcherSynchronizationContext to resume asynchronous continuations on the UI context, because a background thread cannot update the contents of Controls.

private async void Button_Click(object sender, RoutedEventArgs e)
{
    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context

    await CompleteAsynchronously();

    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context

    await CompleteAsynchronously().ConfigureAwait(false);

    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //true
}

private async Task CompleteAsynchronously()
{
    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context

    await Task.Delay(TimeSpan.FromMilliseconds(100)).ConfigureAwait(false);

    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //true
}
```

<p>Here, you see that the <code>continueOnCapturedContext</code> flag of the called method has no effect on the caller. Yet, the called method runs (or at least starts to run) on the thread that the caller was running on, of course.</p>

<p>However, the capturing of the current context (either the current <code>SynchronizationContext</code>; if null then the current <code>TaskScheduler</code>) only occurs when an incomplete Task is awaited. If the Task completes synchronously, <code>continueOnCapturedContext</code> has no effect and the remainder of the method continues to run synchronously on the current thread.</p>

<pre class="lang-cs prettyprint-override"><code>private async void Button_Click(object sender, RoutedEventArgs e)
{
    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context

    await CompleteSynchronously().ConfigureAwait(false);

    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context
}

private async Task CompleteSynchronously()
{
    await Task.Delay(0);
}
</code>```

So, in your library code (assuming you never require context), you should always use ConfigureAwait(false) in order to ensure that no context is captured for asynchronous continuations, regardless of the framework calling into your assemblies (e.g. WPF, ASP.NET Core, Console, ...).

For more details, have a look at Best Practices in Asynchronous Programming (i.a. ConfigureAwait) in this MSDN Magazine Article by Stephen Cleary.

Body:
I have a library with async methods and I have read that for libraries, it is recommended to use ConfigureAwait(false).

For example, if I have something like:

public async Task myMethod01()
{
    await myMethod02();
}

private async Task myMethod02()
{
    await myMethod03();
}

private async Task myMethod03()
{
    await anotherMetodAsync().ConfigureAwait(false);
}

The library user can only use method01, the other 2 methods are private because they are auxliar methods for the main method method01().

But I don't know if it is needed to use ConfigureAwait only in the first method of the chain call or I should to use in all of them.

Body:
tl;dr

Yes, it is needed in order to ensure that all of your asynchronous continuations within your library code are executed on a thread pool thread (depending on the SynchronizationContext/TaskScheduler in use).

Would you like to know more?

Task.ConfigureAwait(Boolean)

true attempts to marshal the remainder of the async method back to the original context captured

false schedules the remainder of the async method on a thread pool thread

Consider the following WPF example:
WPF uses the DispatcherSynchronizationContext to resume asynchronous continuations on the UI context, because a background thread cannot update the contents of Controls.

private async void Button_Click(object sender, RoutedEventArgs e)
{
    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context

    await CompleteAsynchronously();

    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context

    await CompleteAsynchronously().ConfigureAwait(false);

    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //true
}

private async Task CompleteAsynchronously()
{
    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context

    await Task.Delay(TimeSpan.FromMilliseconds(100)).ConfigureAwait(false);

    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //true
}

Here, you see that the continueOnCapturedContext flag of the called method has no effect on the caller. Yet, the called method runs (or at least starts to run) on the thread that the caller was running on, of course.

However, the capturing of the current context (either the current SynchronizationContext; if null then the current TaskScheduler) only occurs when an incomplete Task is awaited. If the Task completes synchronously, continueOnCapturedContext has no effect and the remainder of the method continues to run synchronously on the current thread.

private async void Button_Click(object sender, RoutedEventArgs e)
{
    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context

    await CompleteSynchronously().ConfigureAwait(false);

    logger.LogInformation(Thread.CurrentThread.IsThreadPoolThread); //false -> GUI context
}

private async Task CompleteSynchronously()
{
    await Task.Delay(0);
}

So, in your library code (assuming you never require context), you should always use ConfigureAwait(false) in order to ensure that no context is captured for asynchronous continuations, regardless of the framework calling into your assemblies (e.g. WPF, ASP.NET Core, Console, ...).

For more details, have a look at Best Practices in Asynchronous Programming (i.a. ConfigureAwait) in this MSDN Magazine Article by Stephen Cleary.


问:
Why can't I use a class from webpack bundled file?
I'm extremely new to using webpack. I'm trying to use it to bundle my framework. Anyways my framework's file looks something like this:

```<code>class Rorke {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}
</code>```

In my webpack.config.js:

```<code>module.exports = {
  entry: "./src/rorke.js",
  output: {
    filename: "rorke.bundle.js"
  }
}
</code>```

My package.json:

```<code>{
  "name": "rorke-3.0",
  "version": "1.0.0",
  "description": "",
  "main": "./src/rorke.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "bundle": "webpack ./src/rorke.js dist/rorke.bundle.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.32.2"
  },
  "dependencies": {
    "pixi.js": "^5.0.3",
    "prototype": "0.0.5"
  }
}
</code>```

So i run:

```<code>npm run bundle
</code>```

And it outputs a bundle file. I then include that file like this:

```<code><html>
  <body>
    <script src="dist/rorke.bundle.js"></script>
    <script src="game.js"></script>
  </body>
</html>
</code>```

And finally, this is my game.js:

```<code>const game = new Rorke(800, 600);
</code>```

So when i open the html file, it tells me:

Rorke is not defined

Does anyone know why this is the case? What am i doing wrong here/not understanding?

答:
Developing a website really just means creating an HTML file, a CSS file, and a JavaScript file (or sometimes these are combined, or the CSS and JavaScript or combined, etc). These are just files served via a webserver on request.

I think one of the main reasons to use webpack is to follow require / import statements, that will convert client code spread across multiple files into a single bundle. Frontend development tooling, such as webpack allows for authoring these files as separate components.

Rorke is probably scoped to the bundle. So start with an index.js file, require / import your class, and then use that class. Then change your webpack root to be index.Js.

Body:
I'm extremely new to using webpack. I'm trying to use it to bundle my framework. Anyways my framework's file looks something like this:

class Rorke {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

In my webpack.config.js:

module.exports = {
  entry: "./src/rorke.js",
  output: {
    filename: "rorke.bundle.js"
  }
}

My package.json:

{
  "name": "rorke-3.0",
  "version": "1.0.0",
  "description": "",
  "main": "./src/rorke.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "bundle": "webpack ./src/rorke.js dist/rorke.bundle.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.32.2"
  },
  "dependencies": {
    "pixi.js": "^5.0.3",
    "prototype": "0.0.5"
  }
}

So i run:

npm run bundle

And it outputs a bundle file. I then include that file like this:

And finally, this is my game.js:

const game = new Rorke(800, 600);

So when i open the html file, it tells me:

Rorke is not defined

Does anyone know why this is the case? What am i doing wrong here/not understanding?


问:
How to find a list of 100 elements of the intersection of 3 large sets?
Is there any way of avoiding to calculate the intersection of all 3 sets and then slicing the first 100 numbers?

My code so far is:

def intersection_alg():
    get_set_from_variable = [A,B,C]
    cfs_set = set()
    for logical_name in get_set_from_variable:
            tmp_set = set(get_list_from_db(logical_name))
        cfs_set = cfs_set.intersection(tmp_set) if cfs_set else cfs_set
    return list(cfs_set)[:100]
```

答:
You can use a generator and itertools.islice, see the example below. Depending on what you know about the content of your sets, you may be able to improve performance by changing the order in which you iterate in the for loop.

The exact result may differ between runs, as sets are iterated in arbitrary order.

Playground: https://ideone.com/hMBZIw

import itertools

def lazy_intersection(*sets):
    for x in min(sets, key=lambda s: len(s)):
        if all(x in s for s in sets):
            yield x

a = {2*k for k in range(1000)}
b = {3*k for k in range(1000)}
c = {5*k for k in range(1000)}

generator = lazy_intersection(a, b, c)

first_10 = list(itertools.islice(generator, 10))
print(first_10)
```

<p>Output (note that the ascending order is not guaranteed):</p>

```[0, 30, 60, 90, 120, 150, 180, 210, 240, 270]
```

Resources:

docs.python.org: itertools

docs.python.org: itertools.islice

wiki.python.org: Generators

Body:
You can use a generator and itertools.islice, see the example below. Depending on what you know about the content of your sets, you may be able to improve performance by changing the order in which you iterate in the for loop.

The exact result may differ between runs, as sets are iterated in arbitrary order.

Playground: https://ideone.com/hMBZIw

import itertools

def lazy_intersection(*sets):
    for x in min(sets, key=lambda s: len(s)):
        if all(x in s for s in sets):
            yield x

a = {2*k for k in range(1000)}
b = {3*k for k in range(1000)}
c = {5*k for k in range(1000)}

generator = lazy_intersection(a, b, c)

first_10 = list(itertools.islice(generator, 10))
print(first_10)

Output (note that the ascending order is not guaranteed):

[0, 30, 60, 90, 120, 150, 180, 210, 240, 270]

Resources:

docs.python.org: itertools

docs.python.org: itertools.islice

wiki.python.org: Generators


问:
ASP.Net Core app.UseStaticFiles not working in Production (Azure), calls to static files drop to default route
I have an ASP.Net Core app that also uses Angular. On my local machine, it is able to serve static files such as js and images. When deploying to Azure, calls to static files returns the default route (which retrieves the Angular app default page.)

In my Startup.cs, I use "app.UseStaticFiles". This works locally.

My Startup.cs is found here.

Can this be a configuration issue with Azure? Or some logic that's present in Development environment but not in Production?

答: For anyone else hitting this problem where UseStaticFiles actually is in the startup, my problem was simple: my subfolder files were not marked as CopyAlways (to output folder). </p>